8 from vapi_json_parser import (
23 return "vapi_type_%s" % self.name
26 if self.type.get_c_name() == "vl_api_string_t":
28 return "u8 %s[%d];" % (self.name, self.len)
30 return "vl_api_string_t %s;" % (self.name)
32 if self.len is not None and type(self.len) != dict:
33 return "%s %s[%d];" % (self.type.get_c_name(), self.name, self.len)
35 return "%s %s;" % (self.type.get_c_name(), self.name)
37 def get_swap_to_be_code(self, struct, var):
38 if self.len is not None and type(self.len) != dict:
41 "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"
43 % (self.len, self.type.get_swap_to_be_code(struct, "%s[i]" % var))
46 if self.nelem_field.needs_byte_swap():
47 nelem_field = "%s(%s%s)" % (
48 self.nelem_field.type.get_swap_to_host_func_name(),
50 self.nelem_field.name,
53 nelem_field = "%s%s" % (struct, self.nelem_field.name)
55 "do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
59 self.type.get_swap_to_be_code(struct, "%s[i]" % var),
62 return self.type.get_swap_to_be_code(struct, "%s" % var)
64 def get_swap_to_host_code(self, struct, var):
65 if self.len is not None and type(self.len) != dict:
68 "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"
70 % (self.len, self.type.get_swap_to_host_code(struct, "%s[i]" % var))
73 # nelem_field already swapped to host here...
75 "do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
79 self.nelem_field.name,
80 self.type.get_swap_to_host_code(struct, "%s[i]" % var),
83 return self.type.get_swap_to_host_code(struct, "%s" % var)
85 def needs_byte_swap(self):
86 return self.type.needs_byte_swap()
88 def get_vla_field_length_name(self, path):
89 return "%s_%s_array_size" % ("_".join(path), self.name)
91 def get_alloc_vla_param_names(self, path):
93 result = [self.get_vla_field_length_name(path)]
96 if self.type.has_vla():
97 t = self.type.get_alloc_vla_param_names(path + [self.name])
101 def get_vla_calc_size_code(self, prefix, path):
104 "sizeof(%s.%s[0]) * %s"
106 ".".join([prefix] + path),
108 self.get_vla_field_length_name(path),
113 if self.type.has_vla():
114 t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
118 def get_vla_assign_code(self, prefix, path):
124 ".".join([prefix] + path),
125 self.nelem_field.name,
126 self.get_vla_field_length_name(path),
129 if self.type.has_vla():
130 t = self.type.get_vla_assign_code(prefix, path + [self.name])
135 class CAlias(CField):
136 def get_c_name(self):
137 return "vapi_type_%s" % self.name
140 if self.len is not None:
141 return "typedef %s vapi_type_%s[%d];" % (
142 self.type.get_c_name(),
147 return "typedef %s vapi_type_%s;" % (self.type.get_c_name(), self.name)
150 class CStruct(Struct):
154 "typedef struct __attribute__((__packed__)) {\n%s"
155 % ("\n".join([" %s" % x.get_c_def() for x in self.fields])),
156 "} %s;" % self.get_c_name(),
160 def get_vla_assign_code(self, prefix, path):
165 for x in f.get_vla_assign_code(prefix, path)
168 def get_alloc_vla_param_names(self, path):
173 for x in f.get_alloc_vla_param_names(path)
176 def get_vla_calc_size_code(self, prefix, path):
181 for x in f.get_vla_calc_size_code(prefix, path)
185 class CSimpleType(SimpleType):
195 swap_to_host_dict = {
204 __packed = "__attribute__((packed))"
212 def get_c_name(self):
215 def get_swap_to_be_func_name(self):
216 return self.swap_to_be_dict[self.name]
218 def get_swap_to_host_func_name(self):
219 return self.swap_to_host_dict[self.name]
221 def get_packed_string(self):
222 return self.pack_dict[self.name]
224 def get_swap_to_be_code(self, struct, var, cast=None):
225 x = "%s%s" % (struct, var)
226 return "%s = %s%s(%s);" % (
228 "(%s)" % cast if cast else "",
229 self.get_swap_to_be_func_name(),
233 def get_swap_to_host_code(self, struct, var, cast=None):
234 x = "%s%s" % (struct, var)
235 return "%s = %s%s(%s);" % (
237 "(%s)" % cast if cast else "",
238 self.get_swap_to_host_func_name(),
242 def needs_byte_swap(self):
244 self.get_swap_to_host_func_name()
250 def get_packed(self):
251 return self.pack_dict.get(self.name, "")
255 def get_c_name(self):
256 return "vapi_enum_%s" % self.name
259 return "typedef enum {\n%s\n} %s %s;" % (
260 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
261 self.type.get_packed(),
265 def needs_byte_swap(self):
266 return self.type.needs_byte_swap()
268 def get_swap_to_be_code(self, struct, var):
269 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
271 def get_swap_to_host_code(self, struct, var):
272 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
276 def get_c_name(self):
277 return "vapi_union_%s" % self.name
280 return "typedef union {\n%s\n} %s;" % (
281 "\n".join([" %s %s;" % (i.get_c_name(), j) for i, j in self.type_pairs]),
285 def needs_byte_swap(self):
289 class CStructType(StructType, CStruct):
290 def get_c_name(self):
291 return "vapi_type_%s" % self.name
293 def get_swap_to_be_func_name(self):
294 return "%s_hton" % self.get_c_name()
296 def get_swap_to_host_func_name(self):
297 return "%s_ntoh" % self.get_c_name()
299 def get_swap_to_be_func_decl(self):
300 return "void %s(%s *msg)" % (self.get_swap_to_be_func_name(), self.get_c_name())
302 def get_swap_to_be_func_def(self):
303 return "%s\n{\n%s\n}" % (
304 self.get_swap_to_be_func_decl(),
307 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
309 if p.needs_byte_swap()
314 def get_swap_to_host_func_decl(self):
315 return "void %s(%s *msg)" % (
316 self.get_swap_to_host_func_name(),
320 def get_swap_to_host_func_def(self):
321 return "%s\n{\n%s\n}" % (
322 self.get_swap_to_host_func_decl(),
325 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
327 if p.needs_byte_swap()
332 def get_swap_to_be_code(self, struct, var):
333 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
335 def get_swap_to_host_code(self, struct, var):
336 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
338 def needs_byte_swap(self):
339 for f in self.fields:
340 if f.needs_byte_swap():
345 class CMessage(Message):
346 def __init__(self, logger, definition, json_parser):
347 super(CMessage, self).__init__(logger, definition, json_parser)
348 self.payload_members = [
349 " %s" % p.get_c_def() for p in self.fields if p.type != self.header
352 def has_payload(self):
353 return len(self.payload_members) > 0
355 def get_msg_id_name(self):
356 return "vapi_msg_id_%s" % self.name
358 def get_c_name(self):
359 return "vapi_msg_%s" % self.name
361 def get_payload_struct_name(self):
362 return "vapi_payload_%s" % self.name
364 def get_alloc_func_name(self):
365 return "vapi_alloc_%s" % self.name
367 def get_alloc_vla_param_names(self):
372 for x in f.get_alloc_vla_param_names([])
375 def get_alloc_func_decl(self):
376 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
378 self.get_alloc_func_name(),
379 "".join([", size_t %s" % n for n in self.get_alloc_vla_param_names()]),
382 def get_alloc_func_def(self):
384 if self.header.has_field("client_index"):
385 extra.append(" msg->header.client_index = vapi_get_client_index(ctx);")
386 if self.header.has_field("context"):
387 extra.append(" msg->header.context = 0;")
390 "%s" % self.get_alloc_func_decl(),
392 " %s *msg = NULL;" % self.get_c_name(),
393 " const size_t size = sizeof(%s)%s;"
401 for x in f.get_vla_calc_size_code("msg->payload", [])
405 " /* cast here required to play nicely with C++ world ... */",
406 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
413 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);"
414 % self.get_msg_id_name(),
420 for line in f.get_vla_assign_code("msg->payload", [])
428 def get_calc_msg_size_func_name(self):
429 return "vapi_calc_%s_msg_size" % self.name
431 def get_calc_msg_size_func_decl(self):
432 return "uword %s(%s *msg)" % (
433 self.get_calc_msg_size_func_name(),
437 def get_calc_msg_size_func_def(self):
440 "%s" % self.get_calc_msg_size_func_decl(),
442 " return sizeof(*msg)%s;"
445 "+ msg->payload.%s * sizeof(msg->payload.%s[0])"
446 % (f.nelem_field.name, f.name)
448 if f.nelem_field is not None
455 def get_verify_msg_size_func_name(self):
456 return f"vapi_verify_{self.name}_msg_size"
458 def get_verify_msg_size_func_decl(self):
459 return "int %s(%s *msg, uword buf_size)" % (
460 self.get_verify_msg_size_func_name(),
464 def get_verify_msg_size_func_def(self):
465 return inspect.cleandoc(
467 {self.get_verify_msg_size_func_decl()}
469 if (sizeof({self.get_c_name()}) > buf_size)
471 VAPI_ERR("Truncated '{self.name}' msg received, received %lu"
472 "bytes, expected %lu bytes.", buf_size,
473 sizeof({self.get_c_name()}));
476 if ({self.get_calc_msg_size_func_name()}(msg) > buf_size)
478 VAPI_ERR("Truncated '{self.name}' msg received, received %lu"
479 "bytes, expected %lu bytes.", buf_size,
480 sizeof({self.get_calc_msg_size_func_name()}));
489 if self.has_payload():
492 "typedef struct __attribute__ ((__packed__)) {",
493 "%s " % "\n".join(self.payload_members),
494 "} %s;" % self.get_payload_struct_name(),
496 "typedef struct __attribute__ ((__packed__)) {",
498 " %s %s;" % (self.header.get_c_name(), self.fields[0].name)
499 if self.header is not None
502 " %s payload;" % self.get_payload_struct_name(),
503 "} %s;" % self.get_c_name(),
509 "typedef struct __attribute__ ((__packed__)) {",
511 " %s %s;" % (self.header.get_c_name(), self.fields[0].name)
512 if self.header is not None
515 "} %s;" % self.get_c_name(),
519 def get_swap_payload_to_host_func_name(self):
520 return "%s_payload_ntoh" % self.get_c_name()
522 def get_swap_payload_to_be_func_name(self):
523 return "%s_payload_hton" % self.get_c_name()
525 def get_swap_payload_to_host_func_decl(self):
526 return "void %s(%s *payload)" % (
527 self.get_swap_payload_to_host_func_name(),
528 self.get_payload_struct_name(),
531 def get_swap_payload_to_be_func_decl(self):
532 return "void %s(%s *payload)" % (
533 self.get_swap_payload_to_be_func_name(),
534 self.get_payload_struct_name(),
537 def get_swap_payload_to_be_func_def(self):
538 return "%s\n{\n%s\n}" % (
539 self.get_swap_payload_to_be_func_decl(),
542 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
544 if p.needs_byte_swap() and p.type != self.header
549 def get_swap_payload_to_host_func_def(self):
550 return "%s\n{\n%s\n}" % (
551 self.get_swap_payload_to_host_func_decl(),
554 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
556 if p.needs_byte_swap() and p.type != self.header
561 def get_swap_to_host_func_name(self):
562 return "%s_ntoh" % self.get_c_name()
564 def get_swap_to_be_func_name(self):
565 return "%s_hton" % self.get_c_name()
567 def get_swap_to_host_func_decl(self):
568 return "void %s(%s *msg)" % (
569 self.get_swap_to_host_func_name(),
573 def get_swap_to_be_func_decl(self):
574 return "void %s(%s *msg)" % (self.get_swap_to_be_func_name(), self.get_c_name())
576 def get_swap_to_be_func_def(self):
579 "%s" % self.get_swap_to_be_func_decl(),
582 ' VAPI_DBG("Swapping `%s\'@%%p to big endian", msg);'
585 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
586 if self.header is not None
588 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
589 if self.has_payload()
595 def get_swap_to_host_func_def(self):
598 "%s" % self.get_swap_to_host_func_decl(),
601 ' VAPI_DBG("Swapping `%s\'@%%p to host byte order", msg);'
604 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
605 if self.header is not None
607 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
608 if self.has_payload()
614 def get_op_func_name(self):
615 return "vapi_%s" % self.name
617 def get_op_func_decl(self):
618 if self.reply.has_payload():
619 return "vapi_error_e %s(%s)" % (
620 self.get_op_func_name(),
623 "struct vapi_ctx_s *ctx",
624 "%s *msg" % self.get_c_name(),
625 "vapi_error_e (*callback)(struct vapi_ctx_s *ctx",
626 " void *callback_ctx",
630 % self.reply.get_payload_struct_name(),
631 "void *callback_ctx",
636 return "vapi_error_e %s(%s)" % (
637 self.get_op_func_name(),
640 "struct vapi_ctx_s *ctx",
641 "%s *msg" % self.get_c_name(),
642 "vapi_error_e (*callback)(struct vapi_ctx_s *ctx",
643 " void *callback_ctx",
646 "void *callback_ctx",
651 def get_op_func_def(self):
654 "%s" % self.get_op_func_decl(),
656 " if (!msg || !callback) {",
657 " return VAPI_EINVAL;",
659 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
660 " return VAPI_EAGAIN;",
663 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
666 " u32 req_context = vapi_gen_req_context(ctx);",
667 " msg->header.context = req_context;",
668 " %s(msg);" % self.get_swap_to_be_func_name(),
670 " if (VAPI_OK == (rv = vapi_send_with_control_ping "
671 "(ctx, msg, req_context))) {"
672 if self.reply_is_stream
673 else " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
676 " vapi_store_request(ctx, req_context, %s, "
677 "(vapi_cb_t)callback, callback_ctx);"
678 % ("true" if self.reply_is_stream else "false")
680 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
681 " abort (); /* this really shouldn't happen */",
683 " if (vapi_is_nonblocking(ctx)) {",
686 " rv = vapi_dispatch(ctx);",
689 " %s(msg);" % self.get_swap_to_host_func_name(),
690 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
691 " abort (); /* this really shouldn't happen */",
700 def get_event_cb_func_decl(self):
701 if not self.is_reply and not self.is_event:
702 raise Exception("Cannot register event callback for non-reply message")
703 if self.has_payload():
706 "void vapi_set_%s_event_cb (" % self.get_c_name(),
707 " struct vapi_ctx_s *ctx, ",
709 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
710 "void *callback_ctx, %s *payload),"
711 % self.get_payload_struct_name()
713 " void *callback_ctx)",
719 "void vapi_set_%s_event_cb (" % self.get_c_name(),
720 " struct vapi_ctx_s *ctx, ",
721 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
722 "void *callback_ctx),",
723 " void *callback_ctx)",
727 def get_event_cb_func_def(self):
728 if not self.is_reply and not self.is_event:
729 raise Exception("Cannot register event callback for non-reply function")
732 "%s" % self.get_event_cb_func_decl(),
735 " vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
736 "callback_ctx);" % self.get_msg_id_name()
742 def get_c_metadata_struct_name(self):
743 return "__vapi_metadata_%s" % self.name
745 def get_c_constructor(self):
747 if self.header is not None:
748 has_context = self.header.has_field("context")
751 "static void __attribute__((constructor)) __vapi_constructor_%s()"
754 ' static const char name[] = "%s";' % self.name,
755 ' static const char name_with_crc[] = "%s_%s";'
756 % (self.name, self.crc[2:]),
757 " static vapi_message_desc_t %s = {"
758 % self.get_c_metadata_struct_name(),
760 " sizeof(name) - 1,",
762 " sizeof(name_with_crc) - 1,",
763 " true," if has_context else " false,",
764 " offsetof(%s, context)," % self.header.get_c_name()
767 (" offsetof(%s, payload)," % self.get_c_name())
768 if self.has_payload()
769 else " VAPI_INVALID_MSG_ID,",
770 " (verify_msg_size_fn_t)%s," % self.get_verify_msg_size_func_name(),
771 " (generic_swap_fn_t)%s," % self.get_swap_to_be_func_name(),
772 " (generic_swap_fn_t)%s," % self.get_swap_to_host_func_name(),
773 " VAPI_INVALID_MSG_ID,",
776 " %s = vapi_register_msg(&%s);"
777 % (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
778 ' VAPI_DBG("Assigned msg id %%d to %s", %s);'
779 % (self.name, self.get_msg_id_name()),
785 def emit_definition(parser, json_file, emitted, o):
788 if o.name in ("msg_header1_t", "msg_header2_t"):
790 if hasattr(o, "depends"):
792 emit_definition(parser, json_file, emitted, x)
793 if hasattr(o, "reply"):
794 emit_definition(parser, json_file, emitted, o.reply)
795 if hasattr(o, "get_c_def"):
797 o not in parser.enums_by_json[json_file]
798 and o not in parser.types_by_json[json_file]
799 and o not in parser.unions_by_json[json_file]
800 and o.name not in parser.messages_by_json[json_file]
801 and o not in parser.aliases_by_json[json_file]
804 guard = "defined_%s" % o.get_c_name()
805 print("#ifndef %s" % guard)
806 print("#define %s" % guard)
807 print("%s" % o.get_c_def())
809 function_attrs = "static inline "
810 if o.name in parser.messages_by_json[json_file]:
812 print("%s%s" % (function_attrs, o.get_swap_payload_to_be_func_def()))
814 print("%s%s" % (function_attrs, o.get_swap_payload_to_host_func_def()))
816 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
818 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
820 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
822 print("%s%s" % (function_attrs, o.get_verify_msg_size_func_def()))
823 if not o.is_reply and not o.is_event:
825 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
827 print("%s%s" % (function_attrs, o.get_op_func_def()))
829 print("%s" % o.get_c_constructor())
830 if o.is_reply or o.is_event:
832 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
833 elif hasattr(o, "get_swap_to_be_func_def"):
834 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
836 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
842 def gen_json_unified_header(parser, logger, j, io, name):
843 d, f = os.path.split(j)
844 logger.info("Generating header `%s'" % name)
845 orig_stdout = sys.stdout
847 include_guard = "__included_%s" % (
854 print("#ifndef %s" % include_guard)
855 print("#define %s" % include_guard)
857 print("#include <stdlib.h>")
858 print("#include <stddef.h>")
859 print("#include <arpa/inet.h>")
860 print("#include <vapi/vapi_internal.h>")
861 print("#include <vapi/vapi.h>")
862 print("#include <vapi/vapi_dbg.h>")
864 print("#ifdef __cplusplus")
865 print('extern "C" {')
867 if name == "memclnt.api.vapi.h":
870 "static inline vapi_error_e vapi_send_with_control_ping "
871 "(vapi_ctx_t ctx, void * msg, u32 context);"
873 elif name == "vlib.api.vapi.h":
874 print("#include <vapi/memclnt.api.vapi.h>")
876 print("#include <vapi/vlib.api.vapi.h>")
878 for m in parser.messages_by_json[j].values():
879 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
882 "#define DEFINE_VAPI_MSG_IDS_%s\\"
883 % f.replace(".", "_").replace("/", "_").replace("-", "_").upper()
888 " vapi_msg_id_t %s;" % m.get_msg_id_name()
889 for m in parser.messages_by_json[j].values()
896 for e in parser.enums_by_json[j]:
897 emit_definition(parser, j, emitted, e)
898 for u in parser.unions_by_json[j]:
899 emit_definition(parser, j, emitted, u)
900 for t in parser.types_by_json[j]:
901 emit_definition(parser, j, emitted, t)
902 for a in parser.aliases_by_json[j]:
903 emit_definition(parser, j, emitted, a)
904 for m in parser.messages_by_json[j].values():
905 emit_definition(parser, j, emitted, m)
909 if name == "vlib.api.vapi.h":
910 vapi_send_with_control_ping_function = """
911 static inline vapi_error_e
912 vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
914 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
919 ping->header.context = context;
920 vapi_msg_control_ping_hton (ping);
921 return vapi_send2 (ctx, msg, ping);
924 print("%s" % vapi_send_with_control_ping_function)
927 print("#ifdef __cplusplus")
932 sys.stdout = orig_stdout
935 def json_to_c_header_name(json_name):
936 if json_name.endswith(".json"):
937 return "%s.vapi.h" % os.path.splitext(json_name)[0]
938 raise Exception("Unexpected json name `%s'!" % json_name)
941 def gen_c_unified_headers(parser, logger, prefix, remove_path):
942 if prefix == "" or prefix is None:
945 prefix = "%s/" % prefix
946 for j in parser.json_files:
948 d, f = os.path.split(j)
951 with open("%s%s" % (prefix, json_to_c_header_name(f)), "w") as io:
952 gen_json_unified_header(parser, logger, j, io, json_to_c_header_name(f))
955 if __name__ == "__main__":
957 verbose = int(os.getenv("V", 0))
968 logging.basicConfig(stream=sys.stdout, level=log_level)
969 logger = logging.getLogger("VAPI C GEN")
970 logger.setLevel(log_level)
972 argparser = argparse.ArgumentParser(description="VPP C API generator")
973 argparser.add_argument(
978 help="json api file" "(may be specified multiple times)",
980 argparser.add_argument("--prefix", action="store", default=None, help="path prefix")
981 argparser.add_argument(
982 "--remove-path", action="store_true", help="remove path from filename"
984 args = argparser.parse_args()
986 jsonparser = JsonParser(
989 simple_type_class=CSimpleType,
992 struct_type_class=CStructType,
994 message_class=CMessage,
998 # not using the model of having separate generated header and code files
999 # with generated symbols present in shared library (per discussion with
1000 # Damjan), to avoid symbol version issues in .so
1001 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
1003 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
1005 for e in jsonparser.exceptions: