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.py

171 lines · 8892 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Exercise pure-scalar transport, source refusals, and the GPU_FS_LINK import gate."""
3import os
4from pathlib import Path
5import shutil
6import subprocess
7import tempfile
8
9ROOT = Path(__file__).resolve().parents[2]
10OMC = os.environ['OMEGA_NATIVE_OMC']
11ALLOWED = {'_GLOBAL_OFFSET_TABLE_'}
12# Shared with tests/native/x86/suite.py, which runs the same caller under qemu-x86_64.
13EPOCH = 'fn guard n ulong to ulong\nif eq n 18446744073709551615\ntrap 1\nend\nret n\nend\nfn epoch n ulong to ulong\nx = guard n\nret add x 1\nend\n'
14CALLER = '''#include "omega_native.h"
15#include <pthread.h>
16#include <stdint.h>
17static pthread_barrier_t barrier;
18static void *call(void *arg) {
19 (void)arg;
20 pthread_barrier_wait(&barrier);
21 for (unsigned i = 0; i < 10000; ++i) {
22 uint64_t v = 17;
23 if (omega_epoch(&v, UINT64_MAX) != 1 || v != 17) return (void *)1;
24 if (omega_epoch(&v, 1) || v != 2) return (void *)1;
25 if (omega_smadd(&v, UINT64_C(0x7fffffffffffffff), 2, 0) != 1 || v != 2) return (void *)1;
26 if (omega_smadd(&v, 3, 5, 7) || v != 22) return (void *)1;
27 }
28 return 0;
29}
30int main(void) {
31 pthread_t threads[4];
32 if (omega_epoch(0, 1) != OMEGA_BAD_ARG) return 1;
33 if (pthread_barrier_init(&barrier, 0, 4)) return 1;
34 for (unsigned i = 0; i < 4; ++i) if (pthread_create(&threads[i], 0, call, 0)) return 1;
35 for (unsigned i = 0; i < 4; ++i) { void *v; if (pthread_join(threads[i], &v) || v) return 1; }
36 return pthread_barrier_destroy(&barrier) != 0;
37}
38'''
39
40
41def run(args, **kw):
42 p = subprocess.run([str(a) for a in args], capture_output=True, **kw)
43 if p.returncode:
44 raise AssertionError(f'{args}: exit {p.returncode}\n{p.stdout!r}\n{p.stderr!r}')
45 return p.stdout
46
47
48def imports(obj):
49 return {line.split()[-1] for line in run(['nm', '-u', obj]).decode().splitlines() if line.split()}
50
51
52def main():
53 with tempfile.TemporaryDirectory(prefix='bridge-freestanding-') as td:
54 t = Path(td)
55 epoch = t / 'epoch.om'
56 epoch.write_text(EPOCH)
57 out = t / 'lib'
58 run([ROOT / 'tools/native', '--freestanding', out, epoch, ROOT / 'tests/native/smadd.om'])
59 assert not imports(out / 'omega_native.o') - ALLOWED
60 linked = t / 'freestanding.o'
61 run(['cc', '-r', '-nostdlib', out / 'omega_native.o', '-o', linked])
62 assert not imports(linked) - ALLOWED
63 assert '.tbss' not in run(['readelf', '-SW', linked]).decode()
64 assert '.tdata' not in run(['readelf', '-SW', linked]).decode()
65 assert not (out / 'libomega_native.so').exists()
66 assert not (out / 'omega_native.py').exists()
67 caller = t / 'caller.c'
68 caller.write_text(CALLER)
69 run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', out, caller, linked, '-o', t / 'caller'])
70 run([t / 'caller'])
71 print('PASS freestanding epoch increment/MAX trap, nested trap unwind, signed trap and four-thread isolation; GPU_FS_LINK imports and no TLS')
72 gen = out / 'work/native-gen'
73 code = (out / 'work/epoch.bin').read_bytes()
74 refusals = {
75 'global': 'global a ulong 1\nfn epoch n ulong to ulong\nret n\nend\n',
76 'text': 'text a "a"\nfn epoch n ulong to ulong\nret n\nend\n',
77 'array': 'fn epoch a view ulong 1 to ulong\nret get a 0\nend\n',
78 'local-array': 'fn epoch n ulong to ulong\na = new ulong 1 0\nret n\nend\n',
79 'host': 'fn epoch n ulong to ulong\nr = getpid\nret n\nend\n',
80 'exit': 'fn epoch n ulong to ulong\nexit 0\nret n\nend\n',
81 'hidden-host-helper': 'fn hidden to ulong\nret monons\nend\nfn epoch n ulong to ulong\nret n\nend\n',
82 # OM-2 itself is accepted (tests/native/test_freestanding_om2.py); a frame without the
83 # omega-unit trailer is not.
84 'om2-no-trailer': 'om2\nfn epoch n ulong to ulong\nret n\nend\n',
85 }
86 for name, source in refusals.items():
87 frame = source.encode() + b'\0' + f'{len(code):08d}'.encode() + code
88 p = subprocess.run([gen, 'freest'], input=frame, capture_output=True)
89 assert p.returncode == 110 and not p.stdout, (name, p.returncode, p.stdout)
90 print('PASS freestanding refuses arrays, storage, text, host effects including unused helper and an OM-2 frame without its trailer before any output')
91 # Mutate the .om emitter, not a production C implementation. The normal tools/native gate
92 # must refuse an actual pthread import and leave an already installed library untouched.
93 mutant = t / 'mutant'
94 (mutant / 'tools').mkdir(parents=True)
95 (mutant / 'src').mkdir()
96 shutil.copy2(ROOT / 'tools/native', mutant / 'tools/native')
97 source = (ROOT / 'src/native.om').read_text()
98 import json
99 lines = source.splitlines()
100 for i, line in enumerate(lines):
101 if line.startswith('text fp '):
102 runtime = json.loads(line[len('text fp '):])
103 runtime += '#include <pthread.h>\npthread_t ombr_mutant(void);\npthread_t ombr_mutant(void) { return pthread_self(); }\n'
104 lines[i] = 'text fp ' + json.dumps(runtime)
105 break
106 else:
107 raise AssertionError('freestanding runtime template missing')
108 (mutant / 'src/native.om').write_text('\n'.join(lines) + '\n')
109 before = (out / 'omega_native.o').read_bytes()
110 p = subprocess.run([mutant / 'tools/native', '--freestanding', out, epoch], capture_output=True)
111 assert p.returncode != 0 and b'pthread_self' in p.stderr and b'imports refused' in p.stderr, p.stderr
112 assert (out / 'omega_native.o').read_bytes() == before
113 print('PASS pthread-import emitter mutant rejected by freestanding gate, installed object unchanged')
114 # Inspector failures are refusals, not an empty, implicitly accepted symbol set.
115 fakebin = t / 'fakebin'
116 fakebin.mkdir()
117 inspectenv = os.environ.copy()
118 inspectenv['PATH'] = str(fakebin) + os.pathsep + inspectenv['PATH']
119 for command, status in (('nm', 1), ('nm', 127), ('awk', 1)):
120 fake = fakebin / command
121 fake.write_text(f'#!/bin/sh\nexit {status}\n')
122 fake.chmod(0o755)
123 p = subprocess.run([ROOT / 'tools/native', '--freestanding', out, epoch],
124 env=inspectenv, capture_output=True)
125 assert p.returncode != 0 and b'inspection' in p.stderr, p.stderr
126 assert (out / 'omega_native.o').read_bytes() == before
127 fake.unlink()
128 print('PASS failing/missing symbol inspector and failing import filter refuse; installed object unchanged')
129
130 # Inject a source replacement just after the real, still-pinned compiler
131 # returns. No timing race and no fake compiler/hash oracle are involved.
132 race = t / 'race-tool'
133 (race / 'tools').mkdir(parents=True)
134 (race / 'src').mkdir()
135 shutil.copy2(ROOT / 'src/native.om', race / 'src/native.om')
136 driver = (ROOT / 'tools/native').read_text()
137 marker = ' "$OMC" < "$src" > "$W/work/$b.bin"'
138 assert marker in driver
139 driver = driver.replace(marker, marker + '\n cp -- "$RACE_PURE" "$u"')
140 target = t / 'race.om'
141 unsafe = b'fn race n ulong to ulong\na = new ulong 1 0\nret n\nend\n'
142 safe = b'fn race n ulong to ulong\nret n\nend\n'
143 replacement = t / 'pure.om'
144 replacement.write_bytes(safe)
145 raceenv = os.environ.copy()
146 raceenv['RACE_PURE'] = str(replacement)
147 script = race / 'tools/native'
148 script.write_text(driver)
149 script.chmod(0o755)
150 target.write_bytes(unsafe)
151 p = subprocess.run([script, '--freestanding', out, target], env=raceenv, capture_output=True)
152 assert p.returncode == 110 and b'refused' in p.stderr, p.stderr
153 assert target.read_bytes() == safe
154 assert (out / 'omega_native.o').read_bytes() == before
155 # Restore the old reread defect: now the exact same swap incorrectly
156 # admits non-pure machine code under the replacement's pure source.
157 unsnapshotted = driver.replace('src=$W/work/$b.om', 'src=$u')
158 assert unsnapshotted != driver
159 script.write_text(unsnapshotted)
160 target.write_bytes(unsafe)
161 raceout = t / 'race-mutant-output'
162 run([script, '--freestanding', raceout, target], env=raceenv)
163 frame = (raceout / 'work/units.in').read_bytes()
164 actualsource, payload = frame.split(b'\0', 1)
165 assert actualsource == safe
166 assert payload[8:] == run([OMC], input=unsafe)
167 print('PASS source-swap control refuses original non-pure snapshot; reread mutant admits mismatched source/code and is caught')
168
169
170if __name__ == '__main__':
171 main()