acl: remove api boilerplate
[vpp.git] / src / tools / vppapigen / vppapigen_c.py
1 # C generation
2 import datetime
3 import os
4 import time
5 import sys
6 from io import StringIO
7 import shutil
8
9 datestring = datetime.datetime.utcfromtimestamp(
10     int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
11 input_filename = 'inputfil'
12 top_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
19 #include <stdbool.h>
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 */
26 #else
27 #warning no content included from {input_filename}
28 #endif
29
30 #define VL_API_PACKED(x) x __attribute__ ((packed))
31 '''
32
33 bottom_boilerplate = '''\
34 /****** API CRC (whole file) *****/
35
36 #ifdef vl_api_version
37 vl_api_version({input_filename}, {file_crc:#08x})
38
39 #endif
40 '''
41
42
43 def msg_ids(s):
44     output = '''\
45
46 /****** Message ID / handler enum ******/
47
48 #ifdef vl_msg_id
49 '''
50
51     for t in s['Define']:
52         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
59 def msg_names(s):
60     output = '''\
61
62 /****** Message names ******/
63
64 #ifdef vl_msg_name
65 '''
66
67     for t in s['Define']:
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)
70     output += "#endif"
71
72     return output
73
74
75 def 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
84     for t in s['Define']:
85         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
92 def api2c(fieldtype):
93     mappingtable = {'string': 'vl_api_string_t', }
94     if fieldtype in mappingtable:
95         return mappingtable[fieldtype]
96     return fieldtype
97
98
99 def typedefs(filename):
100
101     output = '''\
102
103 /****** Typedefs ******/
104
105 #ifdef vl_typedefs
106 #include "{include}.api_types.h"
107 #endif
108 '''.format(include=filename)
109     return output
110
111
112 format_strings = {'u8': '%u',
113                   'bool': '%u',
114                   'i8': '%d',
115                   'u16': '%u',
116                   'i16': '%d',
117                   'u32': '%u',
118                   'i32': '%ld',
119                   'u64': '%llu',
120                   'i64': '%llu',
121                   'f64': '%.2f'}
122
123 noprint_fields = {'_vl_msg_id': None,
124                   'client_index': None,
125                   'context': None}
126
127
128 class 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:
220             write('    return format(s, "{} (print not implemented)");\n'
221                   .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
243 def printfun(objs, stream, modulename):
244     write = stream.write
245
246     h = '''\
247 /****** Print functions *****/
248 #ifdef vl_printfun
249 #ifndef included_{module}_printfun
250 #define included_{module}_printfun
251
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 '''
261
262     signature = '''\
263 static 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
295 def printfun_types(objs, stream, modulename):
296     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 = '''\
310 static 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
318     for t in objs:
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')
323             write('}\n\n')
324             continue
325
326         if t.manual_print:
327             write("/***** manual: vl_api_%s_t_print  *****/\n\n" % t.name)
328             continue
329
330         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
336         write(signature.format(name=t.name))
337         for o in t.block:
338             pp.print_obj(o, stream)
339
340         write('    return s;\n')
341         write('}\n\n')
342
343     write("\n#endif")
344     write("\n#endif /* vl_printfun_types */\n")
345
346
347 def 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'
355     return output
356
357
358 endian_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',
365     'f64': 'clib_net_to_host_u64',
366 }
367
368
369 def 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
399 def 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
420 def endianfun(objs, modulename):
421     output = '''\
422
423 /****** Endian swap functions *****/\n\
424 #ifdef vl_endianfun
425 #ifndef included_{module}_endianfun
426 #define included_{module}_endianfun
427
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 '''
436     output = output.format(module=modulename)
437
438     signature = '''\
439 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
440 {{
441     int i __attribute__((unused));
442 '''
443
444     for t in objs:
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]))
450             else:
451                 output += ('    /* a->{name} = a->{name} (no-op) */\n'
452                            .format(name=t.name))
453
454             output += '}\n\n'
455             continue
456
457         if t.manual_endian:
458             output += "/***** manual: vl_api_%s_t_endian  *****/\n\n" % t.name
459             continue
460
461
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
476         output += signature.format(name=t.name)
477
478         for o in t.block:
479             output += endianfun_obj(o)
480         output += '}\n\n'
481
482     output += "\n#endif"
483     output += "\n#endif /* vl_endianfun */\n\n"
484
485     return output
486
487
488 def version_tuple(s, module):
489     output = '''\
490 /****** Version tuple *****/
491
492 #ifdef vl_api_version_tuple
493
494 '''
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)
500
501     output += "\n#endif /* vl_api_version_tuple */\n\n"
502
503     return output
504
505
506 def 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 #
519 def 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
592 def 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
631 def 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('#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')
671         write('   } else {\n')
672         write('      vam->retval = retval;\n')
673         write('      vam->result_ready = 1;\n')
674         write('   }\n')
675         write('}\n')
676         write('#endif\n')
677
678         for e in s.events:
679             if define_hash[e].manual_print:
680                 continue
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))
685             write('}\n')
686
687     write('static void\n')
688     write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
689     for s in services:
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))
696         try:
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']))
699         except:
700             pass
701
702         # Events
703         for e in s.events:
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()))
709
710     write('}\n')
711
712     write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
713     write('{\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')
723     write('#endif\n')
724     write('   return 0;\n')
725     write('}\n')
726
727
728 #
729 # Plugin entry point
730 #
731 def run(args, input_filename, s):
732     stream = StringIO()
733
734     if not args.outputdir:
735         sys.stderr.write('Missing --outputdir argument')
736         return None
737
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')
745
746     # Generate separate types file
747     st = StringIO()
748     generate_include_types(s, modulename, st)
749     with open (filename_types, 'w') as fd:
750         st.seek (0)
751         shutil.copyfileobj (st, fd)
752     st.close()
753
754     # Generate separate enum file
755     st = StringIO()
756     generate_include_enum(s, modulename, st)
757     with open (filename_enum, 'w') as fd:
758         st.seek (0)
759         shutil.copyfileobj (st, fd)
760     st.close()
761
762     # Generate separate C file
763     st = StringIO()
764     generate_c_boilerplate(s['Service'], s['Define'], s['file_crc'],
765                            modulename, st)
766     with open (filename_c, 'w') as fd:
767         st.seek (0)
768         shutil.copyfileobj(st, fd)
769     st.close()
770
771     # Generate separate C test file
772     # This is only supported for plugins at the moment
773     st = StringIO()
774     generate_c_test_plugin_boilerplate(s['Service'], s['Define'], s['file_crc'],
775                                        modulename, st)
776     with open (filename_c_test, 'w') as fd:
777         st.seek (0)
778         shutil.copyfileobj(st, fd)
779     st.close()
780
781     output = top_boilerplate.format(datestring=datestring,
782                                     input_filename=basename)
783     output += imports(s['Import'])
784     output += msg_ids(s)
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()
791     stream.close()
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'])
796
797     return output