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

427 lines · 17832 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Host-only freestanding runtime-view ABI, differential, import and mutation gates."""
4import ctypes as C
5import os
6from pathlib import Path
7import random
8import subprocess
9import tempfile
10
11ROOT = Path(__file__).resolve().parents[1]
12CC = os.environ.get('CC', 'cc')
13NM = os.environ.get('NM', 'nm')
14U = C.c_uint64
15P = C.c_void_p
16
17
18def run(args, **kw):
19 p = subprocess.run([str(a) for a in args], capture_output=True, **kw)
20 assert p.returncode == 0, (args, p.returncode, p.stdout, p.stderr)
21 return p.stdout
22
23
24def emit(src, mode='c', hosted=False, runtime=True):
25 tool = 'bridge-seeded' if hosted else 'bridge-freest'
26 args = [ROOT / 'tools' / tool]
27 if hosted and runtime:
28 args.append('--runtime-views')
29 return run([*args, mode, src])
30
31
32def build(t, name, code, opt='2', freest=True, compiler=CC, load=True):
33 src = t / (name + '.c')
34 obj = t / (name + '.o')
35 lib = t / (name + '.so')
36 src.write_bytes(code)
37 flags = ['-std=gnu11', '-O' + opt, '-Wall', '-Wextra', '-Werror',
38 '-ffp-contract=off', '-fPIC']
39 if freest:
40 flags += ['-ffreestanding', '-fno-builtin', '-fno-stack-protector']
41 run([compiler, *flags, '-c', src, '-o', obj])
42 if freest:
43 # Allowed undefined symbol set is EMPTY, not a libc/compiler-helper allowlist.
44 imports = run([NM, '-u', obj]).strip()
45 assert not imports, (obj, imports)
46 sections = run(['readelf', '-SW', obj])
47 assert b'.tdata' not in sections and b'.tbss' not in sections
48 assert b'__int128' not in code and b'_Thread_local' not in code
49 assert b'setjmp' not in code and b'<unistd.h>' not in code
50 run([compiler, '-shared', *(['-nostdlib'] if freest else []), obj, '-o', lib])
51 return C.CDLL(str(lib)) if load else None
52
53
54def fn(lib, name, params, result=U):
55 f = getattr(lib, 'omega_' + name)
56 f.argtypes = [C.POINTER(result), *params]
57 f.restype = C.c_uint32
58 return f
59
60
61def filled(f, typ, length, count, value):
62 # Extra accessible elements are canaries: a one-past mutant cannot fault the harness.
63 data = (typ * 68)(*([17] * 68))
64 out = U(29)
65 status = f(C.byref(out), data, length, count, value)
66 return status, out.value, bytes(data)
67
68
69def compare(f, g, typ, length, count, value):
70 a, b = filled(f, typ, length, count, value), filled(g, typ, length, count, value)
71 assert a == b, (length, count, value, a[:2], b[:2])
72 return a
73
74
75def attention(t, name, typ, scalar):
76 src = ROOT / 'tests/freest-fixtures' / (name + '.om')
77 code = emit(src)
78 assert code == emit(src), 'C emission is not byte-stable'
79 header = emit(src, 'h')
80 assert header == emit(src, 'h'), 'header emission is not byte-stable'
81 (t / (name + '.h')).write_bytes(header)
82 hosted = build(t, name + '-host', emit(src, hosted=True), freest=False)
83 g = fn(hosted, 'av_' + name.removeprefix('attn_'), [P, U, U, scalar])
84 rng = random.Random(76)
85 for opt in ('0', '2'):
86 lib = build(t, name + '-free-' + opt, code, opt)
87 f = fn(lib, 'av_' + name.removeprefix('attn_'), [P, U, U, scalar])
88 for length in (0, 1, 63, 64):
89 for count in (0, 1, length, 65):
90 result = compare(f, g, typ, length, count, 3)
91 assert result[0] == (0 if count <= length else 3)
92 if result[0]:
93 assert result[1] == 29, 'result was committed after refusal'
94 for _ in range(200):
95 compare(f, g, typ, rng.randrange(65), rng.randrange(67), rng.randrange(256))
96 # Empty NULL is valid; nonempty NULL, misalignment, wrap, overflow and
97 # result overlap refuse before execution. All are compared with hosted.
98 for ptr, length in ((None, 0), (None, 1), (P(1), 1),
99 (P(U(-1).value), 1), (P(8), U(-1).value)):
100 x, y = U(29), U(29)
101 assert f(C.byref(x), ptr, length, 0, 3) == g(C.byref(y), ptr, length, 0, 3)
102 assert x.value == y.value
103 for h in (f, g):
104 assert h(None, None, 0, 0, 3) == 32
105 assert h(C.cast(P(1), C.POINTER(U)), None, 0, 0, 3) == 32
106 out = U(29)
107 assert h(C.byref(out), C.byref(out), 1, 0, 3) == 32
108 print('PASS', name, 'O' + opt, 'hosted differential, boundaries, ABI refusals; nm -u empty; no TLS')
109 return code
110
111
112PROBE = '''om2
113note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
114fn loadval d view ulong * i ulong to ulong
115ret get d i
116end
117fn probe d edit ulong * a ulong b ulong op uint to ulong
118if eq op 0
119ret get d a
120end
121if eq op 1
122put d a b
123ret 0
124end
125if eq op 2
126ret ulong uchar a
127end
128if eq op 3
129r = loadval d a
130put d 0 99
131ret r
132end
133if eq op 4
134while true bound 1
135put d 0 b
136end
137ret 0
138end
139if eq op 5
140ret div a b
141end
142if eq op 6
143ret shl a b
144end
145if eq op 7
146ret ulong add long a long b
147end
148ret len d
149end
150'''
151
152
153def probe_cases(f):
154 answer = []
155 for a, b, op, expected in ((0, 0, 0, 0), (1, 0, 0, 3), (1, 99, 1, 3),
156 (256, 0, 2, 5), (1, 0, 3, 3), (0, 41, 4, 4),
157 (1, 0, 5, 2), (1, 64, 6, 7),
158 (9223372036854775807, 1, 7, 1)):
159 d, out = (U * 2)(17, 23), U(29)
160 rc = f(C.byref(out), d, 1, a, b, op)
161 assert rc == expected, (a, b, op, rc, expected)
162 if rc:
163 assert out.value == 29
164 if op == 3:
165 assert list(d) == [17, 23], 'a nested refusal did not stop subsequent writes'
166 if op == 1:
167 assert d[1] == 23, 'one-past store touched a canary'
168 answer.append((rc, out.value, bytes(d)))
169 return answer
170
171
172def probes(t):
173 src = t / 'probe.om'
174 src.write_text(PROBE)
175 code = emit(src)
176 hosted = build(t, 'probe-host', emit(src, hosted=True), freest=False)
177 args = [P, U, U, U, C.c_uint32]
178 g = fn(hosted, 'probe', args)
179 want = probe_cases(g)
180 for opt in ('0', '2'):
181 lib = build(t, 'probe-free-' + opt, code, opt)
182 assert probe_cases(fn(lib, 'probe', args)) == want
183 print('PASS explicit refusal codes 1/2/3/4/5/7; nested unwind and partial-write state match hosted')
184 return src, args
185
186
187def arithmetic(t):
188 rng = random.Random(76)
189 # Bounds are the exact Wolfram table recorded in the evidence README.
190 for ty, vals in (
191 ('uchar', (0, 1, 127, 128, 255)),
192 ('ushort', (0, 1, 32767, 32768, 65535)),
193 ('uint', (0, 1, 2147483647, 2147483648, 4294967295)),
194 ('ulong', (0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615)),
195 ('byte', (0, 1, 127, U(-1).value, U(-128).value)),
196 ('short', (0, 1, 32767, U(-1).value, U(-32768).value)),
197 ('int', (0, 1, 2147483647, U(-1).value, U(-2147483648).value)),
198 ('long', (0, 1, 9223372036854775807, U(-1).value, U(-9223372036854775808).value))):
199 lines = ['om2', f'fn arith d view ulong * a {ty} b {ty} op uint to {ty}']
200 for i, op in enumerate(('add', 'sub', 'mul', 'div', 'rem', 'shl', 'shr',
201 'eq', 'ne', 'lt', 'le', 'gt', 'ge', 'and', 'or', 'xor')):
202 lines += [f'if eq op {i}']
203 if op in ('eq', 'ne', 'lt', 'le', 'gt', 'ge'):
204 lines += [f'if {op} a b', 'ret 1', 'end', 'ret 0']
205 else:
206 lines += [f'ret {op} a b']
207 lines += ['end']
208 lines += [f'if eq op 16', 'ret neg a', 'end', 'ret not a', 'end', '']
209 src = t / (ty + '.om')
210 src.write_text('\n'.join(lines))
211 g = fn(build(t, ty + '-host', emit(src, hosted=True), freest=False),
212 'arith', [P, U, U, U, C.c_uint32])
213 f = fn(build(t, ty + '-free', emit(src)), 'arith', [P, U, U, U, C.c_uint32])
214 pairs = [(a, b) for a in vals for b in vals]
215 # Native canonical-bit ABI validation also gets arbitrary invalid scalars.
216 pairs += [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(200)]
217 ctype = {'uchar': C.c_uint8, 'ushort': C.c_uint16, 'uint': C.c_uint32,
218 'ulong': U, 'byte': C.c_int8, 'short': C.c_int16,
219 'int': C.c_int32, 'long': C.c_int64}[ty]
220 pairs += [(U(ctype(rng.getrandbits(64)).value).value,
221 U(ctype(rng.getrandbits(64)).value).value) for _ in range(200)]
222 for a, b in pairs:
223 for op in range(18):
224 x, y = U(29), U(29)
225 fr, gr = f(C.byref(x), None, 0, a, b, op), g(C.byref(y), None, 0, a, b, op)
226 assert (fr, x.value) == (gr, y.value), (ty, a, b, op, fr, gr, x.value, y.value)
227 print('PASS integer arithmetic/casts: randomized and canonical min/max pairs, all widths, hosted differential')
228
229
230def float_views(t):
231 source = '''om2
232fn flt d edit f32 * q view f32 4 i ulong to f32
233x = get q i
234put d i add x 1.0f32
235ret get d i
236end
237'''
238 src = t / 'float.om'
239 src.write_text(source)
240 g = fn(build(t, 'float-host', emit(src, hosted=True), freest=False), 'flt',
241 [P, U, P, U, U], C.c_float)
242 code = emit(src)
243 for opt in ('0', '2'):
244 f = fn(build(t, 'float-free-' + opt, code, opt), 'flt', [P, U, P, U, U], C.c_float)
245 for length in (0, 1, 4):
246 for i in (0, 1, 3, 4):
247 x, y = C.c_float(17), C.c_float(17)
248 a, b = (C.c_float * 5)(1, 2, 3, 4, 5), (C.c_float * 5)(1, 2, 3, 4, 5)
249 q = (C.c_float * 4)(1, 2, 3, 4)
250 fr = f(C.byref(x), a, length, q, 4, i)
251 gr = g(C.byref(y), b, length, q, 4, i)
252 assert (fr, bytes(x), bytes(a)) == (gr, bytes(y), bytes(b))
253 # A fixed view is a capacity: shorter is valid; capacity+1 refuses 32.
254 for length in (0, 1, 4, 5):
255 for h in (f, g):
256 out = C.c_float(17)
257 assert h(C.byref(out), None, 0, None, length, 0) == (3 if length == 0 else 32)
258 print('PASS f32 borrowed/fixed-capacity views and scalar result ABI; O0/O2 import-free')
259
260
261def reference_views(t):
262 # Reuse the independent hosted-profile C oracle. Synthetic pointers in this
263 # oracle test range validation without ever dereferencing synthetic storage.
264 import seeded_runtime_views as reference
265 for typ in ('uchar', 'ushort', 'uint', 'ulong', 'f32'):
266 for unsized in (False, True):
267 src = t / 'reference.om'
268 source = reference.unit(typ, unsized)
269 src.write_text(source if unsized else 'om2\n' + source)
270 code, header = emit(src), emit(src, 'h')
271 cap = 0 if unsized else 256
272 name = 'reference-' + typ + ('-unsized' if unsized else '-fixed')
273 for compiler, runner, arch in (
274 (CC, (), 'host'),
275 ('x86_64-linux-gnu-gcc',
276 (os.environ.get('QEMU_X86_64', 'qemu-x86_64'),
277 '-L', '/usr/x86_64-linux-gnu'), 'x86-EMULATED')):
278 for opt in ('0', '2'):
279 build(t, name + '-' + arch + '-' + opt, code, opt,
280 compiler=compiler, load=False)
281 reference.execute(code, header, t, typ, cap, name + '-' + arch,
282 compiler, runner)
283 print('PASS', name, 'independent ABI oracle: NULL, max extent, aliases, bounds; host and x86 EMULATED')
284
285
286def refusals(t):
287 # Valid seeded Omega, but part is not lowered by this converter. No profile retry.
288 src = t / 'unsupported.om'
289 src.write_text('om2\nfn callee d view ulong * to ulong\nret len d\nend\n'
290 'fn caller d view ulong * to ulong\nret callee part d 0 len d\nend\n')
291 assert run([os.environ['OMEGA_SEEDED_OMC']], input=src.read_bytes())
292 for mode in ('c', 'h'):
293 p = subprocess.run([ROOT / 'tools/bridge-freest', mode, src], capture_output=True)
294 assert p.returncode != 0 and not p.stdout, (mode, p.returncode, p.stdout)
295 print('PASS unsupported part capability: seed admits; freest c/h refuse with empty stdout')
296
297
298def mutants(t, src, args):
299 original = (ROOT / 'src/toc.om').read_text()
300 changes = (
301 ('get-bound', 'if(i>=n)return fs_error(fs,3);', 'if(i>n)return fs_error(fs,3);'),
302 ('put-bound', 'if(i>=n){fs_error(fs,3);return;}', 'if(i>n){fs_error(fs,3);return;}'),
303 ('narrow-check', '||!o_valid(t,a)', '||0'),
304 ('nested-unwind', ');if(fs->code)goto fs_fail;fs_value;', ');if(0)goto fs_fail;fs_value;'),
305 ('status', ');return fs->code;', ');return 0;'),
306 ('loop-status', 'fs->code=(c);goto fs_fail;', 'fs->code=1;goto fs_fail;'),
307 )
308 for name, old, new in changes:
309 assert original.count(old) == 1, (name, original.count(old))
310 mutated = original.replace(old, new)
311 converter = t / ('converter-' + name)
312 converter.write_bytes(run([os.environ['OMEGA_SEED']], input=mutated.encode()))
313 converter.chmod(0o755)
314 code = run([converter], input=b'W' + src.read_bytes())
315 lib = build(t, 'mutant-' + name, code)
316 try:
317 probe_cases(fn(lib, 'probe', args))
318 except AssertionError:
319 print('PASS killed emitter mutant', name)
320 else:
321 raise AssertionError('survived emitter mutant ' + name)
322
323
324def pack_case(f, pn=32, an=32, alias=False, result_alias=False):
325 p, a, out = (U * 40)(*([17] * 40)), (C.c_uint32 * 40)(*([41] * 40)), U(99)
326 before = bytes(p), bytes(a)
327 result = C.cast(p, C.POINTER(U)) if result_alias else C.byref(out)
328 rc = f(result, p, pn, p if alias else a, an, 0, 0)
329 if pn != 32 or an != 32 or alias or result_alias:
330 assert rc == 32, ('fixed-view admission', pn, an, alias, result_alias, rc)
331 assert out.value == 99 and (bytes(p), bytes(a)) == before
332 else:
333 assert rc == 0 and out.value == 0
334 return rc, out.value, bytes(p), bytes(a)
335
336
337def fixed_profile(t):
338 src = ROOT / 'tests/freest-fixtures/attn_args.om'
339 code = emit(src)
340 assert code == emit(src) and emit(src, 'h') == emit(src, 'h')
341 hosted = build(t, 'fixed-args-host', emit(src, hosted=True, runtime=False), freest=False)
342 params = [P, U, P, U, U, U]
343 g = fn(hosted, 'av_pack', params)
344 for opt in ('0', '2'):
345 f = fn(build(t, 'fixed-args-free-' + opt, code, opt), 'av_pack', params)
346 assert pack_case(f, pn=31) == pack_case(g, pn=31)
347 for pn in (0, 1, 31, 32, 33):
348 for an in (31, 32, 33):
349 assert pack_case(f, pn, an) == pack_case(g, pn, an)
350 assert pack_case(f, alias=True) == pack_case(g, alias=True)
351 assert pack_case(f, result_alias=True) == pack_case(g, result_alias=True)
352 print('PASS fixed declared counts: attn_args p[31]/p[33] refuse 32 before writes; fixed aliases/result unchanged; hosted default differential')
353
354
355def runtime_aliases(t):
356 src = ROOT / 'tests/freest-fixtures/attn_buf.om'
357 params = [P, U, P, U, U]
358 g = fn(build(t, 'copy-alias-host', emit(src, hosted=True), freest=False), 'av_copy', params)
359 def call(f, sn, dn, n, offset, overlap=False, wrap=False, empty=False):
360 bank, out = (C.c_ubyte * 64)(*range(64)), U(99)
361 before = bytes(bank)
362 result = C.cast(bank, C.POINTER(U)) if overlap else C.byref(out)
363 s = None if empty else P(C.c_uint64(-2).value) if wrap else bank
364 d = None if empty else C.byref(bank, offset)
365 rc = f(result, s, sn, d, dn, n)
366 if rc == 32:
367 assert bytes(bank) == before
368 if rc:
369 assert out.value == 99
370 return rc, out.value, bytes(bank)
371 cases = (
372 ((0, 0, 0, 0), {'empty': True}, 0),
373 ((16, 16, 16, 1), {}, 32),
374 ((16, 16, 16, 16), {}, 0),
375 ((8, 8, 8, 16), {'overlap': True}, 32),
376 ((3, 3, 3, 16), {'wrap': True}, 32),
377 ((2, 2, 3, 16), {}, 3),
378 )
379 for opt in ('0', '2'):
380 f = fn(build(t, 'copy-alias-free-' + opt, emit(src), opt), 'av_copy', params)
381 for args, kw, expected in cases:
382 actual, reference = call(f, *args, **kw), call(g, *args, **kw)
383 assert actual == reference and actual[0] == expected
384 print('PASS runtime copy: overlap/result aliases/wrapping refuse32; adjacent ranges pass; bounds3 retains partial writes and result')
385
386
387def fixed_mutant(t):
388 original = (ROOT / 'src/toc.om').read_text()
389 old = 'uint64_t z=t==11?4:t==12?8:o_width(t)/8;return p&&n==want&&'
390 new = 'uint64_t z=t==11?4:t==12?8:o_width(t)/8;return p&&(want||1)&&'
391 runtime = next(line for line in original.splitlines() if line.startswith('text fsrun '))
392 assert runtime.count(old) == 1
393 mutated = original.replace(runtime, runtime.replace(old, new))
394 converter = t / 'converter-fixed-extent'
395 converter.write_bytes(run([os.environ['OMEGA_SEED']], input=mutated.encode()))
396 converter.chmod(0o755)
397 src = ROOT / 'tests/freest-fixtures/attn_args.om'
398 code = run([converter], input=b'W' + src.read_bytes())
399 f = fn(build(t, 'mutant-fixed-extent', code), 'av_pack', [P, U, P, U, U, U])
400 try:
401 pack_case(f, pn=31)
402 except AssertionError:
403 print('PASS killed emitter mutant fixed-extent-check')
404 else:
405 raise AssertionError('survived fixed-extent-check mutant')
406
407
408def main():
409 assert not os.environ.get('FREEST_RUNNER'), 'ctypes differential runs on the host only'
410 with tempfile.TemporaryDirectory(prefix='bridge-freest-views-') as td:
411 t = Path(td)
412 fixed_profile(t)
413 runtime_aliases(t)
414 fixed_mutant(t)
415 attention(t, 'attn_set', C.c_ubyte, C.c_uint64)
416 attention(t, 'attn_fill', C.c_uint32, C.c_uint64)
417 src, args = probes(t)
418 arithmetic(t)
419 float_views(t)
420 reference_views(t)
421 refusals(t)
422 mutants(t, src, args)
423 print('FREEST-VIEWS PASS')
424
425
426if __name__ == '__main__':
427 main()