blob: eb1006d3a7eefc0ccc44d00202116db2df51af35 [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,\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02008 SimpleType, StructType
9
10
11class CField(Field):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020012 def get_c_def(self):
13 if self.len is not None:
14 return "%s %s[%d]" % (self.type.get_c_name(), self.name, self.len)
15 else:
16 return "%s %s" % (self.type.get_c_name(), self.name)
17
18 def get_swap_to_be_code(self, struct, var):
19 if self.len is not None:
20 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020021 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020022 " while(0);" % (
23 self.len,
24 self.type.get_swap_to_be_code(struct, "%s[i]" % var))
25 else:
26 if self.nelem_field.needs_byte_swap():
27 nelem_field = "%s(%s%s)" % (
28 self.nelem_field.type.get_swap_to_host_func_name(),
29 struct, self.nelem_field.name)
30 else:
31 nelem_field = "%s%s" % (struct, self.nelem_field.name)
32 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020033 "do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020034 " while(0);" %
35 (nelem_field, self.type.get_swap_to_be_code(
36 struct, "%s[i]" % var)))
37 return self.type.get_swap_to_be_code(struct, "%s" % var)
38
39 def get_swap_to_host_code(self, struct, var):
40 if self.len is not None:
41 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020042 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020043 " while(0);" % (
44 self.len,
45 self.type.get_swap_to_host_code(struct, "%s[i]" % var))
46 else:
47 # nelem_field already swapped to host here...
48 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020049 "do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020050 " while(0);" %
51 (struct, self.nelem_field.name,
52 self.type.get_swap_to_host_code(
53 struct, "%s[i]" % var)))
54 return self.type.get_swap_to_host_code(struct, "%s" % var)
55
56 def needs_byte_swap(self):
57 return self.type.needs_byte_swap()
58
Klement Sekera34a962b2018-09-06 19:31:36 +020059 def get_vla_field_length_name(self, path):
60 return "%s_%s_array_size" % ("_".join(path), self.name)
61
62 def get_alloc_vla_param_names(self, path):
63 if self.is_vla():
64 result = [self.get_vla_field_length_name(path)]
65 else:
66 result = []
67 if self.type.has_vla():
68 t = self.type.get_alloc_vla_param_names(path + [self.name])
69 result.extend(t)
70 return result
71
72 def get_vla_calc_size_code(self, prefix, path):
73 if self.is_vla():
74 result = ["sizeof(%s.%s[0]) * %s" % (
75 ".".join([prefix] + path),
76 self.name,
77 self.get_vla_field_length_name(path))]
78 else:
79 result = []
80 if self.type.has_vla():
81 t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
82 result.extend(t)
83 return result
84
85 def get_vla_assign_code(self, prefix, path):
86 result = []
87 if self.is_vla():
88 result.append("%s.%s = %s" % (
89 ".".join([prefix] + path),
90 self.nelem_field.name,
91 self.get_vla_field_length_name(path)))
92 if self.type.has_vla():
93 t = self.type.get_vla_assign_code(prefix, path + [self.name])
94 result.extend(t)
95 return result
96
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020097
98class CStruct(Struct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020099 def get_c_def(self):
100 return "\n".join([
Klement Sekera2108c0c2018-08-24 11:43:20 +0200101 "typedef struct __attribute__((__packed__)) {\n%s;" % (
102 ";\n".join([" %s" % x.get_c_def()
103 for x in self.fields])),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200104 "} %s;" % self.get_c_name()])
105
Klement Sekera34a962b2018-09-06 19:31:36 +0200106 def get_vla_assign_code(self, prefix, path):
107 return [x for f in self.fields if f.has_vla()
108 for x in f.get_vla_assign_code(prefix, path)]
109
110 def get_alloc_vla_param_names(self, path):
111 return [x for f in self.fields
112 if f.has_vla()
113 for x in f.get_alloc_vla_param_names(path)]
114
115 def get_vla_calc_size_code(self, prefix, path):
116 return [x for f in self.fields if f.has_vla()
117 for x in f.get_vla_calc_size_code(prefix, path)]
118
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200119
120class CSimpleType (SimpleType):
121
122 swap_to_be_dict = {
123 'i16': 'htobe16', 'u16': 'htobe16',
124 'i32': 'htobe32', 'u32': 'htobe32',
125 'i64': 'htobe64', 'u64': 'htobe64',
126 }
127
128 swap_to_host_dict = {
129 'i16': 'be16toh', 'u16': 'be16toh',
130 'i32': 'be32toh', 'u32': 'be32toh',
131 'i64': 'be64toh', 'u64': 'be64toh',
132 }
133
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200134 def get_c_name(self):
135 return self.name
136
137 def get_swap_to_be_func_name(self):
138 return self.swap_to_be_dict[self.name]
139
140 def get_swap_to_host_func_name(self):
141 return self.swap_to_host_dict[self.name]
142
Klement Sekera2108c0c2018-08-24 11:43:20 +0200143 def get_swap_to_be_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200144 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200145 return "%s = %s%s(%s);" % (x,
146 "(%s)" % cast if cast else "",
147 self.get_swap_to_be_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200148
Klement Sekera2108c0c2018-08-24 11:43:20 +0200149 def get_swap_to_host_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200150 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200151 return "%s = %s%s(%s);" % (x,
152 "(%s)" % cast if cast else "",
153 self.get_swap_to_host_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200154
155 def needs_byte_swap(self):
156 try:
157 self.get_swap_to_host_func_name()
158 return True
159 except:
160 pass
161 return False
162
163
Klement Sekera2108c0c2018-08-24 11:43:20 +0200164class CEnum(Enum):
165 def get_c_name(self):
166 return "vapi_enum_%s" % self.name
167
168 def get_c_def(self):
169 return "typedef enum {\n%s\n} %s;" % (
170 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
171 self.get_c_name()
172 )
173
174 def needs_byte_swap(self):
175 return self.type.needs_byte_swap()
176
177 def get_swap_to_be_code(self, struct, var):
178 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
179
180 def get_swap_to_host_code(self, struct, var):
181 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
182
183
184class CUnion(Union):
185 def get_c_name(self):
186 return "vapi_union_%s" % self.name
187
188 def get_c_def(self):
189 return "typedef union {\n%s\n} %s;" % (
190 "\n".join([" %s %s;" % (i.get_c_name(), j)
191 for i, j in self.type_pairs]),
192 self.get_c_name()
193 )
194
195 def needs_byte_swap(self):
196 return False
197
198
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200199class CStructType (StructType, CStruct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200200 def get_c_name(self):
201 return "vapi_type_%s" % self.name
202
203 def get_swap_to_be_func_name(self):
204 return "%s_hton" % self.get_c_name()
205
206 def get_swap_to_host_func_name(self):
207 return "%s_ntoh" % self.get_c_name()
208
209 def get_swap_to_be_func_decl(self):
210 return "void %s(%s *msg)" % (
211 self.get_swap_to_be_func_name(), self.get_c_name())
212
213 def get_swap_to_be_func_def(self):
214 return "%s\n{\n%s\n}" % (
215 self.get_swap_to_be_func_decl(),
216 "\n".join([
217 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
218 for p in self.fields if p.needs_byte_swap()]),
219 )
220
221 def get_swap_to_host_func_decl(self):
222 return "void %s(%s *msg)" % (
223 self.get_swap_to_host_func_name(), self.get_c_name())
224
225 def get_swap_to_host_func_def(self):
226 return "%s\n{\n%s\n}" % (
227 self.get_swap_to_host_func_decl(),
228 "\n".join([
229 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
230 for p in self.fields if p.needs_byte_swap()]),
231 )
232
233 def get_swap_to_be_code(self, struct, var):
234 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
235
236 def get_swap_to_host_code(self, struct, var):
237 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
238
239 def needs_byte_swap(self):
240 for f in self.fields:
241 if f.needs_byte_swap():
242 return True
243 return False
244
245
246class CMessage (Message):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200247 def __init__(self, logger, definition, json_parser):
248 super(CMessage, self).__init__(logger, definition, json_parser)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200249 self.payload_members = [
250 " %s" % p.get_c_def()
251 for p in self.fields
252 if p.type != self.header
253 ]
254
255 def has_payload(self):
256 return len(self.payload_members) > 0
257
258 def get_msg_id_name(self):
259 return "vapi_msg_id_%s" % self.name
260
261 def get_c_name(self):
262 return "vapi_msg_%s" % self.name
263
264 def get_payload_struct_name(self):
265 return "vapi_payload_%s" % self.name
266
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200267 def get_alloc_func_name(self):
268 return "vapi_alloc_%s" % self.name
269
Klement Sekeradc15be22017-06-12 06:49:33 +0200270 def get_alloc_vla_param_names(self):
Klement Sekera34a962b2018-09-06 19:31:36 +0200271 return [x for f in self.fields
272 if f.has_vla()
273 for x in f.get_alloc_vla_param_names([])]
Klement Sekeradc15be22017-06-12 06:49:33 +0200274
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200275 def get_alloc_func_decl(self):
276 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
277 self.get_c_name(),
278 self.get_alloc_func_name(),
Klement Sekeradc15be22017-06-12 06:49:33 +0200279 "".join([", size_t %s" % n for n in
280 self.get_alloc_vla_param_names()]))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200281
282 def get_alloc_func_def(self):
283 extra = []
284 if self.header.has_field('client_index'):
285 extra.append(
286 " msg->header.client_index = vapi_get_client_index(ctx);")
287 if self.header.has_field('context'):
288 extra.append(" msg->header.context = 0;")
289 return "\n".join([
290 "%s" % self.get_alloc_func_decl(),
291 "{",
292 " %s *msg = NULL;" % self.get_c_name(),
293 " const size_t size = sizeof(%s)%s;" % (
294 self.get_c_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200295 "".join([" + %s" % x for f in self.fields if f.has_vla()
296 for x in f.get_vla_calc_size_code("msg->payload",
297 [])])),
Klement Sekeradc15be22017-06-12 06:49:33 +0200298 " /* cast here required to play nicely with C++ world ... */",
299 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200300 " if (!msg) {",
301 " return NULL;",
302 " }",
303 ] + extra + [
304 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
305 self.get_msg_id_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200306 "".join([" %s;\n" % line
307 for f in self.fields if f.has_vla()
308 for line in f.get_vla_assign_code("msg->payload", [])]),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200309 " return msg;",
310 "}"])
311
312 def get_calc_msg_size_func_name(self):
313 return "vapi_calc_%s_msg_size" % self.name
314
315 def get_calc_msg_size_func_decl(self):
316 return "uword %s(%s *msg)" % (
317 self.get_calc_msg_size_func_name(),
318 self.get_c_name())
319
320 def get_calc_msg_size_func_def(self):
321 return "\n".join([
322 "%s" % self.get_calc_msg_size_func_decl(),
323 "{",
324 " return sizeof(*msg)%s;" %
325 "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
326 f.nelem_field.name,
327 f.name)
328 for f in self.fields
329 if f.nelem_field is not None
330 ]),
331 "}",
332 ])
333
334 def get_c_def(self):
335 if self.has_payload():
336 return "\n".join([
337 "typedef struct __attribute__ ((__packed__)) {",
338 "%s; " %
339 ";\n".join(self.payload_members),
340 "} %s;" % self.get_payload_struct_name(),
341 "",
342 "typedef struct __attribute__ ((__packed__)) {",
343 (" %s %s;" % (self.header.get_c_name(),
344 self.fields[0].name)
345 if self.header is not None else ""),
346 " %s payload;" % self.get_payload_struct_name(),
347 "} %s;" % self.get_c_name(), ])
348 else:
349 return "\n".join([
350 "typedef struct __attribute__ ((__packed__)) {",
351 (" %s %s;" % (self.header.get_c_name(),
352 self.fields[0].name)
353 if self.header is not None else ""),
354 "} %s;" % self.get_c_name(), ])
355
356 def get_swap_payload_to_host_func_name(self):
357 return "%s_payload_ntoh" % self.get_c_name()
358
359 def get_swap_payload_to_be_func_name(self):
360 return "%s_payload_hton" % self.get_c_name()
361
362 def get_swap_payload_to_host_func_decl(self):
363 return "void %s(%s *payload)" % (
364 self.get_swap_payload_to_host_func_name(),
365 self.get_payload_struct_name())
366
367 def get_swap_payload_to_be_func_decl(self):
368 return "void %s(%s *payload)" % (
369 self.get_swap_payload_to_be_func_name(),
370 self.get_payload_struct_name())
371
372 def get_swap_payload_to_be_func_def(self):
373 return "%s\n{\n%s\n}" % (
374 self.get_swap_payload_to_be_func_decl(),
375 "\n".join([
376 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
377 for p in self.fields
378 if p.needs_byte_swap() and p.type != self.header]),
379 )
380
381 def get_swap_payload_to_host_func_def(self):
382 return "%s\n{\n%s\n}" % (
383 self.get_swap_payload_to_host_func_decl(),
384 "\n".join([
385 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
386 for p in self.fields
387 if p.needs_byte_swap() and p.type != self.header]),
388 )
389
390 def get_swap_to_host_func_name(self):
391 return "%s_ntoh" % self.get_c_name()
392
393 def get_swap_to_be_func_name(self):
394 return "%s_hton" % self.get_c_name()
395
396 def get_swap_to_host_func_decl(self):
397 return "void %s(%s *msg)" % (
398 self.get_swap_to_host_func_name(), self.get_c_name())
399
400 def get_swap_to_be_func_decl(self):
401 return "void %s(%s *msg)" % (
402 self.get_swap_to_be_func_name(), self.get_c_name())
403
404 def get_swap_to_be_func_def(self):
405 return "\n".join([
406 "%s" % self.get_swap_to_be_func_decl(),
407 "{",
408 (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
409 self.get_c_name()),
410 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
411 if self.header is not None else "",
412 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
413 if self.has_payload() else "",
414 "}",
415 ])
416
417 def get_swap_to_host_func_def(self):
418 return "\n".join([
419 "%s" % self.get_swap_to_host_func_decl(),
420 "{",
421 (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
422 self.get_c_name()),
423 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
424 if self.header is not None else "",
425 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
426 if self.has_payload() else "",
427 "}",
428 ])
429
430 def get_op_func_name(self):
431 return "vapi_%s" % self.name
432
433 def get_op_func_decl(self):
434 if self.reply.has_payload():
435 return "vapi_error_e %s(%s)" % (
436 self.get_op_func_name(),
437 ",\n ".join([
438 'struct vapi_ctx_s *ctx',
439 '%s *msg' % self.get_c_name(),
440 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
441 ' void *callback_ctx',
442 ' vapi_error_e rv',
443 ' bool is_last',
444 ' %s *reply)' %
445 self.reply.get_payload_struct_name(),
446 'void *callback_ctx',
447 ])
448 )
449 else:
450 return "vapi_error_e %s(%s)" % (
451 self.get_op_func_name(),
452 ",\n ".join([
453 'struct vapi_ctx_s *ctx',
454 '%s *msg' % self.get_c_name(),
455 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
456 ' void *callback_ctx',
457 ' vapi_error_e rv',
458 ' bool is_last)',
459 'void *callback_ctx',
460 ])
461 )
462
463 def get_op_func_def(self):
464 return "\n".join([
465 "%s" % self.get_op_func_decl(),
466 "{",
467 " if (!msg || !callback) {",
468 " return VAPI_EINVAL;",
469 " }",
470 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
471 " return VAPI_EAGAIN;",
472 " }",
473 " vapi_error_e rv;",
474 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
475 " return rv;",
476 " }",
477 " u32 req_context = vapi_gen_req_context(ctx);",
478 " msg->header.context = req_context;",
479 " %s(msg);" % self.get_swap_to_be_func_name(),
480 (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
481 "(ctx, msg, req_context))) {"
Klement Sekera2108c0c2018-08-24 11:43:20 +0200482 if self.reply_is_stream else
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200483 " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
484 ),
485 (" vapi_store_request(ctx, req_context, %s, "
486 "(vapi_cb_t)callback, callback_ctx);" %
Klement Sekera2108c0c2018-08-24 11:43:20 +0200487 ("true" if self.reply_is_stream else "false")),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200488 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
489 " abort (); /* this really shouldn't happen */",
490 " }",
491 " if (vapi_is_nonblocking(ctx)) {",
492 " rv = VAPI_OK;",
493 " } else {",
494 " rv = vapi_dispatch(ctx);",
495 " }",
496 " } else {",
497 " %s(msg);" % self.get_swap_to_host_func_name(),
498 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
499 " abort (); /* this really shouldn't happen */",
500 " }",
501 " }",
502 " return rv;",
503 "}",
504 "",
505 ])
506
507 def get_event_cb_func_decl(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200508 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200509 raise Exception(
Klement Sekeradc15be22017-06-12 06:49:33 +0200510 "Cannot register event callback for non-reply message")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200511 if self.has_payload():
512 return "\n".join([
513 "void vapi_set_%s_event_cb (" %
514 self.get_c_name(),
515 " struct vapi_ctx_s *ctx, ",
516 (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
517 "void *callback_ctx, %s *payload)," %
518 self.get_payload_struct_name()),
519 " void *callback_ctx)",
520 ])
521 else:
522 return "\n".join([
523 "void vapi_set_%s_event_cb (" %
524 self.get_c_name(),
525 " struct vapi_ctx_s *ctx, ",
526 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
527 "void *callback_ctx),",
528 " void *callback_ctx)",
529 ])
530
531 def get_event_cb_func_def(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200532 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200533 raise Exception(
534 "Cannot register event callback for non-reply function")
535 return "\n".join([
536 "%s" % self.get_event_cb_func_decl(),
537 "{",
538 (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
539 "callback_ctx);" %
540 self.get_msg_id_name()),
541 "}"])
542
543 def get_c_metadata_struct_name(self):
544 return "__vapi_metadata_%s" % self.name
545
546 def get_c_constructor(self):
547 has_context = False
548 if self.header is not None:
549 has_context = self.header.has_field('context')
550 return '\n'.join([
551 'static void __attribute__((constructor)) __vapi_constructor_%s()'
552 % self.name,
553 '{',
554 ' static const char name[] = "%s";' % self.name,
555 ' static const char name_with_crc[] = "%s_%s";'
556 % (self.name, self.crc[2:]),
557 ' static vapi_message_desc_t %s = {' %
558 self.get_c_metadata_struct_name(),
559 ' name,',
560 ' sizeof(name) - 1,',
561 ' name_with_crc,',
562 ' sizeof(name_with_crc) - 1,',
563 ' true,' if has_context else ' false,',
564 ' offsetof(%s, context),' % self.header.get_c_name()
565 if has_context else ' 0,',
566 (' offsetof(%s, payload),' % self.get_c_name())
Klement Sekeradab732a2018-07-04 13:43:46 +0200567 if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200568 ' sizeof(%s),' % self.get_c_name(),
569 ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
570 ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
Klement Sekeradab732a2018-07-04 13:43:46 +0200571 ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200572 ' };',
573 '',
574 ' %s = vapi_register_msg(&%s);' %
575 (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
576 ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
577 (self.name, self.get_msg_id_name()),
578 '}',
579 ])
580
581
582vapi_send_with_control_ping = """
583static inline vapi_error_e
584vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
585{
586 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
587 if (!ping)
588 {
589 return VAPI_ENOMEM;
590 }
591 ping->header.context = context;
592 vapi_msg_control_ping_hton (ping);
593 return vapi_send2 (ctx, msg, ping);
594}
595"""
596
597
Klement Sekera1732e472018-08-28 17:23:18 +0200598def emit_definition(parser, json_file, emitted, o):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200599 if o in emitted:
600 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200601 if o.name in ("msg_header1_t", "msg_header2_t"):
602 return
603 if hasattr(o, "depends"):
604 for x in o.depends:
Klement Sekera1732e472018-08-28 17:23:18 +0200605 emit_definition(parser, json_file, emitted, x)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200606 if hasattr(o, "reply"):
Klement Sekera1732e472018-08-28 17:23:18 +0200607 emit_definition(parser, json_file, emitted, o.reply)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200608 if hasattr(o, "get_c_def"):
609 if (o not in parser.enums_by_json[json_file] and
610 o not in parser.types_by_json[json_file] and
611 o not in parser.unions_by_json[json_file] and
612 o.name not in parser.messages_by_json[json_file]):
613 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200614 guard = "defined_%s" % o.get_c_name()
615 print("#ifndef %s" % guard)
616 print("#define %s" % guard)
617 print("%s" % o.get_c_def())
618 print("")
619 function_attrs = "static inline "
620 if o.name in parser.messages_by_json[json_file]:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200621 if o.has_payload():
Klement Sekera2108c0c2018-08-24 11:43:20 +0200622 print("%s%s" % (function_attrs,
623 o.get_swap_payload_to_be_func_def()))
624 print("")
625 print("%s%s" % (function_attrs,
626 o.get_swap_payload_to_host_func_def()))
627 print("")
628 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
629 print("")
630 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
631 print("")
632 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200633 if not o.is_reply and not o.is_event:
Klement Sekera34a962b2018-09-06 19:31:36 +0200634 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200635 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
636 print("")
637 print("%s%s" % (function_attrs, o.get_op_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200638 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200639 print("%s" % o.get_c_constructor())
Klement Sekera1732e472018-08-28 17:23:18 +0200640 if o.is_reply or o.is_event:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200641 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200642 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200643 elif hasattr(o, "get_swap_to_be_func_def"):
644 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
645 print("")
646 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200647 print("#endif")
Klement Sekera34a962b2018-09-06 19:31:36 +0200648 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200649 emitted.append(o)
650
651
Klement Sekeradc15be22017-06-12 06:49:33 +0200652def gen_json_unified_header(parser, logger, j, io, name):
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200653 d, f = os.path.split(j)
Klement Sekeradc15be22017-06-12 06:49:33 +0200654 logger.info("Generating header `%s'" % name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200655 orig_stdout = sys.stdout
656 sys.stdout = io
657 include_guard = "__included_%s" % (
658 j.replace(".", "_").replace("/", "_").replace("-", "_"))
659 print("#ifndef %s" % include_guard)
660 print("#define %s" % include_guard)
661 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200662 print("#include <stdlib.h>")
663 print("#include <stddef.h>")
664 print("#include <arpa/inet.h>")
665 print("#include <vapi/vapi_internal.h>")
666 print("#include <vapi/vapi.h>")
667 print("#include <vapi/vapi_dbg.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200668 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200669 print("#ifdef __cplusplus")
670 print("extern \"C\" {")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200671 print("#endif")
Klement Sekeradc15be22017-06-12 06:49:33 +0200672 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200673 print("")
674 print("static inline vapi_error_e vapi_send_with_control_ping "
675 "(vapi_ctx_t ctx, void * msg, u32 context);")
676 else:
Klement Sekeradc15be22017-06-12 06:49:33 +0200677 print("#include <vapi/vpe.api.vapi.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200678 print("")
679 for m in parser.messages_by_json[j].values():
680 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
681 print("")
682 print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200683 f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200684 print("\\\n".join([
685 " vapi_msg_id_t %s;" % m.get_msg_id_name()
686 for m in parser.messages_by_json[j].values()
687 ]))
688 print("")
689 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200690 emitted = []
691 for e in parser.enums_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200692 emit_definition(parser, j, emitted, e)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200693 for u in parser.unions_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200694 emit_definition(parser, j, emitted, u)
Ole Troan52ca7562018-03-06 17:45:32 +0100695 for t in parser.types_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200696 emit_definition(parser, j, emitted, t)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200697 for m in parser.messages_by_json[j].values():
Klement Sekera1732e472018-08-28 17:23:18 +0200698 emit_definition(parser, j, emitted, m)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200699
700 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200701
Klement Sekeradc15be22017-06-12 06:49:33 +0200702 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200703 print("%s" % vapi_send_with_control_ping)
704 print("")
705
Klement Sekeradc15be22017-06-12 06:49:33 +0200706 print("#ifdef __cplusplus")
707 print("}")
708 print("#endif")
709 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200710 print("#endif")
711 sys.stdout = orig_stdout
712
713
Klement Sekeradc15be22017-06-12 06:49:33 +0200714def json_to_c_header_name(json_name):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200715 if json_name.endswith(".json"):
716 return "%s.vapi.h" % os.path.splitext(json_name)[0]
717 raise Exception("Unexpected json name `%s'!" % json_name)
718
719
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200720def gen_c_unified_headers(parser, logger, prefix, remove_path):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200721 if prefix == "" or prefix is None:
722 prefix = ""
723 else:
724 prefix = "%s/" % prefix
725 for j in parser.json_files:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200726 if remove_path:
727 d, f = os.path.split(j)
728 else:
729 f = j
730 with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
Klement Sekeradc15be22017-06-12 06:49:33 +0200731 gen_json_unified_header(
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200732 parser, logger, j, io, json_to_c_header_name(f))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200733
734
735if __name__ == '__main__':
736 try:
737 verbose = int(os.getenv("V", 0))
738 except:
739 verbose = 0
740
741 if verbose >= 2:
742 log_level = 10
743 elif verbose == 1:
744 log_level = 20
745 else:
746 log_level = 40
747
748 logging.basicConfig(stream=sys.stdout, level=log_level)
749 logger = logging.getLogger("VAPI C GEN")
750 logger.setLevel(log_level)
751
Klement Sekeradc15be22017-06-12 06:49:33 +0200752 argparser = argparse.ArgumentParser(description="VPP C API generator")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200753 argparser.add_argument('files', metavar='api-file', action='append',
754 type=str, help='json api file'
755 '(may be specified multiple times)')
756 argparser.add_argument('--prefix', action='store', default=None,
757 help='path prefix')
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200758 argparser.add_argument('--remove-path', action='store_true',
759 help='remove path from filename')
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200760 args = argparser.parse_args()
761
762 jsonparser = JsonParser(logger, args.files,
763 simple_type_class=CSimpleType,
Klement Sekera2108c0c2018-08-24 11:43:20 +0200764 enum_class=CEnum,
765 union_class=CUnion,
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200766 struct_type_class=CStructType,
767 field_class=CField,
768 message_class=CMessage)
769
770 # not using the model of having separate generated header and code files
771 # with generated symbols present in shared library (per discussion with
772 # Damjan), to avoid symbol version issues in .so
773 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
774
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200775 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200776
777 for e in jsonparser.exceptions:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200778 logger.warning(e)