2 # Copyright (c) 2020 Cisco and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 # Provide two classes FromJSON and TOJSON that converts between JSON and VPP's
22 This module creates C code for core VPP, VPP plugins and client side VAT and
31 from io import StringIO
34 process_imports = False
37 ###############################################################################
39 """Class to generate functions converting from VPP binary API to JSON."""
42 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
55 def __init__(self, module, types, defines, imported_types, stream):
58 self.defines = defines
60 self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
61 self.defines_hash = {d.name: d for d in defines}
64 """Output the top boilerplate."""
65 write = self.stream.write
66 write("#ifndef included_{}_api_tojson_h\n".format(self.module))
67 write("#define included_{}_api_tojson_h\n".format(self.module))
68 write("#include <vppinfra/cJSON.h>\n\n")
69 write("#include <vppinfra/jsonformat.h>\n\n")
70 if self.module == "interface_types":
71 write("#define vl_printfun\n")
72 write("#include <vnet/interface_types.api.h>\n\n")
75 """Output the bottom boilerplate."""
76 write = self.stream.write
79 def get_base_type(self, t):
82 vt = self.types_hash[t]
83 if vt.type == "Using" and "length" not in vt.alias:
84 vt_type = vt.alias["type"]
89 def get_json_func(self, t):
90 """Given the type, returns the function to use to create a
92 vt, vt_type = self.get_base_type(t)
94 if t in self.is_number or vt_type in self.is_number:
95 return "cJSON_AddNumberToObject", "", False
97 return "cJSON_AddBoolToObject", "", False
99 # Lookup type name check if it's enum
100 if vt.type == "Enum" or vt.type == "EnumFlag":
101 return "{t}_tojson".format(t=t), "", True
102 return "{t}_tojson".format(t=t), "&", True
104 def get_json_array_func(self, t):
105 """Given a type returns the function to create a cJSON object
107 if t in self.is_number:
108 return "cJSON_CreateNumber", ""
110 return "cJSON_CreateBool", ""
111 vt, vt_type = self.get_base_type(t)
112 if vt.type == "Enum" or vt.type == "EnumFlag":
113 return "{t}_tojson".format(t=t), ""
114 return "{t}_tojson".format(t=t), "&"
116 def print_string(self, o):
117 """Create cJSON object from vl_api_string_t"""
118 write = self.stream.write
121 ' vl_api_string_cJSON_AddToObject(o, "{n}", &a->{n});\n'.format(
128 ' cJSON_AddStringToObject(o, "{n}", (char *)a->{n});\n'.format(
133 def print_field(self, o):
134 """Called for every field in a typedef or define."""
135 write = self.stream.write
136 if o.fieldname in self.noprint_fields:
139 f, p, newobj = self.get_json_func(o.fieldtype)
143 ' cJSON_AddItemToObject(o, "{n}", {f}({p}a->{n}));\n'.format(
144 f=f, p=p, n=o.fieldname
148 write(' {f}(o, "{n}", {p}a->{n});\n'.format(f=f, p=p, n=o.fieldname))
150 _dispatch["Field"] = print_field
152 def print_array(self, o):
153 """Converts a VPP API array to cJSON array."""
154 write = self.stream.write
159 cJSON *array = cJSON_AddArrayToObject(o, "{n}");
160 for (i = 0; i < {lfield}; i++) {{
161 cJSON_AddItemToArray(array, {f}({p}a->{n}[i]));
166 if o.fieldtype == "string":
170 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
171 if o.fieldtype == "u8":
173 # What is length field doing here?
175 ' u8 *s = format(0, "0x%U", format_hex_bytes, '
176 "&a->{n}, {lfield});\n".format(n=o.fieldname, lfield=lfield)
179 ' cJSON_AddStringToObject(o, "{n}", (char *)s);\n'.format(
183 write(" vec_free(s);\n")
187 f, p = self.get_json_array_func(o.fieldtype)
188 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname, f=f, p=p))
190 _dispatch["Array"] = print_array
192 def print_enum(self, o):
193 """Create cJSON object (string) for VPP API enum"""
194 write = self.stream.write
196 "static inline cJSON *vl_api_{name}_t_tojson "
197 "(vl_api_{name}_t a) {{\n".format(name=o.name)
200 write(" switch(a) {\n")
202 write(" case %s:\n" % b[1])
203 write(' return cJSON_CreateString("{}");\n'.format(b[0]))
204 write(' default: return cJSON_CreateString("Invalid ENUM");\n')
206 write(" return 0;\n")
209 _dispatch["Enum"] = print_enum
211 def print_enum_flag(self, o):
212 """Create cJSON object (string) for VPP API enum"""
213 write = self.stream.write
215 "static inline cJSON *vl_api_{name}_t_tojson "
216 "(vl_api_{name}_t a) {{\n".format(name=o.name)
218 write(" cJSON *array = cJSON_CreateArray();\n")
223 write(" if (a & {})\n".format(b[0]))
225 ' cJSON_AddItemToArray(array, cJSON_CreateString("{}"));\n'.format(
229 write(" return array;\n")
232 _dispatch["EnumFlag"] = print_enum_flag
234 def print_typedef(self, o):
235 """Create cJSON (dictionary) object from VPP API typedef"""
236 write = self.stream.write
238 "static inline cJSON *vl_api_{name}_t_tojson "
239 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
241 write(" cJSON *o = cJSON_CreateObject();\n")
244 self._dispatch[t.type](self, t)
246 write(" return o;\n")
249 def print_define(self, o):
250 """Create cJSON (dictionary) object from VPP API define"""
251 write = self.stream.write
253 "static inline cJSON *vl_api_{name}_t_tojson "
254 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
256 write(" cJSON *o = cJSON_CreateObject();\n")
257 write(' cJSON_AddStringToObject(o, "_msgname", "{}");\n'.format(o.name))
259 ' cJSON_AddStringToObject(o, "_crc", "{crc:08x}");\n'.format(crc=o.crc)
263 self._dispatch[t.type](self, t)
265 write(" return o;\n")
268 def print_using(self, o):
269 """Create cJSON (dictionary) object from VPP API aliased type"""
273 write = self.stream.write
275 "static inline cJSON *vl_api_{name}_t_tojson "
276 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
279 write(' u8 *s = format(0, "%U", format_vl_api_{}_t, a);\n'.format(o.name))
280 write(" cJSON *o = cJSON_CreateString((char *)s);\n")
281 write(" vec_free(s);\n")
282 write(" return o;\n")
285 _dispatch["Typedef"] = print_typedef
286 _dispatch["Define"] = print_define
287 _dispatch["Using"] = print_using
288 _dispatch["Union"] = print_typedef
290 def generate_function(self, t):
291 """Main entry point"""
292 write = self.stream.write
294 write("/* Manual print {} */\n".format(t.name))
296 self._dispatch[t.type](self, t)
298 def generate_types(self):
299 """Main entry point"""
301 self.generate_function(t)
303 def generate_defines(self):
304 """Main entry point"""
305 for t in self.defines:
306 self.generate_function(t)
311 Parse JSON objects into VPP API binary message structures.
315 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
328 def __init__(self, module, types, defines, imported_types, stream):
331 self.defines = defines
333 self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
334 self.defines_hash = {d.name: d for d in defines}
337 """Output the top boilerplate."""
338 write = self.stream.write
339 write("#ifndef included_{}_api_fromjson_h\n".format(self.module))
340 write("#define included_{}_api_fromjson_h\n".format(self.module))
341 write("#include <vppinfra/cJSON.h>\n\n")
342 write("#include <vppinfra/jsonformat.h>\n\n")
343 write('#pragma GCC diagnostic ignored "-Wunused-label"\n')
345 def is_base_type(self, t):
346 """Check if a type is one of the VPP API base types"""
347 if t in self.is_number:
354 """Output the bottom boilerplate."""
355 write = self.stream.write
358 def print_string(self, o, toplevel=False):
359 """Convert JSON string to vl_api_string_t"""
360 write = self.stream.write
362 msgvar = "a" if toplevel else "*mp"
363 msgsize = "l" if toplevel else "*len"
366 write(" char *p = cJSON_GetStringValue(item);\n")
367 write(" size_t plen = strlen(p);\n")
369 " {msgvar} = cJSON_realloc({msgvar}, {msgsize} + plen, {msgsize});\n".format(
370 msgvar=msgvar, msgsize=msgsize
373 write(" if ({msgvar} == 0) goto error;\n".format(msgvar=msgvar))
375 " vl_api_c_string_to_api_string(p, (void *){msgvar} + "
376 "{msgsize} - sizeof(vl_api_string_t));\n".format(
377 msgvar=msgvar, msgsize=msgsize
380 write(" {msgsize} += plen;\n".format(msgsize=msgsize))
383 " strncpy_s((char *)a->{n}, sizeof(a->{n}), "
384 "cJSON_GetStringValue(item), sizeof(a->{n}) - 1);\n".format(
389 def print_field(self, o, toplevel=False):
390 """Called for every field in a typedef or define."""
391 write = self.stream.write
392 if o.fieldname in self.noprint_fields:
394 is_bt = self.is_base_type(o.fieldtype)
395 t = "vl_api_{}".format(o.fieldtype) if is_bt else o.fieldtype
397 msgvar = "(void **)&a" if toplevel else "mp"
398 msgsize = "&l" if toplevel else "len"
402 " vl_api_{t}_fromjson(item, &a->{n});\n".format(
403 t=o.fieldtype, n=o.fieldname
408 " if ({t}_fromjson({msgvar}, "
409 "{msgsize}, item, &a->{n}) < 0) goto error;\n".format(
410 t=t, n=o.fieldname, msgvar=msgvar, msgsize=msgsize
414 _dispatch["Field"] = print_field
416 def print_array(self, o, toplevel=False):
417 """Convert JSON array to VPP API array"""
418 write = self.stream.write
423 cJSON *array = cJSON_GetObjectItem(o, "{n}");
424 int size = cJSON_GetArraySize(array);
425 if (size != {lfield}) goto error;
426 for (i = 0; i < size; i++) {{
427 cJSON *e = cJSON_GetArrayItem(array, i);
435 cJSON *array = cJSON_GetObjectItem(o, "{n}");
436 int size = cJSON_GetArraySize(array);
438 {realloc} = cJSON_realloc({realloc}, {msgsize} + sizeof({t}) * size, {msgsize});
439 {t} *d = (void *){realloc} + {msgsize};
440 {msgsize} += sizeof({t}) * size;
441 for (i = 0; i < size; i++) {{
442 cJSON *e = cJSON_GetArrayItem(array, i);
448 if o.fieldtype == "string":
449 self.print_string(o, toplevel)
452 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
453 msgvar = "(void **)&a" if toplevel else "mp"
454 realloc = "a" if toplevel else "*mp"
455 msgsize = "l" if toplevel else "*len"
457 if o.fieldtype == "u8":
459 write(' s = u8string_fromjson(o, "{}");\n'.format(o.fieldname))
460 write(" if (!s) goto error;\n")
461 write(" {} = vec_len(s);\n".format(lfield))
464 " {realloc} = cJSON_realloc({realloc}, {msgsize} + "
465 "vec_len(s), {msgsize});\n".format(
466 msgvar=msgvar, msgsize=msgsize, realloc=realloc
470 " memcpy((void *){realloc} + {msgsize}, s, "
471 "vec_len(s));\n".format(realloc=realloc, msgsize=msgsize)
473 write(" {msgsize} += vec_len(s);\n".format(msgsize=msgsize))
475 write(" vec_free(s);\n")
478 ' if (u8string_fromjson2(o, "{n}", a->{n}) < 0) goto error;\n'.format(
484 is_bt = self.is_base_type(o.fieldtype)
488 call = "vl_api_{t}_fromjson(e, &d[i]);".format(t=o.fieldtype)
490 call = "if ({t}_fromjson({msgvar}, len, e, &d[i]) < 0) goto error; ".format(
491 t=o.fieldtype, msgvar=msgvar
505 call = "vl_api_{t}_fromjson(e, &a->{n}[i]);".format(t=t, n=o.fieldname)
507 call = "if ({}_fromjson({}, len, e, &a->{}[i]) < 0) goto error;".format(
508 t, msgvar, o.fieldname
522 _dispatch["Array"] = print_array
524 def print_enum(self, o):
525 """Convert to JSON enum(string) to VPP API enum (int)"""
526 write = self.stream.write
528 "static inline int vl_api_{n}_t_fromjson"
529 "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
531 write(" char *p = cJSON_GetStringValue(o);\n")
534 ' if (strcmp(p, "{}") == 0) {{*a = {}; return 0;}}\n'.format(
539 write(" return -1;\n")
542 _dispatch["Enum"] = print_enum
544 def print_enum_flag(self, o):
545 """Convert to JSON enum(string) to VPP API enum (int)"""
546 write = self.stream.write
548 "static inline int vl_api_{n}_t_fromjson "
549 "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
553 write(" for (i = 0; i < cJSON_GetArraySize(o); i++) {\n")
554 write(" cJSON *e = cJSON_GetArrayItem(o, i);\n")
555 write(" char *p = cJSON_GetStringValue(e);\n")
556 write(" if (!p) return -1;\n")
558 write(' if (strcmp(p, "{}") == 0) *a |= {};\n'.format(b[0], b[1]))
560 write(" return 0;\n")
563 _dispatch["EnumFlag"] = print_enum_flag
565 def print_typedef(self, o):
566 """Convert from JSON object to VPP API binary representation"""
567 write = self.stream.write
570 "static inline int vl_api_{name}_t_fromjson (void **mp, "
571 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
573 write(" cJSON *item __attribute__ ((unused));\n")
574 write(" u8 *s __attribute__ ((unused));\n")
576 if t.type == "Field" and t.is_lengthfield:
578 write('\n item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
579 write(" if (!item) goto error;\n")
580 self._dispatch[t.type](self, t)
582 write("\n return 0;\n")
584 write(" return -1;\n")
587 def print_union(self, o):
588 """Convert JSON object to VPP API binary union"""
589 write = self.stream.write
592 "static inline int vl_api_{name}_t_fromjson (void **mp, "
593 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
595 write(" cJSON *item __attribute__ ((unused));\n")
596 write(" u8 *s __attribute__ ((unused));\n")
598 if t.type == "Field" and t.is_lengthfield:
600 write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
601 write(" if (item) {\n")
602 self._dispatch[t.type](self, t)
604 write("\n return 0;\n")
606 write(" return -1;\n")
609 def print_define(self, o):
610 """Convert JSON object to VPP API message"""
611 write = self.stream.write
614 "static inline vl_api_{name}_t *vl_api_{name}_t_fromjson "
615 "(cJSON *o, int *len) {{\n".format(name=o.name)
617 write(" cJSON *item __attribute__ ((unused));\n")
618 write(" u8 *s __attribute__ ((unused));\n")
619 write(" int l = sizeof(vl_api_{}_t);\n".format(o.name))
620 write(" vl_api_{}_t *a = cJSON_malloc(l);\n".format(o.name))
624 if t.fieldname in self.noprint_fields:
626 if t.type == "Field" and t.is_lengthfield:
628 write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
629 write(" if (!item) goto error;\n")
631 self._dispatch[t.type](self, t, toplevel=True)
634 write(" *len = l;\n")
635 write(" return a;\n")
639 write(" cJSON_free(a);\n")
640 write(" return 0;\n")
643 def print_using(self, o):
644 """Convert JSON field to VPP type alias"""
645 write = self.stream.write
652 "static inline int vl_api_{name}_t_fromjson (void **mp, "
653 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
655 if "length" in o.alias:
656 if t.fieldtype != "u8":
658 "Error in processing type {} for {}".format(t.fieldtype, o.name)
661 " vl_api_u8_string_fromjson(o, (u8 *)a, {});\n".format(
666 write(" vl_api_{t}_fromjson(o, ({t} *)a);\n".format(t=t.fieldtype))
668 write(" return 0;\n")
671 _dispatch["Typedef"] = print_typedef
672 _dispatch["Define"] = print_define
673 _dispatch["Using"] = print_using
674 _dispatch["Union"] = print_union
676 def generate_function(self, t):
677 """Main entry point"""
678 write = self.stream.write
680 write("/* Manual print {} */\n".format(t.name))
682 self._dispatch[t.type](self, t)
684 def generate_types(self):
685 """Main entry point"""
687 self.generate_function(t)
689 def generate_defines(self):
690 """Main entry point"""
691 for t in self.defines:
692 self.generate_function(t)
695 def generate_tojson(s, modulename, stream):
696 """Generate all functions to convert from API to JSON"""
699 write("/* Imported API files */\n")
700 for i in s["Import"]:
701 f = i.filename.replace("plugins/", "")
702 write("#include <{}_tojson.h>\n".format(f))
704 pp = ToJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
707 pp.generate_defines()
712 def generate_fromjson(s, modulename, stream):
713 """Generate all functions to convert from JSON to API"""
715 write("/* Imported API files */\n")
716 for i in s["Import"]:
717 f = i.filename.replace("plugins/", "")
718 write("#include <{}_fromjson.h>\n".format(f))
720 pp = FromJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
723 pp.generate_defines()
729 ###############################################################################
732 DATESTRING = datetime.datetime.utcfromtimestamp(
733 int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
735 TOP_BOILERPLATE = """\
737 * VLIB API definitions {datestring}
738 * Input file: {input_filename}
739 * Automatically generated: please edit the input file NOT this file!
743 #if defined(vl_msg_id)||defined(vl_union_id) \\
744 || defined(vl_printfun) ||defined(vl_endianfun) \\
745 || defined(vl_api_version)||defined(vl_typedefs) \\
746 || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
747 || defined(vl_api_version_tuple) || defined(vl_calcsizefun)
748 /* ok, something was selected */
750 #warning no content included from {input_filename}
753 #define VL_API_PACKED(x) x __attribute__ ((packed))
756 BOTTOM_BOILERPLATE = """\
757 /****** API CRC (whole file) *****/
759 #ifdef vl_api_version
760 vl_api_version({input_filename}, {file_crc:#08x})
767 """Generate macro to map API message id to handler"""
770 /****** Message ID / handler enum ******/
775 for t in s["Define"]:
776 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % (
786 """Generate calls to name mapping macro"""
789 /****** Message names ******/
794 for t in s["Define"]:
795 dont_trace = 0 if t.dont_trace else 1
796 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
802 def msg_name_crc_list(s, suffix):
803 """Generate list of names to CRC mappings"""
806 /****** Message name, crc list ******/
808 #ifdef vl_msg_name_crc_list
810 output += "#define foreach_vl_msg_name_crc_%s " % suffix
812 for t in s["Define"]:
813 output += "\\\n_(VL_API_%s, %s, %08x) " % (t.name.upper(), t.name, t.crc)
819 def api2c(fieldtype):
820 """Map between API type names and internal VPP type names"""
822 "string": "vl_api_string_t",
824 if fieldtype in mappingtable:
825 return mappingtable[fieldtype]
829 def typedefs(filename):
830 """Include in the main files to the types file"""
833 /****** Typedefs ******/
836 #include "{include}.api_types.h"
859 """Functions for pretty printing VPP API messages"""
862 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
864 def __init__(self, stream):
868 def print_string(o, stream):
869 """Pretty print a vl_api_string_t"""
872 write(" if (vl_api_string_len(&a->{f}) > 0) {{\n".format(f=o.fieldname))
874 ' s = format(s, "\\n%U{f}: %U", '
875 "format_white_space, indent, "
876 "vl_api_format_string, (&a->{f}));\n".format(f=o.fieldname)
880 ' s = format(s, "\\n%U{f}:", '
881 "format_white_space, indent);\n".format(f=o.fieldname)
886 ' s = format(s, "\\n%U{f}: %s", '
887 "format_white_space, indent, a->{f});\n".format(f=o.fieldname)
890 def print_field(self, o, stream):
891 """Pretty print API field"""
893 if o.fieldname in self.noprint_fields:
895 if o.fieldtype in FORMAT_STRINGS:
896 f = FORMAT_STRINGS[o.fieldtype]
898 ' s = format(s, "\\n%U{n}: {f}", '
899 "format_white_space, indent, a->{n});\n".format(n=o.fieldname, f=f)
903 ' s = format(s, "\\n%U{n}: %U", '
904 "format_white_space, indent, "
905 "format_{t}, &a->{n}, indent);\n".format(n=o.fieldname, t=o.fieldtype)
908 _dispatch["Field"] = print_field
910 def print_array(self, o, stream):
911 """Pretty print API array"""
915 for (i = 0; i < {lfield}; i++) {{
916 s = format(s, "\\n%U{n}: %U",
917 format_white_space, indent, format_{t}, &a->{n}[i], indent);
921 forloop_format = """\
922 for (i = 0; i < {lfield}; i++) {{
923 s = format(s, "\\n%U{n}: {t}",
924 format_white_space, indent, a->{n}[i]);
928 if o.fieldtype == "string":
929 self.print_string(o, stream)
932 if o.fieldtype == "u8":
935 ' s = format(s, "\\n%U{n}: %U", format_white_space, '
936 "indent, format_hex_bytes, a->{n}, a->{lfield});\n".format(
937 n=o.fieldname, lfield=o.lengthfield
942 ' s = format(s, "\\n%U{n}: %U", format_white_space, '
943 "indent, format_hex_bytes, a, {lfield});\n".format(
944 n=o.fieldname, lfield=o.length
949 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
950 if o.fieldtype in FORMAT_STRINGS:
952 forloop_format.format(
953 lfield=lfield, t=FORMAT_STRINGS[o.fieldtype], n=o.fieldname
957 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
959 _dispatch["Array"] = print_array
962 def print_alias(k, v, stream):
963 """Pretty print type alias"""
965 if "length" in v.alias and v.alias["length"] and v.alias["type"] == "u8":
967 ' return format(s, "%U", format_hex_bytes, a, {});\n'.format(
971 elif v.alias["type"] in FORMAT_STRINGS:
973 ' return format(s, "{}", *a);\n'.format(
974 FORMAT_STRINGS[v.alias["type"]]
978 write(' return format(s, "{} (print not implemented)");\n'.format(k))
981 def print_enum(o, stream):
982 """Pretty print API enum"""
984 write(" switch(*a) {\n")
986 write(" case %s:\n" % b[1])
987 write(' return format(s, "{}");\n'.format(b[0]))
990 _dispatch["Enum"] = print_enum
991 _dispatch["EnumFlag"] = print_enum
993 def print_obj(self, o, stream):
997 if o.type in self._dispatch:
998 self._dispatch[o.type](self, o, stream)
1001 ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
1002 o.type, o.fieldtype, o.fieldname
1007 def printfun(objs, stream, modulename):
1008 """Main entry point for pretty print function generation"""
1009 write = stream.write
1012 /****** Print functions *****/
1014 #ifndef included_{module}_printfun
1015 #define included_{module}_printfun
1018 #define _uword_fmt \"%lld\"
1019 #define _uword_cast (long long)
1021 #define _uword_fmt \"%ld\"
1022 #define _uword_cast long
1025 #include "{module}.api_tojson.h"
1026 #include "{module}.api_fromjson.h"
1031 static inline u8 *vl_api_{name}_t_format (u8 *s, va_list *args)
1033 __attribute__((unused)) vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
1034 u32 indent __attribute__((unused)) = 2;
1035 int i __attribute__((unused));
1038 h = h.format(module=modulename)
1041 pp = Printfun(stream)
1044 write("/***** manual: vl_api_%s_t_format *****/\n\n" % t.name)
1046 write(signature.format(name=t.name, suffix=""))
1047 write(" /* Message definition: vl_api_{}_t: */\n".format(t.name))
1048 write(' s = format(s, "vl_api_%s_t:");\n' % t.name)
1050 pp.print_obj(o, stream)
1051 write(" return s;\n")
1055 write("\n#endif /* vl_printfun */\n")
1060 def printfun_types(objs, stream, modulename):
1061 """Pretty print API types"""
1062 write = stream.write
1063 pp = Printfun(stream)
1066 /****** Print functions *****/
1068 #ifndef included_{module}_printfun_types
1069 #define included_{module}_printfun_types
1072 h = h.format(module=modulename)
1076 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
1078 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
1079 u32 indent __attribute__((unused)) = va_arg (*args, u32);
1080 int i __attribute__((unused));
1085 if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
1086 write(signature.format(name=t.name))
1087 pp.print_enum(t.block, stream)
1088 write(" return s;\n")
1093 write("/***** manual: vl_api_%s_t_format *****/\n\n" % t.name)
1096 if t.__class__.__name__ == "Using":
1097 write(signature.format(name=t.name))
1098 pp.print_alias(t.name, t, stream)
1102 write(signature.format(name=t.name))
1104 pp.print_obj(o, stream)
1106 write(" return s;\n")
1110 write("\n#endif /* vl_printfun_types */\n")
1113 def generate_imports(imports):
1114 """Add #include matching the API import statements"""
1115 output = "/* Imported API files */\n"
1116 output += "#ifndef vl_api_version\n"
1119 s = i.filename.replace("plugins/", "")
1120 output += "#include <{}.h>\n".format(s)
1121 output += "#endif\n"
1126 "u16": "clib_net_to_host_u16",
1127 "u32": "clib_net_to_host_u32",
1128 "u64": "clib_net_to_host_u64",
1129 "i16": "clib_net_to_host_i16",
1130 "i32": "clib_net_to_host_i32",
1131 "i64": "clib_net_to_host_i64",
1132 "f64": "clib_net_to_host_f64",
1136 def endianfun_array(o):
1137 """Generate endian functions for arrays"""
1139 for (i = 0; i < {length}; i++) {{
1140 a->{name}[i] = {format}(a->{name}[i]);
1144 forloop_format = """\
1145 for (i = 0; i < {length}; i++) {{
1146 {type}_endian(&a->{name}[i]);
1151 if o.fieldtype == "u8" or o.fieldtype == "string" or o.fieldtype == "bool":
1152 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
1154 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
1155 if o.fieldtype in ENDIAN_STRINGS:
1156 output += forloop.format(
1157 length=lfield, format=ENDIAN_STRINGS[o.fieldtype], name=o.fieldname
1160 output += forloop_format.format(
1161 length=lfield, type=o.fieldtype, name=o.fieldname
1166 NO_ENDIAN_CONVERSION = {"client_index": None}
1169 def endianfun_obj(o):
1170 """Generate endian conversion function for type"""
1172 if o.type == "Array":
1173 return endianfun_array(o)
1174 if o.type != "Field":
1175 output += ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
1176 o.type, o.fieldtype, o.fieldname
1179 if o.fieldname in NO_ENDIAN_CONVERSION:
1180 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
1182 if o.fieldtype in ENDIAN_STRINGS:
1183 output += " a->{name} = {format}(a->{name});\n".format(
1184 name=o.fieldname, format=ENDIAN_STRINGS[o.fieldtype]
1186 elif o.fieldtype.startswith("vl_api_"):
1187 output += " {type}_endian(&a->{name});\n".format(
1188 type=o.fieldtype, name=o.fieldname
1191 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
1196 def endianfun(objs, modulename):
1197 """Main entry point for endian function generation"""
1200 /****** Endian swap functions *****/\n\
1202 #ifndef included_{module}_endianfun
1203 #define included_{module}_endianfun
1205 #undef clib_net_to_host_uword
1207 #define clib_net_to_host_uword clib_net_to_host_u64
1209 #define clib_net_to_host_uword clib_net_to_host_u32
1213 output = output.format(module=modulename)
1216 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
1218 int i __attribute__((unused));
1222 if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
1223 output += signature.format(name=t.name)
1224 if t.enumtype in ENDIAN_STRINGS:
1225 output += " *a = {}(*a);\n".format(ENDIAN_STRINGS[t.enumtype])
1227 output += " /* a->{name} = a->{name} (no-op) */\n".format(
1235 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
1238 if t.__class__.__name__ == "Using":
1239 output += signature.format(name=t.name)
1240 if "length" in t.alias and t.alias["length"] and t.alias["type"] == "u8":
1241 output += " /* a->{name} = a->{name} (no-op) */\n".format(
1244 elif t.alias["type"] in FORMAT_STRINGS:
1245 output += " *a = {}(*a);\n".format(ENDIAN_STRINGS[t.alias["type"]])
1247 output += " /* Not Implemented yet {} */".format(t.name)
1251 output += signature.format(name=t.name)
1253 # make Array type appear before the others:
1254 # some arrays have dynamic length, and we want to iterate over
1255 # them before changing endiann for the length field
1256 t.block.sort(key=lambda x: x.type)
1259 output += endianfun_obj(o)
1262 output += "\n#endif"
1263 output += "\n#endif /* vl_endianfun */\n\n"
1268 def calc_size_fun(objs, modulename):
1269 """Main entry point for calculate size function generation"""
1272 /****** Calculate size functions *****/\n\
1273 #ifdef vl_calcsizefun
1274 #ifndef included_{module}_calcsizefun
1275 #define included_{module}_calcsizefun
1278 output = output.format(module=modulename)
1281 /* calculate message size of message in network byte order */
1282 static inline uword vl_api_{name}_t_calc_size (vl_api_{name}_t *a)
1287 tname = o.__class__.__name__
1289 output += signature.format(name=o.name)
1290 output += f" return sizeof(*a)"
1291 if tname == "Using":
1292 if "length" in o.alias:
1294 tmp = int(o.alias["length"])
1296 raise (f"Unexpected length '0' for alias {o}")
1298 # output += f" + vl_api_{o.alias.name}_t_calc_size({o.name})"
1304 elif tname == "Enum" or tname == "EnumFlag":
1308 if b.type == "Option":
1310 elif b.type == "Field":
1311 if b.fieldtype.startswith("vl_api_"):
1312 output += f" - sizeof(a->{b.fieldname})"
1313 output += f" + {b.fieldtype}_calc_size(&a->{b.fieldname})"
1314 elif b.type == "Array":
1317 filter(lambda x: x.fieldname == b.lengthfield, o.block)
1321 f"Expected 1 match for field '{b.lengthfield}', got '{m}'"
1324 if lf.fieldtype in ENDIAN_STRINGS:
1325 output += f" + {ENDIAN_STRINGS[lf.fieldtype]}(a->{b.lengthfield}) * sizeof(a->{b.fieldname}[0])"
1326 elif lf.fieldtype == "u8":
1328 f" + a->{b.lengthfield} * sizeof(a->{b.fieldname}[0])"
1332 f"Don't know how to endian swap {lf.fieldtype}"
1335 # Fixed length strings decay to nul terminated u8
1336 if b.fieldtype == "string":
1338 output += f" + vl_api_string_len(&a->{b.fieldname})"
1342 output += "\n#endif"
1343 output += "\n#endif /* vl_calcsizefun */\n\n"
1348 def version_tuple(s, module):
1349 """Generate semantic version string"""
1351 /****** Version tuple *****/
1353 #ifdef vl_api_version_tuple
1356 if "version" in s["Option"]:
1357 v = s["Option"]["version"]
1358 (major, minor, patch) = v.split(".")
1359 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % (
1366 output += "\n#endif /* vl_api_version_tuple */\n\n"
1371 def generate_include_enum(s, module, stream):
1372 """Generate <name>.api_enum.h"""
1373 write = stream.write
1376 write("typedef enum {\n")
1377 for t in s["Define"]:
1378 write(" VL_API_{},\n".format(t.name.upper()))
1379 write(" VL_MSG_{}_LAST\n".format(module.upper()))
1380 write("}} vl_api_{}_enum_t;\n".format(module))
1383 def generate_include_counters(s, stream):
1384 """Include file for the counter data model types."""
1385 write = stream.write
1388 csetname = counters.name
1389 write("typedef enum {\n")
1390 for c in counters.block:
1391 write(" {}_ERROR_{},\n".format(csetname.upper(), c["name"].upper()))
1392 write(" {}_N_ERROR\n".format(csetname.upper()))
1393 write("}} vl_counter_{}_enum_t;\n".format(csetname))
1395 write("extern vlib_error_desc_t {}_error_counters[];\n".format(csetname))
1398 def generate_include_types(s, module, stream):
1399 """Generate separate API _types file."""
1400 write = stream.write
1402 write("#ifndef included_{module}_api_types_h\n".format(module=module))
1403 write("#define included_{module}_api_types_h\n".format(module=module))
1405 if "version" in s["Option"]:
1406 v = s["Option"]["version"]
1407 (major, minor, patch) = v.split(".")
1409 "#define VL_API_{m}_API_VERSION_MAJOR {v}\n".format(
1410 m=module.upper(), v=major
1414 "#define VL_API_{m}_API_VERSION_MINOR {v}\n".format(
1415 m=module.upper(), v=minor
1419 "#define VL_API_{m}_API_VERSION_PATCH {v}\n".format(
1420 m=module.upper(), v=patch
1425 write("/* Imported API files */\n")
1426 for i in s["Import"]:
1427 filename = i.filename.replace("plugins/", "")
1428 write("#include <{}_types.h>\n".format(filename))
1430 for o in itertools.chain(s["types"], s["Define"]):
1431 tname = o.__class__.__name__
1432 if tname == "Using":
1433 if "length" in o.alias:
1435 "typedef %s vl_api_%s_t[%s];\n"
1436 % (o.alias["type"], o.name, o.alias["length"])
1439 write("typedef %s vl_api_%s_t;\n" % (o.alias["type"], o.name))
1440 elif tname == "Enum" or tname == "EnumFlag":
1441 if o.enumtype == "u32":
1442 write("typedef enum {\n")
1444 write("typedef enum __attribute__((packed)) {\n")
1447 write(" %s = %s,\n" % (b[0], b[1]))
1448 write("} vl_api_%s_t;\n" % o.name)
1449 if o.enumtype != "u32":
1450 size1 = "sizeof(vl_api_%s_t)" % o.name
1451 size2 = "sizeof(%s)" % o.enumtype
1452 err_str = "size of API enum %s is wrong" % o.name
1453 write('STATIC_ASSERT(%s == %s, "%s");\n' % (size1, size2, err_str))
1455 if tname == "Union":
1456 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
1459 ("typedef struct __attribute__ ((packed)) _vl_api_%s {\n") % o.name
1462 if b.type == "Option":
1464 if b.type == "Field":
1465 write(" %s %s;\n" % (api2c(b.fieldtype), b.fieldname))
1466 elif b.type == "Array":
1468 write(" %s %s[0];\n" % (api2c(b.fieldtype), b.fieldname))
1470 # Fixed length strings decay to nul terminated u8
1471 if b.fieldtype == "string":
1475 api2c(b.fieldtype), b.fieldname
1479 write(" u8 {}[{}];\n".format(b.fieldname, b.length))
1483 % (api2c(b.fieldtype), b.fieldname, b.length)
1487 "Error in processing type {} for {}".format(b, o.name)
1490 write("} vl_api_%s_t;\n" % o.name)
1492 f"#define VL_API_{o.name.upper()}_IS_CONSTANT_SIZE ({0 if o.vla else 1})\n\n"
1495 for t in s["Define"]:
1497 '#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'.format(
1498 n=t.name, ID=t.name.upper(), crc=t.crc
1505 def generate_c_boilerplate(services, defines, counters, file_crc, module, stream):
1506 """VPP side plugin."""
1507 write = stream.write
1508 define_hash = {d.name: d for d in defines}
1511 #define vl_endianfun /* define message structures */
1512 #include "{module}.api.h"
1515 #define vl_calcsizefun
1516 #include "{module}.api.h"
1517 #undef vl_calsizefun
1519 /* instantiate all the print functions we know about */
1521 #include "{module}.api.h"
1526 write(hdr.format(module=module))
1527 if len(defines) > 0:
1528 write("static u16\n")
1529 write("setup_message_id_table (void) {\n")
1530 write(" api_main_t *am = my_api_main;\n")
1531 write(" vl_msg_api_msg_config_t c;\n")
1533 ' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", '
1534 "VL_MSG_{m}_LAST);\n".format(module, crc=file_crc, m=module.upper())
1539 ' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
1540 " VL_API_{ID} + msg_id_base);\n".format(
1541 n=d.name, ID=d.name.upper(), crc=d.crc
1545 d = define_hash[s.caller]
1547 " c = (vl_msg_api_msg_config_t) "
1548 " {{.id = VL_API_{ID} + msg_id_base,\n"
1550 " .handler = vl_api_{n}_t_handler,\n"
1551 " .endian = vl_api_{n}_t_endian,\n"
1552 " .format_fn = vl_api_{n}_t_format,\n"
1555 " .tojson = vl_api_{n}_t_tojson,\n"
1556 " .fromjson = vl_api_{n}_t_fromjson,\n"
1557 " .calc_size = vl_api_{n}_t_calc_size,\n"
1558 " .is_autoendian = {auto}}};\n".format(
1559 n=s.caller, ID=s.caller.upper(), auto=d.autoendian
1562 write(" vl_msg_api_config (&c);\n")
1564 d = define_hash[s.reply]
1566 " c = (vl_msg_api_msg_config_t) "
1567 "{{.id = VL_API_{ID} + msg_id_base,\n"
1570 " .endian = vl_api_{n}_t_endian,\n"
1571 " .format_fn = vl_api_{n}_t_format,\n"
1574 " .tojson = vl_api_{n}_t_tojson,\n"
1575 " .fromjson = vl_api_{n}_t_fromjson,\n"
1576 " .calc_size = vl_api_{n}_t_calc_size,\n"
1577 " .is_autoendian = {auto}}};\n".format(
1578 n=s.reply, ID=s.reply.upper(), auto=d.autoendian
1581 write(" vl_msg_api_config (&c);\n")
1587 d = define_hash[s.stream_message]
1589 " c = (vl_msg_api_msg_config_t) "
1590 "{{.id = VL_API_{ID} + msg_id_base,\n"
1593 " .endian = vl_api_{n}_t_endian,\n"
1594 " .format_fn = vl_api_{n}_t_format,\n"
1597 " .tojson = vl_api_{n}_t_tojson,\n"
1598 " .fromjson = vl_api_{n}_t_fromjson,\n"
1599 " .calc_size = vl_api_{n}_t_calc_size,\n"
1600 " .is_autoendian = {auto}}};\n".format(
1602 ID=s.stream_message.upper(),
1606 write(" vl_msg_api_config (&c);\n")
1609 if len(defines) > 0:
1610 write(" return msg_id_base;\n")
1614 "error": "VL_COUNTER_SEVERITY_ERROR",
1615 "info": "VL_COUNTER_SEVERITY_INFO",
1616 "warn": "VL_COUNTER_SEVERITY_WARN",
1619 for cnt in counters:
1621 write("vlib_error_desc_t {}_error_counters[] = {{\n".format(csetname))
1624 write(' .name = "{}",\n'.format(c["name"]))
1625 write(' .desc = "{}",\n'.format(c["description"]))
1626 write(" .severity = {},\n".format(severity[c["severity"]]))
1631 def generate_c_test_boilerplate(services, defines, file_crc, module, plugin, stream):
1632 """Generate code for legacy style VAT. To be deleted."""
1633 write = stream.write
1635 define_hash = {d.name: d for d in defines}
1638 #define vl_endianfun /* define message structures */
1639 #include "{module}.api.h"
1642 #define vl_calcsizefun
1643 #include "{module}.api.h"
1644 #undef vl_calsizefun
1646 /* instantiate all the print functions we know about */
1648 #include "{module}.api.h"
1653 write(hdr.format(module=module))
1656 d = define_hash[s.reply]
1662 " * Manual definition requested for: \n"
1663 " * vl_api_{n}_t_handler()\n"
1664 " */\n".format(n=s.reply)
1667 if not define_hash[s.caller].autoreply:
1669 "/* Generation not supported (vl_api_{n}_t_handler()) */\n".format(
1674 write("#ifndef VL_API_{n}_T_HANDLER\n".format(n=s.reply.upper()))
1675 write("static void\n")
1676 write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=s.reply))
1677 write(" vat_main_t * vam = {}_test_main.vat_main;\n".format(module))
1678 write(" i32 retval = ntohl(mp->retval);\n")
1679 write(" if (vam->async_mode) {\n")
1680 write(" vam->async_errors += (retval < 0);\n")
1681 write(" } else {\n")
1682 write(" vam->retval = retval;\n")
1683 write(" vam->result_ready = 1;\n")
1689 if define_hash[e].manual_print:
1691 write("static void\n")
1692 write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=e))
1693 write(' vlib_cli_output(0, "{n} event called:");\n'.format(n=e))
1695 ' vlib_cli_output(0, "%U", vl_api_{n}_t_format, mp);\n'.format(n=e)
1699 write("static void\n")
1700 write("setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n")
1703 " vl_msg_api_config (&(vl_msg_api_msg_config_t){{\n"
1704 " .id = VL_API_{ID} + msg_id_base,\n"
1706 " .handler = vl_api_{n}_t_handler,\n"
1707 " .endian = vl_api_{n}_t_endian,\n"
1708 " .format_fn = vl_api_{n}_t_format,\n"
1709 " .size = sizeof(vl_api_{n}_t),\n"
1711 " .tojson = vl_api_{n}_t_tojson,\n"
1712 " .fromjson = vl_api_{n}_t_fromjson,\n"
1713 " .calc_size = vl_api_{n}_t_calc_size,\n"
1714 " }});".format(n=s.reply, ID=s.reply.upper())
1717 ' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(
1723 ' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'.format(
1724 n=s.caller, help=define_hash[s.caller].options["vat_help"]
1733 " vl_msg_api_config (&(vl_msg_api_msg_config_t){{\n"
1734 " .id = VL_API_{ID} + msg_id_base,\n"
1736 " .handler = vl_api_{n}_t_handler,\n"
1737 " .endian = vl_api_{n}_t_endian,\n"
1738 " .format_fn = vl_api_{n}_t_format,\n"
1739 " .size = sizeof(vl_api_{n}_t),\n"
1741 " .tojson = vl_api_{n}_t_tojson,\n"
1742 " .fromjson = vl_api_{n}_t_fromjson,\n"
1743 " .calc_size = vl_api_{n}_t_calc_size,\n"
1744 " }});".format(n=e, ID=e.upper())
1748 write("clib_error_t * vat_plugin_register (vat_main_t *vam)\n")
1750 write(" {n}_test_main_t * mainp = &{n}_test_main;\n".format(n=module))
1751 write(" mainp->vat_main = vam;\n")
1753 " mainp->msg_id_base = vl_client_get_first_plugin_msg_id "
1754 ' ("{n}_{crc:08x}");\n'.format(n=module, crc=file_crc)
1756 write(" if (mainp->msg_id_base == (u16) ~0)\n")
1758 ' return clib_error_return (0, "{} plugin not loaded...");\n'.format(
1762 write(" setup_message_id_table (vam, mainp->msg_id_base);\n")
1763 write("#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n")
1764 write(" VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n")
1766 write(" return 0;\n")
1771 """Check if a method is generated already."""
1773 def _f(module, d, processed, *args):
1774 if d.name in processed:
1776 processed[d.name] = True
1777 return func(module, d, *args)
1782 def c_test_api_service(s, dump, stream):
1783 """Generate JSON code for a service."""
1784 write = stream.write
1786 req_reply_template = """\
1793 mp = vl_api_{n}_t_fromjson(o, &len);
1795 fprintf(stderr, "Failed converting JSON to API\\n");
1799 mp->_vl_msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1800 vl_api_{n}_t_endian(mp);
1801 vac_write((char *)mp, len);
1807 vac_read(&p, &l, 5); // XXX: Fix timeout
1808 if (p == 0 || l == 0) return 0;
1809 // XXX Will fail in case of event received. Do loop
1810 if (ntohs(*((u16 *)p)) != vac_get_msg_index(VL_API_{R}_CRC)) {{
1811 fprintf(stderr, "Mismatched reply\\n");
1814 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1815 vl_api_{r}_t_endian(rmp);
1816 return vl_api_{r}_t_tojson(rmp);
1820 dump_details_template = """\
1824 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1827 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1829 fprintf(stderr, "Failed converting JSON to API\\n");
1832 mp->_vl_msg_id = msg_id;
1833 vl_api_{n}_t_endian(mp);
1834 vac_write((char *)mp, len);
1837 vat2_control_ping(123); // FIX CONTEXT
1838 cJSON *reply = cJSON_CreateArray();
1840 u16 ping_reply_msg_id = vac_get_msg_index(VL_API_CONTROL_PING_REPLY_CRC);
1841 u16 details_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1847 vac_read(&p, &l, 5); // XXX: Fix timeout
1848 if (p == 0 || l == 0) {{
1853 /* Message can be one of [_details, control_ping_reply
1854 * or unrelated event]
1856 u16 reply_msg_id = ntohs(*((u16 *)p));
1857 if (reply_msg_id == ping_reply_msg_id) {{
1861 if (reply_msg_id == details_msg_id) {{
1862 if (l < sizeof(vl_api_{r}_t)) {{
1866 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1867 vl_api_{r}_t_endian(rmp);
1868 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1875 gets_details_reply_template = """\
1879 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1882 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1884 fprintf(stderr, "Failed converting JSON to API\\n");
1887 mp->_vl_msg_id = msg_id;
1889 vl_api_{n}_t_endian(mp);
1890 vac_write((char *)mp, len);
1893 cJSON *reply = cJSON_CreateArray();
1895 u16 reply_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1896 u16 details_msg_id = vac_get_msg_index(VL_API_{D}_CRC);
1902 vac_read(&p, &l, 5); // XXX: Fix timeout
1904 /* Message can be one of [_details, control_ping_reply
1905 * or unrelated event]
1907 u16 msg_id = ntohs(*((u16 *)p));
1908 if (msg_id == reply_msg_id) {{
1909 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1910 vl_api_{r}_t_endian(rmp);
1911 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1915 if (msg_id == details_msg_id) {{
1916 vl_api_{d}_t *rmp = (vl_api_{d}_t *)p;
1917 vl_api_{d}_t_endian(rmp);
1918 cJSON_AddItemToArray(reply, vl_api_{d}_t_tojson(rmp));
1927 if s.stream_message:
1929 gets_details_reply_template.format(
1935 D=s.stream_message.upper(),
1940 dump_details_template.format(
1941 n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
1946 req_reply_template.format(
1947 n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
1952 def generate_c_test2_boilerplate(services, defines, module, stream):
1953 """Generate code for VAT2 plugin."""
1954 write = stream.write
1956 define_hash = {d.name: d for d in defines}
1960 #include <vlibapi/api.h>
1961 #include <vlibmemory/api.h>
1962 #include <vppinfra/error.h>
1963 #include <vnet/ip/ip_format_fns.h>
1964 #include <vnet/ethernet/ethernet_format_fns.h>
1966 #define vl_typedefs /* define message structures */
1967 #include <vlibmemory/vl_memory_api_h.h>
1968 #include <vlibmemory/vlib.api_types.h>
1969 #include <vlibmemory/vlib.api.h>
1972 #include "{module}.api_enum.h"
1973 #include "{module}.api_types.h"
1975 #define vl_endianfun /* define message structures */
1976 #include "{module}.api.h"
1979 #define vl_calcsizefun
1980 #include "{module}.api.h"
1981 #undef vl_calsizefun
1984 #include "{module}.api.h"
1987 #include "{module}.api_tojson.h"
1988 #include "{module}.api_fromjson.h"
1989 #include <vpp-api/client/vppapiclient.h>
1991 #include <vat2/vat2_helpers.h>
1995 write(hdr.format(module=module))
1998 if s.reply not in define_hash:
2000 c_test_api_service(s, s.stream, stream)
2003 "void vat2_register_function(char *, cJSON * (*)(cJSON *), cJSON * (*)(void *), u32);\n"
2005 # write('__attribute__((constructor))')
2006 write("clib_error_t *\n")
2007 write("vat2_register_plugin (void) {\n")
2009 if s.reply not in define_hash:
2011 crc = define_hash[s.caller].crc
2013 ' vat2_register_function("{n}", api_{n}, (cJSON * (*)(void *))vl_api_{n}_t_tojson, 0x{crc:08x});\n'.format(
2017 write(" return 0;\n")
2022 # Plugin entry point
2024 def run(output_dir, apifilename, s):
2025 """Main plugin entry point."""
2029 sys.stderr.write("Missing --outputdir argument")
2032 basename = os.path.basename(apifilename)
2033 filename, _ = os.path.splitext(basename)
2034 modulename = filename.replace(".", "_")
2035 filename_enum = os.path.join(output_dir + "/" + basename + "_enum.h")
2036 filename_types = os.path.join(output_dir + "/" + basename + "_types.h")
2037 filename_c = os.path.join(output_dir + "/" + basename + ".c")
2038 filename_c_test = os.path.join(output_dir + "/" + basename + "_test.c")
2039 filename_c_test2 = os.path.join(output_dir + "/" + basename + "_test2.c")
2040 filename_c_tojson = os.path.join(output_dir + "/" + basename + "_tojson.h")
2041 filename_c_fromjson = os.path.join(output_dir + "/" + basename + "_fromjson.h")
2043 # Generate separate types file
2045 generate_include_types(s, modulename, st)
2046 with open(filename_types, "w") as fd:
2048 shutil.copyfileobj(st, fd)
2051 # Generate separate enum file
2053 st.write("#ifndef included_{}_api_enum_h\n".format(modulename))
2054 st.write("#define included_{}_api_enum_h\n".format(modulename))
2055 generate_include_enum(s, modulename, st)
2056 generate_include_counters(s["Counters"], st)
2057 st.write("#endif\n")
2058 with open(filename_enum, "w") as fd:
2060 shutil.copyfileobj(st, fd)
2063 # Generate separate C file
2065 generate_c_boilerplate(
2066 s["Service"], s["Define"], s["Counters"], s["file_crc"], modulename, st
2068 with open(filename_c, "w") as fd:
2070 shutil.copyfileobj(st, fd)
2073 # Generate separate C test file
2075 plugin = bool("plugin" in apifilename)
2076 generate_c_test_boilerplate(
2077 s["Service"], s["Define"], s["file_crc"], modulename, plugin, st
2079 with open(filename_c_test, "w") as fd:
2081 shutil.copyfileobj(st, fd)
2084 # Fully autogenerated VATv2 C test file
2086 generate_c_test2_boilerplate(s["Service"], s["Define"], modulename, st)
2087 with open(filename_c_test2, "w") as fd:
2089 shutil.copyfileobj(st, fd)
2092 # Generate separate JSON file
2094 generate_tojson(s, modulename, st)
2095 with open(filename_c_tojson, "w") as fd:
2097 shutil.copyfileobj(st, fd)
2100 generate_fromjson(s, modulename, st)
2101 with open(filename_c_fromjson, "w") as fd:
2103 shutil.copyfileobj(st, fd)
2106 output = TOP_BOILERPLATE.format(datestring=DATESTRING, input_filename=basename)
2107 output += generate_imports(s["Import"])
2108 output += msg_ids(s)
2109 output += msg_names(s)
2110 output += msg_name_crc_list(s, filename)
2111 output += typedefs(modulename)
2112 printfun_types(s["types"], stream, modulename)
2113 printfun(s["Define"], stream, modulename)
2114 output += stream.getvalue()
2116 output += endianfun(s["types"] + s["Define"], modulename)
2117 output += calc_size_fun(s["types"] + s["Define"], modulename)
2118 output += version_tuple(s, basename)
2119 output += BOTTOM_BOILERPLATE.format(input_filename=basename, file_crc=s["file_crc"])