api: multiple connections per process
[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': '%lld',
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_i16',
363     'i32': 'clib_net_to_host_i32',
364     'i64': 'clib_net_to_host_i64',
365     'f64': 'clib_net_to_host_f64',
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         if t.__class__.__name__ == 'Using':
462             output += signature.format(name=t.name)
463             if ('length' in t.alias and t.alias['length'] and
464                     t.alias['type'] == 'u8'):
465                 output += ('    /* a->{name} = a->{name} (no-op) */\n'
466                            .format(name=t.name))
467             elif t.alias['type'] in format_strings:
468                 output += ('    *a = {}(*a);\n'
469                            .format(endian_strings[t.alias['type']]))
470             else:
471                 output += '    /* Not Implemented yet {} */'.format(t.name)
472             output += '}\n\n'
473             continue
474
475         output += signature.format(name=t.name)
476
477         for o in t.block:
478             output += endianfun_obj(o)
479         output += '}\n\n'
480
481     output += "\n#endif"
482     output += "\n#endif /* vl_endianfun */\n\n"
483
484     return output
485
486
487 def version_tuple(s, module):
488     output = '''\
489 /****** Version tuple *****/
490
491 #ifdef vl_api_version_tuple
492
493 '''
494     if 'version' in s['Option']:
495         v = s['Option']['version']
496         (major, minor, patch) = v.split('.')
497         output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
498                   (module, major, minor, patch)
499
500     output += "\n#endif /* vl_api_version_tuple */\n\n"
501
502     return output
503
504
505 def generate_include_enum(s, module, stream):
506     write = stream.write
507
508     if len(s['Define']):
509         write('typedef enum {\n')
510         for t in s['Define']:
511             write('   VL_API_{},\n'.format(t.name.upper()))
512         write('   VL_MSG_FIRST_AVAILABLE\n')
513         write('}} vl_api_{}_enum_t;\n'.format(module))
514
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     for t in s['Define']:
590         write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
591               .format(n=t.name, ID=t.name.upper(), crc=t.crc))
592
593     write("\n#endif\n")
594
595
596 def generate_c_boilerplate(services, defines, file_crc, module, stream):
597     write = stream.write
598
599     hdr = '''\
600 #define vl_endianfun            /* define message structures */
601 #include "{module}.api.h"
602 #undef vl_endianfun
603
604 /* instantiate all the print functions we know about */
605 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
606 #define vl_printfun
607 #include "{module}.api.h"
608 #undef vl_printfun
609
610 '''
611
612     write(hdr.format(module=module))
613     write('static u16\n')
614     write('setup_message_id_table (void) {\n')
615     write('   api_main_t *am = my_api_main;\n')
616     write('   u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", VL_MSG_FIRST_AVAILABLE);\n'
617           .format(module, crc=file_crc))
618
619
620     for d in defines:
621         write('   vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
622               '                                VL_API_{ID} + msg_id_base);\n'
623               .format(n=d.name, ID=d.name.upper(), crc=d.crc))
624     for s in services:
625         write('   vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
626               '                           vl_api_{n}_t_handler, vl_noop_handler,\n'
627               '                           vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
628               '                           sizeof(vl_api_{n}_t), 1);\n'
629               .format(n=s.caller, ID=s.caller.upper()))
630
631     write('   return msg_id_base;\n')
632     write('}\n')
633
634
635 def generate_c_test_plugin_boilerplate(services, defines, file_crc, module, stream):
636     write = stream.write
637
638     define_hash = {d.name:d for d in defines}
639     replies = {}
640
641     hdr = '''\
642 #define vl_endianfun            /* define message structures */
643 #include "{module}.api.h"
644 #undef vl_endianfun
645
646 /* instantiate all the print functions we know about */
647 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
648 #define vl_printfun
649 #include "{module}.api.h"
650 #undef vl_printfun
651
652 '''
653
654     write(hdr.format(module=module))
655     for s in services:
656         try:
657             d = define_hash[s.reply]
658         except:
659             continue
660         if d.manual_print:
661             write('/* Manual definition requested for: vl_api_{n}_t_handler() */\n'
662                   .format(n=s.reply))
663             continue
664         if not define_hash[s.caller].autoreply:
665             write('/* Only autoreply is supported (vl_api_{n}_t_handler()) */\n'
666                   .format(n=s.reply))
667             continue
668         write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
669         write('static void\n')
670         write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
671         write('   vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
672         write('   i32 retval = ntohl(mp->retval);\n')
673         write('   if (vam->async_mode) {\n')
674         write('      vam->async_errors += (retval < 0);\n')
675         write('   } else {\n')
676         write('      vam->retval = retval;\n')
677         write('      vam->result_ready = 1;\n')
678         write('   }\n')
679         write('}\n')
680         write('#endif\n')
681
682         for e in s.events:
683             if define_hash[e].manual_print:
684                 continue
685             write('static void\n')
686             write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
687             write('    vl_print(0, "{n} event called:");\n'.format(n=e))
688             write('    vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
689             write('}\n')
690
691     write('static void\n')
692     write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
693     for s in services:
694         write('   vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
695               '                           vl_api_{n}_t_handler, vl_noop_handler,\n'
696               '                           vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
697               '                           sizeof(vl_api_{n}_t), 1);\n'
698               .format(n=s.reply, ID=s.reply.upper()))
699         write('   hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
700         try:
701             write('   hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
702                   .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
703         except:
704             pass
705
706         # Events
707         for e in s.events:
708             write('   vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
709                   '                           vl_api_{n}_t_handler, vl_noop_handler,\n'
710                   '                           vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
711                   '                           sizeof(vl_api_{n}_t), 1);\n'
712                   .format(n=e, ID=e.upper()))
713
714     write('}\n')
715
716     write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
717     write('{\n')
718     write('   {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
719     write('   mainp->vat_main = vam;\n')
720     write('   mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
721           .format(n=module, crc=file_crc))
722     write('   if (mainp->msg_id_base == (u16) ~0)\n')
723     write('      return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
724     write('   setup_message_id_table (vam, mainp->msg_id_base);\n')
725     write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
726     write('    VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
727     write('#endif\n')
728     write('   return 0;\n')
729     write('}\n')
730
731
732 #
733 # Plugin entry point
734 #
735 def run(args, input_filename, s):
736     stream = StringIO()
737
738     if not args.outputdir:
739         sys.stderr.write('Missing --outputdir argument')
740         return None
741
742     basename = os.path.basename(input_filename)
743     filename, file_extension = os.path.splitext(basename)
744     modulename = filename.replace('.', '_')
745     filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
746     filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
747     filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
748     filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
749
750     # Generate separate types file
751     st = StringIO()
752     generate_include_types(s, modulename, st)
753     with open (filename_types, 'w') as fd:
754         st.seek (0)
755         shutil.copyfileobj (st, fd)
756     st.close()
757
758     # Generate separate enum file
759     st = StringIO()
760     generate_include_enum(s, modulename, st)
761     with open (filename_enum, 'w') as fd:
762         st.seek (0)
763         shutil.copyfileobj (st, fd)
764     st.close()
765
766     # Generate separate C file
767     st = StringIO()
768     generate_c_boilerplate(s['Service'], s['Define'], s['file_crc'],
769                            modulename, st)
770     with open (filename_c, 'w') as fd:
771         st.seek (0)
772         shutil.copyfileobj(st, fd)
773     st.close()
774
775     # Generate separate C test file
776     # This is only supported for plugins at the moment
777     st = StringIO()
778     generate_c_test_plugin_boilerplate(s['Service'], s['Define'], s['file_crc'],
779                                        modulename, st)
780     with open (filename_c_test, 'w') as fd:
781         st.seek (0)
782         shutil.copyfileobj(st, fd)
783     st.close()
784
785     output = top_boilerplate.format(datestring=datestring,
786                                     input_filename=basename)
787     output += imports(s['Import'])
788     output += msg_ids(s)
789     output += msg_names(s)
790     output += msg_name_crc_list(s, filename)
791     output += typedefs(modulename)
792     printfun_types(s['types'], stream, modulename)
793     printfun(s['Define'], stream, modulename)
794     output += stream.getvalue()
795     stream.close()
796     output += endianfun(s['types'] + s['Define'], modulename)
797     output += version_tuple(s, basename)
798     output += bottom_boilerplate.format(input_filename=basename,
799                                         file_crc=s['file_crc'])
800
801     return output