blob: bab255c58a20a6d94c27444e680c080940278add [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',
120 'i64': '%llu',
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))
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))
143 write(' } else {\n')
144 write(' s = format(s, "\\n%U{f}:", '
145 'format_white_space, indent);\n'.format(f=o.fieldname))
146 write(' }\n')
147 else:
148 write(' s = format(s, "\\n%U{f}: %s", '
149 'format_white_space, indent, a->{f});\n'
150 .format(f=o.fieldname))
151
152 def print_field(self, o, stream):
153 write = stream.write
154 if o.fieldname in noprint_fields:
155 return
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))
161 else:
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))
166
167 _dispatch['Field'] = print_field
168
169 def print_array(self, o, stream):
170 write = stream.write
171
172 forloop = '''\
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);
176 }}
177'''
178
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]);
183 }}
184'''
185
186 if o.fieldtype == 'string':
187 return self.print_string(o, stream)
188
189 if o.fieldtype == 'u8':
190 if o.lengthfield:
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))
194 else:
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))
198 return
199
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],
204 n=o.fieldname))
205 else:
206 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
207
208 _dispatch['Array'] = print_array
209
210 def print_alias(self, k, v, stream):
211 write = stream.write
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']]))
219 else:
Ole Troan75761b92019-09-11 17:49:08 +0200220 write(' return format(s, "{} (print not implemented)");\n'
Ole Troan33a58172019-09-04 09:12:29 +0200221 .format(k))
222
223 def print_enum(self, o, stream):
224 write = stream.write
225 write(" switch(*a) {\n")
226 for b in o:
227 write(" case %s:\n" % b[1])
228 write(' return format(s, "{}");\n'.format(b[0]))
229 write(' }\n')
230
231 _dispatch['Enum'] = print_enum
232
233 def print_obj(self, o, stream):
234 write = stream.write
235
236 if o.type in self._dispatch:
237 self._dispatch[o.type](self, o, stream)
238 else:
239 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
240 .format(o.type, o.fieldtype, o.fieldname))
241
242
243def printfun(objs, stream, modulename):
244 write = stream.write
245
246 h = '''\
Ole Troan9d420872017-10-12 13:06:35 +0200247/****** Print functions *****/
248#ifdef vl_printfun
Ole Troan33a58172019-09-04 09:12:29 +0200249#ifndef included_{module}_printfun
250#define included_{module}_printfun
Ole Troan9d420872017-10-12 13:06:35 +0200251
252#ifdef LP64
253#define _uword_fmt \"%lld\"
254#define _uword_cast (long long)
255#else
256#define _uword_fmt \"%ld\"
257#define _uword_cast long
258#endif
259
260'''
Ole Troan33a58172019-09-04 09:12:29 +0200261
262 signature = '''\
263static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
264{{
265 u8 *s = 0;
266 u32 indent __attribute__((unused)) = 2;
267 int i __attribute__((unused));
268'''
269
270 h = h.format(module=modulename)
271 write(h)
272
273 pp = Printfun(stream)
274 for t in objs:
275 if t.manual_print:
276 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
277 continue
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)
281 for o in t.block:
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')
287 write('}\n\n')
288
289 write("\n#endif")
290 write("\n#endif /* vl_printfun */\n")
291
292 return ''
293
294
Ole Troan75761b92019-09-11 17:49:08 +0200295def printfun_types(objs, stream, modulename):
Ole Troan33a58172019-09-04 09:12:29 +0200296 write = stream.write
297 pp = Printfun(stream)
298
299 h = '''\
300/****** Print functions *****/
301#ifdef vl_printfun
302#ifndef included_{module}_printfun_types
303#define included_{module}_printfun_types
304
305'''
306 h = h.format(module=modulename)
307 write(h)
308
309 signature = '''\
310static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
311{{
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));
315 indent += 2;
316'''
317
Ole Troan2c2feab2018-04-24 00:02:37 -0400318 for t in objs:
319 if t.__class__.__name__ == 'Enum':
Ole Troan33a58172019-09-04 09:12:29 +0200320 write(signature.format(name=t.name))
321 pp.print_enum(t.block, stream)
322 write(' return s;\n')
323 write('}\n\n')
Ole Troan2c2feab2018-04-24 00:02:37 -0400324 continue
Ole Troan33a58172019-09-04 09:12:29 +0200325
Ole Troan9d420872017-10-12 13:06:35 +0200326 if t.manual_print:
Ole Troan33a58172019-09-04 09:12:29 +0200327 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
Ole Troan9d420872017-10-12 13:06:35 +0200328 continue
Ole Troan9d420872017-10-12 13:06:35 +0200329
Ole Troan75761b92019-09-11 17:49:08 +0200330 if t.__class__.__name__ == 'Using':
331 write(signature.format(name=t.name))
332 pp.print_alias(t.name, t, stream)
333 write('}\n\n')
334 continue
335
Ole Troan33a58172019-09-04 09:12:29 +0200336 write(signature.format(name=t.name))
Ole Troan9d420872017-10-12 13:06:35 +0200337 for o in t.block:
Ole Troan33a58172019-09-04 09:12:29 +0200338 pp.print_obj(o, stream)
Ole Troan9d420872017-10-12 13:06:35 +0200339
Ole Troan33a58172019-09-04 09:12:29 +0200340 write(' return s;\n')
341 write('}\n\n')
Ole Troan9d420872017-10-12 13:06:35 +0200342
Ole Troan33a58172019-09-04 09:12:29 +0200343 write("\n#endif")
344 write("\n#endif /* vl_printfun_types */\n")
Ole Troan9d420872017-10-12 13:06:35 +0200345
Ole Troan33a58172019-09-04 09:12:29 +0200346
347def imports(imports):
348 output = '/* Imported API files */\n'
349 output += '#ifndef vl_api_version\n'
350
351 for i in imports:
352 s = i.filename.replace('plugins/', '')
353 output += '#include <{}.h>\n'.format(s)
354 output += '#endif\n'
Ole Troan9d420872017-10-12 13:06:35 +0200355 return output
356
357
358endian_strings = {
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_u16',
363 'i32': 'clib_net_to_host_u32',
364 'i64': 'clib_net_to_host_u64',
Paul Vinciguerra07f87542019-07-30 18:24:41 -0400365 'f64': 'clib_net_to_host_u64',
Ole Troan9d420872017-10-12 13:06:35 +0200366}
367
368
Ole Troan33a58172019-09-04 09:12:29 +0200369def endianfun_array(o):
370 forloop = '''\
371 for (i = 0; i < {length}; i++) {{
372 a->{name}[i] = {format}(a->{name}[i]);
373 }}
374'''
375
376 forloop_format = '''\
377 for (i = 0; i < {length}; i++) {{
378 {type}_endian(&a->{name}[i]);
379 }}
380'''
381
382 output = ''
383 if o.fieldtype == 'u8' or o.fieldtype == 'string':
384 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
385 else:
386 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
387 if o.fieldtype in endian_strings:
388 output += (forloop
389 .format(length=lfield,
390 format=endian_strings[o.fieldtype],
391 name=o.fieldname))
392 else:
393 output += (forloop_format
394 .format(length=lfield, type=o.fieldtype,
395 name=o.fieldname))
396 return output
397
398
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
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))
414 else:
415 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
416
417 return output
418
419
Ole Troan75761b92019-09-11 17:49:08 +0200420def endianfun(objs, modulename):
Ole Troan9d420872017-10-12 13:06:35 +0200421 output = '''\
422
423/****** Endian swap functions *****/\n\
424#ifdef vl_endianfun
Ole Troan33a58172019-09-04 09:12:29 +0200425#ifndef included_{module}_endianfun
426#define included_{module}_endianfun
Ole Troan9d420872017-10-12 13:06:35 +0200427
428#undef clib_net_to_host_uword
429#ifdef LP64
430#define clib_net_to_host_uword clib_net_to_host_u64
431#else
432#define clib_net_to_host_uword clib_net_to_host_u32
433#endif
434
435'''
Ole Troan33a58172019-09-04 09:12:29 +0200436 output = output.format(module=modulename)
437
438 signature = '''\
439static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
440{{
441 int i __attribute__((unused));
442'''
443
Ole Troan2c2feab2018-04-24 00:02:37 -0400444 for t in objs:
445 if t.__class__.__name__ == 'Enum':
Ole Troan33a58172019-09-04 09:12:29 +0200446 output += signature.format(name=t.name)
447 if t.enumtype in endian_strings:
448 output += (' *a = {}(*a);\n'
449 .format(endian_strings[t.enumtype]))
450 else:
451 output += (' /* a->{name} = a->{name} (no-op) */\n'
452 .format(name=t.name))
453
454 output += '}\n\n'
Ole Troan2c2feab2018-04-24 00:02:37 -0400455 continue
Ole Troan33a58172019-09-04 09:12:29 +0200456
Ole Troan9d420872017-10-12 13:06:35 +0200457 if t.manual_endian:
458 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
459 continue
Ole Troan33a58172019-09-04 09:12:29 +0200460
Ole Troan75761b92019-09-11 17:49:08 +0200461
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']]))
471 else:
472 output += ' /* Not Implemented yet {} */'.format(t.name)
473 output += '}\n\n'
474 continue
475
Ole Troan33a58172019-09-04 09:12:29 +0200476 output += signature.format(name=t.name)
Ole Troan9d420872017-10-12 13:06:35 +0200477
478 for o in t.block:
Ole Troan33a58172019-09-04 09:12:29 +0200479 output += endianfun_obj(o)
Ole Troan9d420872017-10-12 13:06:35 +0200480 output += '}\n\n'
Ole Troan33a58172019-09-04 09:12:29 +0200481
482 output += "\n#endif"
Ole Troan9d420872017-10-12 13:06:35 +0200483 output += "\n#endif /* vl_endianfun */\n\n"
484
485 return output
486
487
488def version_tuple(s, module):
489 output = '''\
490/****** Version tuple *****/
491
492#ifdef vl_api_version_tuple
493
494'''
Ole Troan2c2feab2018-04-24 00:02:37 -0400495 if 'version' in s['Option']:
496 v = s['Option']['version']
Ole Troan9d420872017-10-12 13:06:35 +0200497 (major, minor, patch) = v.split('.')
498 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
499 (module, major, minor, patch)
500
501 output += "\n#endif /* vl_api_version_tuple */\n\n"
502
503 return output
504
505
Ole Troan2a1ca782019-09-19 01:08:30 +0200506def generate_include_enum(s, module, stream):
507 write = stream.write
508
509 if len(s['Define']):
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))
515
516#
517# Generate separate API _types file.
518#
519def generate_include_types(s, module, stream):
520 write = stream.write
521
522 write('#ifndef included_{module}_api_types_h\n'.format(module=module))
523 write('#define included_{module}_api_types_h\n'.format(module=module))
524
525 if len(s['Import']):
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))
530
531 for o in s['types'] + s['Define']:
532 tname = o.__class__.__name__
533 if tname == 'Using':
534 if 'length' in o.alias:
535 write('typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length']))
536 else:
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")
541 else:
542 write("typedef enum __attribute__((packed)) {\n")
543
544 for b in o.block:
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))
553 else:
554 if tname == 'Union':
555 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
556 else:
557 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
558 % o.name)
559 for b in o.block:
560 if b.type == 'Option':
561 continue
562 if b.type == 'Field':
563 write(" %s %s;\n" % (api2c(b.fieldtype),
564 b.fieldname))
565 elif b.type == 'Array':
566 if b.lengthfield:
567 write(" %s %s[0];\n" % (api2c(b.fieldtype),
568 b.fieldname))
569 else:
570 # Fixed length strings decay to nul terminated u8
571 if b.fieldtype == 'string':
572 if b.modern_vla:
573 write(' {} {};\n'
574 .format(api2c(b.fieldtype),
575 b.fieldname))
576 else:
577 write(' u8 {}[{}];\n'
578 .format(b.fieldname, b.length))
579 else:
580 write(" %s %s[%s];\n" %
581 (api2c(b.fieldtype), b.fieldname,
582 b.length))
583 else:
584 raise ValueError("Error in processing type {} for {}"
585 .format(b, o.name))
586
587 write('} vl_api_%s_t;\n' % o.name)
588
589 write("\n#endif\n")
590
591
592def generate_c_boilerplate(services, defines, file_crc, module, stream):
593 write = stream.write
594
595 hdr = '''\
596#define vl_endianfun /* define message structures */
597#include "{module}.api.h"
598#undef vl_endianfun
599
600/* instantiate all the print functions we know about */
601#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
602#define vl_printfun
603#include "{module}.api.h"
604#undef vl_printfun
605
606'''
607
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))
614
615
616 for d in defines:
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))
620 for s in services:
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()))
626
627 write(' return msg_id_base;\n')
628 write('}\n')
629
630
631def generate_c_test_plugin_boilerplate(services, defines, file_crc, module, stream):
632 write = stream.write
633
634 define_hash = {d.name:d for d in defines}
635 replies = {}
636
637 hdr = '''\
638#define vl_endianfun /* define message structures */
639#include "{module}.api.h"
640#undef vl_endianfun
641
642/* instantiate all the print functions we know about */
643#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
644#define vl_printfun
645#include "{module}.api.h"
646#undef vl_printfun
647
648'''
649
650 write(hdr.format(module=module))
651 for s in services:
652 try:
653 d = define_hash[s.reply]
654 except:
655 continue
656 if d.manual_print:
657 write('/* Manual definition requested for: vl_api_{n}_t_hander() */\n'
658 .format(n=s.reply))
659 continue
660 if not define_hash[s.caller].autoreply:
661 write('/* Only autoreply is supported (vl_api_{n}_t_hander()) */\n'
662 .format(n=s.reply))
663 continue
664 write('static void\n')
665 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
666 write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
667 write(' i32 retval = ntohl(mp->retval);\n')
668 write(' if (vam->async_mode) {\n')
669 write(' vam->async_errors += (retval < 0);\n')
670 write(' } else {\n')
671 write(' vam->retval = retval;\n')
672 write(' vam->result_ready = 1;\n')
673 write(' }\n')
674 write('}\n')
675
676 write('static void\n')
677 write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
678 for s in services:
679 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
680 ' vl_api_{n}_t_handler, vl_noop_handler,\n'
681 ' vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
682 ' sizeof(vl_api_{n}_t), 1);\n'
683 .format(n=s.reply, ID=s.reply.upper()))
684 write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
685 try:
686 write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
687 .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
688 except:
689 pass
690
691 write('}\n')
692
693 write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
694 write('{\n')
695 write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
696 write(' mainp->vat_main = vam;\n')
697 write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
698 .format(n=module, crc=file_crc))
699 write(' if (mainp->msg_id_base == (u16) ~0)\n')
700 write(' return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
701 write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
702 write(' return 0;\n')
703 write('}\n')
704
705
Ole Troan9d420872017-10-12 13:06:35 +0200706#
707# Plugin entry point
708#
Ole Troan2a1ca782019-09-19 01:08:30 +0200709def run(args, input_filename, s):
Ole Troan33a58172019-09-04 09:12:29 +0200710 stream = StringIO()
Ole Troan2a1ca782019-09-19 01:08:30 +0200711
712 if not args.outputdir:
713 sys.stderr.write('Missing --outputdir argument')
714 return None
715
Ole Troan9d420872017-10-12 13:06:35 +0200716 basename = os.path.basename(input_filename)
717 filename, file_extension = os.path.splitext(basename)
Ole Troan33a58172019-09-04 09:12:29 +0200718 modulename = filename.replace('.', '_')
Ole Troan2a1ca782019-09-19 01:08:30 +0200719 filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
720 filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
721 filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
722 filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
723
724 # Generate separate types file
725 st = StringIO()
726 generate_include_types(s, modulename, st)
727 with open (filename_types, 'w') as fd:
728 st.seek (0)
729 shutil.copyfileobj (st, fd)
730 st.close()
731
732 # Generate separate enum file
733 st = StringIO()
734 generate_include_enum(s, modulename, st)
735 with open (filename_enum, 'w') as fd:
736 st.seek (0)
737 shutil.copyfileobj (st, fd)
738 st.close()
739
740 # Generate separate C file
741 st = StringIO()
742 generate_c_boilerplate(s['Service'], s['Define'], s['file_crc'],
743 modulename, st)
744 with open (filename_c, 'w') as fd:
745 st.seek (0)
746 shutil.copyfileobj(st, fd)
747 st.close()
748
749 # Generate separate C test file
750 # This is only supported for plugins at the moment
751 st = StringIO()
752 generate_c_test_plugin_boilerplate(s['Service'], s['Define'], s['file_crc'],
753 modulename, st)
754 with open (filename_c_test, 'w') as fd:
755 st.seek (0)
756 shutil.copyfileobj(st, fd)
757 st.close()
Ole Troan33a58172019-09-04 09:12:29 +0200758
Ole Troan9d420872017-10-12 13:06:35 +0200759 output = top_boilerplate.format(datestring=datestring,
760 input_filename=basename)
Ole Troan33a58172019-09-04 09:12:29 +0200761 output += imports(s['Import'])
Ole Troan9d420872017-10-12 13:06:35 +0200762 output += msg_ids(s)
763 output += msg_names(s)
764 output += msg_name_crc_list(s, filename)
Ole Troan2a1ca782019-09-19 01:08:30 +0200765 output += typedefs(modulename)
Ole Troan75761b92019-09-11 17:49:08 +0200766 printfun_types(s['types'], stream, modulename)
Ole Troan33a58172019-09-04 09:12:29 +0200767 printfun(s['Define'], stream, modulename)
768 output += stream.getvalue()
Ole Troan2a1ca782019-09-19 01:08:30 +0200769 stream.close()
Ole Troan75761b92019-09-11 17:49:08 +0200770 output += endianfun(s['types'] + s['Define'], modulename)
Ole Troan9d420872017-10-12 13:06:35 +0200771 output += version_tuple(s, basename)
772 output += bottom_boilerplate.format(input_filename=basename,
Ole Troan8dbfb432019-04-24 14:31:18 +0200773 file_crc=s['file_crc'])
Ole Troan9d420872017-10-12 13:06:35 +0200774
775 return output