blob: a881ad578ae6461709bf2b458b5aeac4b862690e [file] [log] [blame]
Ole Troan1b1ccad2019-10-25 18:30:40 +02001#!/usr/bin/env python3
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
Neale Rannsb5c0d352020-04-22 16:06:45 +0000156 __packed = "__attribute__((packed))"
157 pack_dict = {
158 'i8': __packed, 'u8': __packed,
159 'i16': __packed, 'u16': __packed,
160 }
161
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200162 def get_c_name(self):
163 return self.name
164
165 def get_swap_to_be_func_name(self):
166 return self.swap_to_be_dict[self.name]
167
168 def get_swap_to_host_func_name(self):
169 return self.swap_to_host_dict[self.name]
170
Neale Rannsb5c0d352020-04-22 16:06:45 +0000171 def get_packed_string(self):
172 return self.pack_dict[self.name]
173
Klement Sekera2108c0c2018-08-24 11:43:20 +0200174 def get_swap_to_be_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200175 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200176 return "%s = %s%s(%s);" % (x,
177 "(%s)" % cast if cast else "",
178 self.get_swap_to_be_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200179
Klement Sekera2108c0c2018-08-24 11:43:20 +0200180 def get_swap_to_host_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200181 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200182 return "%s = %s%s(%s);" % (x,
183 "(%s)" % cast if cast else "",
184 self.get_swap_to_host_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200185
186 def needs_byte_swap(self):
187 try:
188 self.get_swap_to_host_func_name()
189 return True
Ole Troan53fffa12018-11-13 12:36:56 +0100190 except KeyError:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200191 pass
192 return False
193
Neale Rannsb5c0d352020-04-22 16:06:45 +0000194 def get_packed(self):
195 return self.pack_dict.get(self.name, "")
196
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200197
Klement Sekera2108c0c2018-08-24 11:43:20 +0200198class CEnum(Enum):
199 def get_c_name(self):
200 return "vapi_enum_%s" % self.name
201
202 def get_c_def(self):
Neale Rannsb5c0d352020-04-22 16:06:45 +0000203 return "typedef enum {\n%s\n} %s %s;" % (
Klement Sekera2108c0c2018-08-24 11:43:20 +0200204 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
Neale Rannsb5c0d352020-04-22 16:06:45 +0000205 self.type.get_packed(),
Klement Sekera2108c0c2018-08-24 11:43:20 +0200206 self.get_c_name()
207 )
208
209 def needs_byte_swap(self):
210 return self.type.needs_byte_swap()
211
212 def get_swap_to_be_code(self, struct, var):
213 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
214
215 def get_swap_to_host_code(self, struct, var):
216 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
217
218
219class CUnion(Union):
220 def get_c_name(self):
221 return "vapi_union_%s" % self.name
222
223 def get_c_def(self):
224 return "typedef union {\n%s\n} %s;" % (
225 "\n".join([" %s %s;" % (i.get_c_name(), j)
226 for i, j in self.type_pairs]),
227 self.get_c_name()
228 )
229
230 def needs_byte_swap(self):
231 return False
232
233
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200234class CStructType (StructType, CStruct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200235 def get_c_name(self):
236 return "vapi_type_%s" % self.name
237
238 def get_swap_to_be_func_name(self):
239 return "%s_hton" % self.get_c_name()
240
241 def get_swap_to_host_func_name(self):
242 return "%s_ntoh" % self.get_c_name()
243
244 def get_swap_to_be_func_decl(self):
245 return "void %s(%s *msg)" % (
246 self.get_swap_to_be_func_name(), self.get_c_name())
247
248 def get_swap_to_be_func_def(self):
249 return "%s\n{\n%s\n}" % (
250 self.get_swap_to_be_func_decl(),
251 "\n".join([
252 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
253 for p in self.fields if p.needs_byte_swap()]),
254 )
255
256 def get_swap_to_host_func_decl(self):
257 return "void %s(%s *msg)" % (
258 self.get_swap_to_host_func_name(), self.get_c_name())
259
260 def get_swap_to_host_func_def(self):
261 return "%s\n{\n%s\n}" % (
262 self.get_swap_to_host_func_decl(),
263 "\n".join([
264 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
265 for p in self.fields if p.needs_byte_swap()]),
266 )
267
268 def get_swap_to_be_code(self, struct, var):
269 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
270
271 def get_swap_to_host_code(self, struct, var):
272 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
273
274 def needs_byte_swap(self):
275 for f in self.fields:
276 if f.needs_byte_swap():
277 return True
278 return False
279
280
281class CMessage (Message):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200282 def __init__(self, logger, definition, json_parser):
283 super(CMessage, self).__init__(logger, definition, json_parser)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200284 self.payload_members = [
285 " %s" % p.get_c_def()
286 for p in self.fields
287 if p.type != self.header
288 ]
289
290 def has_payload(self):
291 return len(self.payload_members) > 0
292
293 def get_msg_id_name(self):
294 return "vapi_msg_id_%s" % self.name
295
296 def get_c_name(self):
297 return "vapi_msg_%s" % self.name
298
299 def get_payload_struct_name(self):
300 return "vapi_payload_%s" % self.name
301
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200302 def get_alloc_func_name(self):
303 return "vapi_alloc_%s" % self.name
304
Klement Sekeradc15be22017-06-12 06:49:33 +0200305 def get_alloc_vla_param_names(self):
Klement Sekera34a962b2018-09-06 19:31:36 +0200306 return [x for f in self.fields
307 if f.has_vla()
308 for x in f.get_alloc_vla_param_names([])]
Klement Sekeradc15be22017-06-12 06:49:33 +0200309
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200310 def get_alloc_func_decl(self):
311 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
312 self.get_c_name(),
313 self.get_alloc_func_name(),
Klement Sekeradc15be22017-06-12 06:49:33 +0200314 "".join([", size_t %s" % n for n in
315 self.get_alloc_vla_param_names()]))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200316
317 def get_alloc_func_def(self):
318 extra = []
319 if self.header.has_field('client_index'):
320 extra.append(
321 " msg->header.client_index = vapi_get_client_index(ctx);")
322 if self.header.has_field('context'):
323 extra.append(" msg->header.context = 0;")
324 return "\n".join([
325 "%s" % self.get_alloc_func_decl(),
326 "{",
327 " %s *msg = NULL;" % self.get_c_name(),
328 " const size_t size = sizeof(%s)%s;" % (
329 self.get_c_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200330 "".join([" + %s" % x for f in self.fields if f.has_vla()
331 for x in f.get_vla_calc_size_code("msg->payload",
332 [])])),
Klement Sekeradc15be22017-06-12 06:49:33 +0200333 " /* cast here required to play nicely with C++ world ... */",
334 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200335 " if (!msg) {",
336 " return NULL;",
337 " }",
338 ] + extra + [
339 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
340 self.get_msg_id_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200341 "".join([" %s;\n" % line
342 for f in self.fields if f.has_vla()
343 for line in f.get_vla_assign_code("msg->payload", [])]),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200344 " return msg;",
345 "}"])
346
347 def get_calc_msg_size_func_name(self):
348 return "vapi_calc_%s_msg_size" % self.name
349
350 def get_calc_msg_size_func_decl(self):
351 return "uword %s(%s *msg)" % (
352 self.get_calc_msg_size_func_name(),
353 self.get_c_name())
354
355 def get_calc_msg_size_func_def(self):
356 return "\n".join([
357 "%s" % self.get_calc_msg_size_func_decl(),
358 "{",
359 " return sizeof(*msg)%s;" %
360 "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
361 f.nelem_field.name,
362 f.name)
363 for f in self.fields
364 if f.nelem_field is not None
365 ]),
366 "}",
367 ])
368
369 def get_c_def(self):
370 if self.has_payload():
371 return "\n".join([
372 "typedef struct __attribute__ ((__packed__)) {",
Ole Troan53fffa12018-11-13 12:36:56 +0100373 "%s " %
374 "\n".join(self.payload_members),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200375 "} %s;" % self.get_payload_struct_name(),
376 "",
377 "typedef struct __attribute__ ((__packed__)) {",
378 (" %s %s;" % (self.header.get_c_name(),
379 self.fields[0].name)
380 if self.header is not None else ""),
381 " %s payload;" % self.get_payload_struct_name(),
382 "} %s;" % self.get_c_name(), ])
383 else:
384 return "\n".join([
385 "typedef struct __attribute__ ((__packed__)) {",
386 (" %s %s;" % (self.header.get_c_name(),
387 self.fields[0].name)
388 if self.header is not None else ""),
389 "} %s;" % self.get_c_name(), ])
390
391 def get_swap_payload_to_host_func_name(self):
392 return "%s_payload_ntoh" % self.get_c_name()
393
394 def get_swap_payload_to_be_func_name(self):
395 return "%s_payload_hton" % self.get_c_name()
396
397 def get_swap_payload_to_host_func_decl(self):
398 return "void %s(%s *payload)" % (
399 self.get_swap_payload_to_host_func_name(),
400 self.get_payload_struct_name())
401
402 def get_swap_payload_to_be_func_decl(self):
403 return "void %s(%s *payload)" % (
404 self.get_swap_payload_to_be_func_name(),
405 self.get_payload_struct_name())
406
407 def get_swap_payload_to_be_func_def(self):
408 return "%s\n{\n%s\n}" % (
409 self.get_swap_payload_to_be_func_decl(),
410 "\n".join([
411 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
412 for p in self.fields
413 if p.needs_byte_swap() and p.type != self.header]),
414 )
415
416 def get_swap_payload_to_host_func_def(self):
417 return "%s\n{\n%s\n}" % (
418 self.get_swap_payload_to_host_func_decl(),
419 "\n".join([
420 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
421 for p in self.fields
422 if p.needs_byte_swap() and p.type != self.header]),
423 )
424
425 def get_swap_to_host_func_name(self):
426 return "%s_ntoh" % self.get_c_name()
427
428 def get_swap_to_be_func_name(self):
429 return "%s_hton" % self.get_c_name()
430
431 def get_swap_to_host_func_decl(self):
432 return "void %s(%s *msg)" % (
433 self.get_swap_to_host_func_name(), self.get_c_name())
434
435 def get_swap_to_be_func_decl(self):
436 return "void %s(%s *msg)" % (
437 self.get_swap_to_be_func_name(), self.get_c_name())
438
439 def get_swap_to_be_func_def(self):
440 return "\n".join([
441 "%s" % self.get_swap_to_be_func_decl(),
442 "{",
443 (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
444 self.get_c_name()),
445 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
446 if self.header is not None else "",
447 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
448 if self.has_payload() else "",
449 "}",
450 ])
451
452 def get_swap_to_host_func_def(self):
453 return "\n".join([
454 "%s" % self.get_swap_to_host_func_decl(),
455 "{",
456 (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
457 self.get_c_name()),
458 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
459 if self.header is not None else "",
460 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
461 if self.has_payload() else "",
462 "}",
463 ])
464
465 def get_op_func_name(self):
466 return "vapi_%s" % self.name
467
468 def get_op_func_decl(self):
469 if self.reply.has_payload():
470 return "vapi_error_e %s(%s)" % (
471 self.get_op_func_name(),
472 ",\n ".join([
473 'struct vapi_ctx_s *ctx',
474 '%s *msg' % self.get_c_name(),
475 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
476 ' void *callback_ctx',
477 ' vapi_error_e rv',
478 ' bool is_last',
479 ' %s *reply)' %
480 self.reply.get_payload_struct_name(),
481 'void *callback_ctx',
482 ])
483 )
484 else:
485 return "vapi_error_e %s(%s)" % (
486 self.get_op_func_name(),
487 ",\n ".join([
488 'struct vapi_ctx_s *ctx',
489 '%s *msg' % self.get_c_name(),
490 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
491 ' void *callback_ctx',
492 ' vapi_error_e rv',
493 ' bool is_last)',
494 'void *callback_ctx',
495 ])
496 )
497
498 def get_op_func_def(self):
499 return "\n".join([
500 "%s" % self.get_op_func_decl(),
501 "{",
502 " if (!msg || !callback) {",
503 " return VAPI_EINVAL;",
504 " }",
505 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
506 " return VAPI_EAGAIN;",
507 " }",
508 " vapi_error_e rv;",
509 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
510 " return rv;",
511 " }",
512 " u32 req_context = vapi_gen_req_context(ctx);",
513 " msg->header.context = req_context;",
514 " %s(msg);" % self.get_swap_to_be_func_name(),
515 (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
516 "(ctx, msg, req_context))) {"
Klement Sekera2108c0c2018-08-24 11:43:20 +0200517 if self.reply_is_stream else
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200518 " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
519 ),
520 (" vapi_store_request(ctx, req_context, %s, "
521 "(vapi_cb_t)callback, callback_ctx);" %
Klement Sekera2108c0c2018-08-24 11:43:20 +0200522 ("true" if self.reply_is_stream else "false")),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200523 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
524 " abort (); /* this really shouldn't happen */",
525 " }",
526 " if (vapi_is_nonblocking(ctx)) {",
527 " rv = VAPI_OK;",
528 " } else {",
529 " rv = vapi_dispatch(ctx);",
530 " }",
531 " } else {",
532 " %s(msg);" % self.get_swap_to_host_func_name(),
533 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
534 " abort (); /* this really shouldn't happen */",
535 " }",
536 " }",
537 " return rv;",
538 "}",
539 "",
540 ])
541
542 def get_event_cb_func_decl(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200543 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200544 raise Exception(
Klement Sekeradc15be22017-06-12 06:49:33 +0200545 "Cannot register event callback for non-reply message")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200546 if self.has_payload():
547 return "\n".join([
548 "void vapi_set_%s_event_cb (" %
549 self.get_c_name(),
550 " struct vapi_ctx_s *ctx, ",
551 (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
552 "void *callback_ctx, %s *payload)," %
553 self.get_payload_struct_name()),
554 " void *callback_ctx)",
555 ])
556 else:
557 return "\n".join([
558 "void vapi_set_%s_event_cb (" %
559 self.get_c_name(),
560 " struct vapi_ctx_s *ctx, ",
561 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
562 "void *callback_ctx),",
563 " void *callback_ctx)",
564 ])
565
566 def get_event_cb_func_def(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200567 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200568 raise Exception(
569 "Cannot register event callback for non-reply function")
570 return "\n".join([
571 "%s" % self.get_event_cb_func_decl(),
572 "{",
573 (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
574 "callback_ctx);" %
575 self.get_msg_id_name()),
576 "}"])
577
578 def get_c_metadata_struct_name(self):
579 return "__vapi_metadata_%s" % self.name
580
581 def get_c_constructor(self):
582 has_context = False
583 if self.header is not None:
584 has_context = self.header.has_field('context')
585 return '\n'.join([
586 'static void __attribute__((constructor)) __vapi_constructor_%s()'
587 % self.name,
588 '{',
589 ' static const char name[] = "%s";' % self.name,
590 ' static const char name_with_crc[] = "%s_%s";'
591 % (self.name, self.crc[2:]),
592 ' static vapi_message_desc_t %s = {' %
593 self.get_c_metadata_struct_name(),
594 ' name,',
595 ' sizeof(name) - 1,',
596 ' name_with_crc,',
597 ' sizeof(name_with_crc) - 1,',
598 ' true,' if has_context else ' false,',
599 ' offsetof(%s, context),' % self.header.get_c_name()
600 if has_context else ' 0,',
601 (' offsetof(%s, payload),' % self.get_c_name())
Klement Sekeradab732a2018-07-04 13:43:46 +0200602 if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200603 ' sizeof(%s),' % self.get_c_name(),
604 ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
605 ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
Klement Sekeradab732a2018-07-04 13:43:46 +0200606 ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200607 ' };',
608 '',
609 ' %s = vapi_register_msg(&%s);' %
610 (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
611 ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
612 (self.name, self.get_msg_id_name()),
613 '}',
614 ])
615
616
617vapi_send_with_control_ping = """
618static inline vapi_error_e
619vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
620{
621 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
622 if (!ping)
623 {
624 return VAPI_ENOMEM;
625 }
626 ping->header.context = context;
627 vapi_msg_control_ping_hton (ping);
628 return vapi_send2 (ctx, msg, ping);
629}
630"""
631
632
Klement Sekera1732e472018-08-28 17:23:18 +0200633def emit_definition(parser, json_file, emitted, o):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200634 if o in emitted:
635 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200636 if o.name in ("msg_header1_t", "msg_header2_t"):
637 return
638 if hasattr(o, "depends"):
639 for x in o.depends:
Klement Sekera1732e472018-08-28 17:23:18 +0200640 emit_definition(parser, json_file, emitted, x)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200641 if hasattr(o, "reply"):
Klement Sekera1732e472018-08-28 17:23:18 +0200642 emit_definition(parser, json_file, emitted, o.reply)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200643 if hasattr(o, "get_c_def"):
644 if (o not in parser.enums_by_json[json_file] and
645 o not in parser.types_by_json[json_file] and
646 o not in parser.unions_by_json[json_file] and
Ole Troan53fffa12018-11-13 12:36:56 +0100647 o.name not in parser.messages_by_json[json_file] and
648 o not in parser.aliases_by_json[json_file]):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200649 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200650 guard = "defined_%s" % o.get_c_name()
651 print("#ifndef %s" % guard)
652 print("#define %s" % guard)
653 print("%s" % o.get_c_def())
654 print("")
655 function_attrs = "static inline "
656 if o.name in parser.messages_by_json[json_file]:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200657 if o.has_payload():
Klement Sekera2108c0c2018-08-24 11:43:20 +0200658 print("%s%s" % (function_attrs,
659 o.get_swap_payload_to_be_func_def()))
660 print("")
661 print("%s%s" % (function_attrs,
662 o.get_swap_payload_to_host_func_def()))
663 print("")
664 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
665 print("")
666 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
667 print("")
668 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200669 if not o.is_reply and not o.is_event:
Klement Sekera34a962b2018-09-06 19:31:36 +0200670 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200671 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
672 print("")
673 print("%s%s" % (function_attrs, o.get_op_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200674 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200675 print("%s" % o.get_c_constructor())
Klement Sekera1732e472018-08-28 17:23:18 +0200676 if o.is_reply or o.is_event:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200677 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200678 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200679 elif hasattr(o, "get_swap_to_be_func_def"):
680 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
681 print("")
682 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200683 print("#endif")
Klement Sekera34a962b2018-09-06 19:31:36 +0200684 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200685 emitted.append(o)
686
687
Klement Sekeradc15be22017-06-12 06:49:33 +0200688def gen_json_unified_header(parser, logger, j, io, name):
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200689 d, f = os.path.split(j)
Klement Sekeradc15be22017-06-12 06:49:33 +0200690 logger.info("Generating header `%s'" % name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200691 orig_stdout = sys.stdout
692 sys.stdout = io
693 include_guard = "__included_%s" % (
694 j.replace(".", "_").replace("/", "_").replace("-", "_"))
695 print("#ifndef %s" % include_guard)
696 print("#define %s" % include_guard)
697 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200698 print("#include <stdlib.h>")
699 print("#include <stddef.h>")
700 print("#include <arpa/inet.h>")
701 print("#include <vapi/vapi_internal.h>")
702 print("#include <vapi/vapi.h>")
703 print("#include <vapi/vapi_dbg.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200704 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200705 print("#ifdef __cplusplus")
706 print("extern \"C\" {")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200707 print("#endif")
Klement Sekeradc15be22017-06-12 06:49:33 +0200708 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200709 print("")
710 print("static inline vapi_error_e vapi_send_with_control_ping "
711 "(vapi_ctx_t ctx, void * msg, u32 context);")
712 else:
Klement Sekeradc15be22017-06-12 06:49:33 +0200713 print("#include <vapi/vpe.api.vapi.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200714 print("")
715 for m in parser.messages_by_json[j].values():
716 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
717 print("")
718 print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200719 f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200720 print("\\\n".join([
721 " vapi_msg_id_t %s;" % m.get_msg_id_name()
722 for m in parser.messages_by_json[j].values()
723 ]))
724 print("")
725 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200726 emitted = []
727 for e in parser.enums_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200728 emit_definition(parser, j, emitted, e)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200729 for u in parser.unions_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200730 emit_definition(parser, j, emitted, u)
Ole Troan52ca7562018-03-06 17:45:32 +0100731 for t in parser.types_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200732 emit_definition(parser, j, emitted, t)
Ole Troan75761b92019-09-11 17:49:08 +0200733 for a in parser.aliases_by_json[j]:
734 emit_definition(parser, j, emitted, a)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200735 for m in parser.messages_by_json[j].values():
Klement Sekera1732e472018-08-28 17:23:18 +0200736 emit_definition(parser, j, emitted, m)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200737
738 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200739
Klement Sekeradc15be22017-06-12 06:49:33 +0200740 if name == "vpe.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200741 print("%s" % vapi_send_with_control_ping)
742 print("")
743
Klement Sekeradc15be22017-06-12 06:49:33 +0200744 print("#ifdef __cplusplus")
745 print("}")
746 print("#endif")
747 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200748 print("#endif")
749 sys.stdout = orig_stdout
750
751
Klement Sekeradc15be22017-06-12 06:49:33 +0200752def json_to_c_header_name(json_name):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200753 if json_name.endswith(".json"):
754 return "%s.vapi.h" % os.path.splitext(json_name)[0]
755 raise Exception("Unexpected json name `%s'!" % json_name)
756
757
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200758def gen_c_unified_headers(parser, logger, prefix, remove_path):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200759 if prefix == "" or prefix is None:
760 prefix = ""
761 else:
762 prefix = "%s/" % prefix
763 for j in parser.json_files:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200764 if remove_path:
765 d, f = os.path.split(j)
766 else:
767 f = j
768 with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
Klement Sekeradc15be22017-06-12 06:49:33 +0200769 gen_json_unified_header(
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200770 parser, logger, j, io, json_to_c_header_name(f))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200771
772
773if __name__ == '__main__':
774 try:
775 verbose = int(os.getenv("V", 0))
776 except:
777 verbose = 0
778
779 if verbose >= 2:
780 log_level = 10
781 elif verbose == 1:
782 log_level = 20
783 else:
784 log_level = 40
785
786 logging.basicConfig(stream=sys.stdout, level=log_level)
787 logger = logging.getLogger("VAPI C GEN")
788 logger.setLevel(log_level)
789
Klement Sekeradc15be22017-06-12 06:49:33 +0200790 argparser = argparse.ArgumentParser(description="VPP C API generator")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200791 argparser.add_argument('files', metavar='api-file', action='append',
792 type=str, help='json api file'
793 '(may be specified multiple times)')
794 argparser.add_argument('--prefix', action='store', default=None,
795 help='path prefix')
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200796 argparser.add_argument('--remove-path', action='store_true',
797 help='remove path from filename')
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200798 args = argparser.parse_args()
799
800 jsonparser = JsonParser(logger, args.files,
801 simple_type_class=CSimpleType,
Klement Sekera2108c0c2018-08-24 11:43:20 +0200802 enum_class=CEnum,
803 union_class=CUnion,
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200804 struct_type_class=CStructType,
805 field_class=CField,
Ole Troan53fffa12018-11-13 12:36:56 +0100806 message_class=CMessage,
807 alias_class=CAlias)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200808
809 # not using the model of having separate generated header and code files
810 # with generated symbols present in shared library (per discussion with
811 # Damjan), to avoid symbol version issues in .so
812 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
813
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200814 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200815
816 for e in jsonparser.exceptions:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200817 logger.warning(e)