blob: 100263ccbc311818ddb2da413bc935c31a06db42 [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
Klement Sekeraa25ce962021-11-15 15:52:37 +01004import inspect
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02005import os
6import sys
7import logging
Klement Sekera2108c0c2018-08-24 11:43:20 +02008from vapi_json_parser import Field, Struct, Enum, Union, Message, JsonParser,\
Ole Troan53fffa12018-11-13 12:36:56 +01009 SimpleType, StructType, Alias
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020010
11
12class CField(Field):
Ole Troan53fffa12018-11-13 12:36:56 +010013 def get_c_name(self):
Ole Troan8c8acc02018-11-27 10:05:23 +010014 return "vapi_type_%s" % self.name
Ole Troan53fffa12018-11-13 12:36:56 +010015
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020016 def get_c_def(self):
Ole Troane5ff5a32019-08-23 22:55:18 +020017 if self.type.get_c_name() == 'vl_api_string_t':
18 if self.len:
19 return "u8 %s[%d];" % (self.name, self.len)
20 else:
21 return "vl_api_string_t %s;" % (self.name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020022 else:
Paul Vinciguerrad7a32eb2020-05-01 10:09:58 -040023 if self.len is not None and type(self.len) != dict:
Klement Sekeraa25ce962021-11-15 15:52:37 +010024 return "%s %s[%d];" % (self.type.get_c_name(), self.name,
25 self.len)
Ole Troane5ff5a32019-08-23 22:55:18 +020026 else:
27 return "%s %s;" % (self.type.get_c_name(), self.name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020028
29 def get_swap_to_be_code(self, struct, var):
Paul Vinciguerrad7a32eb2020-05-01 10:09:58 -040030 if self.len is not None and type(self.len) != dict:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020031 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020032 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020033 " while(0);" % (
34 self.len,
35 self.type.get_swap_to_be_code(struct, "%s[i]" % var))
36 else:
37 if self.nelem_field.needs_byte_swap():
38 nelem_field = "%s(%s%s)" % (
39 self.nelem_field.type.get_swap_to_host_func_name(),
40 struct, self.nelem_field.name)
41 else:
42 nelem_field = "%s%s" % (struct, self.nelem_field.name)
43 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020044 "do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020045 " while(0);" %
46 (nelem_field, self.type.get_swap_to_be_code(
47 struct, "%s[i]" % var)))
48 return self.type.get_swap_to_be_code(struct, "%s" % var)
49
50 def get_swap_to_host_code(self, struct, var):
Paul Vinciguerrad7a32eb2020-05-01 10:09:58 -040051 if self.len is not None and type(self.len) != dict:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020052 if self.len > 0:
Klement Sekeradc15be22017-06-12 06:49:33 +020053 return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020054 " while(0);" % (
55 self.len,
56 self.type.get_swap_to_host_code(struct, "%s[i]" % var))
57 else:
58 # nelem_field already swapped to host here...
59 return (
Klement Sekeradc15be22017-06-12 06:49:33 +020060 "do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020061 " while(0);" %
62 (struct, self.nelem_field.name,
63 self.type.get_swap_to_host_code(
64 struct, "%s[i]" % var)))
65 return self.type.get_swap_to_host_code(struct, "%s" % var)
66
67 def needs_byte_swap(self):
68 return self.type.needs_byte_swap()
69
Klement Sekera34a962b2018-09-06 19:31:36 +020070 def get_vla_field_length_name(self, path):
71 return "%s_%s_array_size" % ("_".join(path), self.name)
72
73 def get_alloc_vla_param_names(self, path):
74 if self.is_vla():
75 result = [self.get_vla_field_length_name(path)]
76 else:
77 result = []
78 if self.type.has_vla():
79 t = self.type.get_alloc_vla_param_names(path + [self.name])
80 result.extend(t)
81 return result
82
83 def get_vla_calc_size_code(self, prefix, path):
84 if self.is_vla():
85 result = ["sizeof(%s.%s[0]) * %s" % (
86 ".".join([prefix] + path),
87 self.name,
88 self.get_vla_field_length_name(path))]
89 else:
90 result = []
91 if self.type.has_vla():
92 t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
93 result.extend(t)
94 return result
95
96 def get_vla_assign_code(self, prefix, path):
97 result = []
98 if self.is_vla():
99 result.append("%s.%s = %s" % (
100 ".".join([prefix] + path),
101 self.nelem_field.name,
102 self.get_vla_field_length_name(path)))
103 if self.type.has_vla():
104 t = self.type.get_vla_assign_code(prefix, path + [self.name])
105 result.extend(t)
106 return result
107
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200108
Ole Troan53fffa12018-11-13 12:36:56 +0100109class CAlias(CField):
110 def get_c_name(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100111 return "vapi_type_%s" % self.name
Ole Troan53fffa12018-11-13 12:36:56 +0100112
113 def get_c_def(self):
Ole Troan8c8acc02018-11-27 10:05:23 +0100114 if self.len is not None:
Klement Sekera173e20c2018-12-12 12:57:32 +0100115 return "typedef %s vapi_type_%s[%d];" % (
116 self.type.get_c_name(), self.name, self.len)
Ole Troan8c8acc02018-11-27 10:05:23 +0100117 else:
Klement Sekera173e20c2018-12-12 12:57:32 +0100118 return "typedef %s vapi_type_%s;" % (
119 self.type.get_c_name(), self.name)
Ole Troan53fffa12018-11-13 12:36:56 +0100120
121
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200122class CStruct(Struct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200123 def get_c_def(self):
124 return "\n".join([
Ole Troan53fffa12018-11-13 12:36:56 +0100125 "typedef struct __attribute__((__packed__)) {\n%s" % (
126 "\n".join([" %s" % x.get_c_def()
127 for x in self.fields])),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200128 "} %s;" % self.get_c_name()])
129
Klement Sekera34a962b2018-09-06 19:31:36 +0200130 def get_vla_assign_code(self, prefix, path):
131 return [x for f in self.fields if f.has_vla()
132 for x in f.get_vla_assign_code(prefix, path)]
133
134 def get_alloc_vla_param_names(self, path):
135 return [x for f in self.fields
136 if f.has_vla()
137 for x in f.get_alloc_vla_param_names(path)]
138
139 def get_vla_calc_size_code(self, prefix, path):
140 return [x for f in self.fields if f.has_vla()
141 for x in f.get_vla_calc_size_code(prefix, path)]
142
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200143
144class CSimpleType (SimpleType):
145
146 swap_to_be_dict = {
147 'i16': 'htobe16', 'u16': 'htobe16',
148 'i32': 'htobe32', 'u32': 'htobe32',
149 'i64': 'htobe64', 'u64': 'htobe64',
150 }
151
152 swap_to_host_dict = {
153 'i16': 'be16toh', 'u16': 'be16toh',
154 'i32': 'be32toh', 'u32': 'be32toh',
155 'i64': 'be64toh', 'u64': 'be64toh',
156 }
157
Neale Rannsb5c0d352020-04-22 16:06:45 +0000158 __packed = "__attribute__((packed))"
159 pack_dict = {
160 'i8': __packed, 'u8': __packed,
161 'i16': __packed, 'u16': __packed,
162 }
163
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200164 def get_c_name(self):
165 return self.name
166
167 def get_swap_to_be_func_name(self):
168 return self.swap_to_be_dict[self.name]
169
170 def get_swap_to_host_func_name(self):
171 return self.swap_to_host_dict[self.name]
172
Neale Rannsb5c0d352020-04-22 16:06:45 +0000173 def get_packed_string(self):
174 return self.pack_dict[self.name]
175
Klement Sekera2108c0c2018-08-24 11:43:20 +0200176 def get_swap_to_be_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200177 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200178 return "%s = %s%s(%s);" % (x,
179 "(%s)" % cast if cast else "",
180 self.get_swap_to_be_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200181
Klement Sekera2108c0c2018-08-24 11:43:20 +0200182 def get_swap_to_host_code(self, struct, var, cast=None):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200183 x = "%s%s" % (struct, var)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200184 return "%s = %s%s(%s);" % (x,
185 "(%s)" % cast if cast else "",
186 self.get_swap_to_host_func_name(), x)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200187
188 def needs_byte_swap(self):
189 try:
190 self.get_swap_to_host_func_name()
191 return True
Ole Troan53fffa12018-11-13 12:36:56 +0100192 except KeyError:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200193 pass
194 return False
195
Neale Rannsb5c0d352020-04-22 16:06:45 +0000196 def get_packed(self):
197 return self.pack_dict.get(self.name, "")
198
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200199
Klement Sekera2108c0c2018-08-24 11:43:20 +0200200class CEnum(Enum):
201 def get_c_name(self):
202 return "vapi_enum_%s" % self.name
203
204 def get_c_def(self):
Neale Rannsb5c0d352020-04-22 16:06:45 +0000205 return "typedef enum {\n%s\n} %s %s;" % (
Klement Sekera2108c0c2018-08-24 11:43:20 +0200206 "\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
Neale Rannsb5c0d352020-04-22 16:06:45 +0000207 self.type.get_packed(),
Klement Sekera2108c0c2018-08-24 11:43:20 +0200208 self.get_c_name()
209 )
210
211 def needs_byte_swap(self):
212 return self.type.needs_byte_swap()
213
214 def get_swap_to_be_code(self, struct, var):
215 return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
216
217 def get_swap_to_host_code(self, struct, var):
218 return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
219
220
221class CUnion(Union):
222 def get_c_name(self):
223 return "vapi_union_%s" % self.name
224
225 def get_c_def(self):
226 return "typedef union {\n%s\n} %s;" % (
227 "\n".join([" %s %s;" % (i.get_c_name(), j)
228 for i, j in self.type_pairs]),
229 self.get_c_name()
230 )
231
232 def needs_byte_swap(self):
233 return False
234
235
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200236class CStructType (StructType, CStruct):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200237 def get_c_name(self):
238 return "vapi_type_%s" % self.name
239
240 def get_swap_to_be_func_name(self):
241 return "%s_hton" % self.get_c_name()
242
243 def get_swap_to_host_func_name(self):
244 return "%s_ntoh" % self.get_c_name()
245
246 def get_swap_to_be_func_decl(self):
247 return "void %s(%s *msg)" % (
248 self.get_swap_to_be_func_name(), self.get_c_name())
249
250 def get_swap_to_be_func_def(self):
251 return "%s\n{\n%s\n}" % (
252 self.get_swap_to_be_func_decl(),
253 "\n".join([
254 " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
255 for p in self.fields if p.needs_byte_swap()]),
256 )
257
258 def get_swap_to_host_func_decl(self):
259 return "void %s(%s *msg)" % (
260 self.get_swap_to_host_func_name(), self.get_c_name())
261
262 def get_swap_to_host_func_def(self):
263 return "%s\n{\n%s\n}" % (
264 self.get_swap_to_host_func_decl(),
265 "\n".join([
266 " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
267 for p in self.fields if p.needs_byte_swap()]),
268 )
269
270 def get_swap_to_be_code(self, struct, var):
271 return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
272
273 def get_swap_to_host_code(self, struct, var):
274 return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
275
276 def needs_byte_swap(self):
277 for f in self.fields:
278 if f.needs_byte_swap():
279 return True
280 return False
281
282
283class CMessage (Message):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200284 def __init__(self, logger, definition, json_parser):
285 super(CMessage, self).__init__(logger, definition, json_parser)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200286 self.payload_members = [
287 " %s" % p.get_c_def()
288 for p in self.fields
289 if p.type != self.header
290 ]
291
292 def has_payload(self):
293 return len(self.payload_members) > 0
294
295 def get_msg_id_name(self):
296 return "vapi_msg_id_%s" % self.name
297
298 def get_c_name(self):
299 return "vapi_msg_%s" % self.name
300
301 def get_payload_struct_name(self):
302 return "vapi_payload_%s" % self.name
303
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200304 def get_alloc_func_name(self):
305 return "vapi_alloc_%s" % self.name
306
Klement Sekeradc15be22017-06-12 06:49:33 +0200307 def get_alloc_vla_param_names(self):
Klement Sekera34a962b2018-09-06 19:31:36 +0200308 return [x for f in self.fields
309 if f.has_vla()
310 for x in f.get_alloc_vla_param_names([])]
Klement Sekeradc15be22017-06-12 06:49:33 +0200311
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200312 def get_alloc_func_decl(self):
313 return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
314 self.get_c_name(),
315 self.get_alloc_func_name(),
Klement Sekeradc15be22017-06-12 06:49:33 +0200316 "".join([", size_t %s" % n for n in
317 self.get_alloc_vla_param_names()]))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200318
319 def get_alloc_func_def(self):
320 extra = []
321 if self.header.has_field('client_index'):
322 extra.append(
323 " msg->header.client_index = vapi_get_client_index(ctx);")
324 if self.header.has_field('context'):
325 extra.append(" msg->header.context = 0;")
326 return "\n".join([
327 "%s" % self.get_alloc_func_decl(),
328 "{",
329 " %s *msg = NULL;" % self.get_c_name(),
330 " const size_t size = sizeof(%s)%s;" % (
331 self.get_c_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200332 "".join([" + %s" % x for f in self.fields if f.has_vla()
333 for x in f.get_vla_calc_size_code("msg->payload",
334 [])])),
Klement Sekeradc15be22017-06-12 06:49:33 +0200335 " /* cast here required to play nicely with C++ world ... */",
336 " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200337 " if (!msg) {",
338 " return NULL;",
339 " }",
340 ] + extra + [
341 " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
342 self.get_msg_id_name(),
Klement Sekera34a962b2018-09-06 19:31:36 +0200343 "".join([" %s;\n" % line
344 for f in self.fields if f.has_vla()
345 for line in f.get_vla_assign_code("msg->payload", [])]),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200346 " return msg;",
347 "}"])
348
349 def get_calc_msg_size_func_name(self):
350 return "vapi_calc_%s_msg_size" % self.name
351
352 def get_calc_msg_size_func_decl(self):
353 return "uword %s(%s *msg)" % (
354 self.get_calc_msg_size_func_name(),
355 self.get_c_name())
356
357 def get_calc_msg_size_func_def(self):
358 return "\n".join([
359 "%s" % self.get_calc_msg_size_func_decl(),
360 "{",
361 " return sizeof(*msg)%s;" %
362 "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
363 f.nelem_field.name,
364 f.name)
365 for f in self.fields
366 if f.nelem_field is not None
367 ]),
368 "}",
369 ])
370
Klement Sekeraa25ce962021-11-15 15:52:37 +0100371 def get_verify_msg_size_func_name(self):
372 return f"vapi_verify_{self.name}_msg_size"
373
374 def get_verify_msg_size_func_decl(self):
375 return "int %s(%s *msg, uword buf_size)" % (
376 self.get_verify_msg_size_func_name(),
377 self.get_c_name())
378
379 def get_verify_msg_size_func_def(self):
380 return inspect.cleandoc(
381 f"""
382 {self.get_verify_msg_size_func_decl()}
383 {{
384 if (sizeof({self.get_c_name()}) > buf_size)
385 {{
386 VAPI_ERR("Truncated '{self.name}' msg received, received %lu"
387 "bytes, expected %lu bytes.", buf_size,
388 sizeof({self.get_c_name()}));
389 return -1;
390 }}
391 if ({self.get_calc_msg_size_func_name()}(msg) > buf_size)
392 {{
393 VAPI_ERR("Truncated '{self.name}' msg received, received %lu"
394 "bytes, expected %lu bytes.", buf_size,
395 sizeof({self.get_calc_msg_size_func_name()}));
396 return -1;
397 }}
398 return 0;
399 }}
400 """)
401
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200402 def get_c_def(self):
403 if self.has_payload():
404 return "\n".join([
405 "typedef struct __attribute__ ((__packed__)) {",
Ole Troan53fffa12018-11-13 12:36:56 +0100406 "%s " %
407 "\n".join(self.payload_members),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200408 "} %s;" % self.get_payload_struct_name(),
409 "",
410 "typedef struct __attribute__ ((__packed__)) {",
411 (" %s %s;" % (self.header.get_c_name(),
412 self.fields[0].name)
413 if self.header is not None else ""),
414 " %s payload;" % self.get_payload_struct_name(),
415 "} %s;" % self.get_c_name(), ])
416 else:
417 return "\n".join([
418 "typedef struct __attribute__ ((__packed__)) {",
419 (" %s %s;" % (self.header.get_c_name(),
420 self.fields[0].name)
421 if self.header is not None else ""),
422 "} %s;" % self.get_c_name(), ])
423
424 def get_swap_payload_to_host_func_name(self):
425 return "%s_payload_ntoh" % self.get_c_name()
426
427 def get_swap_payload_to_be_func_name(self):
428 return "%s_payload_hton" % self.get_c_name()
429
430 def get_swap_payload_to_host_func_decl(self):
431 return "void %s(%s *payload)" % (
432 self.get_swap_payload_to_host_func_name(),
433 self.get_payload_struct_name())
434
435 def get_swap_payload_to_be_func_decl(self):
436 return "void %s(%s *payload)" % (
437 self.get_swap_payload_to_be_func_name(),
438 self.get_payload_struct_name())
439
440 def get_swap_payload_to_be_func_def(self):
441 return "%s\n{\n%s\n}" % (
442 self.get_swap_payload_to_be_func_decl(),
443 "\n".join([
444 " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
445 for p in self.fields
446 if p.needs_byte_swap() and p.type != self.header]),
447 )
448
449 def get_swap_payload_to_host_func_def(self):
450 return "%s\n{\n%s\n}" % (
451 self.get_swap_payload_to_host_func_decl(),
452 "\n".join([
453 " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
454 for p in self.fields
455 if p.needs_byte_swap() and p.type != self.header]),
456 )
457
458 def get_swap_to_host_func_name(self):
459 return "%s_ntoh" % self.get_c_name()
460
461 def get_swap_to_be_func_name(self):
462 return "%s_hton" % self.get_c_name()
463
464 def get_swap_to_host_func_decl(self):
465 return "void %s(%s *msg)" % (
466 self.get_swap_to_host_func_name(), self.get_c_name())
467
468 def get_swap_to_be_func_decl(self):
469 return "void %s(%s *msg)" % (
470 self.get_swap_to_be_func_name(), self.get_c_name())
471
472 def get_swap_to_be_func_def(self):
473 return "\n".join([
474 "%s" % self.get_swap_to_be_func_decl(),
475 "{",
476 (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
477 self.get_c_name()),
478 " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
479 if self.header is not None else "",
480 " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
481 if self.has_payload() else "",
482 "}",
483 ])
484
485 def get_swap_to_host_func_def(self):
486 return "\n".join([
487 "%s" % self.get_swap_to_host_func_decl(),
488 "{",
489 (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
490 self.get_c_name()),
491 " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
492 if self.header is not None else "",
493 " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
494 if self.has_payload() else "",
495 "}",
496 ])
497
498 def get_op_func_name(self):
499 return "vapi_%s" % self.name
500
501 def get_op_func_decl(self):
502 if self.reply.has_payload():
503 return "vapi_error_e %s(%s)" % (
504 self.get_op_func_name(),
505 ",\n ".join([
506 'struct vapi_ctx_s *ctx',
507 '%s *msg' % self.get_c_name(),
508 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
509 ' void *callback_ctx',
510 ' vapi_error_e rv',
511 ' bool is_last',
512 ' %s *reply)' %
513 self.reply.get_payload_struct_name(),
514 'void *callback_ctx',
515 ])
516 )
517 else:
518 return "vapi_error_e %s(%s)" % (
519 self.get_op_func_name(),
520 ",\n ".join([
521 'struct vapi_ctx_s *ctx',
522 '%s *msg' % self.get_c_name(),
523 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
524 ' void *callback_ctx',
525 ' vapi_error_e rv',
526 ' bool is_last)',
527 'void *callback_ctx',
528 ])
529 )
530
531 def get_op_func_def(self):
532 return "\n".join([
533 "%s" % self.get_op_func_decl(),
534 "{",
535 " if (!msg || !callback) {",
536 " return VAPI_EINVAL;",
537 " }",
538 " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
539 " return VAPI_EAGAIN;",
540 " }",
541 " vapi_error_e rv;",
542 " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
543 " return rv;",
544 " }",
545 " u32 req_context = vapi_gen_req_context(ctx);",
546 " msg->header.context = req_context;",
547 " %s(msg);" % self.get_swap_to_be_func_name(),
548 (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
549 "(ctx, msg, req_context))) {"
Klement Sekera2108c0c2018-08-24 11:43:20 +0200550 if self.reply_is_stream else
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200551 " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
552 ),
553 (" vapi_store_request(ctx, req_context, %s, "
554 "(vapi_cb_t)callback, callback_ctx);" %
Klement Sekera2108c0c2018-08-24 11:43:20 +0200555 ("true" if self.reply_is_stream else "false")),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200556 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
557 " abort (); /* this really shouldn't happen */",
558 " }",
559 " if (vapi_is_nonblocking(ctx)) {",
560 " rv = VAPI_OK;",
561 " } else {",
562 " rv = vapi_dispatch(ctx);",
563 " }",
564 " } else {",
565 " %s(msg);" % self.get_swap_to_host_func_name(),
566 " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
567 " abort (); /* this really shouldn't happen */",
568 " }",
569 " }",
570 " return rv;",
571 "}",
572 "",
573 ])
574
575 def get_event_cb_func_decl(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200576 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200577 raise Exception(
Klement Sekeradc15be22017-06-12 06:49:33 +0200578 "Cannot register event callback for non-reply message")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200579 if self.has_payload():
580 return "\n".join([
581 "void vapi_set_%s_event_cb (" %
582 self.get_c_name(),
583 " struct vapi_ctx_s *ctx, ",
584 (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
585 "void *callback_ctx, %s *payload)," %
586 self.get_payload_struct_name()),
587 " void *callback_ctx)",
588 ])
589 else:
590 return "\n".join([
591 "void vapi_set_%s_event_cb (" %
592 self.get_c_name(),
593 " struct vapi_ctx_s *ctx, ",
594 " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
595 "void *callback_ctx),",
596 " void *callback_ctx)",
597 ])
598
599 def get_event_cb_func_def(self):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200600 if not self.is_reply and not self.is_event:
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200601 raise Exception(
602 "Cannot register event callback for non-reply function")
603 return "\n".join([
604 "%s" % self.get_event_cb_func_decl(),
605 "{",
606 (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
607 "callback_ctx);" %
608 self.get_msg_id_name()),
609 "}"])
610
611 def get_c_metadata_struct_name(self):
612 return "__vapi_metadata_%s" % self.name
613
614 def get_c_constructor(self):
615 has_context = False
616 if self.header is not None:
617 has_context = self.header.has_field('context')
618 return '\n'.join([
619 'static void __attribute__((constructor)) __vapi_constructor_%s()'
620 % self.name,
621 '{',
622 ' static const char name[] = "%s";' % self.name,
623 ' static const char name_with_crc[] = "%s_%s";'
624 % (self.name, self.crc[2:]),
625 ' static vapi_message_desc_t %s = {' %
626 self.get_c_metadata_struct_name(),
627 ' name,',
628 ' sizeof(name) - 1,',
629 ' name_with_crc,',
630 ' sizeof(name_with_crc) - 1,',
631 ' true,' if has_context else ' false,',
632 ' offsetof(%s, context),' % self.header.get_c_name()
633 if has_context else ' 0,',
634 (' offsetof(%s, payload),' % self.get_c_name())
Klement Sekeradab732a2018-07-04 13:43:46 +0200635 if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
Klement Sekeraa25ce962021-11-15 15:52:37 +0100636 ' (verify_msg_size_fn_t)%s,' %
637 self.get_verify_msg_size_func_name(),
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200638 ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
639 ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
Klement Sekeradab732a2018-07-04 13:43:46 +0200640 ' VAPI_INVALID_MSG_ID,',
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200641 ' };',
642 '',
643 ' %s = vapi_register_msg(&%s);' %
644 (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
645 ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
646 (self.name, self.get_msg_id_name()),
647 '}',
648 ])
649
650
651vapi_send_with_control_ping = """
652static inline vapi_error_e
653vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
654{
655 vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
656 if (!ping)
657 {
658 return VAPI_ENOMEM;
659 }
660 ping->header.context = context;
661 vapi_msg_control_ping_hton (ping);
662 return vapi_send2 (ctx, msg, ping);
663}
664"""
665
666
Klement Sekera1732e472018-08-28 17:23:18 +0200667def emit_definition(parser, json_file, emitted, o):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200668 if o in emitted:
669 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200670 if o.name in ("msg_header1_t", "msg_header2_t"):
671 return
672 if hasattr(o, "depends"):
673 for x in o.depends:
Klement Sekera1732e472018-08-28 17:23:18 +0200674 emit_definition(parser, json_file, emitted, x)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200675 if hasattr(o, "reply"):
Klement Sekera1732e472018-08-28 17:23:18 +0200676 emit_definition(parser, json_file, emitted, o.reply)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200677 if hasattr(o, "get_c_def"):
678 if (o not in parser.enums_by_json[json_file] and
679 o not in parser.types_by_json[json_file] and
680 o not in parser.unions_by_json[json_file] and
Ole Troan53fffa12018-11-13 12:36:56 +0100681 o.name not in parser.messages_by_json[json_file] and
682 o not in parser.aliases_by_json[json_file]):
Klement Sekera2108c0c2018-08-24 11:43:20 +0200683 return
Klement Sekera2108c0c2018-08-24 11:43:20 +0200684 guard = "defined_%s" % o.get_c_name()
685 print("#ifndef %s" % guard)
686 print("#define %s" % guard)
687 print("%s" % o.get_c_def())
688 print("")
689 function_attrs = "static inline "
690 if o.name in parser.messages_by_json[json_file]:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200691 if o.has_payload():
Klement Sekera2108c0c2018-08-24 11:43:20 +0200692 print("%s%s" % (function_attrs,
693 o.get_swap_payload_to_be_func_def()))
694 print("")
695 print("%s%s" % (function_attrs,
696 o.get_swap_payload_to_host_func_def()))
697 print("")
698 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
699 print("")
700 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
701 print("")
702 print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
Klement Sekeraa25ce962021-11-15 15:52:37 +0100703 print("")
704 print("%s%s" % (function_attrs, o.get_verify_msg_size_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200705 if not o.is_reply and not o.is_event:
Klement Sekera34a962b2018-09-06 19:31:36 +0200706 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200707 print("%s%s" % (function_attrs, o.get_alloc_func_def()))
708 print("")
709 print("%s%s" % (function_attrs, o.get_op_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200710 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200711 print("%s" % o.get_c_constructor())
Klement Sekera1732e472018-08-28 17:23:18 +0200712 if o.is_reply or o.is_event:
Klement Sekera2108c0c2018-08-24 11:43:20 +0200713 print("")
Klement Sekera34a962b2018-09-06 19:31:36 +0200714 print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200715 elif hasattr(o, "get_swap_to_be_func_def"):
716 print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
717 print("")
718 print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
Klement Sekera2108c0c2018-08-24 11:43:20 +0200719 print("#endif")
Klement Sekera34a962b2018-09-06 19:31:36 +0200720 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200721 emitted.append(o)
722
723
Klement Sekeradc15be22017-06-12 06:49:33 +0200724def gen_json_unified_header(parser, logger, j, io, name):
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200725 d, f = os.path.split(j)
Klement Sekeradc15be22017-06-12 06:49:33 +0200726 logger.info("Generating header `%s'" % name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200727 orig_stdout = sys.stdout
728 sys.stdout = io
729 include_guard = "__included_%s" % (
Klement Sekeraa25ce962021-11-15 15:52:37 +0100730 j.replace(".", "_").replace("/", "_").replace("-", "_").replace(
731 "+", "_"))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200732 print("#ifndef %s" % include_guard)
733 print("#define %s" % include_guard)
734 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200735 print("#include <stdlib.h>")
736 print("#include <stddef.h>")
737 print("#include <arpa/inet.h>")
738 print("#include <vapi/vapi_internal.h>")
739 print("#include <vapi/vapi.h>")
740 print("#include <vapi/vapi_dbg.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200741 print("")
Klement Sekeradc15be22017-06-12 06:49:33 +0200742 print("#ifdef __cplusplus")
743 print("extern \"C\" {")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200744 print("#endif")
Filip Tehlarf0e67d72021-07-23 22:03:05 +0000745 if name == "memclnt.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200746 print("")
747 print("static inline vapi_error_e vapi_send_with_control_ping "
748 "(vapi_ctx_t ctx, void * msg, u32 context);")
749 else:
Florin Corasa1400ce2021-09-15 09:02:08 -0700750 print("#include <vapi/vlib.api.vapi.h>")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200751 print("")
752 for m in parser.messages_by_json[j].values():
753 print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
754 print("")
755 print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200756 f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200757 print("\\\n".join([
758 " vapi_msg_id_t %s;" % m.get_msg_id_name()
759 for m in parser.messages_by_json[j].values()
760 ]))
761 print("")
762 print("")
Klement Sekera2108c0c2018-08-24 11:43:20 +0200763 emitted = []
764 for e in parser.enums_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200765 emit_definition(parser, j, emitted, e)
Klement Sekera2108c0c2018-08-24 11:43:20 +0200766 for u in parser.unions_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200767 emit_definition(parser, j, emitted, u)
Ole Troan52ca7562018-03-06 17:45:32 +0100768 for t in parser.types_by_json[j]:
Klement Sekera1732e472018-08-28 17:23:18 +0200769 emit_definition(parser, j, emitted, t)
Ole Troan75761b92019-09-11 17:49:08 +0200770 for a in parser.aliases_by_json[j]:
771 emit_definition(parser, j, emitted, a)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200772 for m in parser.messages_by_json[j].values():
Klement Sekera1732e472018-08-28 17:23:18 +0200773 emit_definition(parser, j, emitted, m)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200774
775 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200776
Florin Corasa1400ce2021-09-15 09:02:08 -0700777 if name == "vlib.api.vapi.h":
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200778 print("%s" % vapi_send_with_control_ping)
779 print("")
780
Klement Sekeradc15be22017-06-12 06:49:33 +0200781 print("#ifdef __cplusplus")
782 print("}")
783 print("#endif")
784 print("")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200785 print("#endif")
786 sys.stdout = orig_stdout
787
788
Klement Sekeradc15be22017-06-12 06:49:33 +0200789def json_to_c_header_name(json_name):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200790 if json_name.endswith(".json"):
791 return "%s.vapi.h" % os.path.splitext(json_name)[0]
792 raise Exception("Unexpected json name `%s'!" % json_name)
793
794
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200795def gen_c_unified_headers(parser, logger, prefix, remove_path):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200796 if prefix == "" or prefix is None:
797 prefix = ""
798 else:
799 prefix = "%s/" % prefix
800 for j in parser.json_files:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200801 if remove_path:
802 d, f = os.path.split(j)
803 else:
804 f = j
805 with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
Klement Sekeradc15be22017-06-12 06:49:33 +0200806 gen_json_unified_header(
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200807 parser, logger, j, io, json_to_c_header_name(f))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200808
809
810if __name__ == '__main__':
811 try:
812 verbose = int(os.getenv("V", 0))
813 except:
814 verbose = 0
815
816 if verbose >= 2:
817 log_level = 10
818 elif verbose == 1:
819 log_level = 20
820 else:
821 log_level = 40
822
823 logging.basicConfig(stream=sys.stdout, level=log_level)
824 logger = logging.getLogger("VAPI C GEN")
825 logger.setLevel(log_level)
826
Klement Sekeradc15be22017-06-12 06:49:33 +0200827 argparser = argparse.ArgumentParser(description="VPP C API generator")
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200828 argparser.add_argument('files', metavar='api-file', action='append',
829 type=str, help='json api file'
830 '(may be specified multiple times)')
831 argparser.add_argument('--prefix', action='store', default=None,
832 help='path prefix')
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200833 argparser.add_argument('--remove-path', action='store_true',
834 help='remove path from filename')
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200835 args = argparser.parse_args()
836
837 jsonparser = JsonParser(logger, args.files,
838 simple_type_class=CSimpleType,
Klement Sekera2108c0c2018-08-24 11:43:20 +0200839 enum_class=CEnum,
840 union_class=CUnion,
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200841 struct_type_class=CStructType,
842 field_class=CField,
Ole Troan53fffa12018-11-13 12:36:56 +0100843 message_class=CMessage,
844 alias_class=CAlias)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200845
846 # not using the model of having separate generated header and code files
847 # with generated symbols present in shared library (per discussion with
848 # Damjan), to avoid symbol version issues in .so
849 # gen_c_headers_and_code(jsonparser, logger, args.prefix)
850
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200851 gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200852
853 for e in jsonparser.exceptions:
Damjan Marion4c64b6e2018-08-26 18:14:46 +0200854 logger.warning(e)