#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0. """ BDD Bytecode Compiler: JSON -> binary bytecode format. BYTECODE FORMAT SPECIFICATION ============================= All multi-byte integers are big-endian (network byte order). TOP-LEVEL STRUCTURE: [4 bytes] Magic: 0x45504452 ("EPDR") [String Blob Section] [4 bytes] Version string reference [Parameters Section] [Conditions Section] [Results Section] [Nodes Section] STRING BLOB SECTION: [4 bytes] blob_size (uint32) [blob_size bytes] Concatenated ASCII strings, each terminated with "$$". STRING REFERENCE (used throughout): [2 bytes] offset (uint16) - byte offset into string blob [2 bytes] length (uint16) - string length in bytes Note: (0, 0) represents empty/null string PARAMETERS SECTION: [2 bytes] count (uint16) [for each parameter:] [1 byte] opcode: 0x01=string, 0x02=boolean, 0x03=string_array [4 bytes] name string ref [1 byte] has_default: 0=no, 1=yes [if has_default and string: 4 bytes string ref] [if has_default and bool: 1 byte value] [1 byte] is_required: 0=no, 1=yes [1 byte] has_builtin: 0=no, 1=yes [if has_builtin: 4 bytes builtin name string ref] CONDITIONS SECTION: [2 bytes] count (uint16) [for each condition:] [1 byte] opcode: 0x10 [4 bytes] function name string ref [2 bytes] argc (uint16) [argc encoded values] [1 byte] has_assign: 0=no, 1=yes [if has_assign: 4 bytes assign name string ref] RESULTS SECTION: [2 bytes] count (uint16) Note: Loader inserts synthetic "NoMatchRule" at index 0; serialized results map to indices 1+ [for each result:] Endpoint (opcode 0x20): [1 byte] opcode: 0x20 [encoded expr] url [4 bytes] properties_json string ref [2 bytes] headers count [for each header:] [4 bytes] header name string ref [2 bytes] values count [encoded expr] header values Error (opcode 0x21): [1 byte] opcode: 0x21 [encoded expr] error message VALUE ENCODING (recursive): [1 byte] tag Tag 0 (None): no additional data Tag 1 (String): [4 bytes] string ref Tag 2 (Boolean): [1 byte] value (0=false, 1=true) Tag 3 (Integer): [4 bytes] int32 Tag 4 (Reference):[4 bytes] variable name string ref Tag 5 (Function): [4 bytes] fn name ref + [2 bytes] argc + [argc encoded values] Tag 6 (Array): [2 bytes] length + [length encoded values] Tag 7 (Object): [2 bytes] length + [for each: 4 bytes key ref + encoded value] NODES SECTION: [4 bytes] root_ref (int32) - root node reference [4 bytes] node_count (uint32) [2 bytes] base64_length (uint16) [base64_length bytes] Base64-encoded node array Each node (after decoding) is 12 bytes: [4 bytes] condition_index (int32) - index into conditions array [4 bytes] high_ref (int32) - reference when condition is true [4 bytes] low_ref (int32) - reference when condition is false Node references: positive = node index, negative = negated result index (e.g., -1 = result[0], -2 = result[1]) Use --verify flag to dump a human-readable summary of a compiled .bin file. """ import base64 import json import struct import sys from enum import IntEnum MAGIC = 0x45504452 fn_mapping = {"isSet" : 0, "not" : 1, "getAttr" : 2, "substring" : 3, "stringEquals" : 4, "booleanEquals" : 5, "coalesce" : 6, "split" : 7, "ite" : 8, "uriEncode" : 9, "parseURL" : 10, "isValidHostLabel" : 11, "aws.partition" : 12, "aws.parseArn" : 13, "aws.isVirtualHostableS3Bucket" : 14 } class Opcode(IntEnum): PARAM_STRING = 0x01 PARAM_BOOL = 0x02 PARAM_STRING_ARRAY = 0x03 CONDITION = 0x10 RESULT_ENDPOINT = 0x20 RESULT_ERROR = 0x21 class StringBlob: """Collects unique strings into one concatenated blob; returns (offset, length) pairs.""" def __init__(self): self._blob = bytearray() self._index = {} # str -> (offset, length) self._terminator = b"$$" def add(self, s): if not s: return (0, 0) if s not in self._index: if not s.isascii(): raise ValueError(f"Non-ASCII string not supported: {s!r}") raw = s.encode("ascii") offset = len(self._blob) if offset > 0xFFFF: raise ValueError(f"String blob offset {offset} exceeds uint16 max") if len(raw) > 0xFFFF: raise ValueError(f"String length {len(raw)} exceeds uint16 max") self._blob.extend(raw) self._blob.extend(self._terminator) self._index[s] = (offset, len(raw)) return self._index[s] def blob(self): return bytes(self._blob) def write_string_ref(buf, offset, length): """Emit 4 bytes: uint16 offset + uint16 length (little-endian).""" buf.extend(struct.pack("{n}i', raw[:n * 4]) le_bytes = struct.pack(f'<{n}i', *be_values) buf += struct.pack(" 0: string_refs.add((off, ln)) # Version string ref v_off, v_len = read(" 0: string_refs.add((v_off, v_len)) version_str = blob[v_off:v_off + v_len].decode("ascii") if v_len else "" # Parameters param_count = read("", file=sys.stderr) sys.exit(1) verify(args[0]) return if len(sys.argv) < 3: print(f"Usage: {sys.argv[0]} ", file=sys.stderr) sys.exit(1) input_path, output_path = sys.argv[1], sys.argv[2] with open(input_path) as f: data = json.load(f) bytecode = encode(data) with open(output_path, "wb") as f: f.write(bytecode) print(f"Wrote {len(bytecode)} bytes to {output_path}") if __name__ == "__main__": main()