blob: b7a62dc41028151601d910b2317e08f78ad1bdcd [file] [log] [blame]
Ole Troan9d420872017-10-12 13:06:35 +02001# C generation
2import datetime
3import os
Nirmoy Dasc9f40222018-06-28 10:18:43 +02004import time
Ole Troan33a58172019-09-04 09:12:29 +02005import sys
6from io import StringIO
Ole Troan2a1ca782019-09-19 01:08:30 +02007import shutil
Ole Troan9d420872017-10-12 13:06:35 +02008
Ole Troan413f4a52018-11-28 11:36:05 +01009datestring = datetime.datetime.utcfromtimestamp(
10 int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
Ole Troan9d420872017-10-12 13:06:35 +020011input_filename = 'inputfil'
12top_boilerplate = '''\
13/*
14 * VLIB API definitions {datestring}
15 * Input file: {input_filename}
16 * Automatically generated: please edit the input file NOT this file!
17 */
18
Ole Troan288e0932019-05-29 12:30:05 +020019#include <stdbool.h>
Ole Troan9d420872017-10-12 13:06:35 +020020#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 */
26#else
27#warning no content included from {input_filename}
28#endif
29
30#define VL_API_PACKED(x) x __attribute__ ((packed))
31'''
32
33bottom_boilerplate = '''\
34/****** API CRC (whole file) *****/
35
36#ifdef vl_api_version
37vl_api_version({input_filename}, {file_crc:#08x})
38
39#endif
40'''
41
42
43def msg_ids(s):
44 output = '''\
45
46/****** Message ID / handler enum ******/
47
48#ifdef vl_msg_id
49'''
50
Ole Troan2c2feab2018-04-24 00:02:37 -040051 for t in s['Define']:
Ole Troan9d420872017-10-12 13:06:35 +020052 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
53 (t.name.upper(), t.name)
54 output += "#endif"
55
56 return output
57
58
59def msg_names(s):
60 output = '''\
61
62/****** Message names ******/
63
64#ifdef vl_msg_name
65'''
66
Ole Troan2c2feab2018-04-24 00:02:37 -040067 for t in s['Define']:
Ole Troan9d420872017-10-12 13:06:35 +020068 dont_trace = 0 if t.dont_trace else 1
69 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
70 output += "#endif"
71
72 return output
73
74
75def msg_name_crc_list(s, suffix):
76 output = '''\
77
78/****** Message name, crc list ******/
79
80#ifdef vl_msg_name_crc_list
81'''
82 output += "#define foreach_vl_msg_name_crc_%s " % suffix
83
Ole Troan2c2feab2018-04-24 00:02:37 -040084 for t in s['Define']:
Ole Troan9d420872017-10-12 13:06:35 +020085 output += "\\\n_(VL_API_%s, %s, %08x) " % \
86 (t.name.upper(), t.name, t.crc)
87 output += "\n#endif"
88
89 return output
90
91
Ole Troan413f4a52018-11-28 11:36:05 +010092def api2c(fieldtype):
93 mappingtable = {'string': 'vl_api_string_t', }
94 if fieldtype in mappingtable:
95 return mappingtable[fieldtype]
96 return fieldtype
97
98
Ole Troan2a1ca782019-09-19 01:08:30 +020099def typedefs(filename):
Ole Troan9d420872017-10-12 13:06:35 +0200100
Ole Troan2a1ca782019-09-19 01:08:30 +0200101 output = '''\
Ole Troan9d420872017-10-12 13:06:35 +0200102
103/****** Typedefs ******/
104
105#ifdef vl_typedefs
Ole Troan2a1ca782019-09-19 01:08:30 +0200106#include "{include}.api_types.h"
107#endif
108'''.format(include=filename)
Ole Troan9d420872017-10-12 13:06:35 +0200109 return output
110
111
112format_strings = {'u8': '%u',
Ole Troan33a58172019-09-04 09:12:29 +0200113 'bool': '%u',
Ole Troan9d420872017-10-12 13:06:35 +0200114 'i8': '%d',
115 'u16': '%u',
116 'i16': '%d',
117 'u32': '%u',
118 'i32': '%ld',
119 'u64': '%llu',
Paul Vinciguerrab307c712019-11-23 10:13:39 -0500120 'i64': '%lld',
Ole Troan33a58172019-09-04 09:12:29 +0200121 'f64': '%.2f'}
122
123noprint_fields = {'_vl_msg_id': None,
124 'client_index': None,
125 'context': None}
Ole Troan9d420872017-10-12 13:06:35 +0200126
127
Ole Troan33a58172019-09-04 09:12:29 +0200128class Printfun():
129 _dispatch = {}
130
131 def __init__(self, stream):
132 self.stream = stream
133
134 def print_string(self, o, stream):
135 write = stream.write
136 if o.modern_vla:
137 write(' if (vl_api_string_len(&a->{f}) > 0) {{\n'
138 .format(f=o.fieldname))
Jakub Grajciar2dbee932020-02-07 11:30:26 +0100139 write(' s = format(s, "\\n%U{f}: %U", '
Ole Troan33a58172019-09-04 09:12:29 +0200140 'format_white_space, indent, '
Jakub Grajciar2dbee932020-02-07 11:30:26 +0100141 'vl_api_format_string, (&a->{f}));\n'.format(f=o.fieldname))
Ole Troan33a58172019-09-04 09:12:29 +0200142 write(' } else {\n')
143 write(' s = format(s, "\\n%U{f}:", '
144 'format_white_space, indent);\n'.format(f=o.fieldname))
145 write(' }\n')
146 else:
147 write(' s = format(s, "\\n%U{f}: %s", '
148 'format_white_space, indent, a->{f});\n'
149 .format(f=o.fieldname))
150
151 def print_field(self, o, stream):
152 write = stream.write
153 if o.fieldname in noprint_fields:
154 return
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))
160 else:
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))
165
166 _dispatch['Field'] = print_field
167
168 def print_array(self, o, stream):
169 write = stream.write
170
171 forloop = '''\
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);
175 }}
176'''
177
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]);
182 }}
183'''
184
185 if o.fieldtype == 'string':
186 return self.print_string(o, stream)
187
188 if o.fieldtype == 'u8':
189 if o.lengthfield:
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))
193 else:
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))
197 return
198
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],
203 n=o.fieldname))
204 else:
205 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
206
207 _dispatch['Array'] = print_array
208
209 def print_alias(self, k, v, stream):
210 write = stream.write
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']]))
218 else:
Ole Troan75761b92019-09-11 17:49:08 +0200219 write(' return format(s, "{} (print not implemented)");\n'
Ole Troan33a58172019-09-04 09:12:29 +0200220 .format(k))
221
222 def print_enum(self, o, stream):
223 write = stream.write
224 write(" switch(*a) {\n")
225 for b in o:
226 write(" case %s:\n" % b[1])
227 write(' return format(s, "{}");\n'.format(b[0]))
228 write(' }\n')
229
230 _dispatch['Enum'] = print_enum
231
232 def print_obj(self, o, stream):
233 write = stream.write
234
235 if o.type in self._dispatch:
236 self._dispatch[o.type](self, o, stream)
237 else:
238 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
239 .format(o.type, o.fieldtype, o.fieldname))
240
241
242def printfun(objs, stream, modulename):
243 write = stream.write
244
245 h = '''\
Ole Troan9d420872017-10-12 13:06:35 +0200246/****** Print functions *****/
247#ifdef vl_printfun
Ole Troan33a58172019-09-04 09:12:29 +0200248#ifndef included_{module}_printfun
249#define included_{module}_printfun
Ole Troan9d420872017-10-12 13:06:35 +0200250
251#ifdef LP64
252#define _uword_fmt \"%lld\"
253#define _uword_cast (long long)
254#else
255#define _uword_fmt \"%ld\"
256#define _uword_cast long
257#endif
258
259'''
Ole Troan33a58172019-09-04 09:12:29 +0200260
261 signature = '''\
262static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
263{{
264 u8 *s = 0;
265 u32 indent __attribute__((unused)) = 2;
266 int i __attribute__((unused));
267'''
268
269 h = h.format(module=modulename)
270 write(h)
271
272 pp = Printfun(stream)
273 for t in objs:
274 if t.manual_print:
275 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
276 continue
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)
280 for o in t.block:
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')
286 write('}\n\n')
287
288 write("\n#endif")
289 write("\n#endif /* vl_printfun */\n")
290
291 return ''
292
293
Ole Troan75761b92019-09-11 17:49:08 +0200294def printfun_types(objs, stream, modulename):
Ole Troan33a58172019-09-04 09:12:29 +0200295 write = stream.write
296 pp = Printfun(stream)
297
298 h = '''\
299/****** Print functions *****/
300#ifdef vl_printfun
301#ifndef included_{module}_printfun_types
302#define included_{module}_printfun_types
303
304'''
305 h = h.format(module=modulename)
306 write(h)
307
308 signature = '''\
309static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
310{{
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));
314 indent += 2;
315'''
316
Ole Troan2c2feab2018-04-24 00:02:37 -0400317 for t in objs:
318 if t.__class__.__name__ == 'Enum':
Ole Troan33a58172019-09-04 09:12:29 +0200319 write(signature.format(name=t.name))
320 pp.print_enum(t.block, stream)
321 write(' return s;\n')
322 write('}\n\n')
Ole Troan2c2feab2018-04-24 00:02:37 -0400323 continue
Ole Troan33a58172019-09-04 09:12:29 +0200324
Ole Troan9d420872017-10-12 13:06:35 +0200325 if t.manual_print:
Ole Troan33a58172019-09-04 09:12:29 +0200326 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
Ole Troan9d420872017-10-12 13:06:35 +0200327 continue
Ole Troan9d420872017-10-12 13:06:35 +0200328
Ole Troan75761b92019-09-11 17:49:08 +0200329 if t.__class__.__name__ == 'Using':
330 write(signature.format(name=t.name))
331 pp.print_alias(t.name, t, stream)
332 write('}\n\n')
333 continue
334
Ole Troan33a58172019-09-04 09:12:29 +0200335 write(signature.format(name=t.name))
Ole Troan9d420872017-10-12 13:06:35 +0200336 for o in t.block:
Ole Troan33a58172019-09-04 09:12:29 +0200337 pp.print_obj(o, stream)
Ole Troan9d420872017-10-12 13:06:35 +0200338
Ole Troan33a58172019-09-04 09:12:29 +0200339 write(' return s;\n')
340 write('}\n\n')
Ole Troan9d420872017-10-12 13:06:35 +0200341
Ole Troan33a58172019-09-04 09:12:29 +0200342 write("\n#endif")
343 write("\n#endif /* vl_printfun_types */\n")
Ole Troan9d420872017-10-12 13:06:35 +0200344
Ole Troan33a58172019-09-04 09:12:29 +0200345
346def imports(imports):
347 output = '/* Imported API files */\n'
348 output += '#ifndef vl_api_version\n'
349
350 for i in imports:
351 s = i.filename.replace('plugins/', '')
352 output += '#include <{}.h>\n'.format(s)
353 output += '#endif\n'
Ole Troan9d420872017-10-12 13:06:35 +0200354 return output
355
356
357endian_strings = {
358 'u16': 'clib_net_to_host_u16',
359 'u32': 'clib_net_to_host_u32',
360 'u64': 'clib_net_to_host_u64',
Paul Vinciguerra1c200dc2019-11-19 23:30:53 -0500361 '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',
Ole Troan9d420872017-10-12 13:06:35 +0200365}
366
367
Ole Troan33a58172019-09-04 09:12:29 +0200368def endianfun_array(o):
369 forloop = '''\
370 for (i = 0; i < {length}; i++) {{
371 a->{name}[i] = {format}(a->{name}[i]);
372 }}
373'''
374
375 forloop_format = '''\
376 for (i = 0; i < {length}; i++) {{
377 {type}_endian(&a->{name}[i]);
378 }}
379'''
380
381 output = ''
382 if o.fieldtype == 'u8' or o.fieldtype == 'string':
383 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
384 else:
385 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
386 if o.fieldtype in endian_strings:
387 output += (forloop
388 .format(length=lfield,
389 format=endian_strings[o.fieldtype],
390 name=o.fieldname))
391 else:
392 output += (forloop_format
393 .format(length=lfield, type=o.fieldtype,
394 name=o.fieldname))
395 return output
396
Ole Troane796a182020-05-18 11:14:05 +0200397no_endian_conversion = {'client_index': None}
Ole Troan33a58172019-09-04 09:12:29 +0200398
399def endianfun_obj(o):
400 output = ''
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))
406 return output
Ole Troane796a182020-05-18 11:14:05 +0200407 if o.fieldname in no_endian_conversion:
408 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
409 return output
Ole Troan33a58172019-09-04 09:12:29 +0200410 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))
417 else:
418 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
419
420 return output
421
422
Ole Troan75761b92019-09-11 17:49:08 +0200423def endianfun(objs, modulename):
Ole Troan9d420872017-10-12 13:06:35 +0200424 output = '''\
425
426/****** Endian swap functions *****/\n\
427#ifdef vl_endianfun
Ole Troan33a58172019-09-04 09:12:29 +0200428#ifndef included_{module}_endianfun
429#define included_{module}_endianfun
Ole Troan9d420872017-10-12 13:06:35 +0200430
431#undef clib_net_to_host_uword
432#ifdef LP64
433#define clib_net_to_host_uword clib_net_to_host_u64
434#else
435#define clib_net_to_host_uword clib_net_to_host_u32
436#endif
437
438'''
Ole Troan33a58172019-09-04 09:12:29 +0200439 output = output.format(module=modulename)
440
441 signature = '''\
442static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
443{{
444 int i __attribute__((unused));
445'''
446
Ole Troan2c2feab2018-04-24 00:02:37 -0400447 for t in objs:
448 if t.__class__.__name__ == 'Enum':
Ole Troan33a58172019-09-04 09:12:29 +0200449 output += signature.format(name=t.name)
450 if t.enumtype in endian_strings:
451 output += (' *a = {}(*a);\n'
452 .format(endian_strings[t.enumtype]))
453 else:
454 output += (' /* a->{name} = a->{name} (no-op) */\n'
455 .format(name=t.name))
456
457 output += '}\n\n'
Ole Troan2c2feab2018-04-24 00:02:37 -0400458 continue
Ole Troan33a58172019-09-04 09:12:29 +0200459
Ole Troan9d420872017-10-12 13:06:35 +0200460 if t.manual_endian:
461 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
462 continue
Ole Troan33a58172019-09-04 09:12:29 +0200463
Ole Troan75761b92019-09-11 17:49:08 +0200464 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']]))
473 else:
474 output += ' /* Not Implemented yet {} */'.format(t.name)
475 output += '}\n\n'
476 continue
477
Ole Troan33a58172019-09-04 09:12:29 +0200478 output += signature.format(name=t.name)
Ole Troan9d420872017-10-12 13:06:35 +0200479
480 for o in t.block:
Ole Troan33a58172019-09-04 09:12:29 +0200481 output += endianfun_obj(o)
Ole Troan9d420872017-10-12 13:06:35 +0200482 output += '}\n\n'
Ole Troan33a58172019-09-04 09:12:29 +0200483
484 output += "\n#endif"
Ole Troan9d420872017-10-12 13:06:35 +0200485 output += "\n#endif /* vl_endianfun */\n\n"
486
487 return output
488
489
490def version_tuple(s, module):
491 output = '''\
492/****** Version tuple *****/
493
494#ifdef vl_api_version_tuple
495
496'''
Ole Troan2c2feab2018-04-24 00:02:37 -0400497 if 'version' in s['Option']:
498 v = s['Option']['version']
Ole Troan9d420872017-10-12 13:06:35 +0200499 (major, minor, patch) = v.split('.')
500 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
501 (module, major, minor, patch)
502
503 output += "\n#endif /* vl_api_version_tuple */\n\n"
504
505 return output
506
507
Ole Troan2a1ca782019-09-19 01:08:30 +0200508def generate_include_enum(s, module, stream):
509 write = stream.write
510
511 if len(s['Define']):
512 write('typedef enum {\n')
513 for t in s['Define']:
514 write(' VL_API_{},\n'.format(t.name.upper()))
515 write(' VL_MSG_FIRST_AVAILABLE\n')
516 write('}} vl_api_{}_enum_t;\n'.format(module))
517
Paul Vinciguerra7c8803d2019-11-21 17:16:18 -0500518
Ole Troan2a1ca782019-09-19 01:08:30 +0200519#
520# Generate separate API _types file.
521#
522def generate_include_types(s, module, stream):
523 write = stream.write
524
525 write('#ifndef included_{module}_api_types_h\n'.format(module=module))
526 write('#define included_{module}_api_types_h\n'.format(module=module))
527
528 if len(s['Import']):
529 write('/* Imported API files */\n')
530 for i in s['Import']:
531 filename = i.filename.replace('plugins/', '')
532 write('#include <{}_types.h>\n'.format(filename))
533
534 for o in s['types'] + s['Define']:
535 tname = o.__class__.__name__
536 if tname == 'Using':
537 if 'length' in o.alias:
538 write('typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length']))
539 else:
540 write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
541 elif tname == 'Enum':
542 if o.enumtype == 'u32':
543 write("typedef enum {\n")
544 else:
545 write("typedef enum __attribute__((packed)) {\n")
546
547 for b in o.block:
548 write(" %s = %s,\n" % (b[0], b[1]))
549 write('} vl_api_%s_t;\n' % o.name)
550 if o.enumtype != 'u32':
551 size1 = 'sizeof(vl_api_%s_t)' % o.name
552 size2 = 'sizeof(%s)' % o.enumtype
553 err_str = 'size of API enum %s is wrong' % o.name
554 write('STATIC_ASSERT(%s == %s, "%s");\n'
555 % (size1, size2, err_str))
556 else:
557 if tname == 'Union':
558 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
559 else:
560 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
561 % o.name)
562 for b in o.block:
563 if b.type == 'Option':
564 continue
565 if b.type == 'Field':
566 write(" %s %s;\n" % (api2c(b.fieldtype),
567 b.fieldname))
568 elif b.type == 'Array':
569 if b.lengthfield:
570 write(" %s %s[0];\n" % (api2c(b.fieldtype),
571 b.fieldname))
572 else:
573 # Fixed length strings decay to nul terminated u8
574 if b.fieldtype == 'string':
575 if b.modern_vla:
576 write(' {} {};\n'
577 .format(api2c(b.fieldtype),
578 b.fieldname))
579 else:
580 write(' u8 {}[{}];\n'
581 .format(b.fieldname, b.length))
582 else:
583 write(" %s %s[%s];\n" %
584 (api2c(b.fieldtype), b.fieldname,
585 b.length))
586 else:
587 raise ValueError("Error in processing type {} for {}"
588 .format(b, o.name))
589
590 write('} vl_api_%s_t;\n' % o.name)
591
Ole Troan3f2d5712019-12-07 00:39:49 +0100592 for t in s['Define']:
593 write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
594 .format(n=t.name, ID=t.name.upper(), crc=t.crc))
595
Ole Troan2a1ca782019-09-19 01:08:30 +0200596 write("\n#endif\n")
597
598
599def generate_c_boilerplate(services, defines, file_crc, module, stream):
600 write = stream.write
Ole Troane796a182020-05-18 11:14:05 +0200601 define_hash = {d.name:d for d in defines}
Ole Troan2a1ca782019-09-19 01:08:30 +0200602
603 hdr = '''\
604#define vl_endianfun /* define message structures */
605#include "{module}.api.h"
606#undef vl_endianfun
607
608/* instantiate all the print functions we know about */
609#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
610#define vl_printfun
611#include "{module}.api.h"
612#undef vl_printfun
613
614'''
615
616 write(hdr.format(module=module))
617 write('static u16\n')
618 write('setup_message_id_table (void) {\n')
Dave Barach39d69112019-11-27 11:42:13 -0500619 write(' api_main_t *am = my_api_main;\n')
Ole Troane796a182020-05-18 11:14:05 +0200620 write(' vl_msg_api_msg_config_t c;\n')
Ole Troan2a1ca782019-09-19 01:08:30 +0200621 write(' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", VL_MSG_FIRST_AVAILABLE);\n'
622 .format(module, crc=file_crc))
623
624
625 for d in defines:
626 write(' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
627 ' VL_API_{ID} + msg_id_base);\n'
628 .format(n=d.name, ID=d.name.upper(), crc=d.crc))
629 for s in services:
Ole Troane796a182020-05-18 11:14:05 +0200630 d = define_hash[s.caller]
631 write(' c = (vl_msg_api_msg_config_t) {{.id = VL_API_{ID} + msg_id_base,\n'
632 ' .name = "{n}",\n'
633 ' .handler = vl_api_{n}_t_handler,\n'
634 ' .cleanup = vl_noop_handler,\n'
635 ' .endian = vl_api_{n}_t_endian,\n'
636 ' .print = vl_api_{n}_t_print,\n'
637 ' .is_autoendian = 0}};\n'
Ole Troan2a1ca782019-09-19 01:08:30 +0200638 .format(n=s.caller, ID=s.caller.upper()))
Ole Troane796a182020-05-18 11:14:05 +0200639 write(' vl_msg_api_config (&c);\n')
Ole Troan2a1ca782019-09-19 01:08:30 +0200640
641 write(' return msg_id_base;\n')
642 write('}\n')
643
644
645def generate_c_test_plugin_boilerplate(services, defines, file_crc, module, stream):
646 write = stream.write
647
648 define_hash = {d.name:d for d in defines}
649 replies = {}
650
651 hdr = '''\
652#define vl_endianfun /* define message structures */
653#include "{module}.api.h"
654#undef vl_endianfun
655
656/* instantiate all the print functions we know about */
657#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
658#define vl_printfun
659#include "{module}.api.h"
660#undef vl_printfun
661
662'''
663
664 write(hdr.format(module=module))
665 for s in services:
666 try:
667 d = define_hash[s.reply]
668 except:
669 continue
670 if d.manual_print:
Paul Vinciguerra7c8803d2019-11-21 17:16:18 -0500671 write('/* Manual definition requested for: vl_api_{n}_t_handler() */\n'
Ole Troan2a1ca782019-09-19 01:08:30 +0200672 .format(n=s.reply))
673 continue
674 if not define_hash[s.caller].autoreply:
Paul Vinciguerra7c8803d2019-11-21 17:16:18 -0500675 write('/* Only autoreply is supported (vl_api_{n}_t_handler()) */\n'
Ole Troan2a1ca782019-09-19 01:08:30 +0200676 .format(n=s.reply))
677 continue
Paul Vinciguerra7c8803d2019-11-21 17:16:18 -0500678 write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
Ole Troan2a1ca782019-09-19 01:08:30 +0200679 write('static void\n')
680 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
681 write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
682 write(' i32 retval = ntohl(mp->retval);\n')
683 write(' if (vam->async_mode) {\n')
684 write(' vam->async_errors += (retval < 0);\n')
685 write(' } else {\n')
686 write(' vam->retval = retval;\n')
687 write(' vam->result_ready = 1;\n')
688 write(' }\n')
689 write('}\n')
Ole Troan3ae9f5a2019-10-09 12:39:32 +0200690 write('#endif\n')
Ole Troan2a1ca782019-09-19 01:08:30 +0200691
Ole Troanb126ebc2019-10-07 16:22:00 +0200692 for e in s.events:
693 if define_hash[e].manual_print:
694 continue
695 write('static void\n')
696 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
697 write(' vl_print(0, "{n} event called:");\n'.format(n=e))
698 write(' vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
699 write('}\n')
700
Ole Troan2a1ca782019-09-19 01:08:30 +0200701 write('static void\n')
702 write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
703 for s in services:
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=s.reply, ID=s.reply.upper()))
709 write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
710 try:
711 write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
712 .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
713 except:
714 pass
715
Ole Troanb126ebc2019-10-07 16:22:00 +0200716 # Events
717 for e in s.events:
718 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
719 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
720 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
721 ' sizeof(vl_api_{n}_t), 1);\n'
722 .format(n=e, ID=e.upper()))
723
Ole Troan2a1ca782019-09-19 01:08:30 +0200724 write('}\n')
725
726 write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
727 write('{\n')
728 write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
729 write(' mainp->vat_main = vam;\n')
730 write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
731 .format(n=module, crc=file_crc))
732 write(' if (mainp->msg_id_base == (u16) ~0)\n')
733 write(' return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
734 write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
Ole Troan709dad32019-10-09 14:38:14 +0200735 write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
736 write(' VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
737 write('#endif\n')
Ole Troan2a1ca782019-09-19 01:08:30 +0200738 write(' return 0;\n')
739 write('}\n')
740
741
Ole Troan9d420872017-10-12 13:06:35 +0200742#
743# Plugin entry point
744#
Ole Troan2a1ca782019-09-19 01:08:30 +0200745def run(args, input_filename, s):
Ole Troan33a58172019-09-04 09:12:29 +0200746 stream = StringIO()
Ole Troan2a1ca782019-09-19 01:08:30 +0200747
748 if not args.outputdir:
749 sys.stderr.write('Missing --outputdir argument')
750 return None
751
Ole Troan9d420872017-10-12 13:06:35 +0200752 basename = os.path.basename(input_filename)
753 filename, file_extension = os.path.splitext(basename)
Ole Troan33a58172019-09-04 09:12:29 +0200754 modulename = filename.replace('.', '_')
Ole Troan2a1ca782019-09-19 01:08:30 +0200755 filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
756 filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
757 filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
758 filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
759
760 # Generate separate types file
761 st = StringIO()
762 generate_include_types(s, modulename, st)
763 with open (filename_types, 'w') as fd:
764 st.seek (0)
765 shutil.copyfileobj (st, fd)
766 st.close()
767
768 # Generate separate enum file
769 st = StringIO()
770 generate_include_enum(s, modulename, st)
771 with open (filename_enum, 'w') as fd:
772 st.seek (0)
773 shutil.copyfileobj (st, fd)
774 st.close()
775
776 # Generate separate C file
777 st = StringIO()
778 generate_c_boilerplate(s['Service'], s['Define'], s['file_crc'],
779 modulename, st)
780 with open (filename_c, 'w') as fd:
781 st.seek (0)
782 shutil.copyfileobj(st, fd)
783 st.close()
784
785 # Generate separate C test file
786 # This is only supported for plugins at the moment
787 st = StringIO()
788 generate_c_test_plugin_boilerplate(s['Service'], s['Define'], s['file_crc'],
789 modulename, st)
790 with open (filename_c_test, 'w') as fd:
791 st.seek (0)
792 shutil.copyfileobj(st, fd)
793 st.close()
Ole Troan33a58172019-09-04 09:12:29 +0200794
Ole Troan9d420872017-10-12 13:06:35 +0200795 output = top_boilerplate.format(datestring=datestring,
796 input_filename=basename)
Ole Troan33a58172019-09-04 09:12:29 +0200797 output += imports(s['Import'])
Ole Troan9d420872017-10-12 13:06:35 +0200798 output += msg_ids(s)
799 output += msg_names(s)
800 output += msg_name_crc_list(s, filename)
Ole Troan2a1ca782019-09-19 01:08:30 +0200801 output += typedefs(modulename)
Ole Troan75761b92019-09-11 17:49:08 +0200802 printfun_types(s['types'], stream, modulename)
Ole Troan33a58172019-09-04 09:12:29 +0200803 printfun(s['Define'], stream, modulename)
804 output += stream.getvalue()
Ole Troan2a1ca782019-09-19 01:08:30 +0200805 stream.close()
Ole Troan75761b92019-09-11 17:49:08 +0200806 output += endianfun(s['types'] + s['Define'], modulename)
Ole Troan9d420872017-10-12 13:06:35 +0200807 output += version_tuple(s, basename)
808 output += bottom_boilerplate.format(input_filename=basename,
Ole Troan8dbfb432019-04-24 14:31:18 +0200809 file_crc=s['file_crc'])
Ole Troan9d420872017-10-12 13:06:35 +0200810
811 return output