blob: 9a285eb98ad5525655b127c663b24f21cfee99ba [file] [log] [blame]
Klement Sekera958b7502017-09-28 06:31:53 +02001#!/usr/bin/env python2
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02002
3import argparse
4import os
5import sys
6import logging
Klement Sekera2108c0c2018-08-24 11:43:20 +02007from vapi_json_parser import Field, Struct, Enum, Union, Message, JsonParser,\
Ole Troan53fffa12018-11-13 12:36:56 +01008 SimpleType, StructType, Alias
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02009
10
11class CField(Field):
Ole Troan53fffa12018-11-13 12:36:56 +010012 def get_c_name(self):
Ole Troan8c8acc02018-11-27 10:05:23 +010013 return "vapi_type_%s" % self.name
Ole Troan53fffa12018-11-13 12:36:56 +010014
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020015 def get_c_def(self):
Ole Troane5ff5a32019-08-23 22:55:18 +020016 if self.type.get_c_name() == 'vl_api_string_t':
17 if self.len:
18 return "u8 %s[%d];" % (self.name, self.len)
19 else:
20 return "vl_api_string_t %s;" % (self.name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020021 else:
Ole Troane5ff5a32019-08-23 22:55:18 +020022 if self.len is not None:
23 return "%s %s[%d];" % (self.type.get_c_name(), self.name, self.len)
24 else:
25 return "%s %s;" % (self.type.get_c_name(), self.name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020026
27 def get_swap_to_be_code(self, struct, var):
28 if self.len is not None:
29 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020030 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020031 " while(0);" % (
32 self.len,
33 self.type.get_swap_to_be_code(struct, "%s[i]" % var))
34 else:
35 if self.nelem_field.needs_byte_swap():
36 nelem_field = "%s(%s%s)" % (
37 self.nelem_field.type.get_swap_to_host_func_name(),
38 struct, self.nelem_field.name)
39 else:
40 nelem_field = "%s%s" % (struct, self.nelem_field.name)
41 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020042 "do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020043 " while(0);" %
44 (nelem_field, self.type.get_swap_to_be_code(
45 struct, "%s[i]" % var)))
46 return self.type.get_swap_to_be_code(struct, "%s" % var)
47
48 def get_swap_to_host_code(self, struct, var):
49 if self.len is not None:
50 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020051 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020052 " while(0);" % (
53 self.len,
54 self.type.get_swap_to_host_code(struct, "%s[i]" % var))
55 else:
56 # nelem_field already swapped to host here...
57 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020058 "do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020059 " while(0);" %
60 (struct, self.nelem_field.name,
61 self.type.get_swap_to_host_code(
62 struct, "%s[i]" % var)))
63 return self.type.get_swap_to_host_code(struct, "%s" % var)
64
65 def needs_byte_swap(self):
66 return self.type.needs_byte_swap()
67
Klement Sekera34a962b2018-09-06 19:31:36 +020068 def get_vla_field_length_name(self, path):
69 return "%s_%s_array_size" % ("_".join(path), self.name)
70
71 def get_alloc_vla_param_names(self, path):
72 if self.is_vla():
73 result = [self.get_vla_field_length_name(path)]
74 else:
75 result = []
76 if self.type.has_vla():
77 t = self.type.get_alloc_vla_param_names(path + [self.name])
78 result.extend(t)
79 return result
80
81 def get_vla_calc_size_code(self, prefix, path):
82 if self.is_vla():
83 result = ["sizeof(%s.%s[0]) * %s" % (
84 ".".join([prefix] + path),
85 self.name,
86 self.get_vla_field_length_name(path))]
87 else:
88 result = []
89 if self.type.has_vla():
90 t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
91 result.extend(t)
92 return result
93
94 def get_vla_assign_code(self, prefix, path):
95 result = []
96 if self.is_vla():
97 result.append("%s.%s = %s" % (
98 ".".join([prefix] + path),
99 self.nelem_field.name,
100 self.get_vla_field_length_name(path)))
101 if self.type.has_vla():
102 t = self.type.get_vla_assign_code(prefix, path + [self.name])
103 result.extend(t)
104 return result
105
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200106
Ole Troan53fffa12018-11-13 12:36:56 +0100107class CAlias(CField):
108 def get_c_name(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100109 return "vapi_type_%s" % self.name
Ole Troan53fffa12018-11-13 12:36:56 +0100110
111 def get_c_def(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100112 if self.len is not None:
Klement Sekera173e20c2018-12-12 12:57:32 +0100113 return "typedef %s vapi_type_%s[%d];" % (
114 self.type.get_c_name(), self.name, self.len)
Ole Troan8c8acc02018-11-27 10:05:23 +0100115 else:
Klement Sekera173e20c2018-12-12 12:57:32 +0100116 return "typedef %s vapi_type_%s;" % (
117 self.type.get_c_name(), self.name)
Ole Troan53fffa12018-11-13 12:36:56 +0100118
119
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200120class CStruct(Struct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200121 def get_c_def(self):
122 return "\n".join([
Ole Troan53fffa12018-11-13 12:36:56 +0100123 "typedef struct __attribute__((__packed__)) {\n%s" % (
124 "\n".join([" %s" % x.get_c_def()
125 for x in self.fields])),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200126 "} %s;" % self.get_c_name()])
127
Klement Sekera34a962b2018-09-06 19:31:36 +0200128 def get_vla_assign_code(self, prefix, path):
129 return [x for f in self.fields if f.has_vla()
130 for x in f.get_vla_assign_code(prefix, path)]
131
132 def get_alloc_vla_param_names(self, path):
133 return [x for f in self.fields
134 if f.has_vla()
135 for x in f.get_alloc_vla_param_names(path)]
136
137 def get_vla_calc_size_code(self, prefix, path):
138 return [x for f in self.fields if f.has_vla()
139 for x in f.get_vla_calc_size_code(prefix, path)]
140
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200141
142class CSimpleType (SimpleType):
143
144 swap_to_be_dict = {
145 'i16': 'htobe16', 'u16': 'htobe16',
146 'i32': 'htobe32', 'u32': 'htobe32',
147 'i64': 'htobe64', 'u64': 'htobe64',
148 }
149
150 swap_to_host_dict = {
151 'i16': 'be16toh', 'u16': 'be16toh',
152 'i32': 'be32toh', 'u32': 'be32toh',
153 'i64': 'be64toh', 'u64': 'be64toh',
154 }
155
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200156 def get_c_name(self):
157 return self.name
158
159 def get_swap_to_be_func_name(self):
160 return self.swap_to_be_dict[self.name]
161
162 def get_swap_to_host_func_name(self):
163 return self.swap_to_host_dict[self.name]
164
Klement Sekera2108c0c2018-08-24 11:43:20 +0200165 def get_swap_to_be_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200166 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200167 return "%s = %s%s(%s);" % (x,
168 "(%s)" % cast if cast else "",
169 self.get_swap_to_be_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200170
Klement Sekera2108c0c2018-08-24 11:43:20 +0200171 def get_swap_to_host_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200172 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200173 return "%s = %s%s(%s);" % (x,
174 "(%s)" % cast if cast else "",
175 self.get_swap_to_host_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200176
177 def needs_byte_swap(self):
178 try:
179 self.get_swap_to_host_func_name()
180 return True
Ole Troan53fffa12018-11-13 12:36:56 +0100181 except KeyError:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200182 pass
183 return False
184
185
Klement Sekera2108c0c2018-08-24 11:43:20 +0200186class CEnum(Enum):
187 def get_c_name(self):
188 return "vapi_enum_%s" % self.name
189
190 def get_c_def(self):
191 return "typedef enum {\n%s\n} %s;" % (
192 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
193 self.get_c_name()
194 )
195
196 def needs_byte_swap(self):
197 return self.type.needs_byte_swap()
198
199 def get_swap_to_be_code(self, struct, var):
200 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
201
202 def get_swap_to_host_code(self, struct, var):
203 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
204
205
206class CUnion(Union):
207 def get_c_name(self):
208 return "vapi_union_%s" % self.name
209
210 def get_c_def(self):
211 return "typedef union {\n%s\n} %s;" % (
212 "\n".join([" %s %s;" % (i.get_c_name(), j)
213 for i, j in self.type_pairs]),
214 self.get_c_name()
215 )
216
217 def needs_byte_swap(self):
218 return False
219
220
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200221class CStructType (StructType, CStruct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200222 def get_c_name(self):
223 return "vapi_type_%s" % self.name
224
225 def get_swap_to_be_func_name(self):
226 return "%s_hton" % self.get_c_name()
227
228 def get_swap_to_host_func_name(self):
229 return "%s_ntoh" % self.get_c_name()
230
231 def get_swap_to_be_func_decl(self):
232 return "void %s(%s *msg)" % (
233 self.get_swap_to_be_func_name(), self.get_c_name())
234
235 def get_swap_to_be_func_def(self):
236 return "%s\n{\n%s\n}" % (
237 self.get_swap_to_be_func_decl(),
238 "\n".join([
239 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
240 for p in self.fields if p.needs_byte_swap()]),
241 )
242
243 def get_swap_to_host_func_decl(self):
244 return "void %s(%s *msg)" % (
245 self.get_swap_to_host_func_name(), self.get_c_name())
246
247 def get_swap_to_host_func_def(self):
248 return "%s\n{\n%s\n}" % (
249 self.get_swap_to_host_func_decl(),
250 "\n".join([
251 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
252 for p in self.fields if p.needs_byte_swap()]),
253 )
254
255 def get_swap_to_be_code(self, struct, var):
256 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
257
258 def get_swap_to_host_code(self, struct, var):
259 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
260
261 def needs_byte_swap(self):
262 for f in self.fields:
263 if f.needs_byte_swap():
264 return True
265 return False
266
267
268class CMessage (Message):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200269 def __init__(self, logger, definition, json_parser):
270 super(CMessage, self).__init__(logger, definition, json_parser)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200271 self.payload_members = [
272 " %s" % p.get_c_def()
273 for p in self.fields
274 if p.type != self.header
275 ]
276
277 def has_payload(self):
278 return len(self.payload_members) > 0
279
280 def get_msg_id_name(self):
281 return "vapi_msg_id_%s" % self.name
282
283 def get_c_name(self):
284 return "vapi_msg_%s" % self.name
285
286 def get_payload_struct_name(self):
287 return "vapi_payload_%s" % self.name
288
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200289 def get_alloc_func_name(self):
290 return "vapi_alloc_%s" % self.name
291
Klement Sekeradc15be22017-06-12 06:49:33 +0200292 def get_alloc_vla_param_names(self):
Klement Sekera34a962b2018-09-06 19:31:36 +0200293 return [x for f in self.fields
294 if f.has_vla()
295 for x in f.get_alloc_vla_param_names([])]
Klement Sekeradc15be22017-06-12 06:49:33 +0200296
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200297 def get_alloc_func_decl(self):
298 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
299 self.get_c_name(),
300 self.get_alloc_func_name(),
Klement Sekeradc15be22017-06-12 06:49:33 +0200301 "".join([", size_t %s" % n for n in
302 self.get_alloc_vla_param_names()]))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200303
304 def get_alloc_func_def(self):
305 extra = []
306 if self.header.has_field('client_index'):
307 extra.append(
308 " msg->header.client_index = vapi_get_client_index(ctx);")
309 if self.header.has_field('context'):
310 extra.append(" msg->header.context = 0;")
311 return "\n".join([
312 "%s" % self.get_alloc_func_decl(),
313 "{",
314 " %s *msg = NULL;" % self.get_c_name(),
315 " const size_t size = sizeof(%s)%s;" % (
316 self.get_c_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200317 "".join([" + %s" % x for f in self.fields if f.has_vla()
318 for x in f.get_vla_calc_size_code("msg->payload",
319 [])])),
Klement Sekeradc15be22017-06-12 06:49:33 +0200320 " /* cast here required to play nicely with C++ world ... */",
321 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200322 " if (!msg) {",
323 " return NULL;",
324 " }",
325 ] + extra + [
326 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
327 self.get_msg_id_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200328 "".join([" %s;\n" % line
329 for f in self.fields if f.has_vla()
330 for line in f.get_vla_assign_code("msg->payload", [])]),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200331 " return msg;",
332 "}"])
333
334 def get_calc_msg_size_func_name(self):
335 return "vapi_calc_%s_msg_size" % self.name
336
337 def get_calc_msg_size_func_decl(self):
338 return "uword %s(%s *msg)" % (
339 self.get_calc_msg_size_func_name(),
340 self.get_c_name())
341
342 def get_calc_msg_size_func_def(self):
343 return "\n".join([
344 "%s" % self.get_calc_msg_size_func_decl(),
345 "{",
346 " return sizeof(*msg)%s;" %
347 "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
348 f.nelem_field.name,
349 f.name)
350 for f in self.fields
351 if f.nelem_field is not None
352 ]),
353 "}",
354 ])
355
356 def get_c_def(self):
357 if self.has_payload():
358 return "\n".join([
359 "typedef struct __attribute__ ((__packed__)) {",
Ole Troan53fffa12018-11-13 12:36:56 +0100360 "%s " %
361 "\n".join(self.payload_members),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200362 "} %s;" % self.get_payload_struct_name(),
363 "",
364 "typedef struct __attribute__ ((__packed__)) {",
365 (" %s %s;" % (self.header.get_c_name(),
366 self.fields[0].name)
367 if self.header is not None else ""),
368 " %s payload;" % self.get_payload_struct_name(),
369 "} %s;" % self.get_c_name(), ])
370 else:
371 return "\n".join([
372 "typedef struct __attribute__ ((__packed__)) {",
373 (" %s %s;" % (self.header.get_c_name(),
374 self.fields[0].name)
375 if self.header is not None else ""),
376 "} %s;" % self.get_c_name(), ])
377
378 def get_swap_payload_to_host_func_name(self):
379 return "%s_payload_ntoh" % self.get_c_name()
380
381 def get_swap_payload_to_be_func_name(self):
382 return "%s_payload_hton" % self.get_c_name()
383
384 def get_swap_payload_to_host_func_decl(self):
385 return "void %s(%s *payload)" % (
386 self.get_swap_payload_to_host_func_name(),
387 self.get_payload_struct_name())
388
389 def get_swap_payload_to_be_func_decl(self):
390 return "void %s(%s *payload)" % (
391 self.get_swap_payload_to_be_func_name(),
392 self.get_payload_struct_name())
393
394 def get_swap_payload_to_be_func_def(self):
395 return "%s\n{\n%s\n}" % (
396 self.get_swap_payload_to_be_func_decl(),
397 "\n".join([
398 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
399 for p in self.fields
400 if p.needs_byte_swap() and p.type != self.header]),
401 )
402
403 def get_swap_payload_to_host_func_def(self):
404 return "%s\n{\n%s\n}" % (
405 self.get_swap_payload_to_host_func_decl(),
406 "\n".join([
407 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
408 for p in self.fields
409 if p.needs_byte_swap() and p.type != self.header]),
410 )
411
412 def get_swap_to_host_func_name(self):
413 return "%s_ntoh" % self.get_c_name()
414
415 def get_swap_to_be_func_name(self):
416 return "%s_hton" % self.get_c_name()
417
418 def get_swap_to_host_func_decl(self):
419 return "void %s(%s *msg)" % (
420 self.get_swap_to_host_func_name(), self.get_c_name())
421
422 def get_swap_to_be_func_decl(self):
423 return "void %s(%s *msg)" % (
424 self.get_swap_to_be_func_name(), self.get_c_name())
425
426 def get_swap_to_be_func_def(self):
427 return "\n".join([
428 "%s" % self.get_swap_to_be_func_decl(),
429 "{",
430 (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
431 self.get_c_name()),
432 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
433 if self.header is not None else "",
434 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
435 if self.has_payload() else "",
436 "}",
437 ])
438
439 def get_swap_to_host_func_def(self):
440 return "\n".join([
441 "%s" % self.get_swap_to_host_func_decl(),
442 "{",
443 (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
444 self.get_c_name()),
445 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
446 if self.header is not None else "",
447 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
448 if self.has_payload() else "",
449 "}",
450 ])
451
452 def get_op_func_name(self):
453 return "vapi_%s" % self.name
454
455 def get_op_func_decl(self):
456 if self.reply.has_payload():
457 return "vapi_error_e %s(%s)" % (
458 self.get_op_func_name(),
459 ",\n ".join([
460 'struct vapi_ctx_s *ctx',
461 '%s *msg' % self.get_c_name(),
462 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
463 ' void *callback_ctx',
464 ' vapi_error_e rv',
465 ' bool is_last',
466 ' %s *reply)' %
467 self.reply.get_payload_struct_name(),
468 'void *callback_ctx',
469 ])
470 )
471 else:
472 return "vapi_error_e %s(%s)" % (
473 self.get_op_func_name(),
474 ",\n ".join([
475 'struct vapi_ctx_s *ctx',
476 '%s *msg' % self.get_c_name(),
477 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
478 ' void *callback_ctx',
479 ' vapi_error_e rv',
480 ' bool is_last)',
481 'void *callback_ctx',
482 ])
483 )
484
485 def get_op_func_def(self):
486 return "\n".join([
487 "%s" % self.get_op_func_decl(),
488 "{",
489 " if (!msg || !callback) {",
490 " return VAPI_EINVAL;",
491 " }",
492 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
493 " return VAPI_EAGAIN;",
494 " }",
495 " vapi_error_e rv;",
496 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
497 " return rv;",
498 " }",
499 " u32 req_context = vapi_gen_req_context(ctx);",
500 " msg->header.context = req_context;",
501 " %s(msg);" % self.get_swap_to_be_func_name(),
502 (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
503 "(ctx, msg, req_context))) {"
Klement Sekera2108c0c2018-08-24 11:43:20 +0200504 if self.reply_is_stream else
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200505 " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
506 ),
507 (" vapi_store_request(ctx, req_context, %s, "
508 "(vapi_cb_t)callback, callback_ctx);" %
Klement Sekera2108c0c2018-08-24 11:43:20 +0200509 ("true" if self.reply_is_stream else "false")),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200510 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
511 " abort (); /* this really shouldn't happen */",
512 " }",
513 " if (vapi_is_nonblocking(ctx)) {",
514 " rv = VAPI_OK;",
515 " } else {",
516 " rv = vapi_dispatch(ctx);",
517 " }",
518 " } else {",
519 " %s(msg);" % self.get_swap_to_host_func_name(),
520 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
521 " abort (); /* this really shouldn't happen */",
522 " }",
523 " }",
524 " return rv;",
525 "}",
526 "",
527 ])
528
529 def get_event_cb_func_decl(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200530 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200531 raise Exception(
Klement Sekeradc15be22017-06-12 06:49:33 +0200532 "Cannot register event callback for non-reply message")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200533 if self.has_payload():
534 return "\n".join([
535 "void vapi_set_%s_event_cb (" %
536 self.get_c_name(),
537 " struct vapi_ctx_s *ctx, ",
538 (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
539 "void *callback_ctx, %s *payload)," %
540 self.get_payload_struct_name()),
541 " void *callback_ctx)",
542 ])
543 else:
544 return "\n".join([
545 "void vapi_set_%s_event_cb (" %
546 self.get_c_name(),
547 " struct vapi_ctx_s *ctx, ",
548 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
549 "void *callback_ctx),",
550 " void *callback_ctx)",
551 ])
552
553 def get_event_cb_func_def(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200554 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200555 raise Exception(
556 "Cannot register event callback for non-reply function")
557 return "\n".join([
558 "%s" % self.get_event_cb_func_decl(),
559 "{",
560 (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
561 "callback_ctx);" %
562 self.get_msg_id_name()),
563 "}"])
564
565 def get_c_metadata_struct_name(self):
566 return "__vapi_metadata_%s" % self.name
567
568 def get_c_constructor(self):
569 has_context = False
570 if self.header is not None:
571 has_context = self.header.has_field('context')
572 return '\n'.join([
573 'static void __attribute__((constructor)) __vapi_constructor_%s()'
574 % self.name,
575 '{',
576 ' static const char name[] = "%s";' % self.name,
577 ' static const char name_with_crc[] = "%s_%s";'
578 % (self.name, self.crc[2:]),
579 ' static vapi_message_desc_t %s = {' %
580 self.get_c_metadata_struct_name(),
581 ' name,',
582 ' sizeof(name) - 1,',
583 ' name_with_crc,',
584 ' sizeof(name_with_crc) - 1,',
585 ' true,' if has_context else ' false,',
586 ' offsetof(%s, context),' % self.header.get_c_name()
587 if has_context else ' 0,',
588 (' offsetof(%s, payload),' % self.get_c_name())
Klement Sekeradab732a2018-07-04 13:43:46 +0200589 if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200590 ' sizeof(%s),' % self.get_c_name(),
591 ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
592 ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
Klement Sekeradab732a2018-07-04 13:43:46 +0200593 ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200594 ' };',
595 '',
596 ' %s = vapi_register_msg(&%s);' %
597 (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
598 ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
599 (self.name, self.get_msg_id_name()),
600 '}',
601 ])
602
603
604vapi_send_with_control_ping = """
605static inline vapi_error_e
606vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
607{
608 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
609 if (!ping)
610 {
611 return VAPI_ENOMEM;
612 }
613 ping->header.context = context;
614 vapi_msg_control_ping_hton (ping);
615 return vapi_send2 (ctx, msg, ping);
616}
617"""
618
619
Klement Sekera1732e472018-08-28 17:23:18 +0200620def emit_definition(parser, json_file, emitted, o):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200621 if o in emitted:
622 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200623 if o.name in ("msg_header1_t", "msg_header2_t"):
624 return
625 if hasattr(o, "depends"):
626 for x in o.depends:
Klement Sekera1732e472018-08-28 17:23:18 +0200627 emit_definition(parser, json_file, emitted, x)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200628 if hasattr(o, "reply"):
Klement Sekera1732e472018-08-28 17:23:18 +0200629 emit_definition(parser, json_file, emitted, o.reply)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200630 if hasattr(o, "get_c_def"):
631 if (o not in parser.enums_by_json[json_file] and
632 o not in parser.types_by_json[json_file] and
633 o not in parser.unions_by_json[json_file] and
Ole Troan53fffa12018-11-13 12:36:56 +0100634 o.name not in parser.messages_by_json[json_file] and
635 o not in parser.aliases_by_json[json_file]):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200636 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200637 guard = "defined_%s" % o.get_c_name()
638 print("#ifndef %s" % guard)
639 print("#define %s" % guard)
640 print("%s" % o.get_c_def())
641 print("")
642 function_attrs = "static inline "
643 if o.name in parser.messages_by_json[json_file]:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200644 if o.has_payload():
Klement Sekera2108c0c2018-08-24 11:43:20 +0200645 print("%s%s" % (function_attrs,
646 o.get_swap_payload_to_be_func_def()))
647 print("")
648 print("%s%s" % (function_attrs,
649 o.get_swap_payload_to_host_func_def()))
650 print("")
651 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
652 print("")
653 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
654 print("")
655 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200656 if not o.is_reply and not o.is_event:
Klement Sekera34a962b2018-09-06 19:31:36 +0200657 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200658 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
659 print("")
660 print("%s%s" % (function_attrs, o.get_op_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200661 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200662 print("%s" % o.get_c_constructor())
Klement Sekera1732e472018-08-28 17:23:18 +0200663 if o.is_reply or o.is_event:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200664 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200665 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200666 elif hasattr(o, "get_swap_to_be_func_def"):
667 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
668 print("")
669 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200670 print("#endif")
Klement Sekera34a962b2018-09-06 19:31:36 +0200671 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200672 emitted.append(o)
673
674
Klement Sekeradc15be22017-06-12 06:49:33 +0200675def gen_json_unified_header(parser, logger, j, io, name):
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200676 d, f = os.path.split(j)
Klement Sekeradc15be22017-06-12 06:49:33 +0200677 logger.info("Generating header `%s'" % name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200678 orig_stdout = sys.stdout
679 sys.stdout = io
680 include_guard = "__included_%s" % (
681 j.replace(".", "_").replace("/", "_").replace("-", "_"))
682 print("#ifndef %s" % include_guard)
683 print("#define %s" % include_guard)
684 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200685 print("#include <stdlib.h>")
686 print("#include <stddef.h>")
687 print("#include <arpa/inet.h>")
688 print("#include <vapi/vapi_internal.h>")
689 print("#include <vapi/vapi.h>")
690 print("#include <vapi/vapi_dbg.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200691 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200692 print("#ifdef __cplusplus")
693 print("extern \"C\" {")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200694 print("#endif")
Klement Sekeradc15be22017-06-12 06:49:33 +0200695 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200696 print("")
697 print("static inline vapi_error_e vapi_send_with_control_ping "
698 "(vapi_ctx_t ctx, void * msg, u32 context);")
699 else:
Klement Sekeradc15be22017-06-12 06:49:33 +0200700 print("#include <vapi/vpe.api.vapi.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200701 print("")
702 for m in parser.messages_by_json[j].values():
703 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
704 print("")
705 print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200706 f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200707 print("\\\n".join([
708 " vapi_msg_id_t %s;" % m.get_msg_id_name()
709 for m in parser.messages_by_json[j].values()
710 ]))
711 print("")
712 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200713 emitted = []
714 for e in parser.enums_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200715 emit_definition(parser, j, emitted, e)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200716 for u in parser.unions_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200717 emit_definition(parser, j, emitted, u)
Ole Troan52ca7562018-03-06 17:45:32 +0100718 for t in parser.types_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200719 emit_definition(parser, j, emitted, t)
Ole Troan75761b92019-09-11 17:49:08 +0200720 for a in parser.aliases_by_json[j]:
721 emit_definition(parser, j, emitted, a)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200722 for m in parser.messages_by_json[j].values():
Klement Sekera1732e472018-08-28 17:23:18 +0200723 emit_definition(parser, j, emitted, m)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200724
725 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200726
Klement Sekeradc15be22017-06-12 06:49:33 +0200727 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200728 print("%s" % vapi_send_with_control_ping)
729 print("")
730
Klement Sekeradc15be22017-06-12 06:49:33 +0200731 print("#ifdef __cplusplus")
732 print("}")
733 print("#endif")
734 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200735 print("#endif")
736 sys.stdout = orig_stdout
737
738
Klement Sekeradc15be22017-06-12 06:49:33 +0200739def json_to_c_header_name(json_name):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200740 if json_name.endswith(".json"):
741 return "%s.vapi.h" % os.path.splitext(json_name)[0]
742 raise Exception("Unexpected json name `%s'!" % json_name)
743
744
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200745def gen_c_unified_headers(parser, logger, prefix, remove_path):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200746 if prefix == "" or prefix is None:
747 prefix = ""
748 else:
749 prefix = "%s/" % prefix
750 for j in parser.json_files:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200751 if remove_path:
752 d, f = os.path.split(j)
753 else:
754 f = j
755 with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
Klement Sekeradc15be22017-06-12 06:49:33 +0200756 gen_json_unified_header(
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200757 parser, logger, j, io, json_to_c_header_name(f))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200758
759
760if __name__ == '__main__':
761 try:
762 verbose = int(os.getenv("V", 0))
763 except:
764 verbose = 0
765
766 if verbose >= 2:
767 log_level = 10
768 elif verbose == 1:
769 log_level = 20
770 else:
771 log_level = 40
772
773 logging.basicConfig(stream=sys.stdout, level=log_level)
774 logger = logging.getLogger("VAPI C GEN")
775 logger.setLevel(log_level)
776
Klement Sekeradc15be22017-06-12 06:49:33 +0200777 argparser = argparse.ArgumentParser(description="VPP C API generator")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200778 argparser.add_argument('files', metavar='api-file', action='append',
779 type=str, help='json api file'
780 '(may be specified multiple times)')
781 argparser.add_argument('--prefix', action='store', default=None,
782 help='path prefix')
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200783 argparser.add_argument('--remove-path', action='store_true',
784 help='remove path from filename')
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200785 args = argparser.parse_args()
786
787 jsonparser = JsonParser(logger, args.files,
788 simple_type_class=CSimpleType,
Klement Sekera2108c0c2018-08-24 11:43:20 +0200789 enum_class=CEnum,
790 union_class=CUnion,
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200791 struct_type_class=CStructType,
792 field_class=CField,
Ole Troan53fffa12018-11-13 12:36:56 +0100793 message_class=CMessage,
794 alias_class=CAlias)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200795
796 # not using the model of having separate generated header and code files
797 # with generated symbols present in shared library (per discussion with
798 # Damjan), to avoid symbol version issues in .so
799 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
800
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200801 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200802
803 for e in jsonparser.exceptions:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200804 logger.warning(e)