blob: 381dcba7f42a3f0a178911f63d481149cde9af66 [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):
16 if self.len is not None:
Ole Troan7adaa222019-08-27 15:05:27 +020017 return "%s %s[%d];" % (self.type.get_c_name(), self.name, self.len)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020018 else:
Ole Troan53fffa12018-11-13 12:36:56 +010019 return "%s %s;" % (self.type.get_c_name(), self.name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020020
21 def get_swap_to_be_code(self, struct, var):
22 if self.len is not None:
23 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020024 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020025 " while(0);" % (
26 self.len,
27 self.type.get_swap_to_be_code(struct, "%s[i]" % var))
28 else:
29 if self.nelem_field.needs_byte_swap():
30 nelem_field = "%s(%s%s)" % (
31 self.nelem_field.type.get_swap_to_host_func_name(),
32 struct, self.nelem_field.name)
33 else:
34 nelem_field = "%s%s" % (struct, self.nelem_field.name)
35 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020036 "do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020037 " while(0);" %
38 (nelem_field, self.type.get_swap_to_be_code(
39 struct, "%s[i]" % var)))
40 return self.type.get_swap_to_be_code(struct, "%s" % var)
41
42 def get_swap_to_host_code(self, struct, var):
43 if self.len is not None:
44 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020045 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020046 " while(0);" % (
47 self.len,
48 self.type.get_swap_to_host_code(struct, "%s[i]" % var))
49 else:
50 # nelem_field already swapped to host here...
51 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020052 "do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020053 " while(0);" %
54 (struct, self.nelem_field.name,
55 self.type.get_swap_to_host_code(
56 struct, "%s[i]" % var)))
57 return self.type.get_swap_to_host_code(struct, "%s" % var)
58
59 def needs_byte_swap(self):
60 return self.type.needs_byte_swap()
61
Klement Sekera34a962b2018-09-06 19:31:36 +020062 def get_vla_field_length_name(self, path):
63 return "%s_%s_array_size" % ("_".join(path), self.name)
64
65 def get_alloc_vla_param_names(self, path):
66 if self.is_vla():
67 result = [self.get_vla_field_length_name(path)]
68 else:
69 result = []
70 if self.type.has_vla():
71 t = self.type.get_alloc_vla_param_names(path + [self.name])
72 result.extend(t)
73 return result
74
75 def get_vla_calc_size_code(self, prefix, path):
76 if self.is_vla():
77 result = ["sizeof(%s.%s[0]) * %s" % (
78 ".".join([prefix] + path),
79 self.name,
80 self.get_vla_field_length_name(path))]
81 else:
82 result = []
83 if self.type.has_vla():
84 t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
85 result.extend(t)
86 return result
87
88 def get_vla_assign_code(self, prefix, path):
89 result = []
90 if self.is_vla():
91 result.append("%s.%s = %s" % (
92 ".".join([prefix] + path),
93 self.nelem_field.name,
94 self.get_vla_field_length_name(path)))
95 if self.type.has_vla():
96 t = self.type.get_vla_assign_code(prefix, path + [self.name])
97 result.extend(t)
98 return result
99
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200100
Ole Troan53fffa12018-11-13 12:36:56 +0100101class CAlias(CField):
102 def get_c_name(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100103 return "vapi_type_%s" % self.name
Ole Troan53fffa12018-11-13 12:36:56 +0100104
105 def get_c_def(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100106 if self.len is not None:
Klement Sekera173e20c2018-12-12 12:57:32 +0100107 return "typedef %s vapi_type_%s[%d];" % (
108 self.type.get_c_name(), self.name, self.len)
Ole Troan8c8acc02018-11-27 10:05:23 +0100109 else:
Klement Sekera173e20c2018-12-12 12:57:32 +0100110 return "typedef %s vapi_type_%s;" % (
111 self.type.get_c_name(), self.name)
Ole Troan53fffa12018-11-13 12:36:56 +0100112
113
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200114class CStruct(Struct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200115 def get_c_def(self):
116 return "\n".join([
Ole Troan53fffa12018-11-13 12:36:56 +0100117 "typedef struct __attribute__((__packed__)) {\n%s" % (
118 "\n".join([" %s" % x.get_c_def()
119 for x in self.fields])),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200120 "} %s;" % self.get_c_name()])
121
Klement Sekera34a962b2018-09-06 19:31:36 +0200122 def get_vla_assign_code(self, prefix, path):
123 return [x for f in self.fields if f.has_vla()
124 for x in f.get_vla_assign_code(prefix, path)]
125
126 def get_alloc_vla_param_names(self, path):
127 return [x for f in self.fields
128 if f.has_vla()
129 for x in f.get_alloc_vla_param_names(path)]
130
131 def get_vla_calc_size_code(self, prefix, path):
132 return [x for f in self.fields if f.has_vla()
133 for x in f.get_vla_calc_size_code(prefix, path)]
134
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200135
136class CSimpleType (SimpleType):
137
138 swap_to_be_dict = {
139 'i16': 'htobe16', 'u16': 'htobe16',
140 'i32': 'htobe32', 'u32': 'htobe32',
141 'i64': 'htobe64', 'u64': 'htobe64',
142 }
143
144 swap_to_host_dict = {
145 'i16': 'be16toh', 'u16': 'be16toh',
146 'i32': 'be32toh', 'u32': 'be32toh',
147 'i64': 'be64toh', 'u64': 'be64toh',
148 }
149
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200150 def get_c_name(self):
151 return self.name
152
153 def get_swap_to_be_func_name(self):
154 return self.swap_to_be_dict[self.name]
155
156 def get_swap_to_host_func_name(self):
157 return self.swap_to_host_dict[self.name]
158
Klement Sekera2108c0c2018-08-24 11:43:20 +0200159 def get_swap_to_be_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200160 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200161 return "%s = %s%s(%s);" % (x,
162 "(%s)" % cast if cast else "",
163 self.get_swap_to_be_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200164
Klement Sekera2108c0c2018-08-24 11:43:20 +0200165 def get_swap_to_host_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_host_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200170
171 def needs_byte_swap(self):
172 try:
173 self.get_swap_to_host_func_name()
174 return True
Ole Troan53fffa12018-11-13 12:36:56 +0100175 except KeyError:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200176 pass
177 return False
178
179
Klement Sekera2108c0c2018-08-24 11:43:20 +0200180class CEnum(Enum):
181 def get_c_name(self):
182 return "vapi_enum_%s" % self.name
183
184 def get_c_def(self):
185 return "typedef enum {\n%s\n} %s;" % (
186 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
187 self.get_c_name()
188 )
189
190 def needs_byte_swap(self):
191 return self.type.needs_byte_swap()
192
193 def get_swap_to_be_code(self, struct, var):
194 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
195
196 def get_swap_to_host_code(self, struct, var):
197 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
198
199
200class CUnion(Union):
201 def get_c_name(self):
202 return "vapi_union_%s" % self.name
203
204 def get_c_def(self):
205 return "typedef union {\n%s\n} %s;" % (
206 "\n".join([" %s %s;" % (i.get_c_name(), j)
207 for i, j in self.type_pairs]),
208 self.get_c_name()
209 )
210
211 def needs_byte_swap(self):
212 return False
213
214
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200215class CStructType (StructType, CStruct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200216 def get_c_name(self):
217 return "vapi_type_%s" % self.name
218
219 def get_swap_to_be_func_name(self):
220 return "%s_hton" % self.get_c_name()
221
222 def get_swap_to_host_func_name(self):
223 return "%s_ntoh" % self.get_c_name()
224
225 def get_swap_to_be_func_decl(self):
226 return "void %s(%s *msg)" % (
227 self.get_swap_to_be_func_name(), self.get_c_name())
228
229 def get_swap_to_be_func_def(self):
230 return "%s\n{\n%s\n}" % (
231 self.get_swap_to_be_func_decl(),
232 "\n".join([
233 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
234 for p in self.fields if p.needs_byte_swap()]),
235 )
236
237 def get_swap_to_host_func_decl(self):
238 return "void %s(%s *msg)" % (
239 self.get_swap_to_host_func_name(), self.get_c_name())
240
241 def get_swap_to_host_func_def(self):
242 return "%s\n{\n%s\n}" % (
243 self.get_swap_to_host_func_decl(),
244 "\n".join([
245 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
246 for p in self.fields if p.needs_byte_swap()]),
247 )
248
249 def get_swap_to_be_code(self, struct, var):
250 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
251
252 def get_swap_to_host_code(self, struct, var):
253 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
254
255 def needs_byte_swap(self):
256 for f in self.fields:
257 if f.needs_byte_swap():
258 return True
259 return False
260
261
262class CMessage (Message):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200263 def __init__(self, logger, definition, json_parser):
264 super(CMessage, self).__init__(logger, definition, json_parser)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200265 self.payload_members = [
266 " %s" % p.get_c_def()
267 for p in self.fields
268 if p.type != self.header
269 ]
270
271 def has_payload(self):
272 return len(self.payload_members) > 0
273
274 def get_msg_id_name(self):
275 return "vapi_msg_id_%s" % self.name
276
277 def get_c_name(self):
278 return "vapi_msg_%s" % self.name
279
280 def get_payload_struct_name(self):
281 return "vapi_payload_%s" % self.name
282
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200283 def get_alloc_func_name(self):
284 return "vapi_alloc_%s" % self.name
285
Klement Sekeradc15be22017-06-12 06:49:33 +0200286 def get_alloc_vla_param_names(self):
Klement Sekera34a962b2018-09-06 19:31:36 +0200287 return [x for f in self.fields
288 if f.has_vla()
289 for x in f.get_alloc_vla_param_names([])]
Klement Sekeradc15be22017-06-12 06:49:33 +0200290
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200291 def get_alloc_func_decl(self):
292 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
293 self.get_c_name(),
294 self.get_alloc_func_name(),
Klement Sekeradc15be22017-06-12 06:49:33 +0200295 "".join([", size_t %s" % n for n in
296 self.get_alloc_vla_param_names()]))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200297
298 def get_alloc_func_def(self):
299 extra = []
300 if self.header.has_field('client_index'):
301 extra.append(
302 " msg->header.client_index = vapi_get_client_index(ctx);")
303 if self.header.has_field('context'):
304 extra.append(" msg->header.context = 0;")
305 return "\n".join([
306 "%s" % self.get_alloc_func_decl(),
307 "{",
308 " %s *msg = NULL;" % self.get_c_name(),
309 " const size_t size = sizeof(%s)%s;" % (
310 self.get_c_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200311 "".join([" + %s" % x for f in self.fields if f.has_vla()
312 for x in f.get_vla_calc_size_code("msg->payload",
313 [])])),
Klement Sekeradc15be22017-06-12 06:49:33 +0200314 " /* cast here required to play nicely with C++ world ... */",
315 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200316 " if (!msg) {",
317 " return NULL;",
318 " }",
319 ] + extra + [
320 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
321 self.get_msg_id_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200322 "".join([" %s;\n" % line
323 for f in self.fields if f.has_vla()
324 for line in f.get_vla_assign_code("msg->payload", [])]),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200325 " return msg;",
326 "}"])
327
328 def get_calc_msg_size_func_name(self):
329 return "vapi_calc_%s_msg_size" % self.name
330
331 def get_calc_msg_size_func_decl(self):
332 return "uword %s(%s *msg)" % (
333 self.get_calc_msg_size_func_name(),
334 self.get_c_name())
335
336 def get_calc_msg_size_func_def(self):
337 return "\n".join([
338 "%s" % self.get_calc_msg_size_func_decl(),
339 "{",
340 " return sizeof(*msg)%s;" %
341 "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
342 f.nelem_field.name,
343 f.name)
344 for f in self.fields
345 if f.nelem_field is not None
346 ]),
347 "}",
348 ])
349
350 def get_c_def(self):
351 if self.has_payload():
352 return "\n".join([
353 "typedef struct __attribute__ ((__packed__)) {",
Ole Troan53fffa12018-11-13 12:36:56 +0100354 "%s " %
355 "\n".join(self.payload_members),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200356 "} %s;" % self.get_payload_struct_name(),
357 "",
358 "typedef struct __attribute__ ((__packed__)) {",
359 (" %s %s;" % (self.header.get_c_name(),
360 self.fields[0].name)
361 if self.header is not None else ""),
362 " %s payload;" % self.get_payload_struct_name(),
363 "} %s;" % self.get_c_name(), ])
364 else:
365 return "\n".join([
366 "typedef struct __attribute__ ((__packed__)) {",
367 (" %s %s;" % (self.header.get_c_name(),
368 self.fields[0].name)
369 if self.header is not None else ""),
370 "} %s;" % self.get_c_name(), ])
371
372 def get_swap_payload_to_host_func_name(self):
373 return "%s_payload_ntoh" % self.get_c_name()
374
375 def get_swap_payload_to_be_func_name(self):
376 return "%s_payload_hton" % self.get_c_name()
377
378 def get_swap_payload_to_host_func_decl(self):
379 return "void %s(%s *payload)" % (
380 self.get_swap_payload_to_host_func_name(),
381 self.get_payload_struct_name())
382
383 def get_swap_payload_to_be_func_decl(self):
384 return "void %s(%s *payload)" % (
385 self.get_swap_payload_to_be_func_name(),
386 self.get_payload_struct_name())
387
388 def get_swap_payload_to_be_func_def(self):
389 return "%s\n{\n%s\n}" % (
390 self.get_swap_payload_to_be_func_decl(),
391 "\n".join([
392 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
393 for p in self.fields
394 if p.needs_byte_swap() and p.type != self.header]),
395 )
396
397 def get_swap_payload_to_host_func_def(self):
398 return "%s\n{\n%s\n}" % (
399 self.get_swap_payload_to_host_func_decl(),
400 "\n".join([
401 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
402 for p in self.fields
403 if p.needs_byte_swap() and p.type != self.header]),
404 )
405
406 def get_swap_to_host_func_name(self):
407 return "%s_ntoh" % self.get_c_name()
408
409 def get_swap_to_be_func_name(self):
410 return "%s_hton" % self.get_c_name()
411
412 def get_swap_to_host_func_decl(self):
413 return "void %s(%s *msg)" % (
414 self.get_swap_to_host_func_name(), self.get_c_name())
415
416 def get_swap_to_be_func_decl(self):
417 return "void %s(%s *msg)" % (
418 self.get_swap_to_be_func_name(), self.get_c_name())
419
420 def get_swap_to_be_func_def(self):
421 return "\n".join([
422 "%s" % self.get_swap_to_be_func_decl(),
423 "{",
424 (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
425 self.get_c_name()),
426 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
427 if self.header is not None else "",
428 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
429 if self.has_payload() else "",
430 "}",
431 ])
432
433 def get_swap_to_host_func_def(self):
434 return "\n".join([
435 "%s" % self.get_swap_to_host_func_decl(),
436 "{",
437 (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
438 self.get_c_name()),
439 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
440 if self.header is not None else "",
441 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
442 if self.has_payload() else "",
443 "}",
444 ])
445
446 def get_op_func_name(self):
447 return "vapi_%s" % self.name
448
449 def get_op_func_decl(self):
450 if self.reply.has_payload():
451 return "vapi_error_e %s(%s)" % (
452 self.get_op_func_name(),
453 ",\n ".join([
454 'struct vapi_ctx_s *ctx',
455 '%s *msg' % self.get_c_name(),
456 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
457 ' void *callback_ctx',
458 ' vapi_error_e rv',
459 ' bool is_last',
460 ' %s *reply)' %
461 self.reply.get_payload_struct_name(),
462 'void *callback_ctx',
463 ])
464 )
465 else:
466 return "vapi_error_e %s(%s)" % (
467 self.get_op_func_name(),
468 ",\n ".join([
469 'struct vapi_ctx_s *ctx',
470 '%s *msg' % self.get_c_name(),
471 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
472 ' void *callback_ctx',
473 ' vapi_error_e rv',
474 ' bool is_last)',
475 'void *callback_ctx',
476 ])
477 )
478
479 def get_op_func_def(self):
480 return "\n".join([
481 "%s" % self.get_op_func_decl(),
482 "{",
483 " if (!msg || !callback) {",
484 " return VAPI_EINVAL;",
485 " }",
486 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
487 " return VAPI_EAGAIN;",
488 " }",
489 " vapi_error_e rv;",
490 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
491 " return rv;",
492 " }",
493 " u32 req_context = vapi_gen_req_context(ctx);",
494 " msg->header.context = req_context;",
495 " %s(msg);" % self.get_swap_to_be_func_name(),
496 (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
497 "(ctx, msg, req_context))) {"
Klement Sekera2108c0c2018-08-24 11:43:20 +0200498 if self.reply_is_stream else
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200499 " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
500 ),
501 (" vapi_store_request(ctx, req_context, %s, "
502 "(vapi_cb_t)callback, callback_ctx);" %
Klement Sekera2108c0c2018-08-24 11:43:20 +0200503 ("true" if self.reply_is_stream else "false")),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200504 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
505 " abort (); /* this really shouldn't happen */",
506 " }",
507 " if (vapi_is_nonblocking(ctx)) {",
508 " rv = VAPI_OK;",
509 " } else {",
510 " rv = vapi_dispatch(ctx);",
511 " }",
512 " } else {",
513 " %s(msg);" % self.get_swap_to_host_func_name(),
514 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
515 " abort (); /* this really shouldn't happen */",
516 " }",
517 " }",
518 " return rv;",
519 "}",
520 "",
521 ])
522
523 def get_event_cb_func_decl(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200524 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200525 raise Exception(
Klement Sekeradc15be22017-06-12 06:49:33 +0200526 "Cannot register event callback for non-reply message")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200527 if self.has_payload():
528 return "\n".join([
529 "void vapi_set_%s_event_cb (" %
530 self.get_c_name(),
531 " struct vapi_ctx_s *ctx, ",
532 (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
533 "void *callback_ctx, %s *payload)," %
534 self.get_payload_struct_name()),
535 " void *callback_ctx)",
536 ])
537 else:
538 return "\n".join([
539 "void vapi_set_%s_event_cb (" %
540 self.get_c_name(),
541 " struct vapi_ctx_s *ctx, ",
542 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
543 "void *callback_ctx),",
544 " void *callback_ctx)",
545 ])
546
547 def get_event_cb_func_def(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200548 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200549 raise Exception(
550 "Cannot register event callback for non-reply function")
551 return "\n".join([
552 "%s" % self.get_event_cb_func_decl(),
553 "{",
554 (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
555 "callback_ctx);" %
556 self.get_msg_id_name()),
557 "}"])
558
559 def get_c_metadata_struct_name(self):
560 return "__vapi_metadata_%s" % self.name
561
562 def get_c_constructor(self):
563 has_context = False
564 if self.header is not None:
565 has_context = self.header.has_field('context')
566 return '\n'.join([
567 'static void __attribute__((constructor)) __vapi_constructor_%s()'
568 % self.name,
569 '{',
570 ' static const char name[] = "%s";' % self.name,
571 ' static const char name_with_crc[] = "%s_%s";'
572 % (self.name, self.crc[2:]),
573 ' static vapi_message_desc_t %s = {' %
574 self.get_c_metadata_struct_name(),
575 ' name,',
576 ' sizeof(name) - 1,',
577 ' name_with_crc,',
578 ' sizeof(name_with_crc) - 1,',
579 ' true,' if has_context else ' false,',
580 ' offsetof(%s, context),' % self.header.get_c_name()
581 if has_context else ' 0,',
582 (' offsetof(%s, payload),' % self.get_c_name())
Klement Sekeradab732a2018-07-04 13:43:46 +0200583 if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200584 ' sizeof(%s),' % self.get_c_name(),
585 ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
586 ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
Klement Sekeradab732a2018-07-04 13:43:46 +0200587 ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200588 ' };',
589 '',
590 ' %s = vapi_register_msg(&%s);' %
591 (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
592 ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
593 (self.name, self.get_msg_id_name()),
594 '}',
595 ])
596
597
598vapi_send_with_control_ping = """
599static inline vapi_error_e
600vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
601{
602 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
603 if (!ping)
604 {
605 return VAPI_ENOMEM;
606 }
607 ping->header.context = context;
608 vapi_msg_control_ping_hton (ping);
609 return vapi_send2 (ctx, msg, ping);
610}
611"""
612
613
Klement Sekera1732e472018-08-28 17:23:18 +0200614def emit_definition(parser, json_file, emitted, o):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200615 if o in emitted:
616 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200617 if o.name in ("msg_header1_t", "msg_header2_t"):
618 return
619 if hasattr(o, "depends"):
620 for x in o.depends:
Klement Sekera1732e472018-08-28 17:23:18 +0200621 emit_definition(parser, json_file, emitted, x)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200622 if hasattr(o, "reply"):
Klement Sekera1732e472018-08-28 17:23:18 +0200623 emit_definition(parser, json_file, emitted, o.reply)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200624 if hasattr(o, "get_c_def"):
625 if (o not in parser.enums_by_json[json_file] and
626 o not in parser.types_by_json[json_file] and
627 o not in parser.unions_by_json[json_file] and
Ole Troan53fffa12018-11-13 12:36:56 +0100628 o.name not in parser.messages_by_json[json_file] and
629 o not in parser.aliases_by_json[json_file]):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200630 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200631 guard = "defined_%s" % o.get_c_name()
632 print("#ifndef %s" % guard)
633 print("#define %s" % guard)
634 print("%s" % o.get_c_def())
635 print("")
636 function_attrs = "static inline "
637 if o.name in parser.messages_by_json[json_file]:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200638 if o.has_payload():
Klement Sekera2108c0c2018-08-24 11:43:20 +0200639 print("%s%s" % (function_attrs,
640 o.get_swap_payload_to_be_func_def()))
641 print("")
642 print("%s%s" % (function_attrs,
643 o.get_swap_payload_to_host_func_def()))
644 print("")
645 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
646 print("")
647 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
648 print("")
649 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200650 if not o.is_reply and not o.is_event:
Klement Sekera34a962b2018-09-06 19:31:36 +0200651 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200652 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
653 print("")
654 print("%s%s" % (function_attrs, o.get_op_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200655 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200656 print("%s" % o.get_c_constructor())
Klement Sekera1732e472018-08-28 17:23:18 +0200657 if o.is_reply or o.is_event:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200658 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200659 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200660 elif hasattr(o, "get_swap_to_be_func_def"):
661 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
662 print("")
663 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200664 print("#endif")
Klement Sekera34a962b2018-09-06 19:31:36 +0200665 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200666 emitted.append(o)
667
668
Klement Sekeradc15be22017-06-12 06:49:33 +0200669def gen_json_unified_header(parser, logger, j, io, name):
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200670 d, f = os.path.split(j)
Klement Sekeradc15be22017-06-12 06:49:33 +0200671 logger.info("Generating header `%s'" % name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200672 orig_stdout = sys.stdout
673 sys.stdout = io
674 include_guard = "__included_%s" % (
675 j.replace(".", "_").replace("/", "_").replace("-", "_"))
676 print("#ifndef %s" % include_guard)
677 print("#define %s" % include_guard)
678 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200679 print("#include <stdlib.h>")
680 print("#include <stddef.h>")
681 print("#include <arpa/inet.h>")
682 print("#include <vapi/vapi_internal.h>")
683 print("#include <vapi/vapi.h>")
684 print("#include <vapi/vapi_dbg.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200685 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200686 print("#ifdef __cplusplus")
687 print("extern \"C\" {")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200688 print("#endif")
Klement Sekeradc15be22017-06-12 06:49:33 +0200689 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200690 print("")
691 print("static inline vapi_error_e vapi_send_with_control_ping "
692 "(vapi_ctx_t ctx, void * msg, u32 context);")
693 else:
Klement Sekeradc15be22017-06-12 06:49:33 +0200694 print("#include <vapi/vpe.api.vapi.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200695 print("")
696 for m in parser.messages_by_json[j].values():
697 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
698 print("")
699 print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200700 f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200701 print("\\\n".join([
702 " vapi_msg_id_t %s;" % m.get_msg_id_name()
703 for m in parser.messages_by_json[j].values()
704 ]))
705 print("")
706 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200707 emitted = []
708 for e in parser.enums_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200709 emit_definition(parser, j, emitted, e)
Ole Troan53fffa12018-11-13 12:36:56 +0100710 for a in parser.aliases_by_json[j]:
711 emit_definition(parser, j, emitted, a)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200712 for u in parser.unions_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200713 emit_definition(parser, j, emitted, u)
Ole Troan52ca7562018-03-06 17:45:32 +0100714 for t in parser.types_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200715 emit_definition(parser, j, emitted, t)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200716 for m in parser.messages_by_json[j].values():
Klement Sekera1732e472018-08-28 17:23:18 +0200717 emit_definition(parser, j, emitted, m)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200718
719 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200720
Klement Sekeradc15be22017-06-12 06:49:33 +0200721 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200722 print("%s" % vapi_send_with_control_ping)
723 print("")
724
Klement Sekeradc15be22017-06-12 06:49:33 +0200725 print("#ifdef __cplusplus")
726 print("}")
727 print("#endif")
728 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200729 print("#endif")
730 sys.stdout = orig_stdout
731
732
Klement Sekeradc15be22017-06-12 06:49:33 +0200733def json_to_c_header_name(json_name):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200734 if json_name.endswith(".json"):
735 return "%s.vapi.h" % os.path.splitext(json_name)[0]
736 raise Exception("Unexpected json name `%s'!" % json_name)
737
738
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200739def gen_c_unified_headers(parser, logger, prefix, remove_path):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200740 if prefix == "" or prefix is None:
741 prefix = ""
742 else:
743 prefix = "%s/" % prefix
744 for j in parser.json_files:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200745 if remove_path:
746 d, f = os.path.split(j)
747 else:
748 f = j
749 with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
Klement Sekeradc15be22017-06-12 06:49:33 +0200750 gen_json_unified_header(
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200751 parser, logger, j, io, json_to_c_header_name(f))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200752
753
754if __name__ == '__main__':
755 try:
756 verbose = int(os.getenv("V", 0))
757 except:
758 verbose = 0
759
760 if verbose >= 2:
761 log_level = 10
762 elif verbose == 1:
763 log_level = 20
764 else:
765 log_level = 40
766
767 logging.basicConfig(stream=sys.stdout, level=log_level)
768 logger = logging.getLogger("VAPI C GEN")
769 logger.setLevel(log_level)
770
Klement Sekeradc15be22017-06-12 06:49:33 +0200771 argparser = argparse.ArgumentParser(description="VPP C API generator")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200772 argparser.add_argument('files', metavar='api-file', action='append',
773 type=str, help='json api file'
774 '(may be specified multiple times)')
775 argparser.add_argument('--prefix', action='store', default=None,
776 help='path prefix')
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200777 argparser.add_argument('--remove-path', action='store_true',
778 help='remove path from filename')
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200779 args = argparser.parse_args()
780
781 jsonparser = JsonParser(logger, args.files,
782 simple_type_class=CSimpleType,
Klement Sekera2108c0c2018-08-24 11:43:20 +0200783 enum_class=CEnum,
784 union_class=CUnion,
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200785 struct_type_class=CStructType,
786 field_class=CField,
Ole Troan53fffa12018-11-13 12:36:56 +0100787 message_class=CMessage,
788 alias_class=CAlias)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200789
790 # not using the model of having separate generated header and code files
791 # with generated symbols present in shared library (per discussion with
792 # Damjan), to avoid symbol version issues in .so
793 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
794
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200795 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200796
797 for e in jsonparser.exceptions:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200798 logger.warning(e)