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 / x86 / device.py

199 lines · 10386 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Run the unchanged AArch64 fake-device C fixtures on x86 under pinned QEMU.
4No NVIDIA devices are opened. Instruction controls do not model WC reordering.
5"""
6import hashlib
7import os
8from pathlib import Path
9import resource
10import shutil
11import subprocess
12import sys
13
14ROOT = Path(__file__).resolve().parents[3]
15FIX = ROOT / 'tests/native/v2/dev'
16OUT = Path(sys.argv[1] if len(sys.argv) > 1 else ROOT / 'build/native-x86-device').resolve()
17OUT.mkdir(parents=True, exist_ok=True)
18resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
19CC = os.environ.get('X86_CC', 'x86_64-linux-gnu-gcc')
20OMC = Path(os.environ['OMEGA_NATIVE_X86_OMC']).resolve()
21QEMU = os.environ['QEMU_X86_64']
22SYSROOT = os.environ.get('X86_SYSROOT', '/usr/x86_64-linux-gnu')
23ENV = dict(os.environ, CC=CC)
24serial = 0
25
26
27def run(args, expected=0, **kw):
28 global serial
29 p = subprocess.run([str(x) for x in args], cwd=ROOT, capture_output=True, env=ENV, **kw)
30 serial += 1
31 (OUT / ('%04d.log' % serial)).write_bytes(
32 ('COMMAND ' + ' '.join(str(x) for x in args) + '\nRC ' + str(p.returncode) + '\n').encode()
33 + p.stdout + b'\nSTDERR\n' + p.stderr)
34 if expected is not None and p.returncode != expected:
35 raise RuntimeError(f'{args}: rc={p.returncode}, expected={expected}; log {serial:04d}')
36 return p
37
38
39def guest(exe, expected=0):
40 return run([QEMU, '-L', SYSROOT, exe], expected, timeout=45)
41
42
43def library(name, text):
44 d = OUT / name
45 d.mkdir(exist_ok=True)
46 (d / 'omega_native.c').write_text(text)
47 (d / 'omega_native.h').write_bytes((OUT / 'good/omega_native.h').read_bytes())
48 run([CC, '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-Wno-unused-variable',
49 '-fPIC', '-shared', '-pthread', d / 'omega_native.c', '-o', d / 'libomega_native.so'])
50 return d
51
52
53def caller(d, name):
54 source = FIX / (name + '.c') if name != 'failed-cleanup' else Path(__file__).with_name(name + '.c')
55 exe = d / name
56 oracle = ['-DOMEGA_AIEN_QEMU10_ORACLE'] if name == 'aien' else []
57 run([CC, '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', *oracle, '-I' + str(d),
58 source, '-L' + str(d), '-Wl,-rpath,' + str(d), '-lomega_native', '-o', exe])
59 return exe
60
61
62assert b'10.0.14' in run([QEMU, '--version']).stdout.splitlines()[0], 'QEMU oracle version'
63print('QEMU sha256=' + hashlib.sha256(Path(shutil.which(QEMU)).read_bytes()).hexdigest())
64print(run([CC, '--version']).stdout.decode().splitlines()[0])
65run(['tools/native', '--host', '--target', 'x86linux', OUT / 'good', FIX / 'hdev.om'])
66for name in ['dcall', 'context', 'context-ro']:
67 print(guest(caller(OUT / 'good', name)).stdout.decode(), end='')
68aien = run([QEMU, '-strace', '-L', SYSROOT, caller(OUT / 'good', 'aien')], timeout=45)
69for request in ['80704110', 'c0304121', 'c0184122', 'c0484123', 'c0184124']:
70 assert aien.stderr.count(('ioctl(-1,0x' + request + ',').encode()) == 2, request + ' ioctl traversal count'
71assert aien.stderr.count(b'ioctl(-1,') == 10, 'short/long count reached ioctl'
72print(aien.stdout.decode(), end='')
73print('PASS ten exact QEMU ioctl traversals; invalid counts trap before ioctl')
74
75multi = OUT / 'multi'
76run(['tools/native', '--host', '--target', 'x86linux', multi,
77 *[FIX / name for name in ['ctxnew.om', 'ctxput.om', 'ctxget.om']]])
78assert (multi / 'omega_native.c').read_text().count('uint32_t omega_native_context_create(') == 1
79print(guest(caller(multi, 'multi')).stdout.decode(), end='')
80assert run([multi / 'work/native-gen', 'c', 'x86linux'], 110,
81 input=(multi / 'work/units.in').read_bytes()).stdout == b''
82print('PASS three-unit context library has one context API and refuses no-host mode')
83
84pin = hashlib.sha256(OMC.read_bytes()).hexdigest()
85print('COMPILER sha256=' + pin)
86packed = (OUT / 'good/work/units.in').read_bytes()
87gen = OUT / 'good/work/native-gen'
88assert packed.count(pin.encode()) == 1
89assert run([gen, 'c', 'x86host'], 110, input=packed.replace(pin.encode(), b'0' * 64)).stdout == b''
90print('PASS incompatible mapping-compiler format refused')
91
92reserved = OUT / 'reserved.om'
93reserved.write_text('om2\nexport fn ctx_anon to long\nret mapnew neg int 1 0 4096 3 34\nend\n')
94run(['tools/native', '--host', '--target', 'x86linux', OUT / 'reserved', reserved], 110)
95assert not (OUT / 'reserved/libomega_native.so').exists()
96print('PASS context-export namespace collision refused')
97run(['tools/native', '--host', '--target', 'x86linux', '--freestanding',
98 OUT / 'freestanding', FIX / 'hdev.om'], 110)
99assert not (OUT / 'freestanding').exists()
100print('PASS hosted freestanding combination refused before output')
101words = {
102 'monons': 'monons', 'realns': 'realns', 'sleepns': 'sleepns long 1000',
103 'devctl': 'devctl int h uint 21531 b 0 4',
104 'mapnew': 'mapnew neg int 1 0 4096 3 34', 'mapdrop': 'mapdrop h',
105 'mapread': 'mapread h 0 b 0 4', 'mapwrite': 'mapwrite h 0 b 0 4',
106 'devcall': 'devcall int h uint 3223340587 hd 0 32 b 0 16',
107 'uvmctl': 'uvmctl int h uint 75 b 0 8', 'mapaddr': 'mapaddr h',
108 'mapget': 'mapget h 0 4', 'mapset': 'mapset h 0 4 1',
109 'maphold': 'maphold 65536 4096', 'mapbind': 'mapbind h neg int 1 0 3',
110}
111
112
113def frame(source, code):
114 return source + b'\0' + ('%08d' % len(code)).encode() + code + b'omega-unit hdev ' + pin.encode() + b'\n'
115
116
117for word, expression in words.items():
118 source = ('om2\nexport fn test h long to long\nb = new uchar 48 0\nhd = new uchar 32 0\n'
119 'ret long ' + expression + '\nend\n').encode()
120 code = run([OMC], input=b'target x86linux\n' + source).stdout
121 assert run([gen, 'c', 'x86linux'], 110, input=frame(source, code)).stdout == b''
122 print('PASS no-host negative control ' + word)
123c = (OUT / 'good/omega_native.c').read_text()
124for name, before, after, fixture in [
125 ('entry31', 'ombr_no_entry, ombr_maps }};', 'ombr_no_entry, ombr_no_entry }};', 'dcall'),
126 ('context-generation', 'c->maps[1] = id << 26;', 'c->maps[1] = UINT64_C(1) << 26;', 'context'),
127 ('live-destroy', 'if (c->maps[4 + i * 4] != 0)', 'if (0)', 'context'),
128 ('readonly-dispatch', 'if (mprotect(rt, sizeof *rt, PROT_READ) != 0)', 'if (0)', 'context-ro'),
129]:
130 assert c.count(before) == 1, name + ' site'
131 p = guest(caller(library(name, c.replace(before, after)), fixture), None)
132 assert p.returncode != 0, name + ' survived'
133 print('PASS ' + name + ' mutant killed rc=' + str(p.returncode))
134
135src = Path(os.environ.get('OMEGA_NATIVE_X86_SOURCE', OMC.parents[1] / 'omc/omc.om'))
136compiler = src.read_text()
137assert hashlib.sha256(run([OMC], input=compiler.encode()).stdout).hexdigest() == pin, 'source fixpoint'
138unit = (FIX / 'hdev.om').read_bytes()
139control = run([OMC], input=b'target x86linux\n' + unit).stdout
140assert run([gen, 'c', 'x86host'], input=frame(unit, control)).stdout.decode() == c
141assert control.count(b'\x0f\xae\xf0') == 11, 'five ordered accesses plus cpufence'
142
143
144def emit(name, changed):
145 binary = OUT / (name + '-omc')
146 binary.write_bytes(run([OMC], input=changed.encode()).stdout)
147 binary.chmod(0o700)
148 code = run([binary], input=b'target x86linux\n' + unit).stdout
149 text = run([gen, 'c', 'x86host'], input=frame(unit, code)).stdout.decode()
150 return code, text
151
152
153for name, before, after, fixture in [
154 ('wrong-ioctl', 'xhcall 16\nxhdone dst x 0\nret\n', 'xhcall 39\nxhdone dst x 0\nret\n', 'dcall'),
155 ('bind-ownership', 'xmem 139 0 13 24\nxrr 133 0 0\nxtrap 1 3\nxsp 1 32\n',
156 'xmem 139 0 13 24\nxrr 133 0 0\nxsp 1 32\n', 'context'),
157 ('context-capacity', 'xhcmp 0 4098\nxtrap 8 3\nxmem 139 0 13 16\n',
158 'xhcmp 0 128\nxtrap 8 3\nxmem 139 0 13 16\n', 'context'),
159 ('failed-bind-retirement', 'ximm 0 0\nxmem 137 0 13 0\nxmem 137 0 13 8\nxmem 137 0 13 24\n',
160 'ximm 0 0\nxmem 137 0 13 8\nxmem 137 0 13 24\n', 'context'),
161]:
162 assert compiler.count(before) == 1, name + ' site'
163 _, text = emit(name, compiler.replace(before, after))
164 p = guest(caller(library(name, text), fixture), None)
165 assert p.returncode != 0, name + ' survived'
166 print('PASS ' + name + ' mutant killed rc=' + str(p.returncode))
167before = 'xhs 2 get fr add x 22\nxhcmp 2 get fr add x 23\nxtrap 1 3\nxha x 4 7'
168after = 'xhs 2 get fr add x 22\nxhcmp 2 get fr add x 23\nxha x 4 7'
169assert compiler.count(before) == 1, 'ABI1 exact-length guard site'
170_, text = emit('aien-length', compiler.replace(before, after))
171p = guest(caller(library('aien-length', text), 'aien'), 42)
172print('PASS ABI1 exact-length guard mutant killed at short-count assertion rc=42')
173
174before = 'xb 15 174 240\nif eq w 4\nxhput 2 8 0 4\n'
175assert compiler.count(before) == 1
176code, _ = emit('missing-fence', compiler.replace(before, 'if eq w 4\nxhput 2 8 0 4\n'))
177assert code.count(b'\x0f\xae\xf0') != 11, 'missing-fence mutant survived'
178print('PASS missing-fence mutant killed by instruction oracle (not WC timing)')
179
180# Force cleanup failure while retaining the real failed MAP_FIXED call. The positive
181# control must quarantine the token; moving quarantine after cleanup must be detected.
182retire = 'ximm 0 4\nxmem 137 0 13 24\n'
183cleanup = 'xmem 139 7 4 0\nxmem 139 6 4 8\nxhcall 11\nxrr 133 0 0\nxtrap 1 3\n'
184assert compiler.count(retire + cleanup) == 1
185forced = compiler.replace(retire + cleanup, retire + cleanup.replace('xhcall 11', 'xhcall 39'))
186_, text = emit('forced-cleanup', forced)
187print(guest(caller(library('forced-cleanup', text), 'failed-cleanup')).stdout.decode(), end='')
188read_guard = 'xhcmp 0 3\nxtrap 8 3\n'
189assert forced.count(read_guard) == 2
190_, text = emit('quarantine-read-guard', forced.replace(read_guard, ''))
191p = guest(caller(library('quarantine-read-guard', text), 'failed-cleanup'), None)
192assert p.returncode != 0, 'quarantine read-guard mutant survived'
193print('PASS quarantine read-guard mutant killed rc=' + str(p.returncode))
194_, text = emit('late-quarantine', forced.replace(retire + cleanup.replace('xhcall 11', 'xhcall 39'),
195 cleanup.replace('xhcall 11', 'xhcall 39') + retire))
196p = guest(caller(library('late-quarantine', text), 'failed-cleanup'), None)
197assert p.returncode != 0, 'late-quarantine mutant survived'
198print('PASS late-quarantine mutant killed rc=' + str(p.returncode))
199print('NATIVE-X86-DEVICE EMULATED PASS shared fixtures, 15 word controls, 5 ABI1 controls, 3-unit context ABI, 12 mutants; native/driver/chip NOT_RUN')