blob: 643c00590cc2d43f0ac7e9486b0d7a825e3bf2f0 [file] [log] [blame]
Ole Troandf87f802020-11-18 19:17:48 +01001#
2# Copyright (c) 2020 Cisco and/or its affiliates.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at:
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15
16#
17# Provide two classes FromJSON and TOJSON that converts between JSON and VPP's
18# binary API format
19#
20
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020021"""
Ole Troandf87f802020-11-18 19:17:48 +010022This module creates C code for core VPP, VPP plugins and client side VAT and
23VAT2 tests.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020024"""
Ole Troandf87f802020-11-18 19:17:48 +010025
Ole Troan9d420872017-10-12 13:06:35 +020026import datetime
Klement Sekera0eb83f42021-12-02 16:36:34 +000027import itertools
Ole Troan9d420872017-10-12 13:06:35 +020028import os
Nirmoy Dasc9f40222018-06-28 10:18:43 +020029import time
Ole Troan33a58172019-09-04 09:12:29 +020030import sys
31from io import StringIO
Ole Troan2a1ca782019-09-19 01:08:30 +020032import shutil
Ole Troan9d420872017-10-12 13:06:35 +020033
Paul Vinciguerra9046e442020-11-20 23:10:09 -050034process_imports = False
35
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -050036
Ole Troandf87f802020-11-18 19:17:48 +010037###############################################################################
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020038class ToJSON:
39 """Class to generate functions converting from VPP binary API to JSON."""
40
Ole Troandf87f802020-11-18 19:17:48 +010041 _dispatch = {}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020042 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
43 is_number = {
44 "u8": None,
45 "i8": None,
46 "u16": None,
47 "i16": None,
48 "u32": None,
49 "i32": None,
50 "u64": None,
51 "i64": None,
52 "f64": None,
53 }
Ole Troandf87f802020-11-18 19:17:48 +010054
55 def __init__(self, module, types, defines, imported_types, stream):
56 self.stream = stream
57 self.module = module
58 self.defines = defines
59 self.types = types
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020060 self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
Ole Troandf87f802020-11-18 19:17:48 +010061 self.defines_hash = {d.name: d for d in defines}
62
63 def header(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020064 """Output the top boilerplate."""
Ole Troandf87f802020-11-18 19:17:48 +010065 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020066 write("#ifndef included_{}_api_tojson_h\n".format(self.module))
67 write("#define included_{}_api_tojson_h\n".format(self.module))
68 write("#include <vppinfra/cJSON.h>\n\n")
69 write("#include <vppinfra/jsonformat.h>\n\n")
70 if self.module == "interface_types":
71 write("#define vl_printfun\n")
72 write("#include <vnet/interface_types.api.h>\n\n")
Ole Troandf87f802020-11-18 19:17:48 +010073
74 def footer(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020075 """Output the bottom boilerplate."""
Ole Troandf87f802020-11-18 19:17:48 +010076 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020077 write("#endif\n")
Ole Troandf87f802020-11-18 19:17:48 +010078
Ole Troan18327be2021-01-12 21:49:38 +010079 def get_base_type(self, t):
Ole Troandf87f802020-11-18 19:17:48 +010080 vt_type = None
81 try:
82 vt = self.types_hash[t]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020083 if vt.type == "Using" and "length" not in vt.alias:
84 vt_type = vt.alias["type"]
Ole Troandf87f802020-11-18 19:17:48 +010085 except KeyError:
86 vt = t
Ole Troan18327be2021-01-12 21:49:38 +010087 return vt, vt_type
88
89 def get_json_func(self, t):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020090 """Given the type, returns the function to use to create a
91 cJSON object"""
Ole Troan18327be2021-01-12 21:49:38 +010092 vt, vt_type = self.get_base_type(t)
Ole Troandf87f802020-11-18 19:17:48 +010093
94 if t in self.is_number or vt_type in self.is_number:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020095 return "cJSON_AddNumberToObject", "", False
96 if t == "bool":
97 return "cJSON_AddBoolToObject", "", False
Ole Troandf87f802020-11-18 19:17:48 +010098
99 # Lookup type name check if it's enum
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200100 if vt.type == "Enum" or vt.type == "EnumFlag":
101 return "{t}_tojson".format(t=t), "", True
102 return "{t}_tojson".format(t=t), "&", True
Ole Troandf87f802020-11-18 19:17:48 +0100103
104 def get_json_array_func(self, t):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200105 """Given a type returns the function to create a cJSON object
106 for arrays."""
Ole Troandf87f802020-11-18 19:17:48 +0100107 if t in self.is_number:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200108 return "cJSON_CreateNumber", ""
109 if t == "bool":
110 return "cJSON_CreateBool", ""
Ole Troan18327be2021-01-12 21:49:38 +0100111 vt, vt_type = self.get_base_type(t)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200112 if vt.type == "Enum" or vt.type == "EnumFlag":
113 return "{t}_tojson".format(t=t), ""
114 return "{t}_tojson".format(t=t), "&"
Ole Troandf87f802020-11-18 19:17:48 +0100115
116 def print_string(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200117 """Create cJSON object from vl_api_string_t"""
Ole Troandf87f802020-11-18 19:17:48 +0100118 write = self.stream.write
119 if o.modern_vla:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200120 write(
121 ' vl_api_string_cJSON_AddToObject(o, "{n}", &a->{n});\n'.format(
122 n=o.fieldname
123 )
124 )
Ole Troandf87f802020-11-18 19:17:48 +0100125 else:
126
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200127 write(
128 ' cJSON_AddStringToObject(o, "{n}", (char *)a->{n});\n'.format(
129 n=o.fieldname
130 )
131 )
Ole Troandf87f802020-11-18 19:17:48 +0100132
133 def print_field(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200134 """Called for every field in a typedef or define."""
Ole Troandf87f802020-11-18 19:17:48 +0100135 write = self.stream.write
136 if o.fieldname in self.noprint_fields:
137 return
138
139 f, p, newobj = self.get_json_func(o.fieldtype)
140
141 if newobj:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200142 write(
143 ' cJSON_AddItemToObject(o, "{n}", {f}({p}a->{n}));\n'.format(
144 f=f, p=p, n=o.fieldname
145 )
146 )
Ole Troandf87f802020-11-18 19:17:48 +0100147 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200148 write(' {f}(o, "{n}", {p}a->{n});\n'.format(f=f, p=p, n=o.fieldname))
Ole Troandf87f802020-11-18 19:17:48 +0100149
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200150 _dispatch["Field"] = print_field
Ole Troandf87f802020-11-18 19:17:48 +0100151
152 def print_array(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200153 """Converts a VPP API array to cJSON array."""
Ole Troandf87f802020-11-18 19:17:48 +0100154 write = self.stream.write
155
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200156 forloop = """\
Ole Troandf87f802020-11-18 19:17:48 +0100157 {{
158 int i;
159 cJSON *array = cJSON_AddArrayToObject(o, "{n}");
160 for (i = 0; i < {lfield}; i++) {{
161 cJSON_AddItemToArray(array, {f}({p}a->{n}[i]));
162 }}
163 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200164"""
Ole Troandf87f802020-11-18 19:17:48 +0100165
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200166 if o.fieldtype == "string":
Ole Troandf87f802020-11-18 19:17:48 +0100167 self.print_string(o)
168 return
169
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200170 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
171 if o.fieldtype == "u8":
172 write(" {\n")
Ole Troandf87f802020-11-18 19:17:48 +0100173 # What is length field doing here?
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200174 write(
175 ' u8 *s = format(0, "0x%U", format_hex_bytes, '
176 "&a->{n}, {lfield});\n".format(n=o.fieldname, lfield=lfield)
177 )
178 write(
179 ' cJSON_AddStringToObject(o, "{n}", (char *)s);\n'.format(
180 n=o.fieldname
181 )
182 )
183 write(" vec_free(s);\n")
184 write(" }\n")
Ole Troandf87f802020-11-18 19:17:48 +0100185 return
186
187 f, p = self.get_json_array_func(o.fieldtype)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200188 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname, f=f, p=p))
Ole Troandf87f802020-11-18 19:17:48 +0100189
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200190 _dispatch["Array"] = print_array
Ole Troandf87f802020-11-18 19:17:48 +0100191
192 def print_enum(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200193 """Create cJSON object (string) for VPP API enum"""
Ole Troandf87f802020-11-18 19:17:48 +0100194 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200195 write(
196 "static inline cJSON *vl_api_{name}_t_tojson "
197 "(vl_api_{name}_t a) {{\n".format(name=o.name)
198 )
Ole Troandf87f802020-11-18 19:17:48 +0100199
200 write(" switch(a) {\n")
201 for b in o.block:
202 write(" case %s:\n" % b[1])
203 write(' return cJSON_CreateString("{}");\n'.format(b[0]))
204 write(' default: return cJSON_CreateString("Invalid ENUM");\n')
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200205 write(" }\n")
206 write(" return 0;\n")
207 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100208
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200209 _dispatch["Enum"] = print_enum
Ole Troan793be462020-12-04 13:15:30 +0100210
211 def print_enum_flag(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200212 """Create cJSON object (string) for VPP API enum"""
Ole Troan793be462020-12-04 13:15:30 +0100213 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200214 write(
215 "static inline cJSON *vl_api_{name}_t_tojson "
216 "(vl_api_{name}_t a) {{\n".format(name=o.name)
217 )
218 write(" cJSON *array = cJSON_CreateArray();\n")
Ole Troan793be462020-12-04 13:15:30 +0100219
220 for b in o.block:
Ole Troan45517152021-11-23 10:49:36 +0100221 if b[1] == 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200222 continue
223 write(" if (a & {})\n".format(b[0]))
Klement Sekera9b7e8ac2021-11-22 21:26:20 +0100224 write(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200225 ' cJSON_AddItemToArray(array, cJSON_CreateString("{}"));\n'.format(
226 b[0]
227 )
228 )
229 write(" return array;\n")
230 write("}\n")
Ole Troan793be462020-12-04 13:15:30 +0100231
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200232 _dispatch["EnumFlag"] = print_enum_flag
Ole Troandf87f802020-11-18 19:17:48 +0100233
234 def print_typedef(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200235 """Create cJSON (dictionary) object from VPP API typedef"""
Ole Troandf87f802020-11-18 19:17:48 +0100236 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200237 write(
238 "static inline cJSON *vl_api_{name}_t_tojson "
239 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
240 )
241 write(" cJSON *o = cJSON_CreateObject();\n")
Ole Troandf87f802020-11-18 19:17:48 +0100242
243 for t in o.block:
244 self._dispatch[t.type](self, t)
245
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200246 write(" return o;\n")
247 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100248
249 def print_define(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200250 """Create cJSON (dictionary) object from VPP API define"""
Ole Troandf87f802020-11-18 19:17:48 +0100251 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200252 write(
253 "static inline cJSON *vl_api_{name}_t_tojson "
254 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
255 )
256 write(" cJSON *o = cJSON_CreateObject();\n")
257 write(' cJSON_AddStringToObject(o, "_msgname", "{}");\n'.format(o.name))
258 write(
259 ' cJSON_AddStringToObject(o, "_crc", "{crc:08x}");\n'.format(crc=o.crc)
260 )
Ole Troandf87f802020-11-18 19:17:48 +0100261
262 for t in o.block:
263 self._dispatch[t.type](self, t)
264
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200265 write(" return o;\n")
266 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100267
268 def print_using(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200269 """Create cJSON (dictionary) object from VPP API aliased type"""
Ole Troandf87f802020-11-18 19:17:48 +0100270 if o.manual_print:
271 return
272
273 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200274 write(
275 "static inline cJSON *vl_api_{name}_t_tojson "
276 "(vl_api_{name}_t *a) {{\n".format(name=o.name)
277 )
Ole Troandf87f802020-11-18 19:17:48 +0100278
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200279 write(' u8 *s = format(0, "%U", format_vl_api_{}_t, a);\n'.format(o.name))
280 write(" cJSON *o = cJSON_CreateString((char *)s);\n")
281 write(" vec_free(s);\n")
282 write(" return o;\n")
283 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100284
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200285 _dispatch["Typedef"] = print_typedef
286 _dispatch["Define"] = print_define
287 _dispatch["Using"] = print_using
288 _dispatch["Union"] = print_typedef
Ole Troandf87f802020-11-18 19:17:48 +0100289
290 def generate_function(self, t):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200291 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100292 write = self.stream.write
293 if t.manual_print:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200294 write("/* Manual print {} */\n".format(t.name))
Ole Troandf87f802020-11-18 19:17:48 +0100295 return
296 self._dispatch[t.type](self, t)
297
298 def generate_types(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200299 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100300 for t in self.types:
301 self.generate_function(t)
302
303 def generate_defines(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200304 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100305 for t in self.defines:
306 self.generate_function(t)
307
308
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200309class FromJSON:
310 """
Ole Troandf87f802020-11-18 19:17:48 +0100311 Parse JSON objects into VPP API binary message structures.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200312 """
313
Ole Troandf87f802020-11-18 19:17:48 +0100314 _dispatch = {}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200315 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
316 is_number = {
317 "u8": None,
318 "i8": None,
319 "u16": None,
320 "i16": None,
321 "u32": None,
322 "i32": None,
323 "u64": None,
324 "i64": None,
325 "f64": None,
326 }
Ole Troandf87f802020-11-18 19:17:48 +0100327
328 def __init__(self, module, types, defines, imported_types, stream):
329 self.stream = stream
330 self.module = module
331 self.defines = defines
332 self.types = types
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200333 self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
Ole Troandf87f802020-11-18 19:17:48 +0100334 self.defines_hash = {d.name: d for d in defines}
335
336 def header(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200337 """Output the top boilerplate."""
Ole Troandf87f802020-11-18 19:17:48 +0100338 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200339 write("#ifndef included_{}_api_fromjson_h\n".format(self.module))
340 write("#define included_{}_api_fromjson_h\n".format(self.module))
341 write("#include <vppinfra/cJSON.h>\n\n")
342 write("#include <vppinfra/jsonformat.h>\n\n")
Ole Troanfb0afab2021-02-11 11:13:46 +0100343 write('#pragma GCC diagnostic ignored "-Wunused-label"\n')
Ole Troandf87f802020-11-18 19:17:48 +0100344
345 def is_base_type(self, t):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200346 """Check if a type is one of the VPP API base types"""
Ole Troandf87f802020-11-18 19:17:48 +0100347 if t in self.is_number:
348 return True
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200349 if t == "bool":
Ole Troandf87f802020-11-18 19:17:48 +0100350 return True
351 return False
352
353 def footer(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200354 """Output the bottom boilerplate."""
Ole Troandf87f802020-11-18 19:17:48 +0100355 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200356 write("#endif\n")
Ole Troandf87f802020-11-18 19:17:48 +0100357
358 def print_string(self, o, toplevel=False):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200359 """Convert JSON string to vl_api_string_t"""
Ole Troandf87f802020-11-18 19:17:48 +0100360 write = self.stream.write
361
Ole Troanfb0afab2021-02-11 11:13:46 +0100362 msgvar = "a" if toplevel else "*mp"
Ole Troandf87f802020-11-18 19:17:48 +0100363 msgsize = "l" if toplevel else "*len"
364
365 if o.modern_vla:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200366 write(" char *p = cJSON_GetStringValue(item);\n")
367 write(" size_t plen = strlen(p);\n")
368 write(
369 " {msgvar} = cJSON_realloc({msgvar}, {msgsize} + plen, {msgsize});\n".format(
370 msgvar=msgvar, msgsize=msgsize
371 )
372 )
373 write(" if ({msgvar} == 0) goto error;\n".format(msgvar=msgvar))
374 write(
375 " vl_api_c_string_to_api_string(p, (void *){msgvar} + "
376 "{msgsize} - sizeof(vl_api_string_t));\n".format(
377 msgvar=msgvar, msgsize=msgsize
378 )
379 )
380 write(" {msgsize} += plen;\n".format(msgsize=msgsize))
Ole Troandf87f802020-11-18 19:17:48 +0100381 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200382 write(
383 " strncpy_s((char *)a->{n}, sizeof(a->{n}), "
384 "cJSON_GetStringValue(item), sizeof(a->{n}) - 1);\n".format(
385 n=o.fieldname
386 )
387 )
Ole Troandf87f802020-11-18 19:17:48 +0100388
389 def print_field(self, o, toplevel=False):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200390 """Called for every field in a typedef or define."""
Ole Troandf87f802020-11-18 19:17:48 +0100391 write = self.stream.write
Ole Troandf87f802020-11-18 19:17:48 +0100392 if o.fieldname in self.noprint_fields:
393 return
394 is_bt = self.is_base_type(o.fieldtype)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200395 t = "vl_api_{}".format(o.fieldtype) if is_bt else o.fieldtype
Ole Troandf87f802020-11-18 19:17:48 +0100396
Ole Troanfb0afab2021-02-11 11:13:46 +0100397 msgvar = "(void **)&a" if toplevel else "mp"
Ole Troandf87f802020-11-18 19:17:48 +0100398 msgsize = "&l" if toplevel else "len"
399
400 if is_bt:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200401 write(
402 " vl_api_{t}_fromjson(item, &a->{n});\n".format(
403 t=o.fieldtype, n=o.fieldname
404 )
405 )
Ole Troandf87f802020-11-18 19:17:48 +0100406 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200407 write(
408 " if ({t}_fromjson({msgvar}, "
409 "{msgsize}, item, &a->{n}) < 0) goto error;\n".format(
410 t=t, n=o.fieldname, msgvar=msgvar, msgsize=msgsize
411 )
412 )
Ole Troandf87f802020-11-18 19:17:48 +0100413
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200414 _dispatch["Field"] = print_field
Ole Troandf87f802020-11-18 19:17:48 +0100415
416 def print_array(self, o, toplevel=False):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200417 """Convert JSON array to VPP API array"""
Ole Troandf87f802020-11-18 19:17:48 +0100418 write = self.stream.write
419
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200420 forloop = """\
Ole Troandf87f802020-11-18 19:17:48 +0100421 {{
422 int i;
423 cJSON *array = cJSON_GetObjectItem(o, "{n}");
424 int size = cJSON_GetArraySize(array);
Ole Troan384c72f2021-02-17 13:46:54 +0100425 if (size != {lfield}) goto error;
Ole Troandf87f802020-11-18 19:17:48 +0100426 for (i = 0; i < size; i++) {{
427 cJSON *e = cJSON_GetArrayItem(array, i);
428 {call}
429 }}
430 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200431"""
432 forloop_vla = """\
Ole Troandf87f802020-11-18 19:17:48 +0100433 {{
434 int i;
435 cJSON *array = cJSON_GetObjectItem(o, "{n}");
436 int size = cJSON_GetArraySize(array);
437 {lfield} = size;
Filip Tehlar36217e32021-07-23 08:51:10 +0000438 {realloc} = cJSON_realloc({realloc}, {msgsize} + sizeof({t}) * size, {msgsize});
Ole Troancf0102b2021-02-12 11:48:12 +0100439 {t} *d = (void *){realloc} + {msgsize};
Ole Troandf87f802020-11-18 19:17:48 +0100440 {msgsize} += sizeof({t}) * size;
441 for (i = 0; i < size; i++) {{
442 cJSON *e = cJSON_GetArrayItem(array, i);
443 {call}
444 }}
445 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200446"""
Ole Troandf87f802020-11-18 19:17:48 +0100447 t = o.fieldtype
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200448 if o.fieldtype == "string":
Ole Troandf87f802020-11-18 19:17:48 +0100449 self.print_string(o, toplevel)
450 return
451
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200452 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
Ole Troanfb0afab2021-02-11 11:13:46 +0100453 msgvar = "(void **)&a" if toplevel else "mp"
Ole Troancf0102b2021-02-12 11:48:12 +0100454 realloc = "a" if toplevel else "*mp"
Ole Troandf87f802020-11-18 19:17:48 +0100455 msgsize = "l" if toplevel else "*len"
456
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200457 if o.fieldtype == "u8":
Ole Troandf87f802020-11-18 19:17:48 +0100458 if o.lengthfield:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200459 write(' s = u8string_fromjson(o, "{}");\n'.format(o.fieldname))
460 write(" if (!s) goto error;\n")
461 write(" {} = vec_len(s);\n".format(lfield))
Ole Troandf87f802020-11-18 19:17:48 +0100462
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200463 write(
464 " {realloc} = cJSON_realloc({realloc}, {msgsize} + "
465 "vec_len(s), {msgsize});\n".format(
466 msgvar=msgvar, msgsize=msgsize, realloc=realloc
467 )
468 )
469 write(
470 " memcpy((void *){realloc} + {msgsize}, s, "
471 "vec_len(s));\n".format(realloc=realloc, msgsize=msgsize)
472 )
473 write(" {msgsize} += vec_len(s);\n".format(msgsize=msgsize))
Ole Troandf87f802020-11-18 19:17:48 +0100474
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200475 write(" vec_free(s);\n")
Ole Troandf87f802020-11-18 19:17:48 +0100476 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200477 write(
478 ' if (u8string_fromjson2(o, "{n}", a->{n}) < 0) goto error;\n'.format(
479 n=o.fieldname
480 )
481 )
Ole Troandf87f802020-11-18 19:17:48 +0100482 return
483
484 is_bt = self.is_base_type(o.fieldtype)
485
486 if o.lengthfield:
487 if is_bt:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200488 call = "vl_api_{t}_fromjson(e, &d[i]);".format(t=o.fieldtype)
Ole Troandf87f802020-11-18 19:17:48 +0100489 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200490 call = "if ({t}_fromjson({msgvar}, len, e, &d[i]) < 0) goto error; ".format(
491 t=o.fieldtype, msgvar=msgvar
492 )
493 write(
494 forloop_vla.format(
495 lfield=lfield,
496 t=o.fieldtype,
497 n=o.fieldname,
498 call=call,
499 realloc=realloc,
500 msgsize=msgsize,
501 )
502 )
Ole Troandf87f802020-11-18 19:17:48 +0100503 else:
504 if is_bt:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200505 call = "vl_api_{t}_fromjson(e, &a->{n}[i]);".format(t=t, n=o.fieldname)
Ole Troandf87f802020-11-18 19:17:48 +0100506 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200507 call = "if ({}_fromjson({}, len, e, &a->{}[i]) < 0) goto error;".format(
508 t, msgvar, o.fieldname
509 )
510 write(
511 forloop.format(
512 lfield=lfield,
513 t=t,
514 n=o.fieldname,
515 call=call,
516 msgvar=msgvar,
517 realloc=realloc,
518 msgsize=msgsize,
519 )
520 )
Ole Troandf87f802020-11-18 19:17:48 +0100521
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200522 _dispatch["Array"] = print_array
Ole Troandf87f802020-11-18 19:17:48 +0100523
524 def print_enum(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200525 """Convert to JSON enum(string) to VPP API enum (int)"""
Ole Troandf87f802020-11-18 19:17:48 +0100526 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200527 write(
528 "static inline int vl_api_{n}_t_fromjson"
529 "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
530 )
531 write(" char *p = cJSON_GetStringValue(o);\n")
Ole Troandf87f802020-11-18 19:17:48 +0100532 for b in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200533 write(
534 ' if (strcmp(p, "{}") == 0) {{*a = {}; return 0;}}\n'.format(
535 b[0], b[1]
536 )
537 )
538 write(" *a = 0;\n")
539 write(" return -1;\n")
540 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100541
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200542 _dispatch["Enum"] = print_enum
Ole Troan793be462020-12-04 13:15:30 +0100543
544 def print_enum_flag(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200545 """Convert to JSON enum(string) to VPP API enum (int)"""
Ole Troan793be462020-12-04 13:15:30 +0100546 write = self.stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200547 write(
548 "static inline int vl_api_{n}_t_fromjson "
549 "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
550 )
551 write(" int i;\n")
552 write(" *a = 0;\n")
553 write(" for (i = 0; i < cJSON_GetArraySize(o); i++) {\n")
554 write(" cJSON *e = cJSON_GetArrayItem(o, i);\n")
555 write(" char *p = cJSON_GetStringValue(e);\n")
556 write(" if (!p) return -1;\n")
Ole Troan793be462020-12-04 13:15:30 +0100557 for b in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200558 write(' if (strcmp(p, "{}") == 0) *a |= {};\n'.format(b[0], b[1]))
559 write(" }\n")
560 write(" return 0;\n")
561 write("}\n")
Ole Troan793be462020-12-04 13:15:30 +0100562
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200563 _dispatch["EnumFlag"] = print_enum_flag
Ole Troandf87f802020-11-18 19:17:48 +0100564
565 def print_typedef(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200566 """Convert from JSON object to VPP API binary representation"""
Ole Troandf87f802020-11-18 19:17:48 +0100567 write = self.stream.write
568
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200569 write(
570 "static inline int vl_api_{name}_t_fromjson (void **mp, "
571 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
572 )
573 write(" cJSON *item __attribute__ ((unused));\n")
574 write(" u8 *s __attribute__ ((unused));\n")
Ole Troandf87f802020-11-18 19:17:48 +0100575 for t in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200576 if t.type == "Field" and t.is_lengthfield:
Ole Troandf87f802020-11-18 19:17:48 +0100577 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200578 write('\n item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
579 write(" if (!item) goto error;\n")
Ole Troandf87f802020-11-18 19:17:48 +0100580 self._dispatch[t.type](self, t)
581
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200582 write("\n return 0;\n")
583 write("\n error:\n")
584 write(" return -1;\n")
585 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100586
587 def print_union(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200588 """Convert JSON object to VPP API binary union"""
Ole Troandf87f802020-11-18 19:17:48 +0100589 write = self.stream.write
590
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200591 write(
592 "static inline int vl_api_{name}_t_fromjson (void **mp, "
593 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
594 )
595 write(" cJSON *item __attribute__ ((unused));\n")
596 write(" u8 *s __attribute__ ((unused));\n")
Ole Troandf87f802020-11-18 19:17:48 +0100597 for t in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200598 if t.type == "Field" and t.is_lengthfield:
Ole Troandf87f802020-11-18 19:17:48 +0100599 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200600 write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
601 write(" if (item) {\n")
Ole Troandf87f802020-11-18 19:17:48 +0100602 self._dispatch[t.type](self, t)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200603 write(" };\n")
604 write("\n return 0;\n")
605 write("\n error:\n")
606 write(" return -1;\n")
607 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100608
609 def print_define(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200610 """Convert JSON object to VPP API message"""
Ole Troandf87f802020-11-18 19:17:48 +0100611 write = self.stream.write
Ole Troan93c4b1b2021-02-16 18:09:51 +0100612 error = 0
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200613 write(
614 "static inline vl_api_{name}_t *vl_api_{name}_t_fromjson "
615 "(cJSON *o, int *len) {{\n".format(name=o.name)
616 )
617 write(" cJSON *item __attribute__ ((unused));\n")
618 write(" u8 *s __attribute__ ((unused));\n")
619 write(" int l = sizeof(vl_api_{}_t);\n".format(o.name))
620 write(" vl_api_{}_t *a = cJSON_malloc(l);\n".format(o.name))
621 write("\n")
Ole Troandf87f802020-11-18 19:17:48 +0100622
623 for t in o.block:
624 if t.fieldname in self.noprint_fields:
625 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200626 if t.type == "Field" and t.is_lengthfield:
Ole Troandf87f802020-11-18 19:17:48 +0100627 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200628 write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
629 write(" if (!item) goto error;\n")
Ole Troan93c4b1b2021-02-16 18:09:51 +0100630 error += 1
Ole Troandf87f802020-11-18 19:17:48 +0100631 self._dispatch[t.type](self, t, toplevel=True)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200632 write("\n")
Ole Troandf87f802020-11-18 19:17:48 +0100633
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200634 write(" *len = l;\n")
635 write(" return a;\n")
Ole Troan93c4b1b2021-02-16 18:09:51 +0100636
637 if error:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200638 write("\n error:\n")
639 write(" cJSON_free(a);\n")
640 write(" return 0;\n")
641 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100642
643 def print_using(self, o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200644 """Convert JSON field to VPP type alias"""
Ole Troandf87f802020-11-18 19:17:48 +0100645 write = self.stream.write
646
647 if o.manual_print:
648 return
649
650 t = o.using
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200651 write(
652 "static inline int vl_api_{name}_t_fromjson (void **mp, "
653 "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
654 )
655 if "length" in o.alias:
656 if t.fieldtype != "u8":
657 raise ValueError(
658 "Error in processing type {} for {}".format(t.fieldtype, o.name)
659 )
660 write(
661 " vl_api_u8_string_fromjson(o, (u8 *)a, {});\n".format(
662 o.alias["length"]
663 )
664 )
Ole Troandf87f802020-11-18 19:17:48 +0100665 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200666 write(" vl_api_{t}_fromjson(o, ({t} *)a);\n".format(t=t.fieldtype))
Ole Troandf87f802020-11-18 19:17:48 +0100667
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200668 write(" return 0;\n")
669 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +0100670
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200671 _dispatch["Typedef"] = print_typedef
672 _dispatch["Define"] = print_define
673 _dispatch["Using"] = print_using
674 _dispatch["Union"] = print_union
Ole Troandf87f802020-11-18 19:17:48 +0100675
676 def generate_function(self, t):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200677 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100678 write = self.stream.write
679 if t.manual_print:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200680 write("/* Manual print {} */\n".format(t.name))
Ole Troandf87f802020-11-18 19:17:48 +0100681 return
682 self._dispatch[t.type](self, t)
683
684 def generate_types(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200685 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100686 for t in self.types:
687 self.generate_function(t)
688
689 def generate_defines(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200690 """Main entry point"""
Ole Troandf87f802020-11-18 19:17:48 +0100691 for t in self.defines:
692 self.generate_function(t)
693
694
695def generate_tojson(s, modulename, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200696 """Generate all functions to convert from API to JSON"""
Ole Troandf87f802020-11-18 19:17:48 +0100697 write = stream.write
698
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200699 write("/* Imported API files */\n")
700 for i in s["Import"]:
701 f = i.filename.replace("plugins/", "")
702 write("#include <{}_tojson.h>\n".format(f))
Ole Troandf87f802020-11-18 19:17:48 +0100703
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200704 pp = ToJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
Ole Troandf87f802020-11-18 19:17:48 +0100705 pp.header()
706 pp.generate_types()
707 pp.generate_defines()
708 pp.footer()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200709 return ""
Ole Troandf87f802020-11-18 19:17:48 +0100710
711
712def generate_fromjson(s, modulename, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200713 """Generate all functions to convert from JSON to API"""
Ole Troandf87f802020-11-18 19:17:48 +0100714 write = stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200715 write("/* Imported API files */\n")
716 for i in s["Import"]:
717 f = i.filename.replace("plugins/", "")
718 write("#include <{}_fromjson.h>\n".format(f))
Ole Troandf87f802020-11-18 19:17:48 +0100719
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200720 pp = FromJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
Ole Troandf87f802020-11-18 19:17:48 +0100721 pp.header()
722 pp.generate_types()
723 pp.generate_defines()
724 pp.footer()
725
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200726 return ""
727
Ole Troandf87f802020-11-18 19:17:48 +0100728
729###############################################################################
730
731
732DATESTRING = datetime.datetime.utcfromtimestamp(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200733 int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
734)
735TOP_BOILERPLATE = """\
Ole Troan9d420872017-10-12 13:06:35 +0200736/*
737 * VLIB API definitions {datestring}
738 * Input file: {input_filename}
739 * Automatically generated: please edit the input file NOT this file!
740 */
741
Ole Troan288e0932019-05-29 12:30:05 +0200742#include <stdbool.h>
Ole Troan9d420872017-10-12 13:06:35 +0200743#if defined(vl_msg_id)||defined(vl_union_id) \\
744 || defined(vl_printfun) ||defined(vl_endianfun) \\
745 || defined(vl_api_version)||defined(vl_typedefs) \\
746 || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
Klement Sekera9b7e8ac2021-11-22 21:26:20 +0100747 || defined(vl_api_version_tuple) || defined(vl_calcsizefun)
Ole Troan9d420872017-10-12 13:06:35 +0200748/* ok, something was selected */
749#else
750#warning no content included from {input_filename}
751#endif
752
753#define VL_API_PACKED(x) x __attribute__ ((packed))
Dave Wallace39c40fa2023-06-06 12:05:30 -0400754
755/*
756 * Note: VL_API_MAX_ARRAY_SIZE is set to an arbitrarily large limit.
757 *
758 * However, any message with a ~2 billion element array is likely to break the
759 * api handling long before this limit causes array element endian issues.
760 *
761 * Applications should be written to create reasonable api messages.
762 */
763#define VL_API_MAX_ARRAY_SIZE 0x7fffffff
764
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200765"""
Ole Troan9d420872017-10-12 13:06:35 +0200766
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200767BOTTOM_BOILERPLATE = """\
Ole Troan9d420872017-10-12 13:06:35 +0200768/****** API CRC (whole file) *****/
769
770#ifdef vl_api_version
771vl_api_version({input_filename}, {file_crc:#08x})
772
773#endif
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200774"""
Ole Troan9d420872017-10-12 13:06:35 +0200775
776
777def msg_ids(s):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200778 """Generate macro to map API message id to handler"""
779 output = """\
Ole Troan9d420872017-10-12 13:06:35 +0200780
781/****** Message ID / handler enum ******/
782
783#ifdef vl_msg_id
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200784"""
Ole Troan9d420872017-10-12 13:06:35 +0200785
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200786 for t in s["Define"]:
787 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % (
788 t.name.upper(),
789 t.name,
790 )
Ole Troan9d420872017-10-12 13:06:35 +0200791 output += "#endif"
792
793 return output
794
795
796def msg_names(s):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200797 """Generate calls to name mapping macro"""
798 output = """\
Ole Troan9d420872017-10-12 13:06:35 +0200799
800/****** Message names ******/
801
802#ifdef vl_msg_name
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200803"""
Ole Troan9d420872017-10-12 13:06:35 +0200804
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200805 for t in s["Define"]:
Ole Troan9d420872017-10-12 13:06:35 +0200806 dont_trace = 0 if t.dont_trace else 1
807 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
808 output += "#endif"
809
810 return output
811
812
813def msg_name_crc_list(s, suffix):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200814 """Generate list of names to CRC mappings"""
815 output = """\
Ole Troan9d420872017-10-12 13:06:35 +0200816
817/****** Message name, crc list ******/
818
819#ifdef vl_msg_name_crc_list
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200820"""
Ole Troan9d420872017-10-12 13:06:35 +0200821 output += "#define foreach_vl_msg_name_crc_%s " % suffix
822
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200823 for t in s["Define"]:
824 output += "\\\n_(VL_API_%s, %s, %08x) " % (t.name.upper(), t.name, t.crc)
Ole Troan9d420872017-10-12 13:06:35 +0200825 output += "\n#endif"
826
827 return output
828
829
Ole Troan413f4a52018-11-28 11:36:05 +0100830def api2c(fieldtype):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200831 """Map between API type names and internal VPP type names"""
832 mappingtable = {
833 "string": "vl_api_string_t",
834 }
Ole Troan413f4a52018-11-28 11:36:05 +0100835 if fieldtype in mappingtable:
836 return mappingtable[fieldtype]
837 return fieldtype
838
839
Ole Troan2a1ca782019-09-19 01:08:30 +0200840def typedefs(filename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200841 """Include in the main files to the types file"""
842 output = """\
Ole Troan9d420872017-10-12 13:06:35 +0200843
844/****** Typedefs ******/
845
846#ifdef vl_typedefs
Ole Troan2a1ca782019-09-19 01:08:30 +0200847#include "{include}.api_types.h"
848#endif
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200849""".format(
850 include=filename
851 )
Ole Troan9d420872017-10-12 13:06:35 +0200852 return output
853
854
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200855FORMAT_STRINGS = {
856 "u8": "%u",
857 "bool": "%u",
858 "i8": "%d",
859 "u16": "%u",
860 "i16": "%d",
861 "u32": "%u",
862 "i32": "%ld",
863 "u64": "%llu",
864 "i64": "%lld",
865 "f64": "%.2f",
866}
Ole Troan33a58172019-09-04 09:12:29 +0200867
Ole Troan9d420872017-10-12 13:06:35 +0200868
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200869class Printfun:
870 """Functions for pretty printing VPP API messages"""
871
Ole Troan33a58172019-09-04 09:12:29 +0200872 _dispatch = {}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200873 noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
Ole Troan33a58172019-09-04 09:12:29 +0200874
875 def __init__(self, stream):
876 self.stream = stream
877
Ole Troandf87f802020-11-18 19:17:48 +0100878 @staticmethod
879 def print_string(o, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200880 """Pretty print a vl_api_string_t"""
Ole Troan33a58172019-09-04 09:12:29 +0200881 write = stream.write
882 if o.modern_vla:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200883 write(" if (vl_api_string_len(&a->{f}) > 0) {{\n".format(f=o.fieldname))
884 write(
885 ' s = format(s, "\\n%U{f}: %U", '
886 "format_white_space, indent, "
887 "vl_api_format_string, (&a->{f}));\n".format(f=o.fieldname)
888 )
889 write(" } else {\n")
890 write(
891 ' s = format(s, "\\n%U{f}:", '
892 "format_white_space, indent);\n".format(f=o.fieldname)
893 )
894 write(" }\n")
Ole Troan33a58172019-09-04 09:12:29 +0200895 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200896 write(
897 ' s = format(s, "\\n%U{f}: %s", '
898 "format_white_space, indent, a->{f});\n".format(f=o.fieldname)
899 )
Ole Troan33a58172019-09-04 09:12:29 +0200900
901 def print_field(self, o, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200902 """Pretty print API field"""
Ole Troan33a58172019-09-04 09:12:29 +0200903 write = stream.write
Ole Troandf87f802020-11-18 19:17:48 +0100904 if o.fieldname in self.noprint_fields:
Ole Troan33a58172019-09-04 09:12:29 +0200905 return
Ole Troandf87f802020-11-18 19:17:48 +0100906 if o.fieldtype in FORMAT_STRINGS:
907 f = FORMAT_STRINGS[o.fieldtype]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200908 write(
909 ' s = format(s, "\\n%U{n}: {f}", '
910 "format_white_space, indent, a->{n});\n".format(n=o.fieldname, f=f)
911 )
Ole Troan33a58172019-09-04 09:12:29 +0200912 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200913 write(
914 ' s = format(s, "\\n%U{n}: %U", '
915 "format_white_space, indent, "
916 "format_{t}, &a->{n}, indent);\n".format(n=o.fieldname, t=o.fieldtype)
917 )
Ole Troan33a58172019-09-04 09:12:29 +0200918
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200919 _dispatch["Field"] = print_field
Ole Troan33a58172019-09-04 09:12:29 +0200920
921 def print_array(self, o, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200922 """Pretty print API array"""
Ole Troan33a58172019-09-04 09:12:29 +0200923 write = stream.write
924
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200925 forloop = """\
Ole Troan33a58172019-09-04 09:12:29 +0200926 for (i = 0; i < {lfield}; i++) {{
927 s = format(s, "\\n%U{n}: %U",
928 format_white_space, indent, format_{t}, &a->{n}[i], indent);
929 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200930"""
Ole Troan33a58172019-09-04 09:12:29 +0200931
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200932 forloop_format = """\
Ole Troan33a58172019-09-04 09:12:29 +0200933 for (i = 0; i < {lfield}; i++) {{
934 s = format(s, "\\n%U{n}: {t}",
935 format_white_space, indent, a->{n}[i]);
936 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200937"""
Ole Troan33a58172019-09-04 09:12:29 +0200938
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200939 if o.fieldtype == "string":
Ole Troandf87f802020-11-18 19:17:48 +0100940 self.print_string(o, stream)
941 return
Ole Troan33a58172019-09-04 09:12:29 +0200942
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200943 if o.fieldtype == "u8":
Ole Troan33a58172019-09-04 09:12:29 +0200944 if o.lengthfield:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200945 write(
946 ' s = format(s, "\\n%U{n}: %U", format_white_space, '
947 "indent, format_hex_bytes, a->{n}, a->{lfield});\n".format(
948 n=o.fieldname, lfield=o.lengthfield
949 )
950 )
Ole Troan33a58172019-09-04 09:12:29 +0200951 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200952 write(
953 ' s = format(s, "\\n%U{n}: %U", format_white_space, '
954 "indent, format_hex_bytes, a, {lfield});\n".format(
955 n=o.fieldname, lfield=o.length
956 )
957 )
Ole Troan33a58172019-09-04 09:12:29 +0200958 return
959
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200960 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
Ole Troandf87f802020-11-18 19:17:48 +0100961 if o.fieldtype in FORMAT_STRINGS:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200962 write(
963 forloop_format.format(
964 lfield=lfield, t=FORMAT_STRINGS[o.fieldtype], n=o.fieldname
965 )
966 )
Ole Troan33a58172019-09-04 09:12:29 +0200967 else:
968 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
969
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200970 _dispatch["Array"] = print_array
Ole Troan33a58172019-09-04 09:12:29 +0200971
Ole Troandf87f802020-11-18 19:17:48 +0100972 @staticmethod
973 def print_alias(k, v, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200974 """Pretty print type alias"""
Ole Troan33a58172019-09-04 09:12:29 +0200975 write = stream.write
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200976 if "length" in v.alias and v.alias["length"] and v.alias["type"] == "u8":
977 write(
978 ' return format(s, "%U", format_hex_bytes, a, {});\n'.format(
979 v.alias["length"]
980 )
981 )
982 elif v.alias["type"] in FORMAT_STRINGS:
983 write(
984 ' return format(s, "{}", *a);\n'.format(
985 FORMAT_STRINGS[v.alias["type"]]
986 )
987 )
Ole Troan33a58172019-09-04 09:12:29 +0200988 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200989 write(' return format(s, "{} (print not implemented)");\n'.format(k))
Ole Troan33a58172019-09-04 09:12:29 +0200990
Ole Troandf87f802020-11-18 19:17:48 +0100991 @staticmethod
992 def print_enum(o, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200993 """Pretty print API enum"""
Ole Troan33a58172019-09-04 09:12:29 +0200994 write = stream.write
995 write(" switch(*a) {\n")
996 for b in o:
997 write(" case %s:\n" % b[1])
998 write(' return format(s, "{}");\n'.format(b[0]))
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200999 write(" }\n")
Ole Troan33a58172019-09-04 09:12:29 +02001000
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001001 _dispatch["Enum"] = print_enum
1002 _dispatch["EnumFlag"] = print_enum
Ole Troan33a58172019-09-04 09:12:29 +02001003
1004 def print_obj(self, o, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001005 """Entry point"""
Ole Troan33a58172019-09-04 09:12:29 +02001006 write = stream.write
1007
1008 if o.type in self._dispatch:
1009 self._dispatch[o.type](self, o, stream)
1010 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001011 write(
1012 ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
1013 o.type, o.fieldtype, o.fieldname
1014 )
1015 )
Ole Troan33a58172019-09-04 09:12:29 +02001016
1017
1018def printfun(objs, stream, modulename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001019 """Main entry point for pretty print function generation"""
Ole Troan33a58172019-09-04 09:12:29 +02001020 write = stream.write
1021
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001022 h = """\
Ole Troan9d420872017-10-12 13:06:35 +02001023/****** Print functions *****/
1024#ifdef vl_printfun
Ole Troan33a58172019-09-04 09:12:29 +02001025#ifndef included_{module}_printfun
1026#define included_{module}_printfun
Ole Troan9d420872017-10-12 13:06:35 +02001027
1028#ifdef LP64
1029#define _uword_fmt \"%lld\"
1030#define _uword_cast (long long)
1031#else
1032#define _uword_fmt \"%ld\"
1033#define _uword_cast long
1034#endif
1035
Filip Tehlar36217e32021-07-23 08:51:10 +00001036#include "{module}.api_tojson.h"
1037#include "{module}.api_fromjson.h"
1038
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001039"""
Ole Troan33a58172019-09-04 09:12:29 +02001040
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001041 signature = """\
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001042static inline u8 *vl_api_{name}_t_format (u8 *s, va_list *args)
Ole Troan33a58172019-09-04 09:12:29 +02001043{{
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001044 __attribute__((unused)) vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
Ole Troan33a58172019-09-04 09:12:29 +02001045 u32 indent __attribute__((unused)) = 2;
1046 int i __attribute__((unused));
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001047"""
Ole Troan33a58172019-09-04 09:12:29 +02001048
1049 h = h.format(module=modulename)
1050 write(h)
1051
1052 pp = Printfun(stream)
1053 for t in objs:
1054 if t.manual_print:
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001055 write("/***** manual: vl_api_%s_t_format *****/\n\n" % t.name)
Ole Troan33a58172019-09-04 09:12:29 +02001056 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001057 write(signature.format(name=t.name, suffix=""))
1058 write(" /* Message definition: vl_api_{}_t: */\n".format(t.name))
1059 write(' s = format(s, "vl_api_%s_t:");\n' % t.name)
Ole Troan33a58172019-09-04 09:12:29 +02001060 for o in t.block:
1061 pp.print_obj(o, stream)
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001062 write(" return s;\n")
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001063 write("}\n\n")
Filip Tehlar36217e32021-07-23 08:51:10 +00001064
Ole Troan33a58172019-09-04 09:12:29 +02001065 write("\n#endif")
1066 write("\n#endif /* vl_printfun */\n")
1067
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001068 return ""
Ole Troan33a58172019-09-04 09:12:29 +02001069
1070
Ole Troan75761b92019-09-11 17:49:08 +02001071def printfun_types(objs, stream, modulename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001072 """Pretty print API types"""
Ole Troan33a58172019-09-04 09:12:29 +02001073 write = stream.write
1074 pp = Printfun(stream)
1075
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001076 h = """\
Ole Troan33a58172019-09-04 09:12:29 +02001077/****** Print functions *****/
1078#ifdef vl_printfun
1079#ifndef included_{module}_printfun_types
1080#define included_{module}_printfun_types
1081
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001082"""
Ole Troan33a58172019-09-04 09:12:29 +02001083 h = h.format(module=modulename)
1084 write(h)
1085
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001086 signature = """\
Ole Troan33a58172019-09-04 09:12:29 +02001087static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
1088{{
1089 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
1090 u32 indent __attribute__((unused)) = va_arg (*args, u32);
1091 int i __attribute__((unused));
1092 indent += 2;
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001093"""
Ole Troan33a58172019-09-04 09:12:29 +02001094
Ole Troan2c2feab2018-04-24 00:02:37 -04001095 for t in objs:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001096 if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
Ole Troan33a58172019-09-04 09:12:29 +02001097 write(signature.format(name=t.name))
1098 pp.print_enum(t.block, stream)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001099 write(" return s;\n")
1100 write("}\n\n")
Ole Troan2c2feab2018-04-24 00:02:37 -04001101 continue
Ole Troan33a58172019-09-04 09:12:29 +02001102
Ole Troan9d420872017-10-12 13:06:35 +02001103 if t.manual_print:
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001104 write("/***** manual: vl_api_%s_t_format *****/\n\n" % t.name)
Ole Troan9d420872017-10-12 13:06:35 +02001105 continue
Ole Troan9d420872017-10-12 13:06:35 +02001106
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001107 if t.__class__.__name__ == "Using":
Ole Troan75761b92019-09-11 17:49:08 +02001108 write(signature.format(name=t.name))
1109 pp.print_alias(t.name, t, stream)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001110 write("}\n\n")
Ole Troan75761b92019-09-11 17:49:08 +02001111 continue
1112
Ole Troan33a58172019-09-04 09:12:29 +02001113 write(signature.format(name=t.name))
Ole Troan9d420872017-10-12 13:06:35 +02001114 for o in t.block:
Ole Troan33a58172019-09-04 09:12:29 +02001115 pp.print_obj(o, stream)
Ole Troan9d420872017-10-12 13:06:35 +02001116
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001117 write(" return s;\n")
1118 write("}\n\n")
Ole Troan9d420872017-10-12 13:06:35 +02001119
Ole Troan33a58172019-09-04 09:12:29 +02001120 write("\n#endif")
1121 write("\n#endif /* vl_printfun_types */\n")
Ole Troan9d420872017-10-12 13:06:35 +02001122
Ole Troan33a58172019-09-04 09:12:29 +02001123
Ole Troandf87f802020-11-18 19:17:48 +01001124def generate_imports(imports):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001125 """Add #include matching the API import statements"""
1126 output = "/* Imported API files */\n"
1127 output += "#ifndef vl_api_version\n"
Ole Troan33a58172019-09-04 09:12:29 +02001128
1129 for i in imports:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001130 s = i.filename.replace("plugins/", "")
1131 output += "#include <{}.h>\n".format(s)
1132 output += "#endif\n"
Ole Troan9d420872017-10-12 13:06:35 +02001133 return output
1134
1135
Ole Troandf87f802020-11-18 19:17:48 +01001136ENDIAN_STRINGS = {
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001137 "u16": "clib_net_to_host_u16",
1138 "u32": "clib_net_to_host_u32",
1139 "u64": "clib_net_to_host_u64",
1140 "i16": "clib_net_to_host_i16",
1141 "i32": "clib_net_to_host_i32",
1142 "i64": "clib_net_to_host_i64",
1143 "f64": "clib_net_to_host_f64",
Ole Troan9d420872017-10-12 13:06:35 +02001144}
1145
1146
Dave Wallace39c40fa2023-06-06 12:05:30 -04001147def get_endian_string(o, type):
1148 """Return proper endian string conversion function"""
1149 try:
1150 if o.to_network:
1151 return ENDIAN_STRINGS[type].replace("net_to_host", "host_to_net")
1152 except:
1153 pass
1154 return ENDIAN_STRINGS[type]
1155
1156
Ole Troan33a58172019-09-04 09:12:29 +02001157def endianfun_array(o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001158 """Generate endian functions for arrays"""
1159 forloop = """\
Dave Wallace39c40fa2023-06-06 12:05:30 -04001160 {comment}
1161 ASSERT((u32){length} <= (u32)VL_API_MAX_ARRAY_SIZE);
Ole Troan33a58172019-09-04 09:12:29 +02001162 for (i = 0; i < {length}; i++) {{
1163 a->{name}[i] = {format}(a->{name}[i]);
1164 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001165"""
Ole Troan33a58172019-09-04 09:12:29 +02001166
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001167 forloop_format = """\
Ole Troan33a58172019-09-04 09:12:29 +02001168 for (i = 0; i < {length}; i++) {{
1169 {type}_endian(&a->{name}[i]);
1170 }}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001171"""
Ole Troan33a58172019-09-04 09:12:29 +02001172
Dave Wallace39c40fa2023-06-06 12:05:30 -04001173 to_network_comment = ""
1174 try:
1175 if o.to_network:
1176 to_network_comment = """/*
1177 * Array fields processed first to handle variable length arrays and size
1178 * field endian conversion in the proper order for to-network messages.
1179 * Message fields have been sorted by type in the code generator, thus fields
1180 * in this generated code may be converted in a different order than specified
1181 * in the *.api file.
1182 */"""
1183 except:
1184 pass
1185
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001186 output = ""
1187 if o.fieldtype == "u8" or o.fieldtype == "string" or o.fieldtype == "bool":
1188 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
Ole Troan33a58172019-09-04 09:12:29 +02001189 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001190 lfield = "a->" + o.lengthfield if o.lengthfield else o.length
Ole Troandf87f802020-11-18 19:17:48 +01001191 if o.fieldtype in ENDIAN_STRINGS:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001192 output += forloop.format(
Dave Wallace39c40fa2023-06-06 12:05:30 -04001193 comment=to_network_comment,
1194 length=lfield,
1195 format=get_endian_string(o, o.fieldtype),
1196 name=o.fieldname,
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001197 )
Ole Troan33a58172019-09-04 09:12:29 +02001198 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001199 output += forloop_format.format(
1200 length=lfield, type=o.fieldtype, name=o.fieldname
1201 )
Ole Troan33a58172019-09-04 09:12:29 +02001202 return output
1203
Ole Troandf87f802020-11-18 19:17:48 +01001204
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001205NO_ENDIAN_CONVERSION = {"client_index": None}
Ole Troandf87f802020-11-18 19:17:48 +01001206
Ole Troan33a58172019-09-04 09:12:29 +02001207
1208def endianfun_obj(o):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001209 """Generate endian conversion function for type"""
1210 output = ""
1211 if o.type == "Array":
Ole Troan33a58172019-09-04 09:12:29 +02001212 return endianfun_array(o)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001213 if o.type != "Field":
1214 output += ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
1215 o.type, o.fieldtype, o.fieldname
1216 )
Ole Troan33a58172019-09-04 09:12:29 +02001217 return output
Ole Troandf87f802020-11-18 19:17:48 +01001218 if o.fieldname in NO_ENDIAN_CONVERSION:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001219 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
Ole Troane796a182020-05-18 11:14:05 +02001220 return output
Ole Troandf87f802020-11-18 19:17:48 +01001221 if o.fieldtype in ENDIAN_STRINGS:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001222 output += " a->{name} = {format}(a->{name});\n".format(
Dave Wallace39c40fa2023-06-06 12:05:30 -04001223 name=o.fieldname, format=get_endian_string(o, o.fieldtype)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001224 )
1225 elif o.fieldtype.startswith("vl_api_"):
1226 output += " {type}_endian(&a->{name});\n".format(
1227 type=o.fieldtype, name=o.fieldname
1228 )
Ole Troan33a58172019-09-04 09:12:29 +02001229 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001230 output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
Ole Troan33a58172019-09-04 09:12:29 +02001231
1232 return output
1233
1234
Ole Troan75761b92019-09-11 17:49:08 +02001235def endianfun(objs, modulename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001236 """Main entry point for endian function generation"""
1237 output = """\
Ole Troan9d420872017-10-12 13:06:35 +02001238
1239/****** Endian swap functions *****/\n\
1240#ifdef vl_endianfun
Ole Troan33a58172019-09-04 09:12:29 +02001241#ifndef included_{module}_endianfun
1242#define included_{module}_endianfun
Ole Troan9d420872017-10-12 13:06:35 +02001243
1244#undef clib_net_to_host_uword
Dave Wallace39c40fa2023-06-06 12:05:30 -04001245#undef clib_host_to_net_uword
Ole Troan9d420872017-10-12 13:06:35 +02001246#ifdef LP64
1247#define clib_net_to_host_uword clib_net_to_host_u64
Dave Wallace39c40fa2023-06-06 12:05:30 -04001248#define clib_host_to_net_uword clib_host_to_net_u64
Ole Troan9d420872017-10-12 13:06:35 +02001249#else
1250#define clib_net_to_host_uword clib_net_to_host_u32
Dave Wallace39c40fa2023-06-06 12:05:30 -04001251#define clib_host_to_net_uword clib_host_to_net_u32
Ole Troan9d420872017-10-12 13:06:35 +02001252#endif
1253
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001254"""
Ole Troan33a58172019-09-04 09:12:29 +02001255 output = output.format(module=modulename)
1256
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001257 signature = """\
Ole Troan33a58172019-09-04 09:12:29 +02001258static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
1259{{
1260 int i __attribute__((unused));
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001261"""
Ole Troan33a58172019-09-04 09:12:29 +02001262
Ole Troan2c2feab2018-04-24 00:02:37 -04001263 for t in objs:
Dave Wallace39c40fa2023-06-06 12:05:30 -04001264 # Outbound (to network) messages are identified by message nomenclature
1265 # i.e. message names ending with these suffixes are 'to network'
1266 if t.name.endswith("_reply") or t.name.endswith("_details"):
1267 t.to_network = True
1268 else:
1269 t.to_network = False
1270
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001271 if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
Ole Troan33a58172019-09-04 09:12:29 +02001272 output += signature.format(name=t.name)
Ole Troandf87f802020-11-18 19:17:48 +01001273 if t.enumtype in ENDIAN_STRINGS:
Dave Wallace39c40fa2023-06-06 12:05:30 -04001274 output += " *a = {}(*a);\n".format(get_endian_string(t, t.enumtype))
Ole Troan33a58172019-09-04 09:12:29 +02001275 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001276 output += " /* a->{name} = a->{name} (no-op) */\n".format(
1277 name=t.name
1278 )
Ole Troan33a58172019-09-04 09:12:29 +02001279
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001280 output += "}\n\n"
Ole Troan2c2feab2018-04-24 00:02:37 -04001281 continue
Ole Troan33a58172019-09-04 09:12:29 +02001282
Ole Troan9d420872017-10-12 13:06:35 +02001283 if t.manual_endian:
1284 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
1285 continue
Ole Troan33a58172019-09-04 09:12:29 +02001286
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001287 if t.__class__.__name__ == "Using":
Ole Troan75761b92019-09-11 17:49:08 +02001288 output += signature.format(name=t.name)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001289 if "length" in t.alias and t.alias["length"] and t.alias["type"] == "u8":
1290 output += " /* a->{name} = a->{name} (no-op) */\n".format(
1291 name=t.name
1292 )
1293 elif t.alias["type"] in FORMAT_STRINGS:
Dave Wallace39c40fa2023-06-06 12:05:30 -04001294 output += " *a = {}(*a);\n".format(
1295 get_endian_string(t, t.alias["type"])
1296 )
Ole Troan75761b92019-09-11 17:49:08 +02001297 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001298 output += " /* Not Implemented yet {} */".format(t.name)
1299 output += "}\n\n"
Ole Troan75761b92019-09-11 17:49:08 +02001300 continue
1301
Ole Troan33a58172019-09-04 09:12:29 +02001302 output += signature.format(name=t.name)
Ole Troan9d420872017-10-12 13:06:35 +02001303
Dave Wallace39c40fa2023-06-06 12:05:30 -04001304 # For outbound (to network) messages:
1305 # some arrays have dynamic length -- iterate over
1306 # them before changing endianness for the length field
1307 # by making the Array types show up first
1308 if t.to_network:
1309 t.block.sort(key=lambda x: x.type)
Stanislav Zaikin139b2da2022-07-21 19:06:26 +02001310
Ole Troan9d420872017-10-12 13:06:35 +02001311 for o in t.block:
Dave Wallace39c40fa2023-06-06 12:05:30 -04001312 o.to_network = t.to_network
Ole Troan33a58172019-09-04 09:12:29 +02001313 output += endianfun_obj(o)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001314 output += "}\n\n"
Ole Troan33a58172019-09-04 09:12:29 +02001315
1316 output += "\n#endif"
Ole Troan9d420872017-10-12 13:06:35 +02001317 output += "\n#endif /* vl_endianfun */\n\n"
1318
1319 return output
1320
1321
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001322def calc_size_fun(objs, modulename):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001323 """Main entry point for calculate size function generation"""
1324 output = """\
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001325
1326/****** Calculate size functions *****/\n\
1327#ifdef vl_calcsizefun
1328#ifndef included_{module}_calcsizefun
1329#define included_{module}_calcsizefun
1330
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001331"""
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001332 output = output.format(module=modulename)
1333
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001334 signature = """\
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001335/* calculate message size of message in network byte order */
1336static inline uword vl_api_{name}_t_calc_size (vl_api_{name}_t *a)
1337{{
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001338"""
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001339
1340 for o in objs:
1341 tname = o.__class__.__name__
1342
1343 output += signature.format(name=o.name)
1344 output += f" return sizeof(*a)"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001345 if tname == "Using":
1346 if "length" in o.alias:
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001347 try:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001348 tmp = int(o.alias["length"])
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001349 if tmp == 0:
1350 raise (f"Unexpected length '0' for alias {o}")
1351 except:
1352 # output += f" + vl_api_{o.alias.name}_t_calc_size({o.name})"
1353 print("culprit:")
1354 print(o)
1355 print(dir(o.alias))
1356 print(o.alias)
1357 raise
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001358 elif tname == "Enum" or tname == "EnumFlag":
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001359 pass
1360 else:
1361 for b in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001362 if b.type == "Option":
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001363 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001364 elif b.type == "Field":
1365 if b.fieldtype.startswith("vl_api_"):
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001366 output += f" - sizeof(a->{b.fieldname})"
1367 output += f" + {b.fieldtype}_calc_size(&a->{b.fieldname})"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001368 elif b.type == "Array":
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001369 if b.lengthfield:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001370 m = list(
1371 filter(lambda x: x.fieldname == b.lengthfield, o.block)
1372 )
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001373 if len(m) != 1:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001374 raise Exception(
1375 f"Expected 1 match for field '{b.lengthfield}', got '{m}'"
1376 )
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001377 lf = m[0]
1378 if lf.fieldtype in ENDIAN_STRINGS:
Dave Wallace39c40fa2023-06-06 12:05:30 -04001379 output += f" + {get_endian_string(b, lf.fieldtype)}(a->{b.lengthfield}) * sizeof(a->{b.fieldname}[0])"
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001380 elif lf.fieldtype == "u8":
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001381 output += (
1382 f" + a->{b.lengthfield} * sizeof(a->{b.fieldname}[0])"
1383 )
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001384 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001385 raise Exception(
1386 f"Don't know how to endian swap {lf.fieldtype}"
1387 )
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001388 else:
1389 # Fixed length strings decay to nul terminated u8
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001390 if b.fieldtype == "string":
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001391 if b.modern_vla:
1392 output += f" + vl_api_string_len(&a->{b.fieldname})"
1393
1394 output += ";\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001395 output += "}\n\n"
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001396 output += "\n#endif"
1397 output += "\n#endif /* vl_calcsizefun */\n\n"
1398
1399 return output
1400
1401
Ole Troan9d420872017-10-12 13:06:35 +02001402def version_tuple(s, module):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001403 """Generate semantic version string"""
1404 output = """\
Ole Troan9d420872017-10-12 13:06:35 +02001405/****** Version tuple *****/
1406
1407#ifdef vl_api_version_tuple
1408
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001409"""
1410 if "version" in s["Option"]:
1411 v = s["Option"]["version"]
1412 (major, minor, patch) = v.split(".")
1413 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % (
1414 module,
1415 major,
1416 minor,
1417 patch,
1418 )
Ole Troan9d420872017-10-12 13:06:35 +02001419
1420 output += "\n#endif /* vl_api_version_tuple */\n\n"
1421
1422 return output
1423
1424
Ole Troan2a1ca782019-09-19 01:08:30 +02001425def generate_include_enum(s, module, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001426 """Generate <name>.api_enum.h"""
Ole Troan2a1ca782019-09-19 01:08:30 +02001427 write = stream.write
1428
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001429 if "Define" in s:
1430 write("typedef enum {\n")
1431 for t in s["Define"]:
1432 write(" VL_API_{},\n".format(t.name.upper()))
1433 write(" VL_MSG_{}_LAST\n".format(module.upper()))
1434 write("}} vl_api_{}_enum_t;\n".format(module))
Ole Troan2a1ca782019-09-19 01:08:30 +02001435
Paul Vinciguerra7c8803d2019-11-21 17:16:18 -05001436
Ole Troandf87f802020-11-18 19:17:48 +01001437def generate_include_counters(s, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001438 """Include file for the counter data model types."""
Ole Troan148c7b72020-10-07 18:05:37 +02001439 write = stream.write
1440
1441 for counters in s:
1442 csetname = counters.name
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001443 write("typedef enum {\n")
Ole Troan148c7b72020-10-07 18:05:37 +02001444 for c in counters.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001445 write(" {}_ERROR_{},\n".format(csetname.upper(), c["name"].upper()))
1446 write(" {}_N_ERROR\n".format(csetname.upper()))
1447 write("}} vl_counter_{}_enum_t;\n".format(csetname))
Ole Troan148c7b72020-10-07 18:05:37 +02001448
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001449 write("extern vlib_error_desc_t {}_error_counters[];\n".format(csetname))
Ole Troan148c7b72020-10-07 18:05:37 +02001450
Ole Troandf87f802020-11-18 19:17:48 +01001451
Ole Troan2a1ca782019-09-19 01:08:30 +02001452def generate_include_types(s, module, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001453 """Generate separate API _types file."""
Ole Troan2a1ca782019-09-19 01:08:30 +02001454 write = stream.write
1455
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001456 write("#ifndef included_{module}_api_types_h\n".format(module=module))
1457 write("#define included_{module}_api_types_h\n".format(module=module))
Ole Troan2a1ca782019-09-19 01:08:30 +02001458
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001459 if "version" in s["Option"]:
1460 v = s["Option"]["version"]
1461 (major, minor, patch) = v.split(".")
1462 write(
1463 "#define VL_API_{m}_API_VERSION_MAJOR {v}\n".format(
1464 m=module.upper(), v=major
1465 )
1466 )
1467 write(
1468 "#define VL_API_{m}_API_VERSION_MINOR {v}\n".format(
1469 m=module.upper(), v=minor
1470 )
1471 )
1472 write(
1473 "#define VL_API_{m}_API_VERSION_PATCH {v}\n".format(
1474 m=module.upper(), v=patch
1475 )
1476 )
Ole Troanf92bfb12020-02-28 13:45:42 +01001477
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001478 if "Import" in s:
1479 write("/* Imported API files */\n")
1480 for i in s["Import"]:
1481 filename = i.filename.replace("plugins/", "")
1482 write("#include <{}_types.h>\n".format(filename))
Ole Troan2a1ca782019-09-19 01:08:30 +02001483
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001484 for o in itertools.chain(s["types"], s["Define"]):
Ole Troan2a1ca782019-09-19 01:08:30 +02001485 tname = o.__class__.__name__
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001486 if tname == "Using":
1487 if "length" in o.alias:
1488 write(
1489 "typedef %s vl_api_%s_t[%s];\n"
1490 % (o.alias["type"], o.name, o.alias["length"])
1491 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001492 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001493 write("typedef %s vl_api_%s_t;\n" % (o.alias["type"], o.name))
1494 elif tname == "Enum" or tname == "EnumFlag":
1495 if o.enumtype == "u32":
Ole Troan2a1ca782019-09-19 01:08:30 +02001496 write("typedef enum {\n")
1497 else:
1498 write("typedef enum __attribute__((packed)) {\n")
1499
1500 for b in o.block:
1501 write(" %s = %s,\n" % (b[0], b[1]))
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001502 write("} vl_api_%s_t;\n" % o.name)
1503 if o.enumtype != "u32":
1504 size1 = "sizeof(vl_api_%s_t)" % o.name
1505 size2 = "sizeof(%s)" % o.enumtype
1506 err_str = "size of API enum %s is wrong" % o.name
1507 write('STATIC_ASSERT(%s == %s, "%s");\n' % (size1, size2, err_str))
Ole Troan2a1ca782019-09-19 01:08:30 +02001508 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001509 if tname == "Union":
1510 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
Ole Troan2a1ca782019-09-19 01:08:30 +02001511 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001512 write(
1513 ("typedef struct __attribute__ ((packed)) _vl_api_%s {\n") % o.name
1514 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001515 for b in o.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001516 if b.type == "Option":
Ole Troan2a1ca782019-09-19 01:08:30 +02001517 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001518 if b.type == "Field":
1519 write(" %s %s;\n" % (api2c(b.fieldtype), b.fieldname))
1520 elif b.type == "Array":
Ole Troan2a1ca782019-09-19 01:08:30 +02001521 if b.lengthfield:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001522 write(" %s %s[0];\n" % (api2c(b.fieldtype), b.fieldname))
Ole Troan2a1ca782019-09-19 01:08:30 +02001523 else:
1524 # Fixed length strings decay to nul terminated u8
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001525 if b.fieldtype == "string":
Ole Troan2a1ca782019-09-19 01:08:30 +02001526 if b.modern_vla:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001527 write(
1528 " {} {};\n".format(
1529 api2c(b.fieldtype), b.fieldname
1530 )
1531 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001532 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001533 write(" u8 {}[{}];\n".format(b.fieldname, b.length))
Ole Troan2a1ca782019-09-19 01:08:30 +02001534 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001535 write(
1536 " %s %s[%s];\n"
1537 % (api2c(b.fieldtype), b.fieldname, b.length)
1538 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001539 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001540 raise ValueError(
1541 "Error in processing type {} for {}".format(b, o.name)
1542 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001543
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001544 write("} vl_api_%s_t;\n" % o.name)
1545 write(
1546 f"#define VL_API_{o.name.upper()}_IS_CONSTANT_SIZE ({0 if o.vla else 1})\n\n"
1547 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001548
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001549 for t in s["Define"]:
1550 write(
1551 '#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'.format(
1552 n=t.name, ID=t.name.upper(), crc=t.crc
1553 )
1554 )
Ole Troan3f2d5712019-12-07 00:39:49 +01001555
Ole Troan2a1ca782019-09-19 01:08:30 +02001556 write("\n#endif\n")
1557
1558
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001559def generate_c_boilerplate(services, defines, counters, file_crc, module, stream):
1560 """VPP side plugin."""
Ole Troan2a1ca782019-09-19 01:08:30 +02001561 write = stream.write
Ole Troan148c7b72020-10-07 18:05:37 +02001562 define_hash = {d.name: d for d in defines}
Ole Troan2a1ca782019-09-19 01:08:30 +02001563
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001564 hdr = """\
Ole Troan2a1ca782019-09-19 01:08:30 +02001565#define vl_endianfun /* define message structures */
1566#include "{module}.api.h"
1567#undef vl_endianfun
1568
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001569#define vl_calcsizefun
1570#include "{module}.api.h"
1571#undef vl_calsizefun
1572
Ole Troan2a1ca782019-09-19 01:08:30 +02001573/* instantiate all the print functions we know about */
Ole Troan2a1ca782019-09-19 01:08:30 +02001574#define vl_printfun
1575#include "{module}.api.h"
1576#undef vl_printfun
1577
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001578"""
Ole Troan2a1ca782019-09-19 01:08:30 +02001579
1580 write(hdr.format(module=module))
Ole Troan683bdb62023-05-11 22:02:30 +02001581 if len(defines) > 0:
1582 write("static u16\n")
1583 write("setup_message_id_table (void) {\n")
1584 write(" api_main_t *am = my_api_main;\n")
1585 write(" vl_msg_api_msg_config_t c;\n")
1586 write(
1587 ' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", '
1588 "VL_MSG_{m}_LAST);\n".format(module, crc=file_crc, m=module.upper())
1589 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001590
Ole Troan2a1ca782019-09-19 01:08:30 +02001591 for d in defines:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001592 write(
1593 ' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
1594 " VL_API_{ID} + msg_id_base);\n".format(
1595 n=d.name, ID=d.name.upper(), crc=d.crc
1596 )
1597 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001598 for s in services:
Ole Troane796a182020-05-18 11:14:05 +02001599 d = define_hash[s.caller]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001600 write(
1601 " c = (vl_msg_api_msg_config_t) "
1602 " {{.id = VL_API_{ID} + msg_id_base,\n"
1603 ' .name = "{n}",\n'
1604 " .handler = vl_api_{n}_t_handler,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001605 " .endian = vl_api_{n}_t_endian,\n"
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001606 " .format_fn = vl_api_{n}_t_format,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001607 " .traced = 1,\n"
1608 " .replay = 1,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001609 " .tojson = vl_api_{n}_t_tojson,\n"
1610 " .fromjson = vl_api_{n}_t_fromjson,\n"
1611 " .calc_size = vl_api_{n}_t_calc_size,\n"
1612 " .is_autoendian = {auto}}};\n".format(
1613 n=s.caller, ID=s.caller.upper(), auto=d.autoendian
1614 )
1615 )
1616 write(" vl_msg_api_config (&c);\n")
Ole Troanbad67922020-08-24 12:22:01 +02001617 try:
1618 d = define_hash[s.reply]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001619 write(
1620 " c = (vl_msg_api_msg_config_t) "
1621 "{{.id = VL_API_{ID} + msg_id_base,\n"
1622 ' .name = "{n}",\n'
1623 " .handler = 0,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001624 " .endian = vl_api_{n}_t_endian,\n"
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001625 " .format_fn = vl_api_{n}_t_format,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001626 " .traced = 1,\n"
1627 " .replay = 1,\n"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001628 " .tojson = vl_api_{n}_t_tojson,\n"
1629 " .fromjson = vl_api_{n}_t_fromjson,\n"
1630 " .calc_size = vl_api_{n}_t_calc_size,\n"
1631 " .is_autoendian = {auto}}};\n".format(
1632 n=s.reply, ID=s.reply.upper(), auto=d.autoendian
1633 )
1634 )
1635 write(" vl_msg_api_config (&c);\n")
Ole Troanbad67922020-08-24 12:22:01 +02001636 except KeyError:
1637 pass
Ole Troan2a1ca782019-09-19 01:08:30 +02001638
Stanislav Zaikin139b2da2022-07-21 19:06:26 +02001639 try:
1640 if s.stream:
1641 d = define_hash[s.stream_message]
1642 write(
1643 " c = (vl_msg_api_msg_config_t) "
1644 "{{.id = VL_API_{ID} + msg_id_base,\n"
1645 ' .name = "{n}",\n'
1646 " .handler = 0,\n"
1647 " .endian = vl_api_{n}_t_endian,\n"
1648 " .format_fn = vl_api_{n}_t_format,\n"
1649 " .traced = 1,\n"
1650 " .replay = 1,\n"
1651 " .tojson = vl_api_{n}_t_tojson,\n"
1652 " .fromjson = vl_api_{n}_t_fromjson,\n"
1653 " .calc_size = vl_api_{n}_t_calc_size,\n"
1654 " .is_autoendian = {auto}}};\n".format(
1655 n=s.stream_message,
1656 ID=s.stream_message.upper(),
1657 auto=d.autoendian,
1658 )
1659 )
1660 write(" vl_msg_api_config (&c);\n")
1661 except KeyError:
1662 pass
Ole Troan683bdb62023-05-11 22:02:30 +02001663 if len(defines) > 0:
1664 write(" return msg_id_base;\n")
1665 write("}\n")
Ole Troan2a1ca782019-09-19 01:08:30 +02001666
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001667 severity = {
1668 "error": "VL_COUNTER_SEVERITY_ERROR",
1669 "info": "VL_COUNTER_SEVERITY_INFO",
1670 "warn": "VL_COUNTER_SEVERITY_WARN",
1671 }
Ole Troan148c7b72020-10-07 18:05:37 +02001672
1673 for cnt in counters:
1674 csetname = cnt.name
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001675 write("vlib_error_desc_t {}_error_counters[] = {{\n".format(csetname))
Ole Troan148c7b72020-10-07 18:05:37 +02001676 for c in cnt.block:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001677 write(" {\n")
1678 write(' .name = "{}",\n'.format(c["name"]))
1679 write(' .desc = "{}",\n'.format(c["description"]))
1680 write(" .severity = {},\n".format(severity[c["severity"]]))
1681 write(" },\n")
1682 write("};\n")
Ole Troan2a1ca782019-09-19 01:08:30 +02001683
Ole Troandf87f802020-11-18 19:17:48 +01001684
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001685def generate_c_test_boilerplate(services, defines, file_crc, module, plugin, stream):
1686 """Generate code for legacy style VAT. To be deleted."""
Ole Troan2a1ca782019-09-19 01:08:30 +02001687 write = stream.write
1688
Ole Troandf87f802020-11-18 19:17:48 +01001689 define_hash = {d.name: d for d in defines}
Ole Troan2a1ca782019-09-19 01:08:30 +02001690
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001691 hdr = """\
Ole Troandf87f802020-11-18 19:17:48 +01001692#define vl_endianfun /* define message structures */
Ole Troan2a1ca782019-09-19 01:08:30 +02001693#include "{module}.api.h"
1694#undef vl_endianfun
1695
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01001696#define vl_calcsizefun
1697#include "{module}.api.h"
1698#undef vl_calsizefun
1699
Ole Troan2a1ca782019-09-19 01:08:30 +02001700/* instantiate all the print functions we know about */
Ole Troan2a1ca782019-09-19 01:08:30 +02001701#define vl_printfun
1702#include "{module}.api.h"
1703#undef vl_printfun
1704
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001705"""
Ole Troan2a1ca782019-09-19 01:08:30 +02001706
1707 write(hdr.format(module=module))
1708 for s in services:
1709 try:
1710 d = define_hash[s.reply]
Ole Troandf87f802020-11-18 19:17:48 +01001711 except KeyError:
Ole Troan2a1ca782019-09-19 01:08:30 +02001712 continue
1713 if d.manual_print:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001714 write(
1715 "/*\n"
1716 " * Manual definition requested for: \n"
1717 " * vl_api_{n}_t_handler()\n"
1718 " */\n".format(n=s.reply)
1719 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001720 continue
1721 if not define_hash[s.caller].autoreply:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001722 write(
1723 "/* Generation not supported (vl_api_{n}_t_handler()) */\n".format(
1724 n=s.reply
1725 )
1726 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001727 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001728 write("#ifndef VL_API_{n}_T_HANDLER\n".format(n=s.reply.upper()))
1729 write("static void\n")
1730 write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=s.reply))
1731 write(" vat_main_t * vam = {}_test_main.vat_main;\n".format(module))
1732 write(" i32 retval = ntohl(mp->retval);\n")
1733 write(" if (vam->async_mode) {\n")
1734 write(" vam->async_errors += (retval < 0);\n")
1735 write(" } else {\n")
1736 write(" vam->retval = retval;\n")
1737 write(" vam->result_ready = 1;\n")
1738 write(" }\n")
1739 write("}\n")
1740 write("#endif\n")
Ole Troan2a1ca782019-09-19 01:08:30 +02001741
Ole Troanb126ebc2019-10-07 16:22:00 +02001742 for e in s.events:
1743 if define_hash[e].manual_print:
1744 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001745 write("static void\n")
1746 write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=e))
Damjan Marionfe45f8f2022-05-20 16:01:22 +02001747 write(' vlib_cli_output(0, "{n} event called:");\n'.format(n=e))
1748 write(
1749 ' vlib_cli_output(0, "%U", vl_api_{n}_t_format, mp);\n'.format(n=e)
1750 )
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001751 write("}\n")
Ole Troanb126ebc2019-10-07 16:22:00 +02001752
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001753 write("static void\n")
1754 write("setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n")
Ole Troan2a1ca782019-09-19 01:08:30 +02001755 for s in services:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001756 write(
Damjan Mariona2eb5072022-05-20 20:06:01 +02001757 " vl_msg_api_config (&(vl_msg_api_msg_config_t){{\n"
1758 " .id = VL_API_{ID} + msg_id_base,\n"
1759 ' .name = "{n}",\n'
1760 " .handler = vl_api_{n}_t_handler,\n"
1761 " .endian = vl_api_{n}_t_endian,\n"
1762 " .format_fn = vl_api_{n}_t_format,\n"
1763 " .size = sizeof(vl_api_{n}_t),\n"
1764 " .traced = 1,\n"
1765 " .tojson = vl_api_{n}_t_tojson,\n"
1766 " .fromjson = vl_api_{n}_t_fromjson,\n"
1767 " .calc_size = vl_api_{n}_t_calc_size,\n"
1768 " }});".format(n=s.reply, ID=s.reply.upper())
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001769 )
1770 write(
1771 ' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(
1772 n=s.caller
1773 )
1774 )
Ole Troan2a1ca782019-09-19 01:08:30 +02001775 try:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001776 write(
1777 ' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'.format(
1778 n=s.caller, help=define_hash[s.caller].options["vat_help"]
1779 )
1780 )
Ole Troandf87f802020-11-18 19:17:48 +01001781 except KeyError:
Ole Troan2a1ca782019-09-19 01:08:30 +02001782 pass
1783
Ole Troanb126ebc2019-10-07 16:22:00 +02001784 # Events
1785 for e in s.events:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001786 write(
Damjan Mariona2eb5072022-05-20 20:06:01 +02001787 " vl_msg_api_config (&(vl_msg_api_msg_config_t){{\n"
1788 " .id = VL_API_{ID} + msg_id_base,\n"
1789 ' .name = "{n}",\n'
1790 " .handler = vl_api_{n}_t_handler,\n"
1791 " .endian = vl_api_{n}_t_endian,\n"
1792 " .format_fn = vl_api_{n}_t_format,\n"
1793 " .size = sizeof(vl_api_{n}_t),\n"
1794 " .traced = 1,\n"
1795 " .tojson = vl_api_{n}_t_tojson,\n"
1796 " .fromjson = vl_api_{n}_t_fromjson,\n"
1797 " .calc_size = vl_api_{n}_t_calc_size,\n"
1798 " }});".format(n=e, ID=e.upper())
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001799 )
Ole Troanb126ebc2019-10-07 16:22:00 +02001800
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001801 write("}\n")
1802 write("clib_error_t * vat_plugin_register (vat_main_t *vam)\n")
1803 write("{\n")
1804 write(" {n}_test_main_t * mainp = &{n}_test_main;\n".format(n=module))
1805 write(" mainp->vat_main = vam;\n")
1806 write(
1807 " mainp->msg_id_base = vl_client_get_first_plugin_msg_id "
1808 ' ("{n}_{crc:08x}");\n'.format(n=module, crc=file_crc)
1809 )
1810 write(" if (mainp->msg_id_base == (u16) ~0)\n")
1811 write(
1812 ' return clib_error_return (0, "{} plugin not loaded...");\n'.format(
1813 module
1814 )
1815 )
1816 write(" setup_message_id_table (vam, mainp->msg_id_base);\n")
1817 write("#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n")
1818 write(" VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n")
1819 write("#endif\n")
1820 write(" return 0;\n")
1821 write("}\n")
Ole Troan2a1ca782019-09-19 01:08:30 +02001822
Ole Troandf87f802020-11-18 19:17:48 +01001823
1824def apifunc(func):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001825 """Check if a method is generated already."""
1826
Ole Troandf87f802020-11-18 19:17:48 +01001827 def _f(module, d, processed, *args):
1828 if d.name in processed:
1829 return None
1830 processed[d.name] = True
1831 return func(module, d, *args)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001832
Ole Troandf87f802020-11-18 19:17:48 +01001833 return _f
1834
1835
1836def c_test_api_service(s, dump, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001837 """Generate JSON code for a service."""
Ole Troandf87f802020-11-18 19:17:48 +01001838 write = stream.write
1839
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001840 req_reply_template = """\
Ole Troandf87f802020-11-18 19:17:48 +01001841static cJSON *
1842api_{n} (cJSON *o)
1843{{
1844 vl_api_{n}_t *mp;
1845 int len;
1846 if (!o) return 0;
1847 mp = vl_api_{n}_t_fromjson(o, &len);
1848 if (!mp) {{
1849 fprintf(stderr, "Failed converting JSON to API\\n");
1850 return 0;
1851 }}
1852
1853 mp->_vl_msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1854 vl_api_{n}_t_endian(mp);
1855 vac_write((char *)mp, len);
Filip Tehlar36217e32021-07-23 08:51:10 +00001856 cJSON_free(mp);
Ole Troandf87f802020-11-18 19:17:48 +01001857
1858 /* Read reply */
1859 char *p;
1860 int l;
1861 vac_read(&p, &l, 5); // XXX: Fix timeout
Ole Troanedc73fd2021-02-17 13:26:53 +01001862 if (p == 0 || l == 0) return 0;
Ole Troandf87f802020-11-18 19:17:48 +01001863 // XXX Will fail in case of event received. Do loop
1864 if (ntohs(*((u16 *)p)) != vac_get_msg_index(VL_API_{R}_CRC)) {{
1865 fprintf(stderr, "Mismatched reply\\n");
1866 return 0;
1867 }}
1868 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1869 vl_api_{r}_t_endian(rmp);
1870 return vl_api_{r}_t_tojson(rmp);
1871}}
1872
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001873"""
1874 dump_details_template = """\
Ole Troandf87f802020-11-18 19:17:48 +01001875static cJSON *
1876api_{n} (cJSON *o)
1877{{
1878 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1879 int len;
1880 if (!o) return 0;
1881 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1882 if (!mp) {{
1883 fprintf(stderr, "Failed converting JSON to API\\n");
1884 return 0;
1885 }}
1886 mp->_vl_msg_id = msg_id;
1887 vl_api_{n}_t_endian(mp);
1888 vac_write((char *)mp, len);
Filip Tehlar36217e32021-07-23 08:51:10 +00001889 cJSON_free(mp);
Ole Troandf87f802020-11-18 19:17:48 +01001890
1891 vat2_control_ping(123); // FIX CONTEXT
1892 cJSON *reply = cJSON_CreateArray();
1893
1894 u16 ping_reply_msg_id = vac_get_msg_index(VL_API_CONTROL_PING_REPLY_CRC);
1895 u16 details_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1896
1897 while (1) {{
1898 /* Read reply */
1899 char *p;
1900 int l;
1901 vac_read(&p, &l, 5); // XXX: Fix timeout
Ole Troanedc73fd2021-02-17 13:26:53 +01001902 if (p == 0 || l == 0) {{
1903 cJSON_free(reply);
1904 return 0;
1905 }}
Ole Troandf87f802020-11-18 19:17:48 +01001906
1907 /* Message can be one of [_details, control_ping_reply
1908 * or unrelated event]
1909 */
1910 u16 reply_msg_id = ntohs(*((u16 *)p));
1911 if (reply_msg_id == ping_reply_msg_id) {{
1912 break;
1913 }}
1914
1915 if (reply_msg_id == details_msg_id) {{
Ole Troanedc73fd2021-02-17 13:26:53 +01001916 if (l < sizeof(vl_api_{r}_t)) {{
1917 cJSON_free(reply);
1918 return 0;
1919 }}
Ole Troandf87f802020-11-18 19:17:48 +01001920 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1921 vl_api_{r}_t_endian(rmp);
1922 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1923 }}
1924 }}
1925 return reply;
1926}}
1927
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001928"""
1929 gets_details_reply_template = """\
Ole Troandf87f802020-11-18 19:17:48 +01001930static cJSON *
1931api_{n} (cJSON *o)
1932{{
1933 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1934 int len = 0;
1935 if (!o) return 0;
1936 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1937 if (!mp) {{
1938 fprintf(stderr, "Failed converting JSON to API\\n");
1939 return 0;
1940 }}
1941 mp->_vl_msg_id = msg_id;
1942
1943 vl_api_{n}_t_endian(mp);
1944 vac_write((char *)mp, len);
Filip Tehlar36217e32021-07-23 08:51:10 +00001945 cJSON_free(mp);
Ole Troandf87f802020-11-18 19:17:48 +01001946
1947 cJSON *reply = cJSON_CreateArray();
1948
1949 u16 reply_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1950 u16 details_msg_id = vac_get_msg_index(VL_API_{D}_CRC);
1951
1952 while (1) {{
1953 /* Read reply */
1954 char *p;
1955 int l;
1956 vac_read(&p, &l, 5); // XXX: Fix timeout
1957
1958 /* Message can be one of [_details, control_ping_reply
1959 * or unrelated event]
1960 */
1961 u16 msg_id = ntohs(*((u16 *)p));
1962 if (msg_id == reply_msg_id) {{
1963 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1964 vl_api_{r}_t_endian(rmp);
1965 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1966 break;
1967 }}
1968
1969 if (msg_id == details_msg_id) {{
1970 vl_api_{d}_t *rmp = (vl_api_{d}_t *)p;
1971 vl_api_{d}_t_endian(rmp);
1972 cJSON_AddItemToArray(reply, vl_api_{d}_t_tojson(rmp));
1973 }}
1974 }}
1975 return reply;
1976}}
1977
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001978"""
Ole Troandf87f802020-11-18 19:17:48 +01001979
1980 if dump:
1981 if s.stream_message:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001982 write(
1983 gets_details_reply_template.format(
1984 n=s.caller,
1985 r=s.reply,
1986 N=s.caller.upper(),
1987 R=s.reply.upper(),
1988 d=s.stream_message,
1989 D=s.stream_message.upper(),
1990 )
1991 )
Ole Troandf87f802020-11-18 19:17:48 +01001992 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001993 write(
1994 dump_details_template.format(
1995 n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
1996 )
1997 )
Ole Troandf87f802020-11-18 19:17:48 +01001998 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02001999 write(
2000 req_reply_template.format(
2001 n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
2002 )
2003 )
Ole Troandf87f802020-11-18 19:17:48 +01002004
2005
2006def generate_c_test2_boilerplate(services, defines, module, stream):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002007 """Generate code for VAT2 plugin."""
Ole Troandf87f802020-11-18 19:17:48 +01002008 write = stream.write
2009
2010 define_hash = {d.name: d for d in defines}
2011 # replies = {}
2012
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002013 hdr = """\
Ole Troandf87f802020-11-18 19:17:48 +01002014#include <vlibapi/api.h>
2015#include <vlibmemory/api.h>
2016#include <vppinfra/error.h>
2017#include <vnet/ip/ip_format_fns.h>
2018#include <vnet/ethernet/ethernet_format_fns.h>
2019
2020#define vl_typedefs /* define message structures */
Filip Tehlarb7e4d442021-07-08 18:44:19 +00002021#include <vlibmemory/vl_memory_api_h.h>
Florin Corasa1400ce2021-09-15 09:02:08 -07002022#include <vlibmemory/vlib.api_types.h>
2023#include <vlibmemory/vlib.api.h>
Ole Troandf87f802020-11-18 19:17:48 +01002024#undef vl_typedefs
2025
2026#include "{module}.api_enum.h"
2027#include "{module}.api_types.h"
2028
2029#define vl_endianfun /* define message structures */
2030#include "{module}.api.h"
2031#undef vl_endianfun
2032
Klement Sekera9b7e8ac2021-11-22 21:26:20 +01002033#define vl_calcsizefun
2034#include "{module}.api.h"
2035#undef vl_calsizefun
2036
Ole Troandf87f802020-11-18 19:17:48 +01002037#define vl_printfun
2038#include "{module}.api.h"
2039#undef vl_printfun
2040
2041#include "{module}.api_tojson.h"
2042#include "{module}.api_fromjson.h"
2043#include <vpp-api/client/vppapiclient.h>
2044
2045#include <vat2/vat2_helpers.h>
2046
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002047"""
Ole Troandf87f802020-11-18 19:17:48 +01002048
2049 write(hdr.format(module=module))
2050
2051 for s in services:
2052 if s.reply not in define_hash:
2053 continue
2054 c_test_api_service(s, s.stream, stream)
2055
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002056 write(
2057 "void vat2_register_function(char *, cJSON * (*)(cJSON *), cJSON * (*)(void *), u32);\n"
2058 )
Ole Troandf87f802020-11-18 19:17:48 +01002059 # write('__attribute__((constructor))')
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002060 write("clib_error_t *\n")
2061 write("vat2_register_plugin (void) {\n")
Ole Troandf87f802020-11-18 19:17:48 +01002062 for s in services:
Filip Tehlar36217e32021-07-23 08:51:10 +00002063 if s.reply not in define_hash:
2064 continue
2065 crc = define_hash[s.caller].crc
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002066 write(
2067 ' vat2_register_function("{n}", api_{n}, (cJSON * (*)(void *))vl_api_{n}_t_tojson, 0x{crc:08x});\n'.format(
2068 n=s.caller, crc=crc
2069 )
2070 )
2071 write(" return 0;\n")
2072 write("}\n")
Ole Troandf87f802020-11-18 19:17:48 +01002073
2074
Ole Troan9d420872017-10-12 13:06:35 +02002075#
2076# Plugin entry point
2077#
Nathan Skrzypczak1b299fa2022-06-16 17:00:02 +02002078def run(output_dir, apifilename, s):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002079 """Main plugin entry point."""
Ole Troan33a58172019-09-04 09:12:29 +02002080 stream = StringIO()
Ole Troan2a1ca782019-09-19 01:08:30 +02002081
Nathan Skrzypczak1b299fa2022-06-16 17:00:02 +02002082 if not output_dir:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002083 sys.stderr.write("Missing --outputdir argument")
Ole Troan2a1ca782019-09-19 01:08:30 +02002084 return None
2085
Ole Troandf87f802020-11-18 19:17:48 +01002086 basename = os.path.basename(apifilename)
2087 filename, _ = os.path.splitext(basename)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002088 modulename = filename.replace(".", "_")
Nathan Skrzypczak1b299fa2022-06-16 17:00:02 +02002089 filename_enum = os.path.join(output_dir + "/" + basename + "_enum.h")
2090 filename_types = os.path.join(output_dir + "/" + basename + "_types.h")
2091 filename_c = os.path.join(output_dir + "/" + basename + ".c")
2092 filename_c_test = os.path.join(output_dir + "/" + basename + "_test.c")
2093 filename_c_test2 = os.path.join(output_dir + "/" + basename + "_test2.c")
2094 filename_c_tojson = os.path.join(output_dir + "/" + basename + "_tojson.h")
2095 filename_c_fromjson = os.path.join(output_dir + "/" + basename + "_fromjson.h")
Ole Troan2a1ca782019-09-19 01:08:30 +02002096
2097 # Generate separate types file
2098 st = StringIO()
2099 generate_include_types(s, modulename, st)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002100 with open(filename_types, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002101 st.seek(0)
2102 shutil.copyfileobj(st, fd)
Ole Troan2a1ca782019-09-19 01:08:30 +02002103 st.close()
2104
2105 # Generate separate enum file
2106 st = StringIO()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002107 st.write("#ifndef included_{}_api_enum_h\n".format(modulename))
2108 st.write("#define included_{}_api_enum_h\n".format(modulename))
Ole Troan2a1ca782019-09-19 01:08:30 +02002109 generate_include_enum(s, modulename, st)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002110 generate_include_counters(s["Counters"], st)
2111 st.write("#endif\n")
2112 with open(filename_enum, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002113 st.seek(0)
2114 shutil.copyfileobj(st, fd)
Ole Troan2a1ca782019-09-19 01:08:30 +02002115 st.close()
2116
2117 # Generate separate C file
2118 st = StringIO()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002119 generate_c_boilerplate(
2120 s["Service"], s["Define"], s["Counters"], s["file_crc"], modulename, st
2121 )
2122 with open(filename_c, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002123 st.seek(0)
Ole Troan2a1ca782019-09-19 01:08:30 +02002124 shutil.copyfileobj(st, fd)
2125 st.close()
2126
2127 # Generate separate C test file
Ole Troan2a1ca782019-09-19 01:08:30 +02002128 st = StringIO()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002129 plugin = bool("plugin" in apifilename)
2130 generate_c_test_boilerplate(
2131 s["Service"], s["Define"], s["file_crc"], modulename, plugin, st
2132 )
2133 with open(filename_c_test, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002134 st.seek(0)
Ole Troan2a1ca782019-09-19 01:08:30 +02002135 shutil.copyfileobj(st, fd)
2136 st.close()
Ole Troan33a58172019-09-04 09:12:29 +02002137
Ole Troandf87f802020-11-18 19:17:48 +01002138 # Fully autogenerated VATv2 C test file
2139 st = StringIO()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002140 generate_c_test2_boilerplate(s["Service"], s["Define"], modulename, st)
2141 with open(filename_c_test2, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002142 st.seek(0)
2143 shutil.copyfileobj(st, fd)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002144 st.close() #
Ole Troandf87f802020-11-18 19:17:48 +01002145
2146 # Generate separate JSON file
2147 st = StringIO()
2148 generate_tojson(s, modulename, st)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002149 with open(filename_c_tojson, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002150 st.seek(0)
2151 shutil.copyfileobj(st, fd)
2152 st.close()
2153 st = StringIO()
2154 generate_fromjson(s, modulename, st)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002155 with open(filename_c_fromjson, "w") as fd:
Ole Troandf87f802020-11-18 19:17:48 +01002156 st.seek(0)
2157 shutil.copyfileobj(st, fd)
2158 st.close()
2159
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002160 output = TOP_BOILERPLATE.format(datestring=DATESTRING, input_filename=basename)
2161 output += generate_imports(s["Import"])
Ole Troan9d420872017-10-12 13:06:35 +02002162 output += msg_ids(s)
2163 output += msg_names(s)
2164 output += msg_name_crc_list(s, filename)
Ole Troan2a1ca782019-09-19 01:08:30 +02002165 output += typedefs(modulename)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002166 printfun_types(s["types"], stream, modulename)
2167 printfun(s["Define"], stream, modulename)
Ole Troan33a58172019-09-04 09:12:29 +02002168 output += stream.getvalue()
Ole Troan2a1ca782019-09-19 01:08:30 +02002169 stream.close()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002170 output += endianfun(s["types"] + s["Define"], modulename)
2171 output += calc_size_fun(s["types"] + s["Define"], modulename)
Ole Troan9d420872017-10-12 13:06:35 +02002172 output += version_tuple(s, basename)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +02002173 output += BOTTOM_BOILERPLATE.format(input_filename=basename, file_crc=s["file_crc"])
Ole Troan9d420872017-10-12 13:06:35 +02002174
2175 return output