Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/seed/qualification/om2/oracle/sha/trace.py # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / seed / qualification / om2 / oracle / sha / trace.py` 187 lines ยท 7446 bytes Raw Blame History 1 #!/usr/bin/python3 2 # SPDX-License-Identifier: Apache-2.0 3 # ORACLE (outside the delivered closure), OM-2 qualification L836 (#748), phaseB/sha-`f5d14cb2`. 4 # Contract section 8 evidence (b): dynamic comparison of instruction-address and data-address traces 5 # for seeded message pairs with equal lengths, op codes and call sequence (HOST, single-step ptrace). 6 # The child (trace_child.c) stops itself with SIGSTOP before and after each traced call sequence; this script 7 # single-steps it (PTRACE_SINGLESTEP) and records, for every executed instruction inside the embedded 8 # OM-2 code, its byte offset in the artifact and, for loads and stores, the effective address computed 9 # from the register file before the instruction and the operand form printed by GNU objdump 2.42 for 10 # that exact artifact word. It also records the whole-process program-counter sequence (binding, 11 # libc). Segments come in pairs (message A, message B); each pair must be identical in all three. 12 # It also reports, per export, the deepest SP observed below the SP at that export's entry word 13 # (a dynamic cross-check of stack.py's static bound, not a bound itself). 14 # Usage: trace.py CHILD LIB ARTIFACT exit 0 iff every pair is identical 15 import ctypes 16 import os 17 import re 18 import signal 19 import struct 20 import subprocess 21 import sys 22 23 CHILD, LIB, ART = sys.argv[1], os.path.realpath(sys.argv[2]), sys.argv[3] 24 libc = ctypes.CDLL(None, use_errno=True) 25 libc.ptrace.restype = ctypes.c_long 26 libc.ptrace.argtypes = [ctypes.c_long, ctypes.c_long, ctypes.c_void_p, ctypes.c_void_p] 27 TRACEME, PEEK, CONT, STEP, GETREGSET = 0, 2, 7, 9, 0x4204 28 NT_PRSTATUS = 1 29 30 31 class Iov(ctypes.Structure): 32 _fields_ = [("base", ctypes.c_void_p), ("len", ctypes.c_size_t)] 33 34 35 regs = (ctypes.c_uint64 * 34)() 36 iov = Iov(ctypes.cast(regs, ctypes.c_void_p), ctypes.sizeof(regs)) 37 38 39 def getregs(pid): 40 if libc.ptrace(GETREGSET, pid, NT_PRSTATUS, ctypes.byref(iov)) != 0: 41 raise OSError(ctypes.get_errno(), "GETREGSET") 42 return regs # x0..x30, sp (31), pc (32), pstate (33) 43 44 45 # objdump operand forms of the artifact's memory instructions 46 art = open(ART, "rb").read() 47 dis = subprocess.run(["objdump", "-D", "-b", "binary", "-m", "aarch64", ART], check=True, 48 capture_output=True, text=True).stdout 49 MEMOP = {} 50 rx = re.compile(r"^\s*([0-9a-f]+):\t[0-9a-f]{8} \t(\S+)\s*(.*)$") 51 for line in dis.splitlines(): 52 m = rx.match(line) 53 if not m: 54 continue 55 off, mn, ops = int(m.group(1), 16), m.group(2), m.group(3) 56 if not re.match(r"^(ld|st)", mn) or "[" not in ops: 57 if re.match(r"^ldr", mn) and "[" not in ops: 58 MEMOP[off] = ("lit", ops) 59 continue 60 inner = ops[ops.index("[") + 1:ops.index("]")] 61 post = ops[ops.index("]") + 1:].strip() 62 parts = [p.strip() for p in inner.split(",")] 63 MEMOP[off] = ("mem", parts, post) 64 65 66 def reg(r, name): 67 name = name.strip() 68 if name in ("sp", "wsp"): 69 return r[31] 70 if name in ("xzr", "wzr"): 71 return 0 72 v = r[int(name[1:])] 73 return v & 0xFFFFFFFF if name[0] == "w" else v 74 75 76 def ea(r, op): 77 if op[0] == "lit": 78 return int(op[1].split(",")[1].split()[0], 16) if "," in op[1] else -1 79 _, parts, post = op 80 base = reg(r, parts[0]) 81 if len(parts) == 1 or post.startswith("#"): 82 return base # [xn] or post-index: the access is at the base 83 p1 = parts[1] 84 if p1.startswith("#"): 85 return (base + int(p1[1:], 0)) & (2**64 - 1) 86 idx = reg(r, p1) 87 sh = 0 88 if len(parts) > 2: 89 ext = parts[2].split() 90 kind = ext[0] 91 if kind == "sxtw": 92 idx = idx - (1 << 32) if idx & (1 << 31) else idx 93 elif kind == "uxtw": 94 idx &= 0xFFFFFFFF 95 if len(ext) > 1: 96 sh = int(ext[1][1:], 0) 97 return (base + (idx << sh)) & (2**64 - 1) 98 99 100 pid = os.fork() 101 if pid == 0: 102 libc.ptrace(TRACEME, 0, None, None) 103 os.execv(CHILD, [CHILD]) 104 os._exit(127) 105 106 _, st = os.waitpid(pid, 0) # exec stop 107 assert os.WIFSTOPPED(st), st 108 libc.ptrace(CONT, pid, None, None) 109 _, st = os.waitpid(pid, 0) # first SIGSTOP: the library is mapped now 110 assert os.WIFSTOPPED(st) and os.WSTOPSIG(st) == signal.SIGSTOP, st 111 112 bias = None 113 for line in open(f"/proc/{pid}/maps"): 114 f = line.split() 115 if len(f) >= 6 and os.path.realpath(f[5]) == LIB and int(f[2], 16) == 0: 116 bias = int(f[0].split("-")[0], 16) 117 break 118 sym = subprocess.run(["objdump", "-t", LIB], check=True, capture_output=True, text=True).stdout 119 code_off = int([l.split()[0] for l in sym.splitlines() if l.split() and l.split()[-1] == "ombr2_code_sha256_om2"][0], 16) 120 lo = bias + code_off 121 hi = lo + len(art) 122 with open(f"/proc/{pid}/mem", "rb") as mem: 123 mem.seek(lo) 124 live = mem.read(len(art)) 125 print(f"INFO code at {lo:#x}..{hi:#x} ({len(art)} bytes); live bytes == artifact: {live == art}") 126 if live != art: 127 sys.exit(1) 128 129 EXPORTS = ["sha256_init", "sha256_update", "sha256_final", "sha256_hash"] # entry words 0..3, source order 130 maxdepth = {} 131 cur_export, entry_sp = None, 0 132 segs = [] 133 cur = None 134 while True: 135 # at a SIGSTOP stop: start a new segment, suppress the signal 136 cur = {"code": [], "pcs": []} 137 segs.append(cur) 138 while True: 139 libc.ptrace(STEP, pid, None, None) 140 _, st = os.waitpid(pid, 0) 141 if os.WIFEXITED(st) or os.WIFSIGNALED(st): 142 break 143 sig = os.WSTOPSIG(st) 144 if sig == signal.SIGSTOP: 145 break 146 if sig != signal.SIGTRAP: 147 print(f"FAIL unexpected signal {sig}") 148 sys.exit(1) 149 r = getregs(pid) 150 pc = r[32] 151 cur["pcs"].append(pc) 152 if lo <= pc < hi: 153 off = pc - lo 154 op = MEMOP.get(off) 155 cur["code"].append((off, ea(r, op)) if op else (off,)) 156 if off < 4 * len(EXPORTS): # entry word of export off/4: SP at the call's entry 157 cur_export, entry_sp = off // 4, r[31] 158 depth = entry_sp - r[31] 159 if depth > maxdepth.get(cur_export, -1): 160 maxdepth[cur_export] = depth 161 if os.WIFEXITED(st) or os.WIFSIGNALED(st): 162 break 163 164 segs = [s for s in segs if s["code"]] # the final segment (exit path) runs no OM-2 code 165 print(f"INFO child exit status {os.WEXITSTATUS(st) if os.WIFEXITED(st) else 'signal'}; segments with OM-2 code: {len(segs)}") 166 if len(segs) % 2 or not segs: 167 print("FAIL odd or empty segment count") 168 sys.exit(1) 169 bad = 0 170 for i in range(0, len(segs), 2): 171 a, b = segs[i], segs[i + 1] 172 ins_a = [x[0] for x in a["code"]] 173 ins_b = [x[0] for x in b["code"]] 174 da = [x[1] for x in a["code"] if len(x) > 1] 175 db = [x[1] for x in b["code"] if len(x) > 1] 176 same = (ins_a == ins_b, da == db, a["pcs"] == b["pcs"]) 177 tag = "PASS" if all(same) else "FAIL" 178 if not all(same): 179 bad += 1 180 k = next((j for j in range(min(len(ins_a), len(ins_b))) if a["code"][j] != b["code"][j]), min(len(ins_a), len(ins_b))) 181 print(f" first difference at OM-2 step {k}: {a['code'][k:k+1]} vs {b['code'][k:k+1]}") 182 print(f"{tag} pair {i // 2}: om2-instructions={len(ins_a)}/{len(ins_b)} data-addresses={len(da)}/{len(db)} " 183 f"process-pcs={len(a['pcs'])}/{len(b['pcs'])} equal(insn,data,pcs)={same}") 184 for k in sorted(maxdepth): 185 print(f"INFO observed max stack depth below entry SP, export {EXPORTS[k]}: {maxdepth[k]} bytes") 186 print(f"{'PASS' if bad == 0 else 'FAIL'} trace pairs={len(segs) // 2} differing={bad}") 187 sys.exit(1 if bad else 0)