blob: 7c596967cfbd7f2022c63d65818c1ca915e53288 [file] [log] [blame]
Nathan Skrzypczak5c2f9642019-09-09 16:45:06 +02001#!/usr/bin/env python3
Ole Troan9d420872017-10-12 13:06:35 +02002
Ole Troan9d420872017-10-12 13:06:35 +02003import sys
4import argparse
Paul Vinciguerraff47fb62019-08-06 19:58:24 -04005import keyword
Ole Troan9d420872017-10-12 13:06:35 +02006import logging
7import binascii
8import os
Ole Troan5c318c72020-05-05 12:23:47 +02009from subprocess import Popen, PIPE
Ole Troandf87f802020-11-18 19:17:48 +010010import ply.lex as lex
11import ply.yacc as yacc
Ole Troan9d420872017-10-12 13:06:35 +020012
BenoƮt Ganne3f0ae662020-09-09 12:50:07 +020013assert sys.version_info >= (3, 5), \
Ole Troan14a6c0e2020-05-13 11:47:43 +020014 "Not supported Python version: {}".format(sys.version)
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -040015log = logging.getLogger('vppapigen')
16
Ole Troand6743b12018-03-07 08:40:58 +010017# Ensure we don't leave temporary files around
18sys.dont_write_bytecode = True
19
Ole Troan9d420872017-10-12 13:06:35 +020020#
21# VPP API language
22#
23
24# Global dictionary of new types (including enums)
25global_types = {}
26
Paul Vinciguerra4bf84902019-07-31 00:34:05 -040027seen_imports = {}
28
Ole Troan9d420872017-10-12 13:06:35 +020029
Ole Troan8dbfb432019-04-24 14:31:18 +020030def global_type_add(name, obj):
Ole Troan9d420872017-10-12 13:06:35 +020031 '''Add new type to the dictionary of types '''
32 type_name = 'vl_api_' + name + '_t'
Paul Vinciguerra4bf84902019-07-31 00:34:05 -040033 if type_name in global_types:
34 raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
35 name, obj))
Ole Troan8dbfb432019-04-24 14:31:18 +020036 global_types[type_name] = obj
Ole Troan9d420872017-10-12 13:06:35 +020037
38
39# All your trace are belong to us!
40def exception_handler(exception_type, exception, traceback):
Ole Troan17225df2018-04-11 09:50:03 +020041 print("%s: %s" % (exception_type.__name__, exception))
Ole Troan9d420872017-10-12 13:06:35 +020042
43
44#
45# Lexer
46#
47class VPPAPILexer(object):
48 def __init__(self, filename):
49 self.filename = filename
50
51 reserved = {
52 'service': 'SERVICE',
53 'rpc': 'RPC',
54 'returns': 'RETURNS',
Marek Gradzki51e59682018-03-06 10:05:44 +010055 'null': 'NULL',
Ole Troan9d420872017-10-12 13:06:35 +020056 'stream': 'STREAM',
57 'events': 'EVENTS',
58 'define': 'DEFINE',
59 'typedef': 'TYPEDEF',
60 'enum': 'ENUM',
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -050061 'enumflag': 'ENUMFLAG',
Ole Troan9d420872017-10-12 13:06:35 +020062 'typeonly': 'TYPEONLY',
63 'manual_print': 'MANUAL_PRINT',
64 'manual_endian': 'MANUAL_ENDIAN',
65 'dont_trace': 'DONT_TRACE',
66 'autoreply': 'AUTOREPLY',
Neale Ranns9302cfe2021-02-02 09:21:52 +000067 'autoendian': 'AUTOENDIAN',
Ole Troan9d420872017-10-12 13:06:35 +020068 'option': 'OPTION',
69 'u8': 'U8',
70 'u16': 'U16',
71 'u32': 'U32',
72 'u64': 'U64',
73 'i8': 'I8',
74 'i16': 'I16',
75 'i32': 'I32',
76 'i64': 'I64',
77 'f64': 'F64',
78 'bool': 'BOOL',
79 'string': 'STRING',
80 'import': 'IMPORT',
81 'true': 'TRUE',
82 'false': 'FALSE',
Ole Troan2c2feab2018-04-24 00:02:37 -040083 'union': 'UNION',
Ole Troan148c7b72020-10-07 18:05:37 +020084 'counters': 'COUNTERS',
85 'paths': 'PATHS',
86 'units': 'UNITS',
87 'severity': 'SEVERITY',
88 'type': 'TYPE',
89 'description': 'DESCRIPTION',
Ole Troan9d420872017-10-12 13:06:35 +020090 }
91
92 tokens = ['STRING_LITERAL',
93 'ID', 'NUM'] + list(reserved.values())
94
95 t_ignore_LINE_COMMENT = '//.*'
96
Ole Troan33a58172019-09-04 09:12:29 +020097 def t_FALSE(self, t):
98 r'false'
99 t.value = False
100 return t
101
102 def t_TRUE(self, t):
103 r'false'
104 t.value = True
105 return t
106
Ole Troan9d420872017-10-12 13:06:35 +0200107 def t_NUM(self, t):
Paul Vinciguerra063f3742019-07-02 13:00:58 -0400108 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
Ole Troan9d420872017-10-12 13:06:35 +0200109 base = 16 if t.value.startswith('0x') else 10
Paul Vinciguerra063f3742019-07-02 13:00:58 -0400110 if '.' in t.value:
111 t.value = float(t.value)
112 else:
113 t.value = int(t.value, base)
Ole Troan9d420872017-10-12 13:06:35 +0200114 return t
115
116 def t_ID(self, t):
117 r'[a-zA-Z_][a-zA-Z_0-9]*'
118 # Check for reserved words
119 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
120 return t
121
122 # C string
123 def t_STRING_LITERAL(self, t):
124 r'\"([^\\\n]|(\\.))*?\"'
125 t.value = str(t.value).replace("\"", "")
126 return t
127
128 # C or C++ comment (ignore)
129 def t_comment(self, t):
130 r'(/\*(.|\n)*?\*/)|(//.*)'
131 t.lexer.lineno += t.value.count('\n')
132
133 # Error handling rule
134 def t_error(self, t):
135 raise ParseError("Illegal character '{}' ({})"
136 "in {}: line {}".format(t.value[0],
137 hex(ord(t.value[0])),
138 self.filename,
139 t.lexer.lineno))
Ole Troan9d420872017-10-12 13:06:35 +0200140
141 # Define a rule so we can track line numbers
142 def t_newline(self, t):
143 r'\n+'
144 t.lexer.lineno += len(t.value)
145
146 literals = ":{}[];=.,"
147
148 # A string containing ignored characters (spaces and tabs)
149 t_ignore = ' \t'
150
Ole Troan17225df2018-04-11 09:50:03 +0200151
Ole Troandf87f802020-11-18 19:17:48 +0100152def vla_mark_length_field(block):
153 if isinstance(block[-1], Array):
154 lengthfield = block[-1].lengthfield
155 for b in block:
156 if b.fieldname == lengthfield:
157 b.is_lengthfield = True
158
159
Ole Troand5a78a52019-09-18 12:12:47 +0200160def vla_is_last_check(name, block):
161 vla = False
162 for i, b in enumerate(block):
163 if isinstance(b, Array) and b.vla:
164 vla = True
165 if i + 1 < len(block):
166 raise ValueError(
167 'VLA field "{}" must be the last field in message "{}"'
168 .format(b.fieldname, name))
169 elif b.fieldtype.startswith('vl_api_'):
170 if global_types[b.fieldtype].vla:
171 vla = True
172 if i + 1 < len(block):
173 raise ValueError(
174 'VLA field "{}" must be the last '
175 'field in message "{}"'
176 .format(b.fieldname, name))
177 elif b.fieldtype == 'string' and b.length == 0:
178 vla = True
179 if i + 1 < len(block):
180 raise ValueError(
181 'VLA field "{}" must be the last '
182 'field in message "{}"'
183 .format(b.fieldname, name))
184 return vla
185
186
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500187class Processable:
188 type = "<Invalid>"
189
190 def process(self, result): # -> Dict
191 result[self.type].append(self)
192
193
194class Service(Processable):
195 type = 'Service'
196
Ole Troandf87f802020-11-18 19:17:48 +0100197 def __init__(self, caller, reply, events=None, stream_message=None,
198 stream=False):
Ole Troan9d420872017-10-12 13:06:35 +0200199 self.caller = caller
200 self.reply = reply
201 self.stream = stream
Ole Troanf5db3712020-05-20 15:47:06 +0200202 self.stream_message = stream_message
Paul Vinciguerra7e0c48e2019-02-01 19:37:45 -0800203 self.events = [] if events is None else events
Ole Troan9d420872017-10-12 13:06:35 +0200204
205
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500206class Typedef(Processable):
207 type = 'Typedef'
208
Ole Troan9d420872017-10-12 13:06:35 +0200209 def __init__(self, name, flags, block):
210 self.name = name
211 self.flags = flags
212 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200213 self.crc = str(block).encode()
Ole Troan2c2feab2018-04-24 00:02:37 -0400214 self.manual_print = False
215 self.manual_endian = False
216 for f in flags:
217 if f == 'manual_print':
218 self.manual_print = True
219 elif f == 'manual_endian':
220 self.manual_endian = True
Ole Troan8dbfb432019-04-24 14:31:18 +0200221 global_type_add(name, self)
Ole Troan9d420872017-10-12 13:06:35 +0200222
Ole Troand5a78a52019-09-18 12:12:47 +0200223 self.vla = vla_is_last_check(name, block)
Ole Troandf87f802020-11-18 19:17:48 +0100224 vla_mark_length_field(self.block)
Ole Troane5ff5a32019-08-23 22:55:18 +0200225
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500226 def process(self, result):
227 result['types'].append(self)
228
Ole Troan9d420872017-10-12 13:06:35 +0200229 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200230 return self.name + str(self.flags) + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200231
232
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500233class Using(Processable):
234 type = 'Using'
235
Ole Troan33a58172019-09-04 09:12:29 +0200236 def __init__(self, name, flags, alias):
Ole Troan53fffa12018-11-13 12:36:56 +0100237 self.name = name
Ole Troane5ff5a32019-08-23 22:55:18 +0200238 self.vla = False
Ole Troan75761b92019-09-11 17:49:08 +0200239 self.block = []
240 self.manual_print = True
241 self.manual_endian = True
Ole Troan53fffa12018-11-13 12:36:56 +0100242
Ole Troan33a58172019-09-04 09:12:29 +0200243 self.manual_print = False
244 self.manual_endian = False
245 for f in flags:
246 if f == 'manual_print':
247 self.manual_print = True
248 elif f == 'manual_endian':
249 self.manual_endian = True
250
Ole Troan53fffa12018-11-13 12:36:56 +0100251 if isinstance(alias, Array):
Ole Troane5ff5a32019-08-23 22:55:18 +0200252 a = {'type': alias.fieldtype,
253 'length': alias.length}
Ole Troan53fffa12018-11-13 12:36:56 +0100254 else:
Ole Troane5ff5a32019-08-23 22:55:18 +0200255 a = {'type': alias.fieldtype}
Ole Troan53fffa12018-11-13 12:36:56 +0100256 self.alias = a
Ole Troandf87f802020-11-18 19:17:48 +0100257 self.using = alias
258
Ole Troan6006ca82020-08-31 13:54:47 +0200259 #
260 # Should have been:
261 # self.crc = str(alias).encode()
262 # but to be backwards compatible use the block ([])
263 #
264 self.crc = str(self.block).encode()
Ole Troan8dbfb432019-04-24 14:31:18 +0200265 global_type_add(name, self)
Ole Troan53fffa12018-11-13 12:36:56 +0100266
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500267 def process(self, result): # -> Dict
268 result['types'].append(self)
269
Ole Troan53fffa12018-11-13 12:36:56 +0100270 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200271 return self.name + str(self.alias)
Ole Troan53fffa12018-11-13 12:36:56 +0100272
273
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500274class Union(Processable):
275 type = 'Union'
276
Ole Troan33a58172019-09-04 09:12:29 +0200277 def __init__(self, name, flags, block):
Ole Troan2c2feab2018-04-24 00:02:37 -0400278 self.manual_print = False
279 self.manual_endian = False
Ole Troan2c2feab2018-04-24 00:02:37 -0400280 self.name = name
Ole Troan33a58172019-09-04 09:12:29 +0200281
Ole Troan33a58172019-09-04 09:12:29 +0200282 for f in flags:
283 if f == 'manual_print':
284 self.manual_print = True
285 elif f == 'manual_endian':
286 self.manual_endian = True
287
Ole Troan2c2feab2018-04-24 00:02:37 -0400288 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200289 self.crc = str(block).encode()
Ole Troand5a78a52019-09-18 12:12:47 +0200290 self.vla = vla_is_last_check(name, block)
291
Ole Troan8dbfb432019-04-24 14:31:18 +0200292 global_type_add(name, self)
Ole Troan2c2feab2018-04-24 00:02:37 -0400293
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500294 def process(self, result):
295 result['types'].append(self)
296
Ole Troan2c2feab2018-04-24 00:02:37 -0400297 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200298 return str(self.block)
Ole Troan2c2feab2018-04-24 00:02:37 -0400299
300
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500301class Define(Processable):
302 type = 'Define'
303
Ole Troan9d420872017-10-12 13:06:35 +0200304 def __init__(self, name, flags, block):
305 self.name = name
306 self.flags = flags
307 self.block = block
Ole Troan9d420872017-10-12 13:06:35 +0200308 self.dont_trace = False
309 self.manual_print = False
310 self.manual_endian = False
311 self.autoreply = False
Neale Ranns9302cfe2021-02-02 09:21:52 +0000312 self.autoendian = 0
Ole Troan2a1ca782019-09-19 01:08:30 +0200313 self.options = {}
Ole Troan9d420872017-10-12 13:06:35 +0200314 for f in flags:
Ole Troan2c2feab2018-04-24 00:02:37 -0400315 if f == 'dont_trace':
Ole Troan9d420872017-10-12 13:06:35 +0200316 self.dont_trace = True
317 elif f == 'manual_print':
318 self.manual_print = True
319 elif f == 'manual_endian':
320 self.manual_endian = True
321 elif f == 'autoreply':
322 self.autoreply = True
Neale Ranns9302cfe2021-02-02 09:21:52 +0000323 elif f == 'autoendian':
324 self.autoendian = 1
Ole Troan9d420872017-10-12 13:06:35 +0200325
Ole Troan5c318c72020-05-05 12:23:47 +0200326 remove = []
Ole Troand5a78a52019-09-18 12:12:47 +0200327 for b in block:
Ole Troan9d420872017-10-12 13:06:35 +0200328 if isinstance(b, Option):
Ole Troan791c2062020-12-08 20:35:32 +0100329 self.options[b.option] = b.value
Ole Troan5c318c72020-05-05 12:23:47 +0200330 remove.append(b)
Ole Troan2a1ca782019-09-19 01:08:30 +0200331
Ole Troan14a6c0e2020-05-13 11:47:43 +0200332 block = [x for x in block if x not in remove]
Ole Troan5c318c72020-05-05 12:23:47 +0200333 self.block = block
Ole Troand5a78a52019-09-18 12:12:47 +0200334 self.vla = vla_is_last_check(name, block)
Ole Troandf87f802020-11-18 19:17:48 +0100335 vla_mark_length_field(self.block)
336
Ole Troan2a1ca782019-09-19 01:08:30 +0200337 self.crc = str(block).encode()
Ole Troane5ff5a32019-08-23 22:55:18 +0200338
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500339 def autoreply_block(self, name, parent):
340 block = [Field('u32', 'context'),
341 Field('i32', 'retval')]
342 # inherit the parent's options
343 for k, v in parent.options.items():
344 block.append(Option(k, v))
345 return Define(name + '_reply', [], block)
346
347 def process(self, result): # -> Dict
348 tname = self.__class__.__name__
349 result[tname].append(self)
350 if self.autoreply:
351 result[tname].append(self.autoreply_block(self.name, self))
352
Ole Troan9d420872017-10-12 13:06:35 +0200353 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200354 return self.name + str(self.flags) + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200355
356
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500357class Enum(Processable):
358 type = 'Enum'
359
Ole Troan9d420872017-10-12 13:06:35 +0200360 def __init__(self, name, block, enumtype='u32'):
361 self.name = name
362 self.enumtype = enumtype
Ole Troane5ff5a32019-08-23 22:55:18 +0200363 self.vla = False
Ole Troandf87f802020-11-18 19:17:48 +0100364 self.manual_print = False
Ole Troan2c2feab2018-04-24 00:02:37 -0400365
Ole Troan9d420872017-10-12 13:06:35 +0200366 count = 0
Ole Troan6006ca82020-08-31 13:54:47 +0200367 block2 = []
368 block3 = []
369 bc_set = False
370
371 for b in block:
372 if 'value' in b:
373 count = b['value']
Ole Troan9d420872017-10-12 13:06:35 +0200374 else:
375 count += 1
Ole Troan6006ca82020-08-31 13:54:47 +0200376 block2.append([b['id'], count])
377 try:
378 if b['option']['backwards_compatible']:
379 pass
380 bc_set = True
381 except KeyError:
382 block3.append([b['id'], count])
383 if bc_set:
Ole Troandf87f802020-11-18 19:17:48 +0100384 raise ValueError("Backward compatible enum must "
385 "be last {!r} {!r}"
Ole Troan6006ca82020-08-31 13:54:47 +0200386 .format(name, b['id']))
387 self.block = block2
388 self.crc = str(block3).encode()
Ole Troan8dbfb432019-04-24 14:31:18 +0200389 global_type_add(name, self)
Ole Troan9d420872017-10-12 13:06:35 +0200390
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500391 def process(self, result):
392 result['types'].append(self)
393
Ole Troan9d420872017-10-12 13:06:35 +0200394 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200395 return self.name + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200396
397
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500398class EnumFlag(Enum):
399 type = 'EnumFlag'
400
401 def __init__(self, name, block, enumtype='u32'):
402 super(EnumFlag, self).__init__(name, block, enumtype)
403
404 for b in self.block:
405 if bin(b[1])[2:].count("1") > 1:
406 raise TypeError("%s is not a flag enum. No element in a "
407 "flag enum may have more than a "
408 "single bit set." % self.name)
409
410
411class Import(Processable):
412 type = 'Import'
Ole Troandf87f802020-11-18 19:17:48 +0100413 _initialized = False
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500414
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400415 def __new__(cls, *args, **kwargs):
416 if args[0] not in seen_imports:
417 instance = super().__new__(cls)
418 instance._initialized = False
419 seen_imports[args[0]] = instance
420
421 return seen_imports[args[0]]
422
Ole Troan5c318c72020-05-05 12:23:47 +0200423 def __init__(self, filename, revision):
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400424 if self._initialized:
425 return
Ole Troandf87f802020-11-18 19:17:48 +0100426 self.filename = filename
427 # Deal with imports
428 parser = VPPAPI(filename=filename, revision=revision)
429 dirlist = dirlist_get()
430 f = filename
431 for dir in dirlist:
432 f = os.path.join(dir, filename)
433 if os.path.exists(f):
434 break
435 self.result = parser.parse_filename(f, None)
436 self._initialized = True
Ole Troan9d420872017-10-12 13:06:35 +0200437
438 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200439 return self.filename
Ole Troan9d420872017-10-12 13:06:35 +0200440
441
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500442class Option(Processable):
443 type = 'Option'
444
Ole Troan68ebcd52020-08-10 17:06:44 +0200445 def __init__(self, option, value=None):
Ole Troan9d420872017-10-12 13:06:35 +0200446 self.option = option
Ole Troan33a58172019-09-04 09:12:29 +0200447 self.value = value
Ole Troan8dbfb432019-04-24 14:31:18 +0200448 self.crc = str(option).encode()
Ole Troan9d420872017-10-12 13:06:35 +0200449
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500450 def process(self, result): # -> Dict
451 result[self.type][self.option] = self.value
452
Ole Troan9d420872017-10-12 13:06:35 +0200453 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200454 return str(self.option)
Ole Troan9d420872017-10-12 13:06:35 +0200455
456 def __getitem__(self, index):
457 return self.option[index]
458
459
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500460class Array(Processable):
461 type = 'Array'
462
Ole Troane5ff5a32019-08-23 22:55:18 +0200463 def __init__(self, fieldtype, name, length, modern_vla=False):
Ole Troan9d420872017-10-12 13:06:35 +0200464 self.fieldtype = fieldtype
465 self.fieldname = name
Ole Troane5ff5a32019-08-23 22:55:18 +0200466 self.modern_vla = modern_vla
Ole Troan9d420872017-10-12 13:06:35 +0200467 if type(length) is str:
468 self.lengthfield = length
469 self.length = 0
Ole Troane5ff5a32019-08-23 22:55:18 +0200470 self.vla = True
Ole Troan9d420872017-10-12 13:06:35 +0200471 else:
472 self.length = length
473 self.lengthfield = None
Ole Troane5ff5a32019-08-23 22:55:18 +0200474 self.vla = False
Ole Troan9d420872017-10-12 13:06:35 +0200475
476 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200477 return str([self.fieldtype, self.fieldname, self.length,
478 self.lengthfield])
Ole Troan9d420872017-10-12 13:06:35 +0200479
480
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500481class Field(Processable):
482 type = 'Field'
483
Ole Troan9ac11382019-04-23 17:11:01 +0200484 def __init__(self, fieldtype, name, limit=None):
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500485 # limit field has been expanded to an options dict.
486
Ole Troan9d420872017-10-12 13:06:35 +0200487 self.fieldtype = fieldtype
Ole Troandf87f802020-11-18 19:17:48 +0100488 self.is_lengthfield = False
Ole Troane5ff5a32019-08-23 22:55:18 +0200489
490 if self.fieldtype == 'string':
491 raise ValueError("The string type {!r} is an "
492 "array type ".format(name))
493
Paul Vinciguerraff47fb62019-08-06 19:58:24 -0400494 if name in keyword.kwlist:
495 raise ValueError("Fieldname {!r} is a python keyword and is not "
496 "accessible via the python API. ".format(name))
Ole Troan9d420872017-10-12 13:06:35 +0200497 self.fieldname = name
Ole Troan9ac11382019-04-23 17:11:01 +0200498 self.limit = limit
Ole Troan9d420872017-10-12 13:06:35 +0200499
500 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200501 return str([self.fieldtype, self.fieldname])
Ole Troan9d420872017-10-12 13:06:35 +0200502
503
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500504class Counter(Processable):
505 type = 'Counter'
506
Ole Troan148c7b72020-10-07 18:05:37 +0200507 def __init__(self, path, counter):
Ole Troan148c7b72020-10-07 18:05:37 +0200508 self.name = path
509 self.block = counter
510
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500511 def process(self, result): # -> Dict
512 result['Counters'].append(self)
Ole Troan148c7b72020-10-07 18:05:37 +0200513
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500514
515class Paths(Processable):
516 type = 'Paths'
517
Ole Troan148c7b72020-10-07 18:05:37 +0200518 def __init__(self, pathset):
Ole Troan148c7b72020-10-07 18:05:37 +0200519 self.paths = pathset
520
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500521 def __repr__(self):
522 return "%s(paths=%s)" % (
523 self.__class__.__name__, self.paths
524 )
525
Ole Troan148c7b72020-10-07 18:05:37 +0200526
Ole Troan9d420872017-10-12 13:06:35 +0200527class Coord(object):
528 """ Coordinates of a syntactic element. Consists of:
529 - File name
530 - Line number
531 - (optional) column number, for the Lexer
532 """
533 __slots__ = ('file', 'line', 'column', '__weakref__')
534
535 def __init__(self, file, line, column=None):
536 self.file = file
537 self.line = line
538 self.column = column
539
540 def __str__(self):
541 str = "%s:%s" % (self.file, self.line)
542 if self.column:
543 str += ":%s" % self.column
544 return str
545
546
547class ParseError(Exception):
548 pass
549
550
551#
552# Grammar rules
553#
554class VPPAPIParser(object):
555 tokens = VPPAPILexer.tokens
556
Ole Troan5c318c72020-05-05 12:23:47 +0200557 def __init__(self, filename, logger, revision=None):
Ole Troan9d420872017-10-12 13:06:35 +0200558 self.filename = filename
559 self.logger = logger
560 self.fields = []
Ole Troan5c318c72020-05-05 12:23:47 +0200561 self.revision = revision
Ole Troan9d420872017-10-12 13:06:35 +0200562
563 def _parse_error(self, msg, coord):
564 raise ParseError("%s: %s" % (coord, msg))
565
566 def _parse_warning(self, msg, coord):
567 if self.logger:
568 self.logger.warning("%s: %s" % (coord, msg))
569
570 def _coord(self, lineno, column=None):
571 return Coord(
Ole Troandf87f802020-11-18 19:17:48 +0100572 file=self.filename,
573 line=lineno, column=column)
Ole Troan9d420872017-10-12 13:06:35 +0200574
575 def _token_coord(self, p, token_idx):
576 """ Returns the coordinates for the YaccProduction object 'p' indexed
577 with 'token_idx'. The coordinate includes the 'lineno' and
578 'column'. Both follow the lex semantic, starting from 1.
579 """
580 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
581 if last_cr < 0:
582 last_cr = -1
583 column = (p.lexpos(token_idx) - (last_cr))
584 return self._coord(p.lineno(token_idx), column)
585
586 def p_slist(self, p):
587 '''slist : stmt
588 | slist stmt'''
589 if len(p) == 2:
590 p[0] = [p[1]]
591 else:
592 p[0] = p[1] + [p[2]]
593
594 def p_stmt(self, p):
595 '''stmt : define
596 | typedef
597 | option
598 | import
599 | enum
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500600 | enumflag
Ole Troan2c2feab2018-04-24 00:02:37 -0400601 | union
Ole Troan148c7b72020-10-07 18:05:37 +0200602 | service
603 | paths
604 | counters'''
Ole Troan9d420872017-10-12 13:06:35 +0200605 p[0] = p[1]
606
607 def p_import(self, p):
608 '''import : IMPORT STRING_LITERAL ';' '''
Ole Troan5c318c72020-05-05 12:23:47 +0200609 p[0] = Import(p[2], revision=self.revision)
Ole Troan9d420872017-10-12 13:06:35 +0200610
Ole Troan148c7b72020-10-07 18:05:37 +0200611 def p_path_elements(self, p):
612 '''path_elements : path_element
613 | path_elements path_element'''
614 if len(p) == 2:
615 p[0] = p[1]
616 else:
617 if type(p[1]) is dict:
618 p[0] = [p[1], p[2]]
619 else:
620 p[0] = p[1] + [p[2]]
621
622 def p_path_element(self, p):
623 '''path_element : STRING_LITERAL STRING_LITERAL ';' '''
624 p[0] = {'path': p[1], 'counter': p[2]}
625
626 def p_paths(self, p):
627 '''paths : PATHS '{' path_elements '}' ';' '''
628 p[0] = Paths(p[3])
629
630 def p_counters(self, p):
631 '''counters : COUNTERS ID '{' counter_elements '}' ';' '''
632 p[0] = Counter(p[2], p[4])
633
634 def p_counter_elements(self, p):
635 '''counter_elements : counter_element
636 | counter_elements counter_element'''
637 if len(p) == 2:
638 p[0] = p[1]
639 else:
640 if type(p[1]) is dict:
641 p[0] = [p[1], p[2]]
642 else:
643 p[0] = p[1] + [p[2]]
644
645 def p_counter_element(self, p):
646 '''counter_element : ID '{' counter_statements '}' ';' '''
647 p[0] = {**{'name': p[1]}, **p[3]}
648
649 def p_counter_statements(self, p):
650 '''counter_statements : counter_statement
651 | counter_statements counter_statement'''
652 if len(p) == 2:
653 p[0] = p[1]
654 else:
655 p[0] = {**p[1], **p[2]}
656
657 def p_counter_statement(self, p):
658 '''counter_statement : SEVERITY ID ';'
659 | UNITS STRING_LITERAL ';'
660 | DESCRIPTION STRING_LITERAL ';'
661 | TYPE ID ';' '''
662 p[0] = {p[1]: p[2]}
663
Ole Troan9d420872017-10-12 13:06:35 +0200664 def p_service(self, p):
665 '''service : SERVICE '{' service_statements '}' ';' '''
666 p[0] = p[3]
667
668 def p_service_statements(self, p):
669 '''service_statements : service_statement
670 | service_statements service_statement'''
671 if len(p) == 2:
672 p[0] = [p[1]]
673 else:
674 p[0] = p[1] + [p[2]]
675
676 def p_service_statement(self, p):
Marek Gradzki51e59682018-03-06 10:05:44 +0100677 '''service_statement : RPC ID RETURNS NULL ';'
678 | RPC ID RETURNS ID ';'
Ole Troan9d420872017-10-12 13:06:35 +0200679 | RPC ID RETURNS STREAM ID ';'
680 | RPC ID RETURNS ID EVENTS event_list ';' '''
Marek Gradzkifc70e3a2018-03-06 10:56:26 +0100681 if p[2] == p[4]:
682 # Verify that caller and reply differ
Ole Troan17225df2018-04-11 09:50:03 +0200683 self._parse_error(
684 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
685 self._token_coord(p, 1))
Ole Troan9d420872017-10-12 13:06:35 +0200686 if len(p) == 8:
687 p[0] = Service(p[2], p[4], p[6])
688 elif len(p) == 7:
689 p[0] = Service(p[2], p[5], stream=True)
690 else:
691 p[0] = Service(p[2], p[4])
692
Ole Troanf5db3712020-05-20 15:47:06 +0200693 def p_service_statement2(self, p):
694 '''service_statement : RPC ID RETURNS ID STREAM ID ';' '''
695 p[0] = Service(p[2], p[4], stream_message=p[6], stream=True)
696
Ole Troan9d420872017-10-12 13:06:35 +0200697 def p_event_list(self, p):
698 '''event_list : events
699 | event_list events '''
700 if len(p) == 2:
701 p[0] = [p[1]]
702 else:
703 p[0] = p[1] + [p[2]]
704
705 def p_event(self, p):
706 '''events : ID
707 | ID ',' '''
708 p[0] = p[1]
709
710 def p_enum(self, p):
711 '''enum : ENUM ID '{' enum_statements '}' ';' '''
712 p[0] = Enum(p[2], p[4])
713
714 def p_enum_type(self, p):
715 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
716 if len(p) == 9:
717 p[0] = Enum(p[2], p[6], enumtype=p[4])
718 else:
719 p[0] = Enum(p[2], p[4])
720
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500721 def p_enumflag(self, p):
722 '''enumflag : ENUMFLAG ID '{' enum_statements '}' ';' '''
723 p[0] = EnumFlag(p[2], p[4])
724
725 def p_enumflag_type(self, p):
Paul Vinciguerra6d467b32020-12-13 04:12:55 +0000726 ''' enumflag : ENUMFLAG ID ':' enumflag_size '{' enum_statements '}' ';' ''' # noqa : E502
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -0500727 if len(p) == 9:
728 p[0] = EnumFlag(p[2], p[6], enumtype=p[4])
729 else:
730 p[0] = EnumFlag(p[2], p[4])
731
Ole Troan9d420872017-10-12 13:06:35 +0200732 def p_enum_size(self, p):
733 ''' enum_size : U8
734 | U16
Paul Vinciguerra6d467b32020-12-13 04:12:55 +0000735 | U32
736 | I8
737 | I16
738 | I32 '''
739 p[0] = p[1]
740
741 def p_enumflag_size(self, p):
742 ''' enumflag_size : U8
743 | U16
744 | U32 '''
Ole Troan9d420872017-10-12 13:06:35 +0200745 p[0] = p[1]
746
747 def p_define(self, p):
748 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
749 self.fields = []
750 p[0] = Define(p[2], [], p[4])
751
752 def p_define_flist(self, p):
753 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
Ole Troan2c2feab2018-04-24 00:02:37 -0400754 # Legacy typedef
755 if 'typeonly' in p[1]:
Paul Vinciguerrae7174822019-08-07 00:05:59 -0400756 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
757 .format(p[1], p[2], p[4]),
758 self._token_coord(p, 1))
Ole Troan2c2feab2018-04-24 00:02:37 -0400759 else:
760 p[0] = Define(p[3], p[1], p[5])
Ole Troan9d420872017-10-12 13:06:35 +0200761
762 def p_flist(self, p):
763 '''flist : flag
764 | flist flag'''
765 if len(p) == 2:
766 p[0] = [p[1]]
767 else:
768 p[0] = p[1] + [p[2]]
769
770 def p_flag(self, p):
771 '''flag : MANUAL_PRINT
772 | MANUAL_ENDIAN
773 | DONT_TRACE
774 | TYPEONLY
Neale Ranns9302cfe2021-02-02 09:21:52 +0000775 | AUTOENDIAN
Ole Troan9d420872017-10-12 13:06:35 +0200776 | AUTOREPLY'''
777 if len(p) == 1:
778 return
779 p[0] = p[1]
780
781 def p_typedef(self, p):
782 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
783 p[0] = Typedef(p[2], [], p[4])
784
Ole Troan33a58172019-09-04 09:12:29 +0200785 def p_typedef_flist(self, p):
786 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
787 p[0] = Typedef(p[3], p[1], p[5])
788
Ole Troan53fffa12018-11-13 12:36:56 +0100789 def p_typedef_alias(self, p):
790 '''typedef : TYPEDEF declaration '''
Ole Troan33a58172019-09-04 09:12:29 +0200791 p[0] = Using(p[2].fieldname, [], p[2])
792
793 def p_typedef_alias_flist(self, p):
794 '''typedef : flist TYPEDEF declaration '''
795 p[0] = Using(p[3].fieldname, p[1], p[3])
Ole Troan53fffa12018-11-13 12:36:56 +0100796
Ole Troan9d420872017-10-12 13:06:35 +0200797 def p_block_statements_opt(self, p):
Ole Troan2c2feab2018-04-24 00:02:37 -0400798 '''block_statements_opt : block_statements '''
Ole Troan9d420872017-10-12 13:06:35 +0200799 p[0] = p[1]
800
801 def p_block_statements(self, p):
802 '''block_statements : block_statement
803 | block_statements block_statement'''
804 if len(p) == 2:
805 p[0] = [p[1]]
806 else:
807 p[0] = p[1] + [p[2]]
808
809 def p_block_statement(self, p):
810 '''block_statement : declaration
811 | option '''
812 p[0] = p[1]
813
814 def p_enum_statements(self, p):
815 '''enum_statements : enum_statement
Ole Troan9ac11382019-04-23 17:11:01 +0200816 | enum_statements enum_statement'''
Ole Troan9d420872017-10-12 13:06:35 +0200817 if len(p) == 2:
818 p[0] = [p[1]]
819 else:
820 p[0] = p[1] + [p[2]]
821
822 def p_enum_statement(self, p):
823 '''enum_statement : ID '=' NUM ','
Ole Troan6006ca82020-08-31 13:54:47 +0200824 | ID ','
825 | ID '[' field_options ']' ','
826 | ID '=' NUM '[' field_options ']' ',' '''
827 if len(p) == 3:
828 p[0] = {'id': p[1]}
829 elif len(p) == 5:
830 p[0] = {'id': p[1], 'value': p[3]}
831 elif len(p) == 6:
832 p[0] = {'id': p[1], 'option': p[3]}
833 elif len(p) == 8:
834 p[0] = {'id': p[1], 'value': p[3], 'option': p[5]}
Ole Troan9d420872017-10-12 13:06:35 +0200835 else:
Ole Troan6006ca82020-08-31 13:54:47 +0200836 self._parse_error('ERROR', self._token_coord(p, 1))
Ole Troan9d420872017-10-12 13:06:35 +0200837
Ole Troan85465582019-04-30 10:04:36 +0200838 def p_field_options(self, p):
839 '''field_options : field_option
840 | field_options field_option'''
841 if len(p) == 2:
842 p[0] = p[1]
843 else:
Ole Troane5ff5a32019-08-23 22:55:18 +0200844 p[0] = {**p[1], **p[2]}
Ole Troan85465582019-04-30 10:04:36 +0200845
846 def p_field_option(self, p):
Ole Troane5ff5a32019-08-23 22:55:18 +0200847 '''field_option : ID
848 | ID '=' assignee ','
Ole Troan85465582019-04-30 10:04:36 +0200849 | ID '=' assignee
Ole Troane5ff5a32019-08-23 22:55:18 +0200850
Ole Troan85465582019-04-30 10:04:36 +0200851 '''
Ole Troane5ff5a32019-08-23 22:55:18 +0200852 if len(p) == 2:
853 p[0] = {p[1]: None}
854 else:
855 p[0] = {p[1]: p[3]}
Ole Troan85465582019-04-30 10:04:36 +0200856
Ole Troan148c7b72020-10-07 18:05:37 +0200857 def p_variable_name(self, p):
858 '''variable_name : ID
859 | TYPE
860 | SEVERITY
861 | DESCRIPTION
862 | COUNTERS
863 | PATHS
864 '''
865 p[0] = p[1]
866
Ole Troan9d420872017-10-12 13:06:35 +0200867 def p_declaration(self, p):
Ole Troan148c7b72020-10-07 18:05:37 +0200868 '''declaration : type_specifier variable_name ';'
869 | type_specifier variable_name '[' field_options ']' ';'
870 '''
Ole Troan85465582019-04-30 10:04:36 +0200871 if len(p) == 7:
872 p[0] = Field(p[1], p[2], p[4])
Ole Troan9ac11382019-04-23 17:11:01 +0200873 elif len(p) == 4:
874 p[0] = Field(p[1], p[2])
875 else:
Paul Vinciguerra582eac52020-04-03 12:18:40 -0400876 self._parse_error('ERROR', self._token_coord(p, 1))
Ole Troan9d420872017-10-12 13:06:35 +0200877 self.fields.append(p[2])
Ole Troan9ac11382019-04-23 17:11:01 +0200878
Ole Troane5ff5a32019-08-23 22:55:18 +0200879 def p_declaration_array_vla(self, p):
Ole Troan148c7b72020-10-07 18:05:37 +0200880 '''declaration : type_specifier variable_name '[' ']' ';' '''
Ole Troane5ff5a32019-08-23 22:55:18 +0200881 p[0] = Array(p[1], p[2], 0, modern_vla=True)
882
Ole Troan9d420872017-10-12 13:06:35 +0200883 def p_declaration_array(self, p):
Ole Troan148c7b72020-10-07 18:05:37 +0200884 '''declaration : type_specifier variable_name '[' NUM ']' ';'
885 | type_specifier variable_name '[' ID ']' ';' '''
Ole Troane5ff5a32019-08-23 22:55:18 +0200886
Ole Troan9d420872017-10-12 13:06:35 +0200887 if len(p) != 7:
888 return self._parse_error(
889 'array: %s' % p.value,
890 self._coord(lineno=p.lineno))
891
892 # Make this error later
893 if type(p[4]) is int and p[4] == 0:
894 # XXX: Line number is wrong
895 self._parse_warning('Old Style VLA: {} {}[{}];'
896 .format(p[1], p[2], p[4]),
897 self._token_coord(p, 1))
898
899 if type(p[4]) is str and p[4] not in self.fields:
900 # Verify that length field exists
901 self._parse_error('Missing length field: {} {}[{}];'
902 .format(p[1], p[2], p[4]),
903 self._token_coord(p, 1))
904 p[0] = Array(p[1], p[2], p[4])
905
906 def p_option(self, p):
Ole Troan68ebcd52020-08-10 17:06:44 +0200907 '''option : OPTION ID '=' assignee ';'
908 | OPTION ID ';' '''
909 if len(p) == 4:
910 p[0] = Option(p[2])
911 else:
912 p[0] = Option(p[2], p[4])
Ole Troan9d420872017-10-12 13:06:35 +0200913
914 def p_assignee(self, p):
915 '''assignee : NUM
916 | TRUE
917 | FALSE
918 | STRING_LITERAL '''
919 p[0] = p[1]
920
921 def p_type_specifier(self, p):
922 '''type_specifier : U8
923 | U16
924 | U32
925 | U64
926 | I8
927 | I16
928 | I32
929 | I64
930 | F64
931 | BOOL
932 | STRING'''
933 p[0] = p[1]
934
935 # Do a second pass later to verify that user defined types are defined
936 def p_typedef_specifier(self, p):
937 '''type_specifier : ID '''
938 if p[1] not in global_types:
939 self._parse_error('Undefined type: {}'.format(p[1]),
940 self._token_coord(p, 1))
941 p[0] = p[1]
942
Ole Troan2c2feab2018-04-24 00:02:37 -0400943 def p_union(self, p):
944 '''union : UNION ID '{' block_statements_opt '}' ';' '''
Ole Troan33a58172019-09-04 09:12:29 +0200945 p[0] = Union(p[2], [], p[4])
946
947 def p_union_flist(self, p):
948 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
949 p[0] = Union(p[3], p[1], p[5])
Ole Troan2c2feab2018-04-24 00:02:37 -0400950
Ole Troan9d420872017-10-12 13:06:35 +0200951 # Error rule for syntax errors
952 def p_error(self, p):
953 if p:
954 self._parse_error(
955 'before: %s' % p.value,
956 self._coord(lineno=p.lineno))
957 else:
958 self._parse_error('At end of input', self.filename)
959
960
Ole Troandf87f802020-11-18 19:17:48 +0100961class VPPAPI():
Ole Troan9d420872017-10-12 13:06:35 +0200962
Ole Troan5c318c72020-05-05 12:23:47 +0200963 def __init__(self, debug=False, filename='', logger=None, revision=None):
Ole Troan9d420872017-10-12 13:06:35 +0200964 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
Ole Troan5c318c72020-05-05 12:23:47 +0200965 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
966 revision=revision),
Ole Troand6743b12018-03-07 08:40:58 +0100967 write_tables=False, debug=debug)
Ole Troan9d420872017-10-12 13:06:35 +0200968 self.logger = logger
Ole Troan5c318c72020-05-05 12:23:47 +0200969 self.revision = revision
970 self.filename = filename
Ole Troan9d420872017-10-12 13:06:35 +0200971
972 def parse_string(self, code, debug=0, lineno=1):
973 self.lexer.lineno = lineno
974 return self.parser.parse(code, lexer=self.lexer, debug=debug)
975
Ole Troan5c318c72020-05-05 12:23:47 +0200976 def parse_fd(self, fd, debug=0):
Ole Troan9d420872017-10-12 13:06:35 +0200977 data = fd.read()
978 return self.parse_string(data, debug=debug)
979
Ole Troan5c318c72020-05-05 12:23:47 +0200980 def parse_filename(self, filename, debug=0):
981 if self.revision:
BenoƮt Ganne3f0ae662020-09-09 12:50:07 +0200982 git_show = 'git show {}:{}'.format(self.revision, filename)
Ole Troandeecc932020-05-19 12:33:00 +0200983 proc = Popen(git_show.split(), stdout=PIPE, encoding='utf-8')
984 try:
985 data, errs = proc.communicate()
986 if proc.returncode != 0:
Ole Troandf87f802020-11-18 19:17:48 +0100987 print('File not found: {}:{}'
988 .format(self.revision, filename), file=sys.stderr)
Ole Troandeecc932020-05-19 12:33:00 +0200989 sys.exit(2)
990 return self.parse_string(data, debug=debug)
Ole Troandf87f802020-11-18 19:17:48 +0100991 except Exception:
Ole Troandeecc932020-05-19 12:33:00 +0200992 sys.exit(3)
Ole Troan5c318c72020-05-05 12:23:47 +0200993 else:
994 try:
995 with open(filename, encoding='utf-8') as fd:
996 return self.parse_fd(fd, None)
997 except FileNotFoundError:
BenoƮt Ganne3f0ae662020-09-09 12:50:07 +0200998 print('File not found: {}'.format(filename), file=sys.stderr)
Ole Troan5c318c72020-05-05 12:23:47 +0200999 sys.exit(2)
1000
Ole Troan9d420872017-10-12 13:06:35 +02001001 def process(self, objs):
1002 s = {}
Ole Troan2c2feab2018-04-24 00:02:37 -04001003 s['Option'] = {}
1004 s['Define'] = []
1005 s['Service'] = []
1006 s['types'] = []
1007 s['Import'] = []
Ole Troan148c7b72020-10-07 18:05:37 +02001008 s['Counters'] = []
1009 s['Paths'] = []
Ole Troan8dbfb432019-04-24 14:31:18 +02001010 crc = 0
Ole Troan9d420872017-10-12 13:06:35 +02001011 for o in objs:
Ole Troan8dbfb432019-04-24 14:31:18 +02001012 try:
Mark Nelsonea2abba2020-03-04 15:32:09 -05001013 crc = binascii.crc32(o.crc, crc) & 0xffffffff
Ole Troan8dbfb432019-04-24 14:31:18 +02001014 except AttributeError:
1015 pass
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -05001016
1017 if type(o) is list:
Ole Troan9d420872017-10-12 13:06:35 +02001018 for o2 in o:
1019 if isinstance(o2, Service):
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -05001020 o2.process(s)
Ole Troan2c2feab2018-04-24 00:02:37 -04001021 else:
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -05001022 o.process(s)
Ole Troan9d420872017-10-12 13:06:35 +02001023
Ole Troan2c2feab2018-04-24 00:02:37 -04001024 msgs = {d.name: d for d in s['Define']}
1025 svcs = {s.caller: s for s in s['Service']}
1026 replies = {s.reply: s for s in s['Service']}
Marek Gradzki51e59682018-03-06 10:05:44 +01001027 seen_services = {}
Ole Troan9d420872017-10-12 13:06:35 +02001028
Ole Troan8dbfb432019-04-24 14:31:18 +02001029 s['file_crc'] = crc
1030
Ole Troan9d420872017-10-12 13:06:35 +02001031 for service in svcs:
1032 if service not in msgs:
Ole Troan17225df2018-04-11 09:50:03 +02001033 raise ValueError(
1034 'Service definition refers to unknown message'
1035 ' definition: {}'.format(service))
1036 if svcs[service].reply != 'null' and \
1037 svcs[service].reply not in msgs:
Ole Troan9d420872017-10-12 13:06:35 +02001038 raise ValueError('Service definition refers to unknown message'
1039 ' definition in reply: {}'
1040 .format(svcs[service].reply))
Marek Gradzkib533f3f2018-03-06 11:10:56 +01001041 if service in replies:
1042 raise ValueError('Service definition refers to message'
1043 ' marked as reply: {}'.format(service))
Ole Troan9d420872017-10-12 13:06:35 +02001044 for event in svcs[service].events:
1045 if event not in msgs:
1046 raise ValueError('Service definition refers to unknown '
1047 'event: {} in message: {}'
1048 .format(event, service))
Marek Gradzki51e59682018-03-06 10:05:44 +01001049 seen_services[event] = True
Ole Troan9d420872017-10-12 13:06:35 +02001050
Marek Gradzki51e59682018-03-06 10:05:44 +01001051 # Create services implicitly
Ole Troan9d420872017-10-12 13:06:35 +02001052 for d in msgs:
Marek Gradzki51e59682018-03-06 10:05:44 +01001053 if d in seen_services:
1054 continue
Ole Troan9d420872017-10-12 13:06:35 +02001055 if d.endswith('_reply'):
1056 if d[:-6] in svcs:
1057 continue
1058 if d[:-6] not in msgs:
Marek Gradzkicc134712018-03-06 12:25:02 +01001059 raise ValueError('{} missing calling message'
1060 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +02001061 continue
1062 if d.endswith('_dump'):
1063 if d in svcs:
1064 continue
1065 if d[:-5]+'_details' in msgs:
Ole Troan2c2feab2018-04-24 00:02:37 -04001066 s['Service'].append(Service(d, d[:-5]+'_details',
Ole Troan58914252018-10-23 10:50:07 +02001067 stream=True))
Ole Troan9d420872017-10-12 13:06:35 +02001068 else:
Marek Gradzkicc134712018-03-06 12:25:02 +01001069 raise ValueError('{} missing details message'
1070 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +02001071 continue
1072
1073 if d.endswith('_details'):
Jon Loeligerc0b19542020-05-11 08:43:51 -05001074 if d[:-8]+'_get' in msgs:
1075 if d[:-8]+'_get' in svcs:
1076 continue
Ole Troandf87f802020-11-18 19:17:48 +01001077 raise ValueError('{} should be in a stream service'
1078 .format(d[:-8]+'_get'))
Jon Loeligerc0b19542020-05-11 08:43:51 -05001079 if d[:-8]+'_dump' in msgs:
1080 continue
1081 raise ValueError('{} missing dump or get message'
1082 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +02001083
1084 if d in svcs:
1085 continue
1086 if d+'_reply' in msgs:
Ole Troan2c2feab2018-04-24 00:02:37 -04001087 s['Service'].append(Service(d, d+'_reply'))
Ole Troan9d420872017-10-12 13:06:35 +02001088 else:
Ole Troan17225df2018-04-11 09:50:03 +02001089 raise ValueError(
1090 '{} missing reply message ({}) or service definition'
1091 .format(d, d+'_reply'))
Ole Troan9d420872017-10-12 13:06:35 +02001092
1093 return s
1094
Paul Vinciguerraa51f9b32020-11-24 23:26:06 -05001095 def process_imports(self, objs, in_import, result): # -> List
Ole Troan9d420872017-10-12 13:06:35 +02001096 for o in objs:
Ole Troan2c2feab2018-04-24 00:02:37 -04001097 # Only allow the following object types from imported file
Ole Troandf87f802020-11-18 19:17:48 +01001098 if in_import and not isinstance(o, (Enum, Import, Typedef,
1099 Union, Using)):
Ole Troan2c2feab2018-04-24 00:02:37 -04001100 continue
Ole Troan2c2feab2018-04-24 00:02:37 -04001101 if isinstance(o, Import):
Ole Troan33a58172019-09-04 09:12:29 +02001102 result.append(o)
Paul Vinciguerra4bf84902019-07-31 00:34:05 -04001103 result = self.process_imports(o.result, True, result)
Ole Troan10a09892018-06-29 11:32:33 +02001104 else:
1105 result.append(o)
Paul Vinciguerra4bf84902019-07-31 00:34:05 -04001106 return result
Ole Troan9d420872017-10-12 13:06:35 +02001107
Ole Troan58914252018-10-23 10:50:07 +02001108
Ole Troan9d420872017-10-12 13:06:35 +02001109# Add message ids to each message.
1110def add_msg_id(s):
1111 for o in s:
1112 o.block.insert(0, Field('u16', '_vl_msg_id'))
1113 return s
1114
1115
Ole Troan9d420872017-10-12 13:06:35 +02001116dirlist = []
1117
1118
1119def dirlist_add(dirs):
1120 global dirlist
1121 if dirs:
1122 dirlist = dirlist + dirs
1123
1124
1125def dirlist_get():
1126 return dirlist
1127
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001128
Ole Troan8dbfb432019-04-24 14:31:18 +02001129def foldup_blocks(block, crc):
1130 for b in block:
1131 # Look up CRC in user defined types
1132 if b.fieldtype.startswith('vl_api_'):
1133 # Recursively
1134 t = global_types[b.fieldtype]
1135 try:
Ole Troan6006ca82020-08-31 13:54:47 +02001136 crc = binascii.crc32(t.crc, crc) & 0xffffffff
Ole Troan9f84e702020-06-25 14:27:46 +02001137 crc = foldup_blocks(t.block, crc)
Ole Troane5ff5a32019-08-23 22:55:18 +02001138 except AttributeError:
Ole Troan8dbfb432019-04-24 14:31:18 +02001139 pass
1140 return crc
1141
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001142
Ole Troan9f84e702020-06-25 14:27:46 +02001143# keep the CRCs of the existing types of messages compatible with the
1144# old "erroneous" way of calculating the CRC. For that - make a pointed
1145# adjustment of the CRC function.
1146# This is the purpose of the first element of the per-message dictionary.
1147# The second element is there to avoid weakening the duplicate-detecting
1148# properties of crc32. This way, if the new way of calculating the CRC
1149# happens to collide with the old (buggy) way - we will still get
1150# a different result and fail the comparison.
1151
1152fixup_crc_dict = {
Ole Troandf87f802020-11-18 19:17:48 +01001153 "abf_policy_add_del": {0xc6131197: 0xee66f93e},
1154 "abf_policy_details": {0xb7487fa4: 0x6769e504},
1155 "acl_add_replace": {0xee5c2f18: 0x1cabdeab},
1156 "acl_details": {0x95babae0: 0x7a97f21c},
1157 "macip_acl_add": {0xce6fbad0: 0xd648fd0a},
1158 "macip_acl_add_replace": {0x2a461dd4: 0xe34402a7},
1159 "macip_acl_details": {0x27135b59: 0x57c7482f},
1160 "dhcp_proxy_config": {0x4058a689: 0x6767230e},
1161 "dhcp_client_config": {0x1af013ea: 0x959b80a3},
1162 "dhcp_compl_event": {0x554a44e5: 0xe908fd1d},
1163 "dhcp_client_details": {0x3c5cd28a: 0xacd82f5a},
1164 "dhcp_proxy_details": {0xdcbaf540: 0xce16f044},
1165 "dhcp6_send_client_message": {0xf8222476: 0xf6f14ef0},
1166 "dhcp6_pd_send_client_message": {0x3739fd8d: 0x64badb8},
1167 "dhcp6_reply_event": {0x85b7b17e: 0x9f3af9e5},
1168 "dhcp6_pd_reply_event": {0x5e878029: 0xcb3e462b},
1169 "ip6_add_del_address_using_prefix": {0x3982f30a: 0x9b3d11e0},
1170 "gbp_bridge_domain_add": {0x918e8c01: 0x8454bfdf},
1171 "gbp_bridge_domain_details": {0x51d51be9: 0x2acd15f9},
1172 "gbp_route_domain_add": {0x204c79e1: 0x2d0afe38},
1173 "gbp_route_domain_details": {0xa78bfbca: 0x8ab11375},
1174 "gbp_endpoint_add": {0x7b3af7de: 0x9ce16d5a},
1175 "gbp_endpoint_details": {0x8dd8fbd3: 0x8aecb60},
1176 "gbp_endpoint_group_add": {0x301ddf15: 0x8e0f4054},
1177 "gbp_endpoint_group_details": {0xab71d723: 0x8f38292c},
1178 "gbp_subnet_add_del": {0xa8803c80: 0x888aca35},
1179 "gbp_subnet_details": {0xcbc5ca18: 0x4ed84156},
1180 "gbp_contract_add_del": {0xaa8d652d: 0x553e275b},
1181 "gbp_contract_details": {0x65dec325: 0x2a18db6e},
1182 "gbp_ext_itf_add_del": {0x7606d0e1: 0x12ed5700},
1183 "gbp_ext_itf_details": {0x519c3d3c: 0x408a45c0},
1184 "gtpu_add_del_tunnel": {0xca983a2b: 0x9a9c0426},
1185 "gtpu_tunnel_update_tteid": {0x79f33816: 0x8a2db108},
1186 "gtpu_tunnel_details": {0x27f434ae: 0x4535cf95},
1187 "igmp_listen": {0x19a49f1e: 0x3f93a51a},
1188 "igmp_details": {0x38f09929: 0x52f12a89},
1189 "igmp_event": {0x85fe93ec: 0xd7696eaf},
1190 "igmp_group_prefix_set": {0x5b14a5ce: 0xd4f20ac5},
1191 "igmp_group_prefix_details": {0x259ccd81: 0xc3b3c526},
1192 "ikev2_set_responder": {0xb9aa4d4e: 0xf0d3dc80},
1193 "vxlan_gpe_ioam_export_enable_disable": {0xd4c76d3a: 0xe4d4ebfa},
1194 "ioam_export_ip6_enable_disable": {0xd4c76d3a: 0xe4d4ebfa},
1195 "vxlan_gpe_ioam_vni_enable": {0xfbb5fb1: 0x997161fb},
1196 "vxlan_gpe_ioam_vni_disable": {0xfbb5fb1: 0x997161fb},
1197 "vxlan_gpe_ioam_transit_enable": {0x3d3ec657: 0x553f5b7b},
1198 "vxlan_gpe_ioam_transit_disable": {0x3d3ec657: 0x553f5b7b},
1199 "udp_ping_add_del": {0xfa2628fc: 0xc692b188},
1200 "l3xc_update": {0xe96aabdf: 0x787b1d3},
1201 "l3xc_details": {0xbc5bf852: 0xd4f69627},
1202 "sw_interface_lacp_details": {0xd9a83d2f: 0x745ae0ba},
1203 "lb_conf": {0x56cd3261: 0x22ddb739},
1204 "lb_add_del_vip": {0x6fa569c7: 0xd15b7ddc},
1205 "lb_add_del_as": {0x35d72500: 0x78628987},
1206 "lb_vip_dump": {0x56110cb7: 0xc7bcb124},
1207 "lb_vip_details": {0x1329ec9b: 0x8f39bed},
1208 "lb_as_details": {0x8d24c29e: 0x9c39f60e},
1209 "mactime_add_del_range": {0xcb56e877: 0x101858ef},
1210 "mactime_details": {0xda25b13a: 0x44921c06},
1211 "map_add_domain": {0x249f195c: 0x7a5a18c9},
1212 "map_domain_details": {0x796edb50: 0xfc1859dd},
1213 "map_param_add_del_pre_resolve": {0xdae5af03: 0x17008c66},
1214 "map_param_get_reply": {0x26272c90: 0x28092156},
1215 "memif_details": {0xda34feb9: 0xd0382c4c},
1216 "dslite_add_del_pool_addr_range": {0xde2a5b02: 0xc448457a},
1217 "dslite_set_aftr_addr": {0x78b50fdf: 0x1e955f8d},
1218 "dslite_get_aftr_addr_reply": {0x8e23608e: 0x38e30db1},
1219 "dslite_set_b4_addr": {0x78b50fdf: 0x1e955f8d},
1220 "dslite_get_b4_addr_reply": {0x8e23608e: 0x38e30db1},
1221 "nat44_add_del_address_range": {0x6f2b8055: 0xd4c7568c},
1222 "nat44_address_details": {0xd1beac1: 0x45410ac4},
1223 "nat44_add_del_static_mapping": {0x5ae5f03e: 0xe165e83b},
1224 "nat44_static_mapping_details": {0x6cb40b2: 0x1a433ef7},
1225 "nat44_add_del_identity_mapping": {0x2faaa22: 0x8e12743f},
1226 "nat44_identity_mapping_details": {0x2a52a030: 0x36d21351},
1227 "nat44_add_del_interface_addr": {0x4aed50c0: 0xfc835325},
1228 "nat44_interface_addr_details": {0xe4aca9ca: 0x3e687514},
1229 "nat44_user_session_details": {0x2cf6e16d: 0x1965fd69},
1230 "nat44_add_del_lb_static_mapping": {0x4f68ee9d: 0x53b24611},
1231 "nat44_lb_static_mapping_add_del_local": {0x7ca47547: 0x2910a151},
1232 "nat44_lb_static_mapping_details": {0xed5ce876: 0x2267b9e8},
1233 "nat44_del_session": {0x15a5bf8c: 0x4c49c387},
1234 "nat_det_add_del_map": {0x1150a190: 0x112fde05},
1235 "nat_det_map_details": {0xad91dc83: 0x88000ee1},
1236 "nat_det_close_session_out": {0xf6b259d1: 0xc1b6cbfb},
1237 "nat_det_close_session_in": {0x3c68e073: 0xa10ef64},
1238 "nat64_add_del_pool_addr_range": {0xa3b944e3: 0x21234ef3},
1239 "nat64_add_del_static_bib": {0x1c404de5: 0x90fae58a},
1240 "nat64_bib_details": {0x43bc3ddf: 0x62c8541d},
1241 "nat64_st_details": {0xdd3361ed: 0xc770d620},
1242 "nat66_add_del_static_mapping": {0x3ed88f71: 0xfb64e50b},
1243 "nat66_static_mapping_details": {0xdf39654b: 0x5c568448},
1244 "nsh_add_del_map": {0xa0f42b0: 0x898d857d},
1245 "nsh_map_details": {0x2fefcf49: 0xb34ac8a1},
1246 "nsim_cross_connect_enable_disable": {0x9c3ead86: 0x16f70bdf},
1247 "pppoe_add_del_session": {0xf6fd759e: 0x46ace853},
1248 "pppoe_session_details": {0x4b8e8a4a: 0x332bc742},
1249 "stn_add_del_rule": {0x224c6edd: 0x53f751e6},
1250 "stn_rules_details": {0xa51935a6: 0xb0f6606c},
1251 "svs_route_add_del": {0xe49bc63c: 0xd39e31fc},
1252 "svs_details": {0x6282cd55: 0xb8523d64},
1253 "vmxnet3_details": {0x6a1a5498: 0x829ba055},
1254 "vrrp_vr_add_del": {0xc5cf15aa: 0x6dc4b881},
1255 "vrrp_vr_details": {0x46edcebd: 0x412fa71},
1256 "vrrp_vr_set_peers": {0x20bec71f: 0xbaa2e52b},
1257 "vrrp_vr_peer_details": {0x3d99c108: 0xabd9145e},
1258 "vrrp_vr_track_if_add_del": {0xd67df299: 0x337f4ba4},
1259 "vrrp_vr_track_if_details": {0x73c36f81: 0x99bcca9c},
1260 "proxy_arp_add_del": {0x1823c3e7: 0x85486cbd},
1261 "proxy_arp_details": {0x5b948673: 0x9228c150},
1262 "bfd_udp_get_echo_source_reply": {0xe3d736a1: 0x1e00cfce},
1263 "bfd_udp_add": {0x939cd26a: 0x7a6d1185},
1264 "bfd_udp_mod": {0x913df085: 0x783a3ff6},
1265 "bfd_udp_del": {0xdcb13a89: 0x8096514d},
1266 "bfd_udp_session_details": {0x9fb2f2d: 0x60653c02},
1267 "bfd_udp_session_set_flags": {0x4b4bdfd: 0xcf313851},
1268 "bfd_udp_auth_activate": {0x21fd1bdb: 0x493ee0ec},
1269 "bfd_udp_auth_deactivate": {0x9a05e2e0: 0x99978c32},
1270 "bier_route_add_del": {0xfd02f3ea: 0xf29edca0},
1271 "bier_route_details": {0x4008caee: 0x39ee6a56},
1272 "bier_disp_entry_add_del": {0x9eb80cb4: 0x648323eb},
1273 "bier_disp_entry_details": {0x84c218f1: 0xe5b039a9},
1274 "bond_create": {0xf1dbd4ff: 0x48883c7e},
1275 "bond_enslave": {0xe7d14948: 0x76ecfa7},
1276 "sw_interface_bond_details": {0xbb7c929b: 0xf5ef2106},
1277 "pipe_create_reply": {0xb7ce310c: 0xd4c2c2b3},
1278 "pipe_details": {0xc52b799d: 0x43ac107a},
1279 "tap_create_v2": {0x2d0d6570: 0x445835fd},
1280 "sw_interface_tap_v2_details": {0x1e2b2a47: 0xe53c16de},
1281 "sw_interface_vhost_user_details": {0xcee1e53: 0x98530df1},
1282 "virtio_pci_create": {0x1944f8db: 0xa9f1370c},
1283 "sw_interface_virtio_pci_details": {0x6ca9c167: 0x16187f3a},
1284 "p2p_ethernet_add": {0x36a1a6dc: 0xeeb8e717},
1285 "p2p_ethernet_del": {0x62f81c8c: 0xb62c386},
1286 "geneve_add_del_tunnel": {0x99445831: 0x976693b5},
1287 "geneve_tunnel_details": {0x6b16eb24: 0xe27e2748},
1288 "gre_tunnel_add_del": {0xa27d7f17: 0x6efc9c22},
1289 "gre_tunnel_details": {0x24435433: 0x3bfbf1},
1290 "sw_interface_set_flags": {0xf5aec1b8: 0x6a2b491a},
1291 "sw_interface_event": {0x2d3d95a7: 0xf709f78d},
1292 "sw_interface_details": {0x6c221fc7: 0x17b69fa2},
1293 "sw_interface_add_del_address": {0x5463d73b: 0x5803d5c4},
1294 "sw_interface_set_unnumbered": {0x154a6439: 0x938ef33b},
1295 "sw_interface_set_mac_address": {0xc536e7eb: 0x6aca746a},
1296 "sw_interface_set_rx_mode": {0xb04d1cfe: 0x780f5cee},
1297 "sw_interface_rx_placement_details": {0x9e44a7ce: 0xf6d7d024},
1298 "create_subif": {0x790ca755: 0xcb371063},
1299 "ip_neighbor_add_del": {0x607c257: 0x105518b6},
1300 "ip_neighbor_dump": {0xd817a484: 0xcd831298},
1301 "ip_neighbor_details": {0xe29d79f0: 0x870e80b9},
1302 "want_ip_neighbor_events": {0x73e70a86: 0x1a312870},
1303 "ip_neighbor_event": {0xbdb092b2: 0x83933131},
1304 "ip_route_add_del": {0xb8ecfe0d: 0xc1ff832d},
1305 "ip_route_details": {0xbda8f315: 0xd1ffaae1},
1306 "ip_route_lookup": {0x710d6471: 0xe2986185},
1307 "ip_route_lookup_reply": {0x5d8febcb: 0xae99de8e},
1308 "ip_mroute_add_del": {0x85d762f3: 0xf6627d17},
1309 "ip_mroute_details": {0x99341a45: 0xc1cb4b44},
1310 "ip_address_details": {0xee29b797: 0xb1199745},
1311 "ip_unnumbered_details": {0xcc59bd42: 0xaa12a483},
1312 "mfib_signal_details": {0x6f4a4cfb: 0x64398a9a},
1313 "ip_punt_redirect": {0x6580f635: 0xa9a5592c},
1314 "ip_punt_redirect_details": {0x2cef63e7: 0x3924f5d3},
1315 "ip_container_proxy_add_del": {0x7df1dff1: 0x91189f40},
1316 "ip_container_proxy_details": {0xa8085523: 0xee460e8},
1317 "ip_source_and_port_range_check_add_del": {0x92a067e3: 0x8bfc76f2},
1318 "sw_interface_ip6_set_link_local_address": {0x1c10f15f: 0x2931d9fa},
1319 "ip_reassembly_enable_disable": {0xeb77968d: 0x885c85a6},
1320 "set_punt": {0xaa83d523: 0x83799618},
1321 "punt_socket_register": {0x95268cbf: 0xc8cd10fa},
1322 "punt_socket_details": {0xde575080: 0x1de0ce75},
1323 "punt_socket_deregister": {0x98fc9102: 0x98a444f4},
1324 "sw_interface_ip6nd_ra_prefix": {0x82cc1b28: 0xe098785f},
1325 "ip6nd_proxy_add_del": {0xc2e4a686: 0x3fdf6659},
1326 "ip6nd_proxy_details": {0x30b9ff4a: 0xd35be8ff},
1327 "ip6_ra_event": {0x364c1c5: 0x47e8cfbe},
1328 "set_ipfix_exporter": {0x5530c8a0: 0x69284e07},
1329 "ipfix_exporter_details": {0xdedbfe4: 0x11e07413},
1330 "ipip_add_tunnel": {0x2ac399f5: 0xa9decfcd},
1331 "ipip_6rd_add_tunnel": {0xb9ec1863: 0x56e93cc0},
1332 "ipip_tunnel_details": {0xd31cb34e: 0x53236d75},
1333 "ipsec_spd_entry_add_del": {0x338b7411: 0x9f384b8d},
1334 "ipsec_spd_details": {0x5813d7a2: 0xf2222790},
1335 "ipsec_sad_entry_add_del": {0xab64b5c6: 0xb8def364},
1336 "ipsec_tunnel_protect_update": {0x30d5f133: 0x143f155d},
1337 "ipsec_tunnel_protect_del": {0xcd239930: 0xddd2ba36},
1338 "ipsec_tunnel_protect_details": {0x21663a50: 0xac6c823b},
1339 "ipsec_tunnel_if_add_del": {0x20e353fa: 0x2b135e68},
1340 "ipsec_sa_details": {0x345d14a7: 0xb30c7f41},
1341 "l2_xconnect_details": {0x472b6b67: 0xc8aa6b37},
1342 "l2_fib_table_details": {0xa44ef6b8: 0xe8d2fc72},
1343 "l2fib_add_del": {0xeddda487: 0xf29d796c},
1344 "l2_macs_event": {0x44b8fd64: 0x2eadfc8b},
1345 "bridge_domain_details": {0xfa506fd: 0x979f549d},
1346 "l2_interface_pbb_tag_rewrite": {0x38e802a8: 0x612efa5a},
1347 "l2_patch_add_del": {0xa1f6a6f3: 0x522f3445},
1348 "sw_interface_set_l2_xconnect": {0x4fa28a85: 0x1aaa2dbb},
1349 "sw_interface_set_l2_bridge": {0xd0678b13: 0x2e483cd0},
1350 "bd_ip_mac_add_del": {0x257c869: 0x5f2b84e2},
1351 "bd_ip_mac_details": {0x545af86a: 0xa52f8044},
1352 "l2_arp_term_event": {0x6963e07a: 0x85ff71ea},
1353 "l2tpv3_create_tunnel": {0x15bed0c2: 0x596892cb},
1354 "sw_if_l2tpv3_tunnel_details": {0x50b88993: 0x1dab5c7e},
1355 "lisp_add_del_local_eid": {0x4e5a83a2: 0x21f573bd},
1356 "lisp_add_del_map_server": {0xce19e32d: 0x6598ea7c},
1357 "lisp_add_del_map_resolver": {0xce19e32d: 0x6598ea7c},
1358 "lisp_use_petr": {0xd87dbad9: 0x9e141831},
1359 "show_lisp_use_petr_reply": {0x22b9a4b0: 0xdcad8a81},
1360 "lisp_add_del_remote_mapping": {0x6d5c789e: 0xfae8ed77},
1361 "lisp_add_del_adjacency": {0x2ce0e6f6: 0xcf5edb61},
1362 "lisp_locator_details": {0x2c620ffe: 0xc0c4c2a7},
1363 "lisp_eid_table_details": {0x1c29f792: 0x4bc32e3a},
1364 "lisp_eid_table_dump": {0x629468b5: 0xb959b73b},
1365 "lisp_adjacencies_get_reply": {0x807257bf: 0x3f97bcdd},
1366 "lisp_map_resolver_details": {0x3e78fc57: 0x82a09deb},
1367 "lisp_map_server_details": {0x3e78fc57: 0x82a09deb},
1368 "one_add_del_local_eid": {0x4e5a83a2: 0x21f573bd},
1369 "one_add_del_map_server": {0xce19e32d: 0x6598ea7c},
1370 "one_add_del_map_resolver": {0xce19e32d: 0x6598ea7c},
1371 "one_use_petr": {0xd87dbad9: 0x9e141831},
1372 "show_one_use_petr_reply": {0x84a03528: 0x10e744a6},
1373 "one_add_del_remote_mapping": {0x6d5c789e: 0xfae8ed77},
1374 "one_add_del_l2_arp_entry": {0x1aa5e8b3: 0x33209078},
1375 "one_l2_arp_entries_get_reply": {0xb0dd200f: 0xb0a47bbe},
1376 "one_add_del_ndp_entry": {0xf8a287c: 0xd1629a2f},
1377 "one_ndp_entries_get_reply": {0x70719b1a: 0xbd34161},
1378 "one_add_del_adjacency": {0x9e830312: 0xe48e7afe},
1379 "one_locator_details": {0x2c620ffe: 0xc0c4c2a7},
1380 "one_eid_table_details": {0x1c29f792: 0x4bc32e3a},
1381 "one_eid_table_dump": {0xbd190269: 0x95151038},
1382 "one_adjacencies_get_reply": {0x85bab89: 0xa8ed89a5},
1383 "one_map_resolver_details": {0x3e78fc57: 0x82a09deb},
1384 "one_map_server_details": {0x3e78fc57: 0x82a09deb},
1385 "one_stats_details": {0x2eb74678: 0xff6ef238},
1386 "gpe_add_del_fwd_entry": {0xf0847644: 0xde6df50f},
1387 "gpe_fwd_entries_get_reply": {0xc4844876: 0xf9f53f1b},
1388 "gpe_fwd_entry_path_details": {0x483df51a: 0xee80b19a},
1389 "gpe_add_del_native_fwd_rpath": {0x43fc8b54: 0x812da2f2},
1390 "gpe_native_fwd_rpaths_get_reply": {0x7a1ca5a2: 0x79d54eb9},
1391 "sw_interface_set_lldp": {0x57afbcd4: 0xd646ae0f},
1392 "mpls_ip_bind_unbind": {0xc7533b32: 0x48249a27},
1393 "mpls_tunnel_add_del": {0x44350ac1: 0xe57ce61d},
1394 "mpls_tunnel_details": {0x57118ae3: 0xf3c0928e},
1395 "mpls_route_add_del": {0x8e1d1e07: 0x343cff54},
1396 "mpls_route_details": {0x9b5043dc: 0xd0ac384c},
1397 "policer_add_del": {0x2b31dd38: 0xcb948f6e},
1398 "policer_details": {0x72d0e248: 0xa43f781a},
1399 "qos_store_enable_disable": {0xf3abcc8b: 0x3507235e},
1400 "qos_store_details": {0x3ee0aad7: 0x38a6d48},
1401 "qos_record_enable_disable": {0x2f1a4a38: 0x25b33f88},
1402 "qos_record_details": {0xa425d4d3: 0x4956ccdd},
1403 "session_rule_add_del": {0xe4895422: 0xe31f9443},
1404 "session_rules_details": {0x28d71830: 0x304b91f0},
1405 "sw_interface_span_enable_disable": {0x23ddd96b: 0xacc8fea1},
1406 "sw_interface_span_details": {0x8a20e79f: 0x55643fc},
1407 "sr_mpls_steering_add_del": {0x64acff63: 0x7d1b0a0b},
1408 "sr_mpls_policy_assign_endpoint_color": {0xe7eb978: 0x5e1c5c13},
1409 "sr_localsid_add_del": {0x5a36c324: 0x26fa3309},
1410 "sr_policy_add": {0x44ac92e8: 0xec79ee6a},
1411 "sr_policy_mod": {0xb97bb56e: 0xe531a102},
1412 "sr_steering_add_del": {0xe46b0a0f: 0x3711dace},
1413 "sr_localsids_details": {0x2e9221b9: 0x6a6c0265},
1414 "sr_policies_details": {0xdb6ff2a1: 0x7ec2d93},
1415 "sr_steering_pol_details": {0xd41258c9: 0x1c1ee786},
1416 "syslog_set_sender": {0xb8011d0b: 0xbb641285},
1417 "syslog_get_sender_reply": {0x424cfa4e: 0xd3da60ac},
1418 "tcp_configure_src_addresses": {0x67eede0d: 0x4b02b946},
1419 "teib_entry_add_del": {0x8016cfd2: 0x5aa0a538},
1420 "teib_details": {0x981ee1a1: 0xe3b6a503},
1421 "udp_encap_add": {0xf74a60b1: 0x61d5fc48},
1422 "udp_encap_details": {0x8cfb9c76: 0x87c82821},
1423 "vxlan_gbp_tunnel_add_del": {0x6c743427: 0x8c819166},
1424 "vxlan_gbp_tunnel_details": {0x66e94a89: 0x1da24016},
1425 "vxlan_gpe_add_del_tunnel": {0xa645b2b0: 0x7c6da6ae},
1426 "vxlan_gpe_tunnel_details": {0x968fc8b: 0x57712346},
1427 "vxlan_add_del_tunnel": {0xc09dc80: 0xa35dc8f5},
1428 "vxlan_tunnel_details": {0xc3916cb1: 0xe782f70f},
1429 "vxlan_offload_rx": {0x9cc95087: 0x89a1564b},
1430 "log_details": {0x3d61cc0: 0x255827a1},
Ole Troan9f84e702020-06-25 14:27:46 +02001431}
1432
1433
Ole Troan8dbfb432019-04-24 14:31:18 +02001434def foldup_crcs(s):
1435 for f in s:
1436 f.crc = foldup_blocks(f.block,
Mark Nelsonea2abba2020-03-04 15:32:09 -05001437 binascii.crc32(f.crc) & 0xffffffff)
Ole Troan9d420872017-10-12 13:06:35 +02001438
Ole Troan9f84e702020-06-25 14:27:46 +02001439 # fixup the CRCs to make the fix seamless
1440 if f.name in fixup_crc_dict:
1441 if f.crc in fixup_crc_dict.get(f.name):
1442 f.crc = fixup_crc_dict.get(f.name).get(f.crc)
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001443
Ole Troandf87f802020-11-18 19:17:48 +01001444
Ole Troan9d420872017-10-12 13:06:35 +02001445#
1446# Main
1447#
1448def main():
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001449 if sys.version_info < (3, 5,):
1450 log.exception('vppapigen requires a supported version of python. '
1451 'Please use version 3.5 or greater. '
Ole Troandf87f802020-11-18 19:17:48 +01001452 'Using %s', sys.version)
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001453 return 1
1454
Ole Troan9d420872017-10-12 13:06:35 +02001455 cliparser = argparse.ArgumentParser(description='VPP API generator')
Ole Troandf87f802020-11-18 19:17:48 +01001456 cliparser.add_argument('--pluginpath', default="")
1457 cliparser.add_argument('--includedir', action='append')
1458 cliparser.add_argument('--outputdir', action='store')
Ole Troan5c318c72020-05-05 12:23:47 +02001459 cliparser.add_argument('--input')
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001460 cliparser.add_argument('--output', nargs='?',
1461 type=argparse.FileType('w', encoding='UTF-8'),
1462 default=sys.stdout)
Ole Troan9d420872017-10-12 13:06:35 +02001463
1464 cliparser.add_argument('output_module', nargs='?', default='C')
1465 cliparser.add_argument('--debug', action='store_true')
1466 cliparser.add_argument('--show-name', nargs=1)
Ole Troan5c318c72020-05-05 12:23:47 +02001467 cliparser.add_argument('--git-revision',
1468 help="Git revision to use for opening files")
Ole Troan9d420872017-10-12 13:06:35 +02001469 args = cliparser.parse_args()
1470
1471 dirlist_add(args.includedir)
1472 if not args.debug:
1473 sys.excepthook = exception_handler
1474
1475 # Filename
1476 if args.show_name:
1477 filename = args.show_name[0]
Ole Troan5c318c72020-05-05 12:23:47 +02001478 elif args.input:
1479 filename = args.input
Ole Troan9d420872017-10-12 13:06:35 +02001480 else:
1481 filename = ''
1482
Marek Gradzki51e59682018-03-06 10:05:44 +01001483 if args.debug:
1484 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
1485 else:
1486 logging.basicConfig()
Marek Gradzki51e59682018-03-06 10:05:44 +01001487
Ole Troan9d420872017-10-12 13:06:35 +02001488 #
1489 # Generate representation
1490 #
Paul Vinciguerraf4647ed2019-02-12 12:21:01 -08001491 from importlib.machinery import SourceFileLoader
Ole Troan9d420872017-10-12 13:06:35 +02001492
1493 # Default path
Ole Troan30787372018-03-01 13:33:39 +01001494 pluginpath = ''
Ole Troan9d420872017-10-12 13:06:35 +02001495 if not args.pluginpath:
Ole Troan30787372018-03-01 13:33:39 +01001496 cand = []
1497 cand.append(os.path.dirname(os.path.realpath(__file__)))
Ole Troan17225df2018-04-11 09:50:03 +02001498 cand.append(os.path.dirname(os.path.realpath(__file__)) +
Ole Troan30787372018-03-01 13:33:39 +01001499 '/../share/vpp/')
1500 for c in cand:
1501 c += '/'
Ole Troan58914252018-10-23 10:50:07 +02001502 if os.path.isfile('{}vppapigen_{}.py'
1503 .format(c, args.output_module.lower())):
Ole Troan30787372018-03-01 13:33:39 +01001504 pluginpath = c
1505 break
Ole Troan9d420872017-10-12 13:06:35 +02001506 else:
1507 pluginpath = args.pluginpath + '/'
Ole Troan30787372018-03-01 13:33:39 +01001508 if pluginpath == '':
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001509 log.exception('Output plugin not found')
1510 return 1
Ole Troan58914252018-10-23 10:50:07 +02001511 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1512 args.output_module.lower())
Ole Troan9d420872017-10-12 13:06:35 +02001513
1514 try:
Paul Vinciguerraf4647ed2019-02-12 12:21:01 -08001515 plugin = SourceFileLoader(args.output_module,
1516 module_path).load_module()
Ole Troan58914252018-10-23 10:50:07 +02001517 except Exception as err:
Ole Troandf87f802020-11-18 19:17:48 +01001518 log.exception('Error importing output plugin: %s, %s',
1519 module_path, err)
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001520 return 1
Ole Troan9d420872017-10-12 13:06:35 +02001521
Paul Vinciguerra9046e442020-11-20 23:10:09 -05001522 parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
1523 revision=args.git_revision)
1524
1525 try:
1526 if not args.input:
1527 parsed_objects = parser.parse_fd(sys.stdin, log)
1528 else:
1529 parsed_objects = parser.parse_filename(args.input, log)
1530 except ParseError as e:
1531 print('Parse error: ', e, file=sys.stderr)
1532 sys.exit(1)
1533
1534 # Build a list of objects. Hash of lists.
1535 result = []
1536
1537 # if the variable is not set in the plugin, assume it to be false.
1538 try:
1539 plugin.process_imports
1540 except AttributeError:
1541 plugin.process_imports = False
1542
1543 if plugin.process_imports:
1544 result = parser.process_imports(parsed_objects, False, result)
1545 s = parser.process(result)
1546 else:
1547 s = parser.process(parsed_objects)
Ole Troandf87f802020-11-18 19:17:48 +01001548 imports = parser.process_imports(parsed_objects, False, result)
1549 s['imported'] = parser.process(imports)
Paul Vinciguerra9046e442020-11-20 23:10:09 -05001550
1551 # Add msg_id field
1552 s['Define'] = add_msg_id(s['Define'])
1553
1554 # Fold up CRCs
1555 foldup_crcs(s['Define'])
1556
1557 #
1558 # Debug
1559 if args.debug:
1560 import pprint
1561 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
1562 for t in s['Define']:
1563 pp.pprint([t.name, t.flags, t.block])
1564 for t in s['types']:
1565 pp.pprint([t.name, t.block])
1566
Ole Troan2a1ca782019-09-19 01:08:30 +02001567 result = plugin.run(args, filename, s)
Ole Troan9d420872017-10-12 13:06:35 +02001568 if result:
Ole Troan17225df2018-04-11 09:50:03 +02001569 print(result, file=args.output)
Ole Troan9d420872017-10-12 13:06:35 +02001570 else:
Ole Troandf87f802020-11-18 19:17:48 +01001571 log.exception('Running plugin failed: %s %s', filename, result)
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001572 return 1
1573 return 0
Ole Troan9d420872017-10-12 13:06:35 +02001574
1575
1576if __name__ == '__main__':
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001577 sys.exit(main())