Debian Codegraph @

crt/aws-c-sdkutils/compiler/bdd-bytecoder.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 # SPDX-License-Identifier: Apache-2.0.
4
5 """
6 BDD Bytecode Compiler: JSON -> binary bytecode format.
7
8 BYTECODE FORMAT SPECIFICATION
9 =============================
10 All multi-byte integers are big-endian (network byte order).
11
12 TOP-LEVEL STRUCTURE:
13 [4 bytes] Magic: 0x45504452 ("EPDR")
14 [String Blob Section]
15 [4 bytes] Version string reference
16 [Parameters Section]
17 [Conditions Section]
18 [Results Section]
19 [Nodes Section]
20
21 STRING BLOB SECTION:
22 [4 bytes] blob_size (uint32)
23 [blob_size bytes] Concatenated ASCII strings, each terminated with "$$".
24
25 STRING REFERENCE (used throughout):
26 [2 bytes] offset (uint16) - byte offset into string blob
27 [2 bytes] length (uint16) - string length in bytes
28 Note: (0, 0) represents empty/null string
29
30 PARAMETERS SECTION:
31 [2 bytes] count (uint16)
32 [for each parameter:]
33 [1 byte] opcode: 0x01=string, 0x02=boolean, 0x03=string_array
34 [4 bytes] name string ref
35 [1 byte] has_default: 0=no, 1=yes
36 [if has_default and string: 4 bytes string ref]
37 [if has_default and bool: 1 byte value]
38 [1 byte] is_required: 0=no, 1=yes
39 [1 byte] has_builtin: 0=no, 1=yes
40 [if has_builtin: 4 bytes builtin name string ref]
41
42 CONDITIONS SECTION:
43 [2 bytes] count (uint16)
44 [for each condition:]
45 [1 byte] opcode: 0x10
46 [4 bytes] function name string ref
47 [2 bytes] argc (uint16)
48 [argc encoded values]
49 [1 byte] has_assign: 0=no, 1=yes
50 [if has_assign: 4 bytes assign name string ref]
51
52 RESULTS SECTION:
53 [2 bytes] count (uint16)
54 Note: Loader inserts synthetic "NoMatchRule" at index 0; serialized results map to indices 1+
55 [for each result:]
56 Endpoint (opcode 0x20):
57 [1 byte] opcode: 0x20
58 [encoded expr] url
59 [4 bytes] properties_json string ref
60 [2 bytes] headers count
61 [for each header:]
62 [4 bytes] header name string ref
63 [2 bytes] values count
64 [encoded expr] header values
65 Error (opcode 0x21):
66 [1 byte] opcode: 0x21
67 [encoded expr] error message
68
69 VALUE ENCODING (recursive):
70 [1 byte] tag
71 Tag 0 (None): no additional data
72 Tag 1 (String): [4 bytes] string ref
73 Tag 2 (Boolean): [1 byte] value (0=false, 1=true)
74 Tag 3 (Integer): [4 bytes] int32
75 Tag 4 (Reference):[4 bytes] variable name string ref
76 Tag 5 (Function): [4 bytes] fn name ref + [2 bytes] argc + [argc encoded values]
77 Tag 6 (Array): [2 bytes] length + [length encoded values]
78 Tag 7 (Object): [2 bytes] length + [for each: 4 bytes key ref + encoded value]
79
80 NODES SECTION:
81 [4 bytes] root_ref (int32) - root node reference
82 [4 bytes] node_count (uint32)
83 [2 bytes] base64_length (uint16)
84 [base64_length bytes] Base64-encoded node array
85
86 Each node (after decoding) is 12 bytes:
87 [4 bytes] condition_index (int32) - index into conditions array
88 [4 bytes] high_ref (int32) - reference when condition is true
89 [4 bytes] low_ref (int32) - reference when condition is false
90
91 Node references: positive = node index, negative = negated result index
92 (e.g., -1 = result[0], -2 = result[1])
93
94 Use --verify flag to dump a human-readable summary of a compiled .bin file.
95 """
96
97 import base64
98 import json
99 import struct
100 import sys
101 from enum import IntEnum
102
103 MAGIC = 0x45504452
104
105 fn_mapping = {"isSet" : 0, "not" : 1, "getAttr" : 2, "substring" : 3, "stringEquals" : 4, "booleanEquals" : 5, "coalesce" : 6,
106 "split" : 7, "ite" : 8, "uriEncode" : 9, "parseURL" : 10, "isValidHostLabel" : 11, "aws.partition" : 12, "aws.parseArn" : 13, "aws.isVirtualHostableS3Bucket" : 14 }
107
108
109 class Opcode(IntEnum):
110 PARAM_STRING = 0x01
111 PARAM_BOOL = 0x02
112 PARAM_STRING_ARRAY = 0x03
113 CONDITION = 0x10
114 RESULT_ENDPOINT = 0x20
115 RESULT_ERROR = 0x21
116
117
118 class StringBlob:
119 """Collects unique strings into one concatenated blob; returns (offset, length) pairs."""
120
121 def __init__(self):
122 self._blob = bytearray()
123 self._index = {} # str -> (offset, length)
124 self._terminator = b"$$"
125
126 def add(self, s):
127 if not s:
128 return (0, 0)
129 if s not in self._index:
130 if not s.isascii():
131 raise ValueError(f"Non-ASCII string not supported: {s!r}")
132 raw = s.encode("ascii")
133 offset = len(self._blob)
134 if offset > 0xFFFF:
135 raise ValueError(f"String blob offset {offset} exceeds uint16 max")
136 if len(raw) > 0xFFFF:
137 raise ValueError(f"String length {len(raw)} exceeds uint16 max")
138 self._blob.extend(raw)
139 self._blob.extend(self._terminator)
140 self._index[s] = (offset, len(raw))
141 return self._index[s]
142
143 def blob(self):
144 return bytes(self._blob)
145
146
147 def write_string_ref(buf, offset, length):
148 """Emit 4 bytes: uint16 offset + uint16 length (little-endian)."""
149 buf.extend(struct.pack("<HH", offset, length))
150
151
152 def encode_value(buf, val, strings):
153 """Recursively encode a value with type tag (0-7)."""
154 if val is None:
155 buf += struct.pack("<B", 0)
156 elif isinstance(val, bool):
157 buf += struct.pack("<BB", 2, 1 if val else 0)
158 elif isinstance(val, str):
159 buf += struct.pack("<B", 1)
160 write_string_ref(buf, *strings.add(val))
161 elif isinstance(val, int):
162 buf += struct.pack("<Bi", 3, val)
163 elif isinstance(val, dict) and "ref" in val:
164 buf += struct.pack("<B", 4)
165 write_string_ref(buf, *strings.add(val["ref"]))
166 elif isinstance(val, dict) and "fn" in val:
167 buf += struct.pack("<B", 5)
168 buf += struct.pack("<B", fn_mapping[val["fn"]])
169 args = val.get("argv", [])
170 buf += struct.pack("<H", len(args))
171 for a in args:
172 encode_value(buf, a, strings)
173 elif isinstance(val, list):
174 buf += struct.pack("<BH", 6, len(val))
175 for item in val:
176 encode_value(buf, item, strings)
177 elif isinstance(val, dict):
178 buf += struct.pack("<BH", 7, len(val))
179 for k, v in val.items():
180 write_string_ref(buf, *strings.add(k))
181 encode_value(buf, v, strings)
182 else:
183 raise ValueError(f"Unsupported value type: {type(val)}")
184
185
186 def encode_parameters(buf, data, strings):
187 """Emit parameter count (uint16) then each parameter record."""
188 params = data.get("parameters", {})
189 buf += struct.pack("<H", len(params))
190 for name, p in params.items():
191 ptype = p.get("type", "string").lower()
192 if ptype == "string":
193 opcode = Opcode.PARAM_STRING
194 elif ptype == "boolean":
195 opcode = Opcode.PARAM_BOOL
196 elif ptype == "stringarray":
197 opcode = Opcode.PARAM_STRING_ARRAY
198 else:
199 raise ValueError(f"Unsupported parameter type: {ptype}")
200 buf += struct.pack("<B", opcode)
201 write_string_ref(buf, *strings.add(name))
202 dv = p.get("default")
203 has_default = dv is not None
204 buf += struct.pack("<B", 1 if has_default else 0)
205 if has_default:
206 if ptype == "boolean":
207 buf += struct.pack("<B", 1 if dv else 0)
208 else:
209 write_string_ref(buf, *strings.add(str(dv)))
210 buf += struct.pack("<B", 1 if p.get("required") else 0)
211 built_in = p.get("builtIn")
212 buf += struct.pack("<B", 1 if built_in else 0)
213 if built_in:
214 write_string_ref(buf, *strings.add(built_in))
215
216 def encode_conditions(buf, data, strings):
217 """Emit condition count (uint16) then each condition record."""
218 conditions = data.get("conditions", [])
219 buf += struct.pack("<H", len(conditions))
220 for c in conditions:
221 buf += struct.pack("<B", Opcode.CONDITION)
222 buf += struct.pack("<B", fn_mapping[c["fn"]])
223 args = c.get("argv", [])
224 buf += struct.pack("<H", len(args))
225 for a in args:
226 encode_value(buf, a, strings)
227 assign = c.get("assign")
228 buf += struct.pack("<B", 1 if assign else 0)
229 if assign:
230 write_string_ref(buf, *strings.add(assign))
231
232
233 def encode_results(buf, data, strings):
234 """Emit result count (uint16) then each result record."""
235 results = data.get("results", [])
236 buf += struct.pack("<H", len(results))
237 for r in results:
238 if "endpoint" in r:
239 ep = r["endpoint"]
240 buf += struct.pack("<B", Opcode.RESULT_ENDPOINT)
241 encode_value(buf, ep.get("url"), strings)
242 # Store properties as opaque JSON string
243 props = ep.get("properties", {})
244 props_json = json.dumps(props, separators=(",", ":")) if props else ""
245 write_string_ref(buf, *strings.add(props_json))
246 headers = data.get("headers", {})
247 buf += struct.pack("<H", len(headers))
248 for name, vs in headers.items():
249 write_string_ref(buf, *strings.add(name))
250 buf += struct.pack("<H", len(vs))
251 for v in vs:
252 encode_value(buf, v, strings)
253
254 elif "error" in r:
255 buf += struct.pack("<B", Opcode.RESULT_ERROR)
256 encode_value(buf, r["error"], strings)
257 else:
258 raise ValueError(f"Unsupported result type: {r}")
259
260
261 def encode_nodes(buf, data):
262 """Emit root_ref (int32), node_count (uint32), then base64 nodes blob with uint16 length prefix.
263 The source JSON has nodes in a base64 blob with big-endian int32s. We re-encode to little-endian."""
264 root_ref = data.get("root", 0)
265 node_count = data.get("nodeCount", 0)
266 buf += struct.pack("<iI", root_ref, node_count)
267
268 nodes_b64 = data.get("nodes", "")
269 if not nodes_b64:
270 buf += struct.pack("<H", 0)
271 return
272
273 raw = base64.b64decode(nodes_b64)
274 if len(raw) != node_count * 12:
275 raise ValueError(f"Node blob size {len(raw)} != expected {node_count * 12}")
276
277 n = len(raw) // 4
278
279 # Unpack as big-endian int32, then repack as little-endian int32
280 be_values = struct.unpack(f'>{n}i', raw[:n * 4])
281 le_bytes = struct.pack(f'<{n}i', *be_values)
282
283 buf += struct.pack("<H", len(le_bytes))
284 buf += le_bytes
285
286
287 def encode(data):
288 """Single-pass: build all segments in memory, then assemble final bytecode."""
289 strings = StringBlob()
290
291 # Build each segment into its own buffer, strings accumulate as we go
292 version_buf = bytearray()
293 v = data.get("version")
294 off, ln = strings.add(v) if v else (0, 0)
295 write_string_ref(version_buf, off, ln)
296
297 params_buf = bytearray()
298 encode_parameters(params_buf, data, strings)
299
300 conditions_buf = bytearray()
301 encode_conditions(conditions_buf, data, strings)
302
303 results_buf = bytearray()
304 encode_results(results_buf, data, strings)
305
306 nodes_buf = bytearray()
307 encode_nodes(nodes_buf, data)
308
309 # Now assemble: magic + string blob + version + params + conditions + results + nodes
310 # Re-encode version ref since blob may have grown after initial version ref was written
311 version_buf = bytearray()
312 off, ln = strings.add(v) if v else (0, 0)
313 write_string_ref(version_buf, off, ln)
314
315 out = bytearray()
316 out += struct.pack("<I", MAGIC)
317 blob = strings.blob()
318 out += struct.pack("<I", len(blob))
319 out += blob
320 out += version_buf
321 out += params_buf
322 out += conditions_buf
323 out += results_buf
324 out += nodes_buf
325 return bytes(out)
326
327
328 def verify(bin_path):
329 """Read a compiled .bin file and print a human-readable summary."""
330 with open(bin_path, "rb") as f:
331 data = f.read()
332 pos = 0
333
334 def read(fmt):
335 nonlocal pos
336 size = struct.calcsize(fmt)
337 val = struct.unpack_from(fmt, data, pos)
338 pos += size
339 return val[0] if len(val) == 1 else val
340
341 try:
342 magic = read("<I")
343 if magic != MAGIC:
344 print(f"ERROR: bad magic 0x{magic:08X} (expected 0x{MAGIC:08X})", file=sys.stderr)
345 sys.exit(1)
346
347 blob_size = read("<I")
348 blob = data[pos:pos + blob_size]
349 pos += blob_size
350
351 string_refs = set()
352
353 def track_ref():
354 nonlocal pos
355 off, ln = struct.unpack_from("<HH", data, pos)
356 pos += 4
357 if ln > 0:
358 string_refs.add((off, ln))
359
360 # Version string ref
361 v_off, v_len = read("<HH")
362 if v_len > 0:
363 string_refs.add((v_off, v_len))
364 version_str = blob[v_off:v_off + v_len].decode("ascii") if v_len else ""
365
366 # Parameters
367 param_count = read("<H")
368 for _ in range(param_count):
369 opcode = read("<B")
370 track_ref() # name
371 has_def = read("<B")
372 if has_def:
373 if opcode == Opcode.PARAM_STRING or opcode == Opcode.PARAM_STRING_ARRAY:
374 track_ref()
375 else:
376 pos += 1
377 pos += 1 # required
378 has_bi = read("<B")
379 if has_bi:
380 track_ref()
381
382 # Conditions
383 cond_count = read("<H")
384
385 def skip_value():
386 nonlocal pos
387 tag = read("<B")
388 if tag == 0:
389 pass
390 elif tag == 1:
391 track_ref()
392 elif tag == 2:
393 pos += 1
394 elif tag == 3:
395 pos += 4
396 elif tag == 4:
397 track_ref()
398 elif tag == 5:
399 track_ref()
400 argc = read("<H")
401 for _ in range(argc):
402 skip_value()
403 elif tag == 6:
404 n = read("<H")
405 for _ in range(n):
406 skip_value()
407 elif tag == 7:
408 n = read("<H")
409 for _ in range(n):
410 track_ref()
411 skip_value()
412 else:
413 print(f"ERROR: unknown value tag {tag} at offset {pos}", file=sys.stderr)
414 sys.exit(1)
415
416 for _ in range(cond_count):
417 pos += 1 # opcode
418 track_ref() # fn ref
419 argc = read("<H")
420 for _ in range(argc):
421 skip_value()
422 has_assign = read("<B")
423 if has_assign:
424 track_ref()
425
426 # Results
427 result_count = read("<H")
428 for _ in range(result_count):
429 opcode = read("<B")
430 if opcode == Opcode.RESULT_ENDPOINT:
431 track_ref() # url ref
432 track_ref() # properties json ref
433 elif opcode == Opcode.RESULT_ERROR:
434 track_ref() # error ref
435
436 # Nodes
437 root_ref, node_count = read("<iI")
438 nodes_len = read("<H")
439 pos += nodes_len
440
441 except struct.error:
442 print(f"ERROR: file truncated at offset {pos}", file=sys.stderr)
443 sys.exit(1)
444
445 print(f"Magic: 0x{magic:08X}")
446 print(f"Blob size: {blob_size} bytes")
447 print(f"Strings: {len(string_refs)}")
448 print(f"Version: {version_str!r}")
449 print(f"Parameters: {param_count}")
450 print(f"Conditions: {cond_count}")
451 print(f"Results: {result_count}")
452 print(f"Node count: {node_count}")
453 print(f"Root ref: {root_ref}")
454 print(f"Nodes blob: {nodes_len} bytes (base64)")
455 print(f"Total size: {len(data)} bytes")
456
457
458 def main():
459 if "--verify" in sys.argv:
460 args = [a for a in sys.argv[1:] if a != "--verify"]
461 if not args:
462 print(f"Usage: {sys.argv[0]} --verify <file.bin>", file=sys.stderr)
463 sys.exit(1)
464 verify(args[0])
465 return
466
467 if len(sys.argv) < 3:
468 print(f"Usage: {sys.argv[0]} <input.json> <output.bin>", file=sys.stderr)
469 sys.exit(1)
470
471 input_path, output_path = sys.argv[1], sys.argv[2]
472
473 with open(input_path) as f:
474 data = json.load(f)
475
476 bytecode = encode(data)
477
478 with open(output_path, "wb") as f:
479 f.write(bytecode)
480
481 print(f"Wrote {len(bytecode)} bytes to {output_path}")
482
483
484 if __name__ == "__main__":
485 main()