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
omega-mv / seed / omc / tests / objhost / check.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Host effects in native objects (DRA-542): an independent test oracle, not a linker. |
| 3 | |
| 4 | Usage: check.py OMC OUT_DIR. OMC is the compiler under test; the module driver is built from |
| 5 | seed/ng/sha256.om + seed/modules/driver.om by the same OMC. OUT_DIR must not exist. |
| 6 | Checks, each printed PASS or raising with a named contract: |
| 7 | accept each word of the object host subset compiles to OMOBJ001 whose code equals the |
| 8 | function-mode compile of the same source; |
| 9 | refuse device words, program-only host words, globals and text still refuse with error 9; |
| 10 | record a function's stack record covers its host-word pushes (the private 4096-byte path buffer); |
| 11 | run a linked two-module program reads stdin, writes stdout, creates/stats/reads a file, |
| 12 | reads the clock and exits through a module, matching a single-unit program build; |
| 13 | stack the module driver refuses (37, at build) a call chain that fits 8 MiB only if a host push is ignored, |
| 14 | and links and runs the same chain once the push fits. |
| 15 | """ |
| 16 | import hashlib, os, pathlib, re, shutil, struct, subprocess, sys |
| 17 | |
| 18 | P = pathlib.Path |
| 19 | REPO = P(__file__).resolve().parents[4] |
| 20 | OMC = P(sys.argv[1]).resolve() |
| 21 | OUT = P(sys.argv[2]).resolve() |
| 22 | OUT.mkdir(parents=True) |
| 23 | os.chdir(OUT) |
| 24 | MIB8 = 8 * 1024 * 1024 |
| 25 | sha = lambda b: hashlib.sha256(b).hexdigest() |
| 26 | COMP = sha(OMC.read_bytes()) |
| 27 | |
| 28 | |
| 29 | def ok(label): |
| 30 | print("PASS", label, flush=True) |
| 31 | |
| 32 | |
| 33 | def omc(src, status=0): |
| 34 | r = subprocess.run([OMC], input=src.encode(), capture_output=True, timeout=60) |
| 35 | assert r.returncode == status, (src, r.returncode, status, r.stderr.decode()) |
| 36 | if status: |
| 37 | assert not r.stdout, "refusal wrote output" |
| 38 | return r.stdout |
| 39 | |
| 40 | |
| 41 | def u64(b, o): |
| 42 | return struct.unpack_from("<Q", b, o)[0] |
| 43 | |
| 44 | |
| 45 | def parse(data): |
| 46 | """OMOBJ001 per spec/omegese-modules.md: returns (functions, calls, code range).""" |
| 47 | assert data[:8] == b"OMOBJ001", "object-magic" |
| 48 | start, end, nf, nc = u64(data, 32), u64(data, 40), u64(data, 48), u64(data, 56) |
| 49 | p, fns = end, [] |
| 50 | for _ in range(nf): |
| 51 | flags, addr, ret, np, stack, nlen = [u64(data, p + 8 * i) for i in range(6)] |
| 52 | p += 48 |
| 53 | name = data[p:p + nlen].decode() |
| 54 | p += nlen |
| 55 | p += (-p) % 8 |
| 56 | p += 40 * np |
| 57 | fns.append(dict(flags=flags, name=name, stack=stack)) |
| 58 | calls = [] |
| 59 | for _ in range(nc): |
| 60 | calls.append([u64(data, p + 8 * i) for i in range(4)]) |
| 61 | p += 32 |
| 62 | assert p == len(data), "object-exact-end" |
| 63 | return fns, calls, (start, end) |
| 64 | |
| 65 | |
| 66 | # accept: every word of the subset, and the object's code is the function-mode code. |
| 67 | SUBSET = { |
| 68 | "write": "n = write 1 b 0 len b\nret n", |
| 69 | "read": "n = read 0 b 0 len b\nret n", |
| 70 | "exit": "exit 3", |
| 71 | "monons": "n = monons\nret n", |
| 72 | "realns": "n = realns\nret n", |
| 73 | "sleepns": "n = sleepns long 1000\nret n", |
| 74 | "fopen+fclose": "fd = fopen b 0 len b 0 0\nc = fclose int fd\nret long c", |
| 75 | "fstat": "n = fstat int 0 b 0 128\nret n", |
| 76 | "stat": "n = stat b 0 1 b 0 128\nret n", |
| 77 | "lstat": "n = lstat b 0 1 b 0 128\nret n", |
| 78 | "getuid": "n = getuid\nret n", |
| 79 | "geteuid": "n = geteuid\nret n", |
| 80 | "getgid": "n = getgid\nret n", |
| 81 | "getegid": "n = getegid\nret n", |
| 82 | } |
| 83 | OBJDUMP = shutil.which("aarch64-linux-gnu-objdump") or shutil.which("objdump") |
| 84 | |
| 85 | |
| 86 | def sp_walk(code): |
| 87 | """Independent decoder (GNU objdump): the deepest SP and the final SP along the emitted words, read in |
| 88 | order. Valid for the straight-line one-statement bodies below (no early ret, no frame allocation after |
| 89 | a push), where the record must equal it; in general the record is an upper bound.""" |
| 90 | (OUT / "code.bin").write_bytes(code) |
| 91 | r = subprocess.run([OBJDUMP, "-D", "-b", "binary", "-m", "aarch64", str(OUT / "code.bin")], |
| 92 | capture_output=True, text=True) |
| 93 | if r.returncode != 0: |
| 94 | return None |
| 95 | cur = deep = low = 0 |
| 96 | for line in r.stdout.splitlines(): |
| 97 | if re.search(r"\bmov\s+sp\b|\[sp, #-?0x[0-9a-f]+\]!|\[sp\], #-?0x[0-9a-f]+", line): |
| 98 | raise AssertionError(("object-sp-write-unmodelled", line)) |
| 99 | m = re.search(r"\t(sub|add)\s+sp, sp, #0x([0-9a-f]+)(, lsl #12)?", line) |
| 100 | if m: |
| 101 | v = int(m.group(2), 16) << (12 if m.group(3) else 0) |
| 102 | cur += v if m.group(1) == "sub" else -v |
| 103 | deep, low = max(deep, cur), min(low, cur) |
| 104 | elif re.search(r"\t(sub|add)\s+sp,", line): |
| 105 | raise AssertionError(("object-sp-write-unmodelled", line)) |
| 106 | return deep, cur, low |
| 107 | |
| 108 | |
| 109 | for word, body in SUBSET.items(): |
| 110 | sig = "to void" if word == "exit" else "to long" |
| 111 | src = f"om2\nexport fn t b edit uchar * {sig}\n{body}\nend\n" |
| 112 | obj = omc("object\n" + src) |
| 113 | fns, calls, (s, e) = parse(obj) |
| 114 | assert obj[s:e] == omc(src), f"object-code-equals-function-mode {word}" |
| 115 | walk = sp_walk(obj[s:e]) if OBJDUMP else None |
| 116 | if walk is None: |
| 117 | ok(f"accept {word} (objdump cross-check NOT_RUN)") |
| 118 | continue |
| 119 | assert walk == (fns[0]["stack"], 0, 0), ("object-host-stack-record", word, fns[0]["stack"], walk) |
| 120 | ok(f"accept {word}; record {fns[0]['stack']} = deepest SP in objdump's decode, SP back to 0") |
| 121 | |
| 122 | # refuse: what still needs state the module linker does not provide. |
| 123 | REFUSE = { |
| 124 | "device mapdrop": "export fn t to long\nn = mapdrop 1\nret n", |
| 125 | "program-only argcnt": "export fn t to long\nn = argcnt\nret n", |
| 126 | "global": "global g uchar 1\nexport fn t to uchar\nret get g 0", |
| 127 | "text": "text g \"a\"\nexport fn t to uchar\nret get g 0", |
| 128 | } |
| 129 | for label, body in REFUSE.items(): |
| 130 | omc(f"object\nom2\n{body}\nend\n", 9) |
| 131 | ok(f"refuse {label}") |
| 132 | |
| 133 | # record: the stack record covers the 4096-byte private path buffer and its save area. |
| 134 | fns, _, _ = parse(omc("object\nom2\nexport fn t b view uchar * to long\nfd = fopen b 0 len b 0 0\nret fd\nend\n")) |
| 135 | assert fns[0]["stack"] >= 4096 + 16 and fns[0]["stack"] % 16 == 0, ("object-host-stack-record", fns) |
| 136 | ok(f"record fopen stack {fns[0]['stack']} >= 4112") |
| 137 | fns, _, _ = parse(omc("object\nom2\nexport fn t to long\nn = getuid\nret n\nend\n")) |
| 138 | ok(f"record getuid stack {fns[0]['stack']}") |
| 139 | |
| 140 | # Nested calls as arguments: measure whether a call's record ever exceeds frame + its own save area. |
| 141 | nest = "object\nom2\nfn g a ulong to ulong\nret add a 1\nend\nexport fn f a ulong to ulong\nret g g g a\nend\n" |
| 142 | fns, calls, _ = parse(omc(nest)) |
| 143 | print("MEASURE nested call costs", [c[3] for c in calls], "record f", fns[1]["stack"], flush=True) |
| 144 | assert fns[1]["stack"] >= max(c[3] for c in calls if c[1] == 1), "object-record-covers-calls" |
| 145 | ok("record covers its calls") |
| 146 | |
| 147 | # The module driver, built from the seeded sources by the compiler under test. |
| 148 | drv_src = b"om2\n" + (REPO / "seed/ng/sha256.om").read_bytes() + (REPO / "seed/modules/driver.om").read_bytes() |
| 149 | r = subprocess.run([OMC], input=drv_src, capture_output=True) |
| 150 | assert r.returncode == 0, r.stderr.decode() |
| 151 | DRV = OUT / "ommod" |
| 152 | DRV.write_bytes(r.stdout) |
| 153 | DRV.chmod(0o755) |
| 154 | STORE = OUT / "store" |
| 155 | STORE.mkdir() |
| 156 | |
| 157 | |
| 158 | def drv(args, status=0): |
| 159 | r = subprocess.run([DRV, *map(str, args)], capture_output=True, timeout=120) |
| 160 | assert r.returncode == status, (args, r.returncode, status, r.stdout, r.stderr) |
| 161 | return r |
| 162 | |
| 163 | |
| 164 | def build(name, text, status=0): |
| 165 | p = OUT / (name + ".om") |
| 166 | p.write_text(text) |
| 167 | h = sha(p.read_bytes()) |
| 168 | r = drv(["build", OMC, COMP, "debug", "aarch64-linux", STORE, p, h], status) |
| 169 | return h, (r.stdout.decode().split()[-1] if status == 0 else None) |
| 170 | |
| 171 | |
| 172 | def link(h, art, dest, entry, status=0): |
| 173 | return drv(["link", STORE, COMP, "debug", "aarch64-linux", h, art, "program", entry, dest], status) |
| 174 | |
| 175 | |
| 176 | def run(exe, stdin=b""): |
| 177 | return subprocess.run([str(exe)], input=stdin, capture_output=True, timeout=60) |
| 178 | |
| 179 | |
| 180 | # run: a two-module program with real I/O, against a single-unit build of the same functions. |
| 181 | IO = """export fn say b view uchar * n ulong to long |
| 182 | w = write 1 b 0 n |
| 183 | ret w |
| 184 | end |
| 185 | export fn hear b edit uchar * to long |
| 186 | n = read 0 b 0 len b |
| 187 | ret n |
| 188 | end |
| 189 | export fn mkfile b edit uchar * to long |
| 190 | fd = fopen b 0 5 577 420 |
| 191 | w = write int fd b 0 len b |
| 192 | s = fstat int fd b 0 128 |
| 193 | c = fclose int fd |
| 194 | if or lt fd 0 or lt w 0 or lt s 0 lt c 0 |
| 195 | ret 0 |
| 196 | end |
| 197 | ret long add ulong get b 48 mul ulong get b 49 256 |
| 198 | end |
| 199 | export fn later to long |
| 200 | a = monons |
| 201 | b = monons |
| 202 | ret long sub b a |
| 203 | end |
| 204 | export fn stop v int to void |
| 205 | exit v |
| 206 | end |
| 207 | """ |
| 208 | MAIN = """export fn main2 to int |
| 209 | b = new uchar 64 0 |
| 210 | n = hear b |
| 211 | w = say b ulong n |
| 212 | f = new uchar 300 0 |
| 213 | put f 0 111 |
| 214 | put f 1 104 |
| 215 | put f 2 111 |
| 216 | put f 3 115 |
| 217 | put f 4 116 |
| 218 | z = mkfile f |
| 219 | d = later |
| 220 | if lt d 0 |
| 221 | stop 5 |
| 222 | end |
| 223 | if ne z 300 |
| 224 | stop 6 |
| 225 | end |
| 226 | stop int add 10 n |
| 227 | ret 0 |
| 228 | end |
| 229 | """ |
| 230 | ioh, ioart = build("io", "om2\n" + IO) |
| 231 | calls = {"hear": "dep_hear", "say": "dep_say", "mkfile": "dep_mkfile", "later": "dep_later", "stop": "dep_stop"} |
| 232 | root = "om2\n" + "".join(f"import {a} {ioh} {e}\n" for e, a in calls.items()) |
| 233 | body = MAIN |
| 234 | for e, a in calls.items(): |
| 235 | body = re.sub(rf"(?m)(^|= ){e}\b", rf"\g<1>{a}", body) |
| 236 | rh, rart = build("root", root + body) |
| 237 | link(rh, rart, OUT / "io.elf", "main2") |
| 238 | got = run(OUT / "io.elf", b"hello module\n") |
| 239 | mono = omc("om2\n" + IO.replace("export fn", "fn") + MAIN.replace("export fn main2", "fn main") ) |
| 240 | (OUT / "mono").write_bytes(mono) |
| 241 | (OUT / "mono").chmod(0o755) |
| 242 | (OUT / "ohost").unlink() |
| 243 | want = run(OUT / "mono", b"hello module\n") |
| 244 | assert got.stdout == b"hello module\n" and got.returncode == 23, ("objhost-run", got) |
| 245 | assert (got.stdout, got.returncode) == (want.stdout, want.returncode), ("objhost-differential", got, want) |
| 246 | assert (OUT / "ohost").stat().st_size == 300, "objhost-file" |
| 247 | ok("run linked modules: stdin->stdout, fopen/write/fstat/fclose, monons, exit 23 = single-unit build") |
| 248 | |
| 249 | |
| 250 | # stack: a chain that fits 8 MiB only if the leaf's host push is ignored must be refused (37). |
| 251 | def chain(mid_bytes, host, status=0): |
| 252 | word = "fd = fopen b 0 len b 0 0\nret fd" if host else "ret long get a 0" |
| 253 | leaf = f"om2\nexport fn leaf b view uchar * to long\na = new uchar 4194304 1\n{word}\nend\n" |
| 254 | lh, la = build(f"leaf{host}{mid_bytes}", leaf) |
| 255 | mid = (f"om2\nimport dep {lh} leaf\nexport fn top to int\nm = new uchar {mid_bytes} 0\n" |
| 256 | f"put m 0 47\nput m 1 0\nr = dep part m 0 1\nret int and r 0\nend\n") |
| 257 | mh, ma = build(f"mid{host}{mid_bytes}", mid, status) |
| 258 | leafobj = parse(omc("object\n" + leaf))[0][0]["stack"] |
| 259 | return mh, ma, leafobj |
| 260 | |
| 261 | |
| 262 | # Find the frame of mid so that frame + call cost + leaf frame lands just under 8 MiB without the push. |
| 263 | midobj = lambda n: parse(omc(f"object\nom2\nextern fn dep b view uchar * to long\nexport fn top to int\nm = new uchar {n} 0\nput m 0 47\nput m 1 0\nr = dep part m 0 1\nret int and r 0\nend\n"))[1][0][3] |
| 264 | size = MIB8 - 4194304 - 4096 |
| 265 | while midobj(size) + 4194304 + 2048 > MIB8: |
| 266 | size -= 16 |
| 267 | cost = midobj(size) |
| 268 | mh, ma, leafrec = chain(size, True, 37) |
| 269 | print("MEASURE mid call cost", cost, "leaf record with fopen", leafrec, "sum", cost + leafrec, "limit", MIB8, flush=True) |
| 270 | assert cost + 4194304 <= MIB8 < cost + leafrec, "objhost-chain-shape" |
| 271 | ok("stack: chain over 8 MiB only through the host push is refused 37") |
| 272 | ph, pa, _ = chain(size, False) |
| 273 | link(ph, pa, OUT / "pure.elf", "top") |
| 274 | assert run(OUT / "pure.elf").returncode == 0, "objhost-pure-chain-runs" |
| 275 | ok("stack: same chain without the host push links and runs") |
| 276 | small = size - 8192 |
| 277 | sh_, sa, srec = chain(small, True) |
| 278 | assert midobj(small) + srec <= MIB8 |
| 279 | link(sh_, sa, OUT / "fits.elf", "top") |
| 280 | res = run(OUT / "fits.elf") |
| 281 | assert res.returncode == 0, ("objhost-deep-fopen-runs", res.returncode) |
| 282 | ok(f"stack: host push deep in an 8 MiB chain that fits links and runs (exit {res.returncode})") |
| 283 | print("OBJHOST PASS", flush=True) |