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}: %.*s", '
140 'format_white_space, indent, '
141 'vl_api_string_len(&a->{f}) - 1, '
142 'vl_api_from_api_string(&a->{f}));\n'.format(f=o.fieldname))
144 write(' s = format(s, "\\n%U{f}:", '
145 'format_white_space, indent);\n'.format(f=o.fieldname))
148 write(' s = format(s, "\\n%U{f}: %s", '
149 'format_white_space, indent, a->{f});\n'
150 .format(f=o.fieldname))
152 def print_field(self, o, stream):
154 if o.fieldname in noprint_fields:
156 if o.fieldtype in format_strings:
157 f = format_strings[o.fieldtype]
158 write(' s = format(s, "\\n%U{n}: {f}", '
159 'format_white_space, indent, a->{n});\n'
160 .format(n=o.fieldname, f=f))
162 write(' s = format(s, "\\n%U{n}: %U", '
163 'format_white_space, indent, '
164 'format_{t}, &a->{n}, indent);\n'
165 .format(n=o.fieldname, t=o.fieldtype))
167 _dispatch['Field'] = print_field
169 def print_array(self, o, stream):
173 for (i = 0; i < {lfield}; i++) {{
174 s = format(s, "\\n%U{n}: %U",
175 format_white_space, indent, format_{t}, &a->{n}[i], indent);
179 forloop_format = '''\
180 for (i = 0; i < {lfield}; i++) {{
181 s = format(s, "\\n%U{n}: {t}",
182 format_white_space, indent, a->{n}[i]);
186 if o.fieldtype == 'string':
187 return self.print_string(o, stream)
189 if o.fieldtype == 'u8':
191 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
192 'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
193 .format(n=o.fieldname, lfield=o.lengthfield))
195 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
196 'indent, format_hex_bytes, a, {lfield});\n'
197 .format(n=o.fieldname, lfield=o.length))
200 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
201 if o.fieldtype in format_strings:
202 write(forloop_format.format(lfield=lfield,
203 t=format_strings[o.fieldtype],
206 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
208 _dispatch['Array'] = print_array
210 def print_alias(self, k, v, stream):
212 if ('length' in v.alias and v.alias['length'] and
213 v.alias['type'] == 'u8'):
214 write(' return format(s, "%U", format_hex_bytes, a, {});\n'
215 .format(v.alias['length']))
216 elif v.alias['type'] in format_strings:
217 write(' return format(s, "{}", *a);\n'
218 .format(format_strings[v.alias['type']]))
220 write(' return format(s, "{} (print not implemented)");\n'
223 def print_enum(self, o, stream):
225 write(" switch(*a) {\n")
227 write(" case %s:\n" % b[1])
228 write(' return format(s, "{}");\n'.format(b[0]))
231 _dispatch['Enum'] = print_enum
233 def print_obj(self, o, stream):
236 if o.type in self._dispatch:
237 self._dispatch[o.type](self, o, stream)
239 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
240 .format(o.type, o.fieldtype, o.fieldname))
243 def printfun(objs, stream, modulename):
247 /****** Print functions *****/
249 #ifndef included_{module}_printfun
250 #define included_{module}_printfun
253 #define _uword_fmt \"%lld\"
254 #define _uword_cast (long long)
256 #define _uword_fmt \"%ld\"
257 #define _uword_cast long
263 static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
266 u32 indent __attribute__((unused)) = 2;
267 int i __attribute__((unused));
270 h = h.format(module=modulename)
273 pp = Printfun(stream)
276 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
278 write(signature.format(name=t.name))
279 write(' /* Message definition: vl_api_{}_t: */\n'.format(t.name))
280 write(" s = format(s, \"vl_api_%s_t:\");\n" % t.name)
282 pp.print_obj(o, stream)
283 write(' vec_add1(s, 0);\n')
284 write(' vl_print (handle, (char *)s);\n')
285 write(' vec_free (s);\n')
286 write(' return handle;\n')
290 write("\n#endif /* vl_printfun */\n")
295 def printfun_types(objs, stream, modulename):
297 pp = Printfun(stream)
300 /****** Print functions *****/
302 #ifndef included_{module}_printfun_types
303 #define included_{module}_printfun_types
306 h = h.format(module=modulename)
310 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
312 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
313 u32 indent __attribute__((unused)) = va_arg (*args, u32);
314 int i __attribute__((unused));
319 if t.__class__.__name__ == 'Enum':
320 write(signature.format(name=t.name))
321 pp.print_enum(t.block, stream)
322 write(' return s;\n')
327 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
330 if t.__class__.__name__ == 'Using':
331 write(signature.format(name=t.name))
332 pp.print_alias(t.name, t, stream)
336 write(signature.format(name=t.name))
338 pp.print_obj(o, stream)
340 write(' return s;\n')
344 write("\n#endif /* vl_printfun_types */\n")
347 def imports(imports):
348 output = '/* Imported API files */\n'
349 output += '#ifndef vl_api_version\n'
352 s = i.filename.replace('plugins/', '')
353 output += '#include <{}.h>\n'.format(s)
359 'u16': 'clib_net_to_host_u16',
360 'u32': 'clib_net_to_host_u32',
361 'u64': 'clib_net_to_host_u64',
362 'i16': 'clib_net_to_host_i16',
363 'i32': 'clib_net_to_host_i32',
364 'i64': 'clib_net_to_host_i64',
365 'f64': 'clib_net_to_host_f64',
369 def endianfun_array(o):
371 for (i = 0; i < {length}; i++) {{
372 a->{name}[i] = {format}(a->{name}[i]);
376 forloop_format = '''\
377 for (i = 0; i < {length}; i++) {{
378 {type}_endian(&a->{name}[i]);
383 if o.fieldtype == 'u8' or o.fieldtype == 'string':
384 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
386 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
387 if o.fieldtype in endian_strings:
389 .format(length=lfield,
390 format=endian_strings[o.fieldtype],
393 output += (forloop_format
394 .format(length=lfield, type=o.fieldtype,
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.fieldtype in endian_strings:
408 output += (' a->{name} = {format}(a->{name});\n'
409 .format(name=o.fieldname,
410 format=endian_strings[o.fieldtype]))
411 elif o.fieldtype.startswith('vl_api_'):
412 output += (' {type}_endian(&a->{name});\n'
413 .format(type=o.fieldtype, name=o.fieldname))
415 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
420 def endianfun(objs, modulename):
423 /****** Endian swap functions *****/\n\
425 #ifndef included_{module}_endianfun
426 #define included_{module}_endianfun
428 #undef clib_net_to_host_uword
430 #define clib_net_to_host_uword clib_net_to_host_u64
432 #define clib_net_to_host_uword clib_net_to_host_u32
436 output = output.format(module=modulename)
439 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
441 int i __attribute__((unused));
445 if t.__class__.__name__ == 'Enum':
446 output += signature.format(name=t.name)
447 if t.enumtype in endian_strings:
448 output += (' *a = {}(*a);\n'
449 .format(endian_strings[t.enumtype]))
451 output += (' /* a->{name} = a->{name} (no-op) */\n'
452 .format(name=t.name))
458 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
462 if t.__class__.__name__ == 'Using':
463 output += signature.format(name=t.name)
464 if ('length' in t.alias and t.alias['length'] and
465 t.alias['type'] == 'u8'):
466 output += (' /* a->{name} = a->{name} (no-op) */\n'
467 .format(name=t.name))
468 elif t.alias['type'] in format_strings:
469 output += (' *a = {}(*a);\n'
470 .format(endian_strings[t.alias['type']]))
472 output += ' /* Not Implemented yet {} */'.format(t.name)
476 output += signature.format(name=t.name)
479 output += endianfun_obj(o)
483 output += "\n#endif /* vl_endianfun */\n\n"
488 def version_tuple(s, module):
490 /****** Version tuple *****/
492 #ifdef vl_api_version_tuple
495 if 'version' in s['Option']:
496 v = s['Option']['version']
497 (major, minor, patch) = v.split('.')
498 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
499 (module, major, minor, patch)
501 output += "\n#endif /* vl_api_version_tuple */\n\n"
506 def generate_include_enum(s, module, stream):
510 write('typedef enum {\n')
511 for t in s['Define']:
512 write(' VL_API_{},\n'.format(t.name.upper()))
513 write(' VL_MSG_FIRST_AVAILABLE\n')
514 write('}} vl_api_{}_enum_t;\n'.format(module))
517 # Generate separate API _types file.
519 def generate_include_types(s, module, stream):
522 write('#ifndef included_{module}_api_types_h\n'.format(module=module))
523 write('#define included_{module}_api_types_h\n'.format(module=module))
526 write('/* Imported API files */\n')
527 for i in s['Import']:
528 filename = i.filename.replace('plugins/', '')
529 write('#include <{}_types.h>\n'.format(filename))
531 for o in s['types'] + s['Define']:
532 tname = o.__class__.__name__
534 if 'length' in o.alias:
535 write('typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length']))
537 write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
538 elif tname == 'Enum':
539 if o.enumtype == 'u32':
540 write("typedef enum {\n")
542 write("typedef enum __attribute__((packed)) {\n")
545 write(" %s = %s,\n" % (b[0], b[1]))
546 write('} vl_api_%s_t;\n' % o.name)
547 if o.enumtype != 'u32':
548 size1 = 'sizeof(vl_api_%s_t)' % o.name
549 size2 = 'sizeof(%s)' % o.enumtype
550 err_str = 'size of API enum %s is wrong' % o.name
551 write('STATIC_ASSERT(%s == %s, "%s");\n'
552 % (size1, size2, err_str))
555 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
557 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
560 if b.type == 'Option':
562 if b.type == 'Field':
563 write(" %s %s;\n" % (api2c(b.fieldtype),
565 elif b.type == 'Array':
567 write(" %s %s[0];\n" % (api2c(b.fieldtype),
570 # Fixed length strings decay to nul terminated u8
571 if b.fieldtype == 'string':
574 .format(api2c(b.fieldtype),
577 write(' u8 {}[{}];\n'
578 .format(b.fieldname, b.length))
580 write(" %s %s[%s];\n" %
581 (api2c(b.fieldtype), b.fieldname,
584 raise ValueError("Error in processing type {} for {}"
587 write('} vl_api_%s_t;\n' % o.name)
592 def generate_c_boilerplate(services, defines, file_crc, module, stream):
596 #define vl_endianfun /* define message structures */
597 #include "{module}.api.h"
600 /* instantiate all the print functions we know about */
601 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
603 #include "{module}.api.h"
608 write(hdr.format(module=module))
609 write('static u16\n')
610 write('setup_message_id_table (void) {\n')
611 write(' api_main_t *am = &api_main;\n')
612 write(' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", VL_MSG_FIRST_AVAILABLE);\n'
613 .format(module, crc=file_crc))
617 write(' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
618 ' VL_API_{ID} + msg_id_base);\n'
619 .format(n=d.name, ID=d.name.upper(), crc=d.crc))
621 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
622 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
623 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
624 ' sizeof(vl_api_{n}_t), 1);\n'
625 .format(n=s.caller, ID=s.caller.upper()))
627 write(' return msg_id_base;\n')
631 def generate_c_test_plugin_boilerplate(services, defines, file_crc, module, stream):
634 define_hash = {d.name:d for d in defines}
638 #define vl_endianfun /* define message structures */
639 #include "{module}.api.h"
642 /* instantiate all the print functions we know about */
643 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
645 #include "{module}.api.h"
650 write(hdr.format(module=module))
653 d = define_hash[s.reply]
657 write('/* Manual definition requested for: vl_api_{n}_t_hander() */\n'
660 if not define_hash[s.caller].autoreply:
661 write('/* Only autoreply is supported (vl_api_{n}_t_hander()) */\n'
664 write('#ifndef VL_API_{n}_T_HANLDER\n'.format(n=s.reply.upper()))
665 write('static void\n')
666 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
667 write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
668 write(' i32 retval = ntohl(mp->retval);\n')
669 write(' if (vam->async_mode) {\n')
670 write(' vam->async_errors += (retval < 0);\n')
672 write(' vam->retval = retval;\n')
673 write(' vam->result_ready = 1;\n')
679 if define_hash[e].manual_print:
681 write('static void\n')
682 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
683 write(' vl_print(0, "{n} event called:");\n'.format(n=e))
684 write(' vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
687 write('static void\n')
688 write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
690 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
691 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
692 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
693 ' sizeof(vl_api_{n}_t), 1);\n'
694 .format(n=s.reply, ID=s.reply.upper()))
695 write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
697 write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
698 .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
704 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
705 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
706 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
707 ' sizeof(vl_api_{n}_t), 1);\n'
708 .format(n=e, ID=e.upper()))
712 write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
714 write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
715 write(' mainp->vat_main = vam;\n')
716 write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
717 .format(n=module, crc=file_crc))
718 write(' if (mainp->msg_id_base == (u16) ~0)\n')
719 write(' return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
720 write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
721 write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
722 write(' VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
724 write(' return 0;\n')
731 def run(args, input_filename, s):
734 if not args.outputdir:
735 sys.stderr.write('Missing --outputdir argument')
738 basename = os.path.basename(input_filename)
739 filename, file_extension = os.path.splitext(basename)
740 modulename = filename.replace('.', '_')
741 filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
742 filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
743 filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
744 filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
746 # Generate separate types file
748 generate_include_types(s, modulename, st)
749 with open (filename_types, 'w') as fd:
751 shutil.copyfileobj (st, fd)
754 # Generate separate enum file
756 generate_include_enum(s, modulename, st)
757 with open (filename_enum, 'w') as fd:
759 shutil.copyfileobj (st, fd)
762 # Generate separate C file
764 generate_c_boilerplate(s['Service'], s['Define'], s['file_crc'],
766 with open (filename_c, 'w') as fd:
768 shutil.copyfileobj(st, fd)
771 # Generate separate C test file
772 # This is only supported for plugins at the moment
774 generate_c_test_plugin_boilerplate(s['Service'], s['Define'], s['file_crc'],
776 with open (filename_c_test, 'w') as fd:
778 shutil.copyfileobj(st, fd)
781 output = top_boilerplate.format(datestring=datestring,
782 input_filename=basename)
783 output += imports(s['Import'])
785 output += msg_names(s)
786 output += msg_name_crc_list(s, filename)
787 output += typedefs(modulename)
788 printfun_types(s['types'], stream, modulename)
789 printfun(s['Define'], stream, modulename)
790 output += stream.getvalue()
792 output += endianfun(s['types'] + s['Define'], modulename)
793 output += version_tuple(s, basename)
794 output += bottom_boilerplate.format(input_filename=basename,
795 file_crc=s['file_crc'])