6 from io import StringIO
9 datestring = datetime.datetime.utcfromtimestamp(
10 int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
11 input_filename = 'inputfil'
12 top_boilerplate = '''\
14 * VLIB API definitions {datestring}
15 * Input file: {input_filename}
16 * Automatically generated: please edit the input file NOT this file!
20 #if defined(vl_msg_id)||defined(vl_union_id) \\
21 || defined(vl_printfun) ||defined(vl_endianfun) \\
22 || defined(vl_api_version)||defined(vl_typedefs) \\
23 || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
24 || defined(vl_api_version_tuple)
25 /* ok, something was selected */
27 #warning no content included from {input_filename}
30 #define VL_API_PACKED(x) x __attribute__ ((packed))
33 bottom_boilerplate = '''\
34 /****** API CRC (whole file) *****/
37 vl_api_version({input_filename}, {file_crc:#08x})
46 /****** Message ID / handler enum ******/
52 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
53 (t.name.upper(), t.name)
62 /****** Message names ******/
68 dont_trace = 0 if t.dont_trace else 1
69 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
75 def msg_name_crc_list(s, suffix):
78 /****** Message name, crc list ******/
80 #ifdef vl_msg_name_crc_list
82 output += "#define foreach_vl_msg_name_crc_%s " % suffix
85 output += "\\\n_(VL_API_%s, %s, %08x) " % \
86 (t.name.upper(), t.name, t.crc)
93 mappingtable = {'string': 'vl_api_string_t', }
94 if fieldtype in mappingtable:
95 return mappingtable[fieldtype]
99 def typedefs(filename):
103 /****** Typedefs ******/
106 #include "{include}.api_types.h"
108 '''.format(include=filename)
112 format_strings = {'u8': '%u',
123 noprint_fields = {'_vl_msg_id': None,
124 'client_index': None,
131 def __init__(self, stream):
134 def print_string(self, o, stream):
137 write(' if (vl_api_string_len(&a->{f}) > 0) {{\n'
138 .format(f=o.fieldname))
139 write(' s = format(s, "\\n%U{f}: %U", '
140 'format_white_space, indent, '
141 'vl_api_format_string, (&a->{f}));\n'.format(f=o.fieldname))
143 write(' s = format(s, "\\n%U{f}:", '
144 'format_white_space, indent);\n'.format(f=o.fieldname))
147 write(' s = format(s, "\\n%U{f}: %s", '
148 'format_white_space, indent, a->{f});\n'
149 .format(f=o.fieldname))
151 def print_field(self, o, stream):
153 if o.fieldname in noprint_fields:
155 if o.fieldtype in format_strings:
156 f = format_strings[o.fieldtype]
157 write(' s = format(s, "\\n%U{n}: {f}", '
158 'format_white_space, indent, a->{n});\n'
159 .format(n=o.fieldname, f=f))
161 write(' s = format(s, "\\n%U{n}: %U", '
162 'format_white_space, indent, '
163 'format_{t}, &a->{n}, indent);\n'
164 .format(n=o.fieldname, t=o.fieldtype))
166 _dispatch['Field'] = print_field
168 def print_array(self, o, stream):
172 for (i = 0; i < {lfield}; i++) {{
173 s = format(s, "\\n%U{n}: %U",
174 format_white_space, indent, format_{t}, &a->{n}[i], indent);
178 forloop_format = '''\
179 for (i = 0; i < {lfield}; i++) {{
180 s = format(s, "\\n%U{n}: {t}",
181 format_white_space, indent, a->{n}[i]);
185 if o.fieldtype == 'string':
186 return self.print_string(o, stream)
188 if o.fieldtype == 'u8':
190 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
191 'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
192 .format(n=o.fieldname, lfield=o.lengthfield))
194 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
195 'indent, format_hex_bytes, a, {lfield});\n'
196 .format(n=o.fieldname, lfield=o.length))
199 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
200 if o.fieldtype in format_strings:
201 write(forloop_format.format(lfield=lfield,
202 t=format_strings[o.fieldtype],
205 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
207 _dispatch['Array'] = print_array
209 def print_alias(self, k, v, stream):
211 if ('length' in v.alias and v.alias['length'] and
212 v.alias['type'] == 'u8'):
213 write(' return format(s, "%U", format_hex_bytes, a, {});\n'
214 .format(v.alias['length']))
215 elif v.alias['type'] in format_strings:
216 write(' return format(s, "{}", *a);\n'
217 .format(format_strings[v.alias['type']]))
219 write(' return format(s, "{} (print not implemented)");\n'
222 def print_enum(self, o, stream):
224 write(" switch(*a) {\n")
226 write(" case %s:\n" % b[1])
227 write(' return format(s, "{}");\n'.format(b[0]))
230 _dispatch['Enum'] = print_enum
232 def print_obj(self, o, stream):
235 if o.type in self._dispatch:
236 self._dispatch[o.type](self, o, stream)
238 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
239 .format(o.type, o.fieldtype, o.fieldname))
242 def printfun(objs, stream, modulename):
246 /****** Print functions *****/
248 #ifndef included_{module}_printfun
249 #define included_{module}_printfun
252 #define _uword_fmt \"%lld\"
253 #define _uword_cast (long long)
255 #define _uword_fmt \"%ld\"
256 #define _uword_cast long
262 static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
265 u32 indent __attribute__((unused)) = 2;
266 int i __attribute__((unused));
269 h = h.format(module=modulename)
272 pp = Printfun(stream)
275 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
277 write(signature.format(name=t.name))
278 write(' /* Message definition: vl_api_{}_t: */\n'.format(t.name))
279 write(" s = format(s, \"vl_api_%s_t:\");\n" % t.name)
281 pp.print_obj(o, stream)
282 write(' vec_add1(s, 0);\n')
283 write(' vl_print (handle, (char *)s);\n')
284 write(' vec_free (s);\n')
285 write(' return handle;\n')
289 write("\n#endif /* vl_printfun */\n")
294 def printfun_types(objs, stream, modulename):
296 pp = Printfun(stream)
299 /****** Print functions *****/
301 #ifndef included_{module}_printfun_types
302 #define included_{module}_printfun_types
305 h = h.format(module=modulename)
309 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
311 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
312 u32 indent __attribute__((unused)) = va_arg (*args, u32);
313 int i __attribute__((unused));
318 if t.__class__.__name__ == 'Enum':
319 write(signature.format(name=t.name))
320 pp.print_enum(t.block, stream)
321 write(' return s;\n')
326 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
329 if t.__class__.__name__ == 'Using':
330 write(signature.format(name=t.name))
331 pp.print_alias(t.name, t, stream)
335 write(signature.format(name=t.name))
337 pp.print_obj(o, stream)
339 write(' return s;\n')
343 write("\n#endif /* vl_printfun_types */\n")
346 def imports(imports):
347 output = '/* Imported API files */\n'
348 output += '#ifndef vl_api_version\n'
351 s = i.filename.replace('plugins/', '')
352 output += '#include <{}.h>\n'.format(s)
358 'u16': 'clib_net_to_host_u16',
359 'u32': 'clib_net_to_host_u32',
360 'u64': 'clib_net_to_host_u64',
361 'i16': 'clib_net_to_host_i16',
362 'i32': 'clib_net_to_host_i32',
363 'i64': 'clib_net_to_host_i64',
364 'f64': 'clib_net_to_host_f64',
368 def endianfun_array(o):
370 for (i = 0; i < {length}; i++) {{
371 a->{name}[i] = {format}(a->{name}[i]);
375 forloop_format = '''\
376 for (i = 0; i < {length}; i++) {{
377 {type}_endian(&a->{name}[i]);
382 if o.fieldtype == 'u8' or o.fieldtype == 'string':
383 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
385 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
386 if o.fieldtype in endian_strings:
388 .format(length=lfield,
389 format=endian_strings[o.fieldtype],
392 output += (forloop_format
393 .format(length=lfield, type=o.fieldtype,
397 no_endian_conversion = {'client_index': None}
399 def endianfun_obj(o):
401 if o.type == 'Array':
402 return endianfun_array(o)
403 elif o.type != 'Field':
404 output += (' s = format(s, "\\n{} {} {} (print not implemented");\n'
405 .format(o.type, o.fieldtype, o.fieldname))
407 if o.fieldname in no_endian_conversion:
408 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
410 if o.fieldtype in endian_strings:
411 output += (' a->{name} = {format}(a->{name});\n'
412 .format(name=o.fieldname,
413 format=endian_strings[o.fieldtype]))
414 elif o.fieldtype.startswith('vl_api_'):
415 output += (' {type}_endian(&a->{name});\n'
416 .format(type=o.fieldtype, name=o.fieldname))
418 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
423 def endianfun(objs, modulename):
426 /****** Endian swap functions *****/\n\
428 #ifndef included_{module}_endianfun
429 #define included_{module}_endianfun
431 #undef clib_net_to_host_uword
433 #define clib_net_to_host_uword clib_net_to_host_u64
435 #define clib_net_to_host_uword clib_net_to_host_u32
439 output = output.format(module=modulename)
442 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
444 int i __attribute__((unused));
448 if t.__class__.__name__ == 'Enum':
449 output += signature.format(name=t.name)
450 if t.enumtype in endian_strings:
451 output += (' *a = {}(*a);\n'
452 .format(endian_strings[t.enumtype]))
454 output += (' /* a->{name} = a->{name} (no-op) */\n'
455 .format(name=t.name))
461 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
464 if t.__class__.__name__ == 'Using':
465 output += signature.format(name=t.name)
466 if ('length' in t.alias and t.alias['length'] and
467 t.alias['type'] == 'u8'):
468 output += (' /* a->{name} = a->{name} (no-op) */\n'
469 .format(name=t.name))
470 elif t.alias['type'] in format_strings:
471 output += (' *a = {}(*a);\n'
472 .format(endian_strings[t.alias['type']]))
474 output += ' /* Not Implemented yet {} */'.format(t.name)
478 output += signature.format(name=t.name)
481 output += endianfun_obj(o)
485 output += "\n#endif /* vl_endianfun */\n\n"
490 def version_tuple(s, module):
492 /****** Version tuple *****/
494 #ifdef vl_api_version_tuple
497 if 'version' in s['Option']:
498 v = s['Option']['version']
499 (major, minor, patch) = v.split('.')
500 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
501 (module, major, minor, patch)
503 output += "\n#endif /* vl_api_version_tuple */\n\n"
508 def generate_include_enum(s, module, stream):
512 write('typedef enum {\n')
513 for t in s['Define']:
514 write(' VL_API_{},\n'.format(t.name.upper()))
515 write(' VL_MSG_{}_LAST\n'.format(module.upper()))
516 write('}} vl_api_{}_enum_t;\n'.format(module))
519 def generate_include_counters(s, module, stream):
523 csetname = counters.name
524 write('typedef enum {\n')
525 for c in counters.block:
526 write(' {}_ERROR_{},\n'
527 .format(csetname.upper(), c['name'].upper()))
528 write(' {}_N_ERROR\n'.format(csetname.upper()))
529 write('}} vl_counter_{}_enum_t;\n'.format(csetname))
531 # write('extern char *{}_error_strings[];\n'.format(csetname))
532 # write('extern char *{}_description_strings[];\n'.format(csetname))
533 write('extern vl_counter_t {}_error_counters[];\n'.format(csetname))
536 # Generate separate API _types file.
538 def generate_include_types(s, module, stream):
541 write('#ifndef included_{module}_api_types_h\n'.format(module=module))
542 write('#define included_{module}_api_types_h\n'.format(module=module))
544 if 'version' in s['Option']:
545 v = s['Option']['version']
546 (major, minor, patch) = v.split('.')
547 write('#define VL_API_{m}_API_VERSION_MAJOR {v}\n'.format(m=module.upper(), v=major))
548 write('#define VL_API_{m}_API_VERSION_MINOR {v}\n'.format(m=module.upper(), v=minor))
549 write('#define VL_API_{m}_API_VERSION_PATCH {v}\n'.format(m=module.upper(), v=patch))
552 write('/* Imported API files */\n')
553 for i in s['Import']:
554 filename = i.filename.replace('plugins/', '')
555 write('#include <{}_types.h>\n'.format(filename))
557 for o in s['types'] + s['Define']:
558 tname = o.__class__.__name__
560 if 'length' in o.alias:
561 write('typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length']))
563 write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
564 elif tname == 'Enum':
565 if o.enumtype == 'u32':
566 write("typedef enum {\n")
568 write("typedef enum __attribute__((packed)) {\n")
571 write(" %s = %s,\n" % (b[0], b[1]))
572 write('} vl_api_%s_t;\n' % o.name)
573 if o.enumtype != 'u32':
574 size1 = 'sizeof(vl_api_%s_t)' % o.name
575 size2 = 'sizeof(%s)' % o.enumtype
576 err_str = 'size of API enum %s is wrong' % o.name
577 write('STATIC_ASSERT(%s == %s, "%s");\n'
578 % (size1, size2, err_str))
581 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
583 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
586 if b.type == 'Option':
588 if b.type == 'Field':
589 write(" %s %s;\n" % (api2c(b.fieldtype),
591 elif b.type == 'Array':
593 write(" %s %s[0];\n" % (api2c(b.fieldtype),
596 # Fixed length strings decay to nul terminated u8
597 if b.fieldtype == 'string':
600 .format(api2c(b.fieldtype),
603 write(' u8 {}[{}];\n'
604 .format(b.fieldname, b.length))
606 write(" %s %s[%s];\n" %
607 (api2c(b.fieldtype), b.fieldname,
610 raise ValueError("Error in processing type {} for {}"
613 write('} vl_api_%s_t;\n' % o.name)
615 for t in s['Define']:
616 write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
617 .format(n=t.name, ID=t.name.upper(), crc=t.crc))
622 def generate_c_boilerplate(services, defines, counters, file_crc,
625 define_hash = {d.name: d for d in defines}
628 #define vl_endianfun /* define message structures */
629 #include "{module}.api.h"
632 /* instantiate all the print functions we know about */
633 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
635 #include "{module}.api.h"
640 write(hdr.format(module=module))
641 write('static u16\n')
642 write('setup_message_id_table (void) {\n')
643 write(' api_main_t *am = my_api_main;\n')
644 write(' vl_msg_api_msg_config_t c;\n')
645 write(' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", VL_MSG_{m}_LAST);\n'
646 .format(module, crc=file_crc, m=module.upper()))
650 write(' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
651 ' VL_API_{ID} + msg_id_base);\n'
652 .format(n=d.name, ID=d.name.upper(), crc=d.crc))
654 d = define_hash[s.caller]
655 write(' c = (vl_msg_api_msg_config_t) {{.id = VL_API_{ID} + msg_id_base,\n'
657 ' .handler = vl_api_{n}_t_handler,\n'
658 ' .cleanup = vl_noop_handler,\n'
659 ' .endian = vl_api_{n}_t_endian,\n'
660 ' .print = vl_api_{n}_t_print,\n'
661 ' .is_autoendian = 0}};\n'
662 .format(n=s.caller, ID=s.caller.upper()))
663 write(' vl_msg_api_config (&c);\n')
665 d = define_hash[s.reply]
666 write(' c = (vl_msg_api_msg_config_t) {{.id = VL_API_{ID} + msg_id_base,\n'
669 ' .cleanup = vl_noop_handler,\n'
670 ' .endian = vl_api_{n}_t_endian,\n'
671 ' .print = vl_api_{n}_t_print,\n'
672 ' .is_autoendian = 0}};\n'
673 .format(n=s.reply, ID=s.reply.upper()))
674 write(' vl_msg_api_config (&c);\n')
678 write(' return msg_id_base;\n')
681 severity = {'error': 'VL_COUNTER_SEVERITY_ERROR',
682 'info': 'VL_COUNTER_SEVERITY_INFO',
683 'warn': 'VL_COUNTER_SEVERITY_WARN'}
688 write('char *{}_error_strings[] = {{\n'.format(csetname))
690 write(' "{}",\n'.format(c['name']))
692 write('char *{}_description_strings[] = {{\n'.format(csetname))
694 write(' "{}",\n'.format(c['description']))
697 write('vl_counter_t {}_error_counters[] = {{\n'.format(csetname))
700 write(' .name = "{}",\n'.format(c['name']))
701 write(' .desc = "{}",\n'.format(c['description']))
702 write(' .severity = {},\n'.format(severity[c['severity']]))
706 def generate_c_test_boilerplate(services, defines, file_crc, module, plugin, stream):
709 define_hash = {d.name:d for d in defines}
713 #define vl_endianfun /* define message structures */
714 #include "{module}.api.h"
717 /* instantiate all the print functions we know about */
718 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
720 #include "{module}.api.h"
725 write(hdr.format(module=module))
728 d = define_hash[s.reply]
732 write('/* Manual definition requested for: vl_api_{n}_t_handler() */\n'
735 if not define_hash[s.caller].autoreply:
736 write('/* Only autoreply is supported (vl_api_{n}_t_handler()) */\n'
739 write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
740 write('static void\n')
741 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
742 write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
743 write(' i32 retval = ntohl(mp->retval);\n')
744 write(' if (vam->async_mode) {\n')
745 write(' vam->async_errors += (retval < 0);\n')
747 write(' vam->retval = retval;\n')
748 write(' vam->result_ready = 1;\n')
754 if define_hash[e].manual_print:
756 write('static void\n')
757 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
758 write(' vl_print(0, "{n} event called:");\n'.format(n=e))
759 write(' vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
762 write('static void\n')
763 write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
765 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
766 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
767 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
768 ' sizeof(vl_api_{n}_t), 1);\n'
769 .format(n=s.reply, ID=s.reply.upper()))
770 write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
772 write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
773 .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
779 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
780 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
781 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
782 ' sizeof(vl_api_{n}_t), 1);\n'
783 .format(n=e, ID=e.upper()))
787 write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
789 write('clib_error_t * vat_{}_plugin_register (vat_main_t *vam)\n'.format(module))
791 write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
792 write(' mainp->vat_main = vam;\n')
793 write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
794 .format(n=module, crc=file_crc))
795 write(' if (mainp->msg_id_base == (u16) ~0)\n')
796 write(' return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
797 write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
798 write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
799 write(' VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
801 write(' return 0;\n')
807 def run(args, input_filename, s):
810 if not args.outputdir:
811 sys.stderr.write('Missing --outputdir argument')
814 basename = os.path.basename(input_filename)
815 filename, file_extension = os.path.splitext(basename)
816 modulename = filename.replace('.', '_')
817 filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
818 filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
819 filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
820 filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
822 # Generate separate types file
824 generate_include_types(s, modulename, st)
825 with open (filename_types, 'w') as fd:
827 shutil.copyfileobj (st, fd)
830 # Generate separate enum file
832 st.write('#ifndef included_{}_api_enum_h\n'.format(modulename))
833 st.write('#define included_{}_api_enum_h\n'.format(modulename))
834 generate_include_enum(s, modulename, st)
835 generate_include_counters(s['Counters'], modulename, st)
837 with open (filename_enum, 'w') as fd:
839 shutil.copyfileobj (st, fd)
842 # Generate separate C file
844 generate_c_boilerplate(s['Service'], s['Define'], s['Counters'],
845 s['file_crc'], modulename, st)
846 with open (filename_c, 'w') as fd:
848 shutil.copyfileobj(st, fd)
851 # Generate separate C test file
853 plugin = True if 'plugin' in input_filename else False
854 generate_c_test_boilerplate(s['Service'], s['Define'], s['file_crc'],
855 modulename, plugin, st)
856 with open (filename_c_test, 'w') as fd:
858 shutil.copyfileobj(st, fd)
861 output = top_boilerplate.format(datestring=datestring,
862 input_filename=basename)
863 output += imports(s['Import'])
865 output += msg_names(s)
866 output += msg_name_crc_list(s, filename)
867 output += typedefs(modulename)
868 printfun_types(s['types'], stream, modulename)
869 printfun(s['Define'], stream, modulename)
870 output += stream.getvalue()
872 output += endianfun(s['types'] + s['Define'], modulename)
873 output += version_tuple(s, basename)
874 output += bottom_boilerplate.format(input_filename=basename,
875 file_crc=s['file_crc'])