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 / v2 / dev / run.py

177 lines · 9775 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""CPU-only device-word qualification. No NVIDIA device or GPU runtime is opened."""
4import hashlib
5import os
6from pathlib import Path
7import resource
8import subprocess
9import sys
10
11ROOT = Path(__file__).resolve().parents[4]
12FIX = Path(__file__).resolve().parent
13OUT = Path(sys.argv[1] if len(sys.argv) > 1 else ROOT / 'build/native-device').resolve()
14OUT.mkdir(parents=True, exist_ok=True)
15resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
16
17def run(args, expected=0, **kw):
18 if isinstance(kw.get('input'), str):
19 kw['input'] = kw['input'].encode('latin1')
20 p = subprocess.run([str(x) for x in args], cwd=ROOT, capture_output=True, **kw)
21 # ELF bytes must not pass through universal-newline translation.
22 p.stdout = p.stdout.decode('latin1')
23 p.stderr = p.stderr.decode('latin1')
24 if p.returncode != expected:
25 print(p.stdout, p.stderr, file=sys.stderr)
26 raise RuntimeError(f'{args}: rc={p.returncode}, expected {expected}')
27 return p
28
29# Green C reference / Omega differential and ordered-store observation by another thread.
30run(['tools/native', '--host', OUT / 'good', FIX / 'hdev.om'])
31
32def caller(directory, source='dcall'):
33 exe = directory / source
34 run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror',
35 '-pthread', '-I' + str(directory), FIX / (source + '.c'), '-L' + str(directory),
36 '-Wl,-rpath,' + str(directory), '-lomega_native', '-o', exe])
37 return exe
38
39print(run([caller(OUT / 'good')], timeout=30).stdout, end='')
40print(run([caller(OUT / 'good', 'aien')], timeout=30).stdout, end='')
41print(run([caller(OUT / 'good', 'context')], timeout=30).stdout, end='')
42print(run([caller(OUT / 'good', 'context-ro')], timeout=30).stdout, end='')
43# One invocation must share a mapping runtime across separately compiled units.
44multi_units = [FIX / name for name in ('ctxnew.om', 'ctxput.om', 'ctxget.om')]
45run(['tools/native', '--host', OUT / 'multi', *multi_units])
46multi_c = (OUT / 'multi/omega_native.c').read_text()
47assert multi_c.count('uint32_t omega_native_context_create(') == 1
48print(run([caller(OUT / 'multi', 'multi')], timeout=30).stdout, end='')
49run(['tools/native', OUT / 'multi-no-host', *multi_units], expected=110)
50assert not (OUT / 'multi-no-host/libomega_native.so').exists()
51print('PASS three-unit library no-host refusal110; no library installed')
52# Each newly admitted word must still fail closed without the explicit host grant.
53# The old compiler is not silently substituted: the compiler identified by OMEGA_NATIVE_OMC2
54# compiles each unit first; this catches an unsupported compiler before interpreting refusal.
55words = {
56 'monons': 'monons', 'realns': 'realns', 'sleepns': 'sleepns long 1000',
57 'devctl': 'devctl int h uint 21531 b 0 4',
58 'mapnew': 'mapnew neg int 1 0 4096 3 34', 'mapdrop': 'mapdrop h',
59 'mapread': 'mapread h 0 b 0 4', 'mapwrite': 'mapwrite h 0 b 0 4',
60 'devcall': 'devcall int h uint 3223340587 hd 0 32 b 0 16',
61 'uvmctl': 'uvmctl int h uint 75 b 0 8', 'mapaddr': 'mapaddr h',
62 'mapget': 'mapget h 0 4', 'mapset': 'mapset h 0 4 1',
63 'maphold': 'maphold 65536 4096', 'mapbind': 'mapbind h neg int 1 0 3',
64}
65for word, expression in words.items():
66 source = OUT / (word + '.om')
67 source.write_text('note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n'
68 'om2\nexport fn test h long to long\n'
69 'b = new uchar 48 0\nhd = new uchar 32 0\nret long ' + expression + '\nend\n')
70 run([os.environ['OMEGA_NATIVE_OMC2']], input=source.read_text())
71 p = run(['tools/native', OUT / ('refuse-' + word), source], expected=110)
72 assert not (OUT / ('refuse-' + word) / 'libomega_native.so').exists()
73 print('PASS no-host negative control ' + word)
74
75# The new header/13-slot-bit runtime must reject old/unknown compiler metadata.
76pin = hashlib.sha256(Path(os.environ['OMEGA_NATIVE_OMC2']).read_bytes()).hexdigest()
77packed = (OUT / 'good/work/units.in').read_bytes()
78assert packed.count(pin.encode()) == 1
79bad = packed.replace(pin.encode(), b'0' * 64)
80gen = OUT / 'good/work/native-gen'
81assert run([gen, 'c', 'host'], input=bad.decode('latin1'), expected=110).stdout == ''
82print('PASS incompatible mapping-compiler format refused')
83reserved = OUT / 'reserved.om'
84reserved.write_text('om2\nexport fn ctx_anon to long\nret mapnew neg int 1 0 4096 3 34\nend\n')
85run(['tools/native', '--host', OUT / 'reserved', reserved], expected=110)
86assert not (OUT / 'reserved/libomega_native.so').exists()
87print('PASS context-export namespace collision refused')
88
89c = (OUT / 'good/omega_native.c').read_text()
90header = (OUT / 'good/omega_native.h').read_bytes()
91
92def library(name, text):
93 directory = OUT / name
94 directory.mkdir(exist_ok=True)
95 (directory / 'omega_native.c').write_text(text)
96 (directory / 'omega_native.h').write_bytes(header)
97 run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror',
98 '-Wno-unused-variable', '-fPIC', '-shared', '-pthread', directory / 'omega_native.c',
99 '-o', directory / 'libomega_native.so'])
100 return directory
101
102def mutant_library(name, text, source):
103 directory = library(name, text)
104 p = subprocess.run([str(caller(directory, source))], cwd=ROOT, capture_output=True, timeout=30)
105 assert p.returncode != 0, name + ' survived'
106 print('PASS ' + name + ' killed rc=' + str(p.returncode))
107
108runtime_mutants = [
109 ('entry31', 'ombr_no_entry, ombr_maps }};', 'ombr_no_entry, ombr_no_entry }};', 'dcall'),
110 ('context-generation', 'c->maps[1] = id << 26;', 'c->maps[1] = UINT64_C(1) << 26;', 'context'),
111 ('live-destroy', 'if (c->maps[4 + i * 4] != 0)', 'if (0)', 'context'),
112 ('readonly-dispatch', 'if (mprotect(rt, sizeof *rt, PROT_READ) != 0)', 'if (0)', 'context-ro'),
113]
114for name, before, after, source in runtime_mutants:
115 assert c.count(before) == 1, name + ' mutation site'
116 mutant_library(name, c.replace(before, after), source)
117
118# Rebuild the exact source into the pinned fixpoint before changing a lowerer.
119# Mutated code is deliberately framed with the original compiler metadata for
120# this negative oracle only; production generation always hashes the compiler.
121omc = Path(os.environ['OMEGA_NATIVE_OMC2']).resolve()
122src = Path(os.environ.get('OMEGA_NATIVE_OMC2_SOURCE', omc.parents[1] / 'omc/omc.om'))
123compiler_source = src.read_text()
124baseline = run([omc], input=compiler_source).stdout.encode('latin1')
125assert hashlib.sha256(baseline).hexdigest() == pin, 'mutation source is not the compiler fixpoint'
126unit_source = (FIX / 'hdev.om').read_bytes()
127
128def framed(code):
129 return (unit_source + b'\0' + ('%08d' % len(code)).encode() + code
130 + b'omega-unit hdev ' + pin.encode() + b'\n').decode('latin1')
131
132def compiled_c(name, text):
133 binary = OUT / (name + '-omc')
134 binary.write_bytes(run([omc], input=text).stdout.encode('latin1'))
135 binary.chmod(0o700)
136 code = run([binary], input=unit_source.decode()).stdout.encode('latin1')
137 return run([gen, 'c', 'host'], input=framed(code)).stdout
138
139control_code = run([omc], input=unit_source.decode()).stdout.encode('latin1')
140assert run([gen, 'c', 'host'], input=framed(control_code)).stdout == c
141compiler_mutants = [
142 ('bind-ownership', 'mload 15 11 3\nmimmed 4043309056 31 15 0\ntrapc 1 3\n',
143 'mload 15 11 3\nmimmed 4043309056 31 15 0\n'),
144 ('context-capacity', 'matconst 15 4098\ne3 3942645760 31 12 15\n',
145 'matconst 15 128\ne3 3942645760 31 12 15\n'),
146 ('handle-slot-bits', 'matconst 15 8191\n', 'matconst 15 255\n'),
147 ('failed-bind-retirement', 'trapc 1 3\nmstore 31 11 0\nmstore 31 11 1\nmstore 31 11 3\n',
148 'trapc 1 3\nmstore 31 11 1\nmstore 31 11 3\n'),
149]
150for name, before, after in compiler_mutants:
151 assert compiler_source.count(before) == 1, name + ' mutation site'
152 changed = compiled_c(name, compiler_source.replace(before, after))
153 mutant_library(name, changed, 'context')
154# Force only bind's cleanup syscall to return nonzero, while mapdrop's real
155# munmap stays unchanged. This proves recovery rather than discarding ownership.
156cleanup_site = 'mstore 15 11 3\nend\nhsys 215\nmimmed'
157assert compiler_source.count(cleanup_site) == 1
158forced = compiler_source.replace(cleanup_site, cleanup_site.replace('hsys 215', 'hsys 172'))
159control = library('cleanup-failure', compiled_c('cleanup-failure', forced))
160print(run([caller(control, 'cleanup')]).stdout, end='')
161mark = 'matconst 15 4\nmstore 15 11 3\n'
162assert forced.count(mark) == 1
163mutant_library('quarantine-bind', compiled_c('quarantine-bind', forced.replace(mark,
164 'matconst 15 0\nmstore 15 11 3\n')), 'cleanup')
165guard = 'if eq get progmode 0 0\nmimmed 4043309056 31 15 3\ntrapc 8 3\nend\n'
166assert forced.count(guard) == 2
167mutant_library('quarantine-read', compiled_c('quarantine-read', forced.replace(guard, '')), 'cleanup')
168# A function-mode ABI1 call must exercise the guard, not an oversized-view trap.
169# Exit42 identifies its short-count assertion; a launch/exact-call failure is not a kill.
170aien_guard = ('put fr add x 23 xhreq 166 x\ne = harray x 1\nt = alloc\n'
171 'matconst t get fr add x 23\ne3 3942645760 31 get fr add x 22 t\ntrapc 1 3')
172assert compiler_source.count(aien_guard) == 1
173aien_changed = compiler_source.replace(aien_guard, aien_guard.removesuffix('\ntrapc 1 3'))
174aien_mutant = library('aien-length', compiled_c('aien-length', aien_changed))
175run([caller(aien_mutant, 'aien')], expected=42, timeout=30)
176print('PASS aien-length mutant killed at short-count assertion rc=42')
177print('NATIVE-DEVICE-QUAL PASS (15 word controls, 2 ABI controls, 5 ioctl controls, 3-unit shared-context fixture, cleanup-failure control, 11 mutants; chip NOT_RUN)')