interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / seed / omc / tests / objhost / check.py

283 lines · 11533 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Host effects in native objects (DRA-542): an independent test oracle, not a linker.
3
4Usage: check.py OMC OUT_DIR. OMC is the compiler under test; the module driver is built from
5seed/ng/sha256.om + seed/modules/driver.om by the same OMC. OUT_DIR must not exist.
6Checks, 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"""
16import hashlib, os, pathlib, re, shutil, struct, subprocess, sys
17
18P = pathlib.Path
19REPO = P(__file__).resolve().parents[4]
20OMC = P(sys.argv[1]).resolve()
21OUT = P(sys.argv[2]).resolve()
22OUT.mkdir(parents=True)
23os.chdir(OUT)
24MIB8 = 8 * 1024 * 1024
25sha = lambda b: hashlib.sha256(b).hexdigest()
26COMP = sha(OMC.read_bytes())
27
28
29def ok(label):
30 print("PASS", label, flush=True)
31
32
33def 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
41def u64(b, o):
42 return struct.unpack_from("<Q", b, o)[0]
43
44
45def 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.
67SUBSET = {
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}
83OBJDUMP = shutil.which("aarch64-linux-gnu-objdump") or shutil.which("objdump")
84
85
86def 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
109for 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.
123REFUSE = {
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}
129for 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.
134fns, _, _ = parse(omc("object\nom2\nexport fn t b view uchar * to long\nfd = fopen b 0 len b 0 0\nret fd\nend\n"))
135assert fns[0]["stack"] >= 4096 + 16 and fns[0]["stack"] % 16 == 0, ("object-host-stack-record", fns)
136ok(f"record fopen stack {fns[0]['stack']} >= 4112")
137fns, _, _ = parse(omc("object\nom2\nexport fn t to long\nn = getuid\nret n\nend\n"))
138ok(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.
141nest = "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"
142fns, calls, _ = parse(omc(nest))
143print("MEASURE nested call costs", [c[3] for c in calls], "record f", fns[1]["stack"], flush=True)
144assert fns[1]["stack"] >= max(c[3] for c in calls if c[1] == 1), "object-record-covers-calls"
145ok("record covers its calls")
146
147# The module driver, built from the seeded sources by the compiler under test.
148drv_src = b"om2\n" + (REPO / "seed/ng/sha256.om").read_bytes() + (REPO / "seed/modules/driver.om").read_bytes()
149r = subprocess.run([OMC], input=drv_src, capture_output=True)
150assert r.returncode == 0, r.stderr.decode()
151DRV = OUT / "ommod"
152DRV.write_bytes(r.stdout)
153DRV.chmod(0o755)
154STORE = OUT / "store"
155STORE.mkdir()
156
157
158def 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
164def 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
172def link(h, art, dest, entry, status=0):
173 return drv(["link", STORE, COMP, "debug", "aarch64-linux", h, art, "program", entry, dest], status)
174
175
176def 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.
181IO = """export fn say b view uchar * n ulong to long
182w = write 1 b 0 n
183ret w
184end
185export fn hear b edit uchar * to long
186n = read 0 b 0 len b
187ret n
188end
189export fn mkfile b edit uchar * to long
190fd = fopen b 0 5 577 420
191w = write int fd b 0 len b
192s = fstat int fd b 0 128
193c = fclose int fd
194if or lt fd 0 or lt w 0 or lt s 0 lt c 0
195ret 0
196end
197ret long add ulong get b 48 mul ulong get b 49 256
198end
199export fn later to long
200a = monons
201b = monons
202ret long sub b a
203end
204export fn stop v int to void
205exit v
206end
207"""
208MAIN = """export fn main2 to int
209b = new uchar 64 0
210n = hear b
211w = say b ulong n
212f = new uchar 300 0
213put f 0 111
214put f 1 104
215put f 2 111
216put f 3 115
217put f 4 116
218z = mkfile f
219d = later
220if lt d 0
221stop 5
222end
223if ne z 300
224stop 6
225end
226stop int add 10 n
227ret 0
228end
229"""
230ioh, ioart = build("io", "om2\n" + IO)
231calls = {"hear": "dep_hear", "say": "dep_say", "mkfile": "dep_mkfile", "later": "dep_later", "stop": "dep_stop"}
232root = "om2\n" + "".join(f"import {a} {ioh} {e}\n" for e, a in calls.items())
233body = MAIN
234for e, a in calls.items():
235 body = re.sub(rf"(?m)(^|= ){e}\b", rf"\g<1>{a}", body)
236rh, rart = build("root", root + body)
237link(rh, rart, OUT / "io.elf", "main2")
238got = run(OUT / "io.elf", b"hello module\n")
239mono = 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()
243want = run(OUT / "mono", b"hello module\n")
244assert got.stdout == b"hello module\n" and got.returncode == 23, ("objhost-run", got)
245assert (got.stdout, got.returncode) == (want.stdout, want.returncode), ("objhost-differential", got, want)
246assert (OUT / "ohost").stat().st_size == 300, "objhost-file"
247ok("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).
251def 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.
263midobj = 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]
264size = MIB8 - 4194304 - 4096
265while midobj(size) + 4194304 + 2048 > MIB8:
266 size -= 16
267cost = midobj(size)
268mh, ma, leafrec = chain(size, True, 37)
269print("MEASURE mid call cost", cost, "leaf record with fopen", leafrec, "sum", cost + leafrec, "limit", MIB8, flush=True)
270assert cost + 4194304 <= MIB8 < cost + leafrec, "objhost-chain-shape"
271ok("stack: chain over 8 MiB only through the host push is refused 37")
272ph, pa, _ = chain(size, False)
273link(ph, pa, OUT / "pure.elf", "top")
274assert run(OUT / "pure.elf").returncode == 0, "objhost-pure-chain-runs"
275ok("stack: same chain without the host push links and runs")
276small = size - 8192
277sh_, sa, srec = chain(small, True)
278assert midobj(small) + srec <= MIB8
279link(sh_, sa, OUT / "fits.elf", "top")
280res = run(OUT / "fits.elf")
281assert res.returncode == 0, ("objhost-deep-fopen-runs", res.returncode)
282ok(f"stack: host push deep in an 8 MiB chain that fits links and runs (exit {res.returncode})")
283print("OBJHOST PASS", flush=True)