interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / tests / native / test_freestanding_om2.py

238 lines · 13752 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Pure OM-2 native binding: array/out transport, private f32/f64, strict no-libc imports,
3hosted differentials, bounded declaration scanning, and attributed runtime/refusal mutants."""
4import json
5import os
6from pathlib import Path
7import shutil
8import subprocess
9import tempfile
10import sys
11
12ROOT = Path(__file__).resolve().parents[2]
13ALLOWED = {'_GLOBAL_OFFSET_TABLE_'}
14UNITS = (ROOT / 'tests/native/v2/sha256-om2.om', ROOT / 'tests/native/v2/fsout.om',
15 ROOT / 'tests/native/freestanding/f64.om')
16# FIPS 180-2/180-4 examples: empty, "abc", the 448-bit message, and 1,000,000 'a'.
17WANT = {
18 'empty': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
19 'abc': 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
20 '448': '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1',
21 'million': 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0',
22}
23# What the caller prints with the copy-back dropped: its 0xa5 pre-call fill, unchanged.
24MUTANT = {name: 'a5' * 32 for name in WANT}
25
26
27def run(args, **kw):
28 p = subprocess.run([str(a) for a in args], capture_output=True, **kw)
29 if p.returncode:
30 raise AssertionError(f'{args}: exit {p.returncode}\n{p.stdout!r}\n{p.stderr!r}')
31 return p.stdout
32
33
34def mutate_fq(source, old, new):
35 """Change exactly one freestanding OM-2 template site, never the hosted runtime."""
36 lines = source.splitlines()
37 for i, line in enumerate(lines):
38 if line.startswith('text fq '):
39 parts = json.loads(line[len('text fq '):]).split('~')
40 assert parts[0].count(old) == 1, old
41 parts[0] = parts[0].replace(old, new)
42 lines[i] = 'text fq ' + json.dumps('~'.join(parts))
43 return '\n'.join(lines) + '\n'
44 raise AssertionError('freestanding OM-2 runtime template missing')
45
46
47def drop_copyback(source):
48 return mutate_fq(source, 'ombr2_copy_bytes(o[i].dst, buf[i], o[i].n);',
49 '(void)ombr2_copy_bytes, (void)buf[i];')
50
51
52def main():
53 with tempfile.TemporaryDirectory(prefix='bridge-freestanding-om2-') as td:
54 t = Path(td)
55 out = t / 'lib'
56 run([ROOT / 'tools/native', '--freestanding', out,
57 *UNITS])
58 assert not (out / 'libomega_native.so').exists()
59 defined = set()
60 imports = {}
61 for obj in ('omega_native.o', 'omega_api_defs.o'):
62 imports[obj] = {line.split()[-1]
63 for line in run(['nm', '-u', out / obj]).decode().splitlines() if line.split()}
64 defined |= {line.split()[-1]
65 for line in run(['nm', '--defined-only', '-g', out / obj]).decode().splitlines()
66 if line.split()}
67 sections = run(['readelf', '-SW', out / obj]).decode()
68 assert '.tbss' not in sections and '.tdata' not in sections
69 for obj, names in imports.items():
70 assert not names - ALLOWED - defined, (obj, names - ALLOWED - defined)
71 linked = t / 'freestanding.o'
72 run(['cc', '-r', '-nostdlib', out / 'omega_native.o', out / 'omega_api_defs.o',
73 '-o', linked])
74 unresolved = {line.split()[-1]
75 for line in run(['nm', '-u', linked]).decode().splitlines() if line.split()}
76 assert not unresolved - {'_GLOBAL_OFFSET_TABLE_'}, ('no-libc link imports', unresolved)
77 print('PASS OM-2 freestanding no-libc link: native + API objects have no runtime imports')
78 assert not (out / 'omega_api.h').exists()
79 # The freestanding object compiled as the consumer would, with the required flags.
80 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-Wmissing-prototypes',
81 '-ffreestanding', '-fno-builtin', '-fno-stack-protector',
82 '-include', out / 'omega_native.h', '-c', out / 'omega_native.c', '-o', t / 'again.o'])
83 caller = t / 'fsom2'
84 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', out,
85 ROOT / 'tests/native/v2/fsom2.c', out / 'omega_native.o', out / 'omega_api_defs.o',
86 '-o', caller])
87 lines = run([caller]).decode().splitlines()
88 got = dict(line.split() for line in lines if line.split()[0] in WANT)
89 assert got == WANT, got
90 assert 'badarg 32 1' in lines and 'outok 0 2 7 1' in lines and 'outtrap 5 1' in lines
91 assert 'threads 1' in lines and 'floatbits 1' in lines
92 print('PASS OM-2 freestanding: FIPS 180-4 digests, bad-arg and trap leave out untouched, four threads')
93 hosted = t / 'hosted'
94 run([ROOT / 'tools/native', hosted,
95 *UNITS])
96 hcaller = t / 'hfsom2'
97 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', hosted,
98 ROOT / 'tests/native/v2/fsom2.c', hosted / 'omega_api_defs.c', '-L', hosted,
99 f'-Wl,-rpath,{hosted}', '-lomega_native', '-o', hcaller])
100 assert run([hcaller]).decode().splitlines() == lines
101 print('PASS OM-2 freestanding outputs exactly match hosted FIPS/out/trap/thread controls')
102 # A trap instruction: 133 when the shell reports it, -5 (SIGTRAP) when Python does.
103 p = subprocess.run([caller, 'trap'], capture_output=True)
104 assert p.returncode in (133, -5) and not p.stdout, (p.returncode, p.stdout)
105 print('PASS fapic wrapper traps on a nonzero status (exit 133)')
106
107 # Negative control: drop the copy-back from the runtime. The digest checks must then fail,
108 # because the caller's buffer keeps its pre-call fill.
109 mutant = t / 'mutant'
110 (mutant / 'tools').mkdir(parents=True)
111 (mutant / 'src').mkdir()
112 shutil.copy2(ROOT / 'tools/native', mutant / 'tools/native')
113 (mutant / 'src/native.om').write_text(drop_copyback((ROOT / 'src/native.om').read_text()))
114 mout = t / 'mutlib'
115 run([mutant / 'tools/native', '--freestanding', mout,
116 *UNITS])
117 mcaller = t / 'mfsom2'
118 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', mout,
119 ROOT / 'tests/native/v2/fsom2.c', mout / 'omega_native.o', mout / 'omega_api_defs.o',
120 '-o', mcaller])
121 mp = subprocess.run([mcaller], capture_output=True)
122 mlines = mp.stdout.decode().splitlines()
123 mgot = dict(line.split() for line in mlines if line.split() and line.split()[0] in WANT)
124 # Every digest is the untouched pre-call fill: a crash or partial run is not a detection.
125 assert mp.returncode == 0 and mgot == MUTANT, (mp.returncode, mgot)
126 print('PASS mutant runtime (copy-back dropped) leaves the pre-call fill in every digest')
127 good = (ROOT / 'src/native.om').read_text()
128 for name, old, new, witness in (
129 ('wrong-zero', 'd[i] = 0;', 'd[i] = 0xa5;', 'outok 0 2 7 0'),
130 ('copy-on-trap', 'if (s == OMEGA_OK) {', 'if (1) {', 'outtrap 5 0')):
131 tree = t / name
132 (tree / 'tools').mkdir(parents=True)
133 (tree / 'src').mkdir()
134 shutil.copy2(ROOT / 'tools/native', tree / 'tools/native')
135 (tree / 'src/native.om').write_text(mutate_fq(good, old, new))
136 lib = tree / 'lib'
137 run([tree / 'tools/native', '--freestanding', lib, *UNITS])
138 exe = tree / 'caller'
139 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread',
140 '-I', lib, ROOT / 'tests/native/v2/fsom2.c', lib / 'omega_native.o',
141 lib / 'omega_api_defs.o', '-o', exe])
142 result = subprocess.run([exe], capture_output=True)
143 assert result.returncode == 0 and witness in result.stdout.decode().splitlines(), (
144 name, result.returncode, result.stdout, result.stderr)
145 print(f'PASS {name} runtime mutant caught by exact witness: {witness}')
146
147 # Force a real undefined libc helper through a volatile function pointer: compilation
148 # alone cannot count as detection. The strict import gate must name it and preserve out.
149 tree = t / 'libc-import'
150 (tree / 'tools').mkdir(parents=True)
151 (tree / 'src').mkdir()
152 shutil.copy2(ROOT / 'tools/native', tree / 'tools/native')
153 imported = ('(void)d;\n'
154 ' void *(*volatile move)(void *, const void *, __SIZE_TYPE__) = __builtin_memmove;\n'
155 ' (void)move(p, s, n);')
156 (tree / 'src/native.om').write_text(mutate_fq(
157 good, 'for (uint64_t i = 0; i < n; i++) d[i] = s[i];', imported))
158 before = (out / 'omega_native.o').read_bytes()
159 result = subprocess.run([tree / 'tools/native', '--freestanding', out, *UNITS],
160 capture_output=True)
161 assert result.returncode == 1 and b'imports refused by inspection' in result.stderr
162 assert b'memmove' in result.stderr and (out / 'omega_native.o').read_bytes() == before
163 print('PASS libc-copy import mutant refused by nm gate; installed object unchanged')
164
165 # Generator-only malformed-frame controls reuse real pinned code; none is executed.
166 import hashlib
167 source = UNITS[2].read_text()
168 code = (out / 'work/f64.bin').read_bytes()
169 pin = hashlib.sha256(Path(os.environ['OMEGA_NATIVE_OMC2']).read_bytes()).hexdigest()
170
171 def scanner_frame(body, generator=out / 'work/native-gen'):
172 frame = body.encode() + b'\0' + f'{len(code):08d}'.encode() + code
173 frame += f'omega-unit f64 {pin}\n'.encode()
174 return subprocess.run([generator, 'freest'], input=frame, capture_output=True)
175
176 # These are scanner-only frames, never executed with their deliberately reused code.
177 # The registry has 1024 DISTINCT names: root + parameter + 1022 assignment names.
178 edge = 'om2\nfn edge x ulong to ulong\n'
179 edge += ''.join(f'n{i} = 0\n' for i in range(1022))
180 edge += 'n0 = 1\nret x\nend\n' # A duplicate at full capacity must not consume a slot.
181 repeated = 'om2\nfn repeat x ulong to ulong\n' + 'x = add x 0\n' * 1025 + 'ret x\nend\n'
182 named = source.replace('om2\n', 'om2\nconst CAP ulong 4\n', 1)
183 named += ('fn named w view ulong CAP x ulong to ulong\nret x\nend\n'
184 'fn freshnamed w edit uint CAP fresh x ulong to void\n'
185 'put w 0 0\nput w 1 0\nput w 2 0\nput w 3 0\nret\nend\n'
186 'layout box 8\nfield value ulong at 0 little\nend\n'
187 'fn boxed c edit box x ulong to ulong\nret x\nend\n')
188 results = [(label, scanner_frame(body)) for label, body in
189 (('duplicate-at-capacity', edge), ('repeated-name', repeated),
190 ('named-extents', named))]
191 for label, result in results:
192 assert result.returncode == 0 and result.stdout, (
193 label, result.returncode, result.stdout, result.stderr)
194 too_many = edge.replace('ret x\n', 'overflow = 0\nret x\n')
195 result = scanner_frame(too_many)
196 assert result.returncode == 110 and not result.stdout, (
197 'distinct-name-overflow', result.returncode, result.stdout, result.stderr)
198 print('PASS distinct-name boundary, duplicate at full capacity, repeated assignments and named/fresh extents')
199 dedup = ('for j ulong n\nif eq fmatch k get fns j get fne j 1\n'
200 'ret\nend\nend\n')
201 assert good.count(dedup) == 1
202 generator = t / 'dedup-mutant-gen'
203 generator.write_bytes(run([os.environ['OMEGA_NATIVE_OMC']],
204 input=good.replace(dedup, '').encode()))
205 generator.chmod(0o755)
206 result = scanner_frame(repeated, generator)
207 assert result.returncode == 110 and not result.stdout, (
208 'name-dedup-mutant', result.returncode, result.stdout, result.stderr)
209 print('PASS name-dedup mutant restores repeated-name refusal and is caught')
210 refusals = {
211 'public-f64': source.replace('mode ulong', 'mode f64'),
212 'private-f128-type': source.replace('fn average a f64', 'fn average a f128'),
213 'malformed-f32-literal': source.replace('2.0e+0', '2.0e+f32'),
214 'private-f128-after-fresh': source + (
215 'fn hidden w edit uint 4 fresh x f128 to void\n'
216 'put w 0 0\nput w 1 0\nput w 2 0\nput w 3 0\nret\nend\n'),
217 'private-f128-after-named-extent': source.replace(
218 'om2\n', 'om2\nconst CAP ulong 4\n', 1) + (
219 'fn hidden w view ulong CAP x f128 to void\nret\nend\n'),
220 'malformed-f64-literal': source.replace('2.0e+0', '2.0e+'),
221 'unused-host-helper': source + 'fn hidden to ulong\nret monons\nend\n',
222 'global': source.replace('om2\n', 'om2\nglobal storage ulong 1\n', 1),
223 }
224 for name, refused in refusals.items():
225 assert refused != source
226 frame = refused.encode() + b'\0' + f'{len(code):08d}'.encode() + code
227 frame += f'omega-unit f64 {pin}\n'.encode()
228 result = subprocess.run([out / 'work/native-gen', 'freest'],
229 input=frame, capture_output=True)
230 assert result.returncode == 110 and not result.stdout, (
231 name, result.returncode, result.stdout, result.stderr)
232 print('PASS OM-2 public floats, unsupported private type, malformed literals, unused host helper and storage refused before output')
233 print(run([sys.executable, ROOT / 'tests/native/test_freestanding_f32.py',
234 '--out', t / 'f32']).decode(), end='')
235
236
237if __name__ == '__main__':
238 main()