interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / universal / translation / s2_selftest.py

1049 lines · 49167 bytes Raw Blame History
1#!/usr/bin/env python3
2"""S2 author self-test (spec/universal/translation-s2-v1.md section 6): signed i64, comparisons, select.
3
4Three directions, each exercised through its public command and checked against external oracles:
5 c-import tools/adapters/c-i64-import; every unit is evaluated by this file's bigint reference and
6 compared with the C source compiled by gcc -O0 -fsanitize=signed-integer-overflow
7 -fno-sanitize-recover=all (one fork per vector; a sanitizer exit is the error outcome)
8 rust tools/adapters/rust-i64-export; rustc build-setting matrix (section 6): D debug (overflow-checks
9 on, panic = error), R release (opt-level 3, overflow-checks off: attribute 6 overflow wraps, a
10 REFINEMENT of the C error), RC release with overflow-checks on (panic = error)
11 native tools/adapters/lower-s2 -> pinned omc 734f0a39 (function mode) -> pinned omega-bridge generator
12 -> C caller (ABI v1: an i64 travels as its uint64_t two's-complement bits); status 1 = error
13plus the v3 codec (v1/v2 decode byte-identical with the v2 codec build/L832/sa over a mutated corpus, v3
14positive and refusal rows), the composition C -> Omega -> Rust (rustc output equal to the C oracle on every
15vector), and tool-source mutants (>= 8 per direction, each recompiled with its pinned compiler, all killed).
16Exit: 0 PASS, 1 FAIL, 3 NOT_RUN (an oracle or pin is absent; nothing is passed).
17"""
18from pathlib import Path
19import argparse, hashlib, itertools, json, os, random, struct, subprocess, sys, tempfile, time
20
21HERE = Path(__file__).resolve().parent
22ROOT = HERE.parents[2]
23sys.dont_write_bytecode = True
24sys.path.insert(0, str(HERE))
25import validate_g1 as V # noqa: E402 (process runner, vector packing and the native caller template)
26
27MASK = (1 << 64) - 1
28MIN, MAX = -(1 << 63), (1 << 63) - 1
29U = 65535
30SEED_OMC = '191b776ef98821597c3e30655da6d680a9b66edbc9ceaca3c39c61ea6df098e9'
31NATIVE_OMC = '734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61'
32BOUNDARY = [MIN, MIN + 1, -3037000500, -2, -1, 0, 1, 2, 3037000499, 3037000500, 1 << 32, MAX - 1, MAX]
33GCC_ORACLE = ['-std=c17', '-O0', '-fsanitize=signed-integer-overflow', '-fno-sanitize-recover=all',
34 '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter']
35RUSTC = ['--edition', '2021', '-C', 'opt-level=0', '-C', 'debug-assertions=on', '-C', 'overflow-checks=on',
36 '-A', 'warnings']
37# Build-setting matrix (translation-s2-v1 section 6). R spells rustc's release defaults explicitly so the
38# default is never assumed.
39RUST_SETTINGS = {
40 'D': RUSTC,
41 'R': ['--edition', '2021', '-C', 'opt-level=3', '-C', 'debug-assertions=off', '-C', 'overflow-checks=off',
42 '-A', 'warnings'],
43 'RC': ['--edition', '2021', '-C', 'opt-level=3', '-C', 'overflow-checks=on', '-A', 'warnings'],
44}
45MATRIX = ('D', 'R', 'RC')
46
47
48class NotRun(Exception):
49 pass
50
51
52def s64(x):
53 x &= MASK
54 return x - (1 << 64) if x >> 63 else x
55
56
57def sha(b):
58 return hashlib.sha256(b).hexdigest()
59
60
61# ------------------------------------------------------------------ reference decoder and evaluator
62def records(env):
63 """OMSA records of a structurally valid envelope (the codec under test has already accepted it)."""
64 sn = struct.unpack_from('<I', env, 5)[0]
65 sem = env[13:13 + sn]
66 n = struct.unpack_from('<H', sem, 10)[0]
67 out = []
68 for i in range(n):
69 d, ver, op, t, at, ef, al, ob, a, b, imm = struct.unpack_from('<8BHHQ', sem, 44 + 20 * i)
70 out.append(dict(op=op, t=t, at=at, ob=ob, a=a, b=b, imm=imm))
71 return {'ver': sem[4], 'lang': sem[5], 'prof': sem[6], 'rt': sem[8], 'abi': sem[9]}, out
72
73
74class Trap(Exception):
75 pass
76
77
78def evaluate(ops, args, cov=None, wrap6=False):
79 """Demand-driven bigint evaluation (translation-s2-v1 section 3, amendment A2): select evaluates its
80 condition and only the chosen arm; attribute 6 i64 overflow is the error outcome, or with wrap6 (the
81 rustc overflow-checks=off build) the result reduced mod 2^64. -> (status, bits)."""
82 memo = {}
83
84 def ev(k):
85 if k in memo:
86 return memo[k]
87 r = ops[k]
88 op, t = r['op'], r['t']
89 if op == 9:
90 x = args[r['imm']]
91 v = s64(x) if t == 5 else x & MASK
92 elif op == 1:
93 v = s64(r['imm']) if t == 5 else r['imm']
94 elif op in (2, 3, 4):
95 a, b = ev(r['a']), ev(r['b'])
96 e = a + b if op == 2 else a - b if op == 3 else a * b
97 if t == 1:
98 v = e & MASK
99 elif r['at'] == 5:
100 v = s64(e)
101 else:
102 if not MIN <= e <= MAX:
103 if not wrap6:
104 raise Trap()
105 e = s64(e)
106 v = e
107 elif 10 <= op <= 15:
108 a, b = ev(r['a']), ev(r['b'])
109 v = int([a == b, a != b, a < b, a <= b, a > b, a >= b][op - 10])
110 if cov is not None:
111 cov.add((k, v))
112 elif op == 16:
113 c = ev(r['a'])
114 if cov is not None:
115 cov.add((k, c))
116 v = ev(r['b']) if c else ev(r['imm'])
117 elif op == 17:
118 v = 1 - ev(r['a'])
119 else:
120 raise AssertionError('op %d' % op)
121 memo[k] = v
122 return v
123
124 try:
125 return (0, ev(len(ops) - 1) & MASK)
126 except Trap:
127 return (1, None)
128
129
130def same(ref, got):
131 return ref[0] == got[0] and (ref[0] != 0 or ref[1] == got[1])
132
133
134def vectors(n, tag, extra=()):
135 if n == 0:
136 return [()]
137 bits = [v & MASK for v in BOUNDARY]
138 if len(bits) ** n <= 2200:
139 out = list(itertools.product(bits, repeat=n))
140 else:
141 out = [tuple([v] * n) for v in bits]
142 for pos in range(n):
143 for base in bits:
144 for v in bits:
145 t = [base] * n
146 t[pos] = v
147 out.append(tuple(t))
148 rs = random.Random('S2-boundary-' + tag)
149 out += [tuple(rs.choice(bits) for _ in range(n)) for _ in range(600)]
150 rr = random.Random('S2-random-' + tag)
151 out += [tuple(rr.getrandbits(64) for _ in range(n)) for _ in range(64)]
152 out += [tuple(rr.randint(-40, 40) & MASK for _ in range(n)) for _ in range(64)]
153 out += [tuple(v & MASK for v in e) for e in extra]
154 seen, uniq = set(), []
155 for v in out:
156 if v not in seen:
157 seen.add(v)
158 uniq.append(v)
159 return uniq
160
161
162# ------------------------------------------------------------------ fixtures (spec section 6 classes)
163PARAMS = 'abcdef'
164
165
166def csrc(n, body):
167 ps = ', '.join('int64_t %s' % PARAMS[i] for i in range(n)) or 'void'
168 return '#include <stdint.h>\nint64_t calc(%s) { return %s; }\n' % (ps, body)
169
170
171W = '(int64_t)((uint64_t)%s %s (uint64_t)%s)'
172C_POS = [ # (id, n, body, explicit at-boundary and one-past vectors)
173 ('add', 2, 'a + b', [(MAX, 0), (MAX, 1), (MIN, 0), (MIN, -1), (MAX, MIN)]),
174 ('sub', 2, 'a - b', [(MIN, 0), (MIN, 1), (MAX, -1), (MAX, 0), (-1, MAX), (-2, MAX)]),
175 ('mul', 2, 'a * b', [(MIN, -1), (MIN, 1), (3037000499, 3037000499), (3037000500, 3037000500),
176 (-3037000499, 3037000499), (4294967296, 2147483648), (4294967296, 2147483647)]),
177 ('wadd', 2, W % ('a', '+', 'b'), [(MAX, 1), (MIN, -1)]),
178 ('wsub', 2, W % ('a', '-', 'b'), [(MIN, 1), (MAX, -1)]),
179 ('wmul', 2, W % ('a', '*', 'b'), [(MIN, -1), (3037000500, 3037000500)]),
180 ('eq', 2, 'a == b ? a : b - 1LL', [(MIN, MIN), (MIN, MIN + 1)]),
181 ('ne', 2, 'a != b ? a - b : 7LL', [(5, 5), (0, MIN), (-1, MAX)]),
182 ('lt', 2, 'a < b ? b - a : a - b', [(MIN, MAX), (MAX, MIN), (-1, MAX), (0, MIN)]),
183 ('le', 2, 'a <= b ? a : b', [(MAX, MAX), (MIN, MIN)]),
184 ('gt', 2, 'a > b ? a * 2LL : b', [(4611686018427387903, 0), (4611686018427387904, 0)]),
185 ('ge', 2, 'a >= b ? 1LL : 0LL', [(MIN, MAX), (MAX, MIN)]),
186 ('max3', 3, 'a < b ? (b < c ? c : b) : a < c ? c : a', []),
187 ('guard', 1, 'a < 9223372036854775807LL ? a + 1LL : a', [(MAX,), (MAX - 1,)]),
188 ('guardmul', 2, 'b == 0LL ? 0LL : a > 3037000499LL ? 1LL : a < 0LL - 3037000499LL ? 2LL : b > 3037000499LL '
189 '? 3LL : b < 0LL - 3037000499LL ? 4LL : a * b', []),
190 ('minlit', 1, 'a - 9223372036854775807LL - 1LL', [(0,), (-1,), (MAX,)]),
191 ('mixwrap', 2, W % ('a', '*', '9223372036854775807LL') + ' + b', [(1, 1), (2, 0), (2, MIN)]),
192 ('ovfcheck', 2, W % ('a', '+', 'b') + ' < a ? 1LL : 0LL', [(MAX, 1), (1, -1)]),
193 ('condovf', 3, 'a * b > c ? a : c', [(MIN, -1, 0), (MAX, 2, 0)]),
194 ('prec', 2, '(a + b) * (a - b) >= 0LL ? a * a - b * b : 0LL', []),
195 ('six', 6, 'a + b + c + d + e + f', [(MAX, 1, 0, 0, 0, -1), (MAX, 0, 0, 0, 0, 1)]),
196 ('six-sel', 6, 'a + b > c - d ? e * f : a - f', [(MAX, 1, 0, 0, 2, 3), (0, 0, 0, 0, MAX, 2), (MIN, 0, 0, 0, 0, 1)]),
197 ('ident', 1, 'a', []),
198 ('neg', 1, '0LL - a', [(MIN,), (MIN + 1,)]),
199 ('const', 0, '5LL', []),
200 ('nestwrap', 2, '(int64_t)((uint64_t)(a < b ? a : b) - (uint64_t)(a * 2LL))', [(MIN, 0), (4611686018427387904, 0)]),
201]
202
203C_REFUSE = [ # (id, source text, expected exit)
204 ('u64-param', '#include <stdint.h>\nint64_t calc(uint64_t a) { return a; }\n', 66),
205 ('u64-return', '#include <stdint.h>\nuint64_t calc(int64_t a) { return a; }\n', 66),
206 ('int-param', '#include <stdint.h>\nint64_t calc(int a) { return a; }\n', 66),
207 ('no-suffix', csrc(1, 'a + 1'), 68),
208 ('ull-suffix', csrc(1, 'a + 1ULL'), 68),
209 ('lit-2p63', csrc(1, 'a + 9223372036854775808LL'), 67),
210 ('octal', csrc(1, 'a + 01LL'), 68),
211 ('unary-minus', csrc(1, '-a'), 68),
212 ('logical-not', csrc(2, '!a'), 68),
213 ('div', csrc(2, 'a / b'), 68),
214 ('rem', csrc(2, 'a % b'), 68),
215 ('shift', csrc(2, 'a << b'), 68),
216 ('cmp-value', csrc(2, 'a < b'), 68),
217 ('cmp-in-arith', csrc(2, '(a < b) + 1LL'), 68),
218 ('cond-not-cmp', csrc(3, 'a ? b : c'), 68),
219 ('chained-cmp', csrc(3, 'a < b < c ? a : b'), 68),
220 ('plain-cast', csrc(1, '(int64_t)a'), 68),
221 ('wrap-div', csrc(2, W % ('a', '/', 'b')), 68),
222 ('wrap-u64-result', csrc(2, '(uint64_t)((uint64_t)a + (uint64_t)b)'), 68),
223 ('wrap-half', csrc(2, '(int64_t)((uint64_t)a + b)'), 68),
224 ('assign', csrc(2, 'a = b'), 69),
225 ('spaced-le', csrc(2, 'a < = b ? a : b'), 68),
226 ('logical-and', csrc(2, 'a && b'), 68),
227 ('missing-semi', '#include <stdint.h>\nint64_t calc(int64_t a) { return a }\n', 65),
228 ('missing-colon', csrc(2, 'a < b ? a b'), 65),
229 ('nul', '#include <stdint.h>\nint64_t calc(int64_t a) { return a;\0 }\n', 65),
230 ('backslash', '#include <stdint.h>\nint64_t calc(int64_t a) { return \\\na; }\n', 72),
231 ('no-header', 'int64_t calc(int64_t a) { return a; }\n', 72),
232 ('seven-params', '#include <stdint.h>\nint64_t calc(int64_t a, int64_t b, int64_t c, int64_t d, int64_t e, '
233 'int64_t f, int64_t g) { return a; }\n', 67),
234 ('deep', csrc(1, '(' * 18 + 'a' + ')' * 18), 67),
235 ('dup-param', '#include <stdint.h>\nint64_t calc(int64_t a, int64_t a) { return a; }\n', 71),
236 ('bad-name', '#include <stdint.h>\nint64_t calc(int64_t uint64_t) { return 1LL; }\n', 71),
237 ('statement', '#include <stdint.h>\nint64_t calc(int64_t a) { if (a) return a; }\n', 69),
238]
239
240
241def sem(ops, lang=1, prof=10, rt=0, abi=1, ver=3):
242 recs = b''
243 for r in ops:
244 recs += struct.pack('<8BHHQ', r.get('d', lang), r.get('v', 1), r['op'], r['t'], r['at'], r.get('ef', 0),
245 r.get('al', 0), r['ob'], r['a'], r['b'], r['imm'])
246 return b'OMSA' + bytes([ver, lang, prof, 1, rt, abi]) + struct.pack('<H', len(ops)) + V.SEMANTICS_DIGEST + recs
247
248
249def env_of(s, side=b''):
250 return b'OMSB\x01' + struct.pack('<II', len(s), len(side)) + s + side
251
252
253def R(op, t, at, ob, a=U, b=U, imm=0, **kw):
254 d = dict(op=op, t=t, at=at, ob=ob, a=a, b=b, imm=imm)
255 d.update(kw)
256 return d
257
258
259def IN(s, t=5):
260 return R(9, t, 0, 1, imm=s)
261
262
263def K(v, t=5):
264 return R(1, t, 1 if t == 1 else 0, 0, imm=v & MASK)
265
266
267def AR(op, a, b, at=6, t=5):
268 return R(op, t, 1 if t == 1 else at, 1 if t == 1 or at == 5 else 33, a, b)
269
270
271def CMP(op, a, b):
272 return R(op, 6, 0, 0, a, b)
273
274
275def SEL(c, x, y, t=5):
276 return R(16, t, 0, 0, c, x, y)
277
278
279def NOT(a):
280 return R(17, 6, 0, 0, a)
281
282
283HAND = [ # (id, ops, lang, prof): units no C source produces (u64, bool results, not, negative constants)
284 ('not-bool', [IN(0), IN(1), CMP(12, 0, 1), NOT(2)], 1, 10),
285 ('u64-mix', [IN(0, 1), IN(1, 1), CMP(12, 0, 1), AR(3, 1, 0, t=1), AR(3, 0, 1, t=1), SEL(2, 3, 4, t=1)], 2, 11),
286 ('negconst', [IN(0), K(MIN), K(-5), CMP(13, 0, 2), AR(2, 0, 1, 5), SEL(3, 1, 4)], 3, 12),
287 ('sel-not', [IN(0), IN(1), CMP(10, 0, 1), NOT(2), AR(4, 0, 1), SEL(3, 4, 0)], 5, 13),
288 ('bool-const', [IN(0), K(1, 6), K(0, 6), AR(2, 0, 0), SEL(2, 3, 0), SEL(1, 4, 3)], 6, 14),
289 ('shared-ovf', [IN(0), IN(1), AR(2, 0, 1), CMP(14, 0, 1), SEL(3, 2, 1), SEL(3, 1, 2), AR(3, 4, 5)], 7, 15),
290 ('bool-sel', [IN(0), IN(1), CMP(12, 0, 1), CMP(15, 0, 1), SEL(2, 3, 2, t=6), NOT(4)], 1, 10),
291 ('u64-cmp-i64', [IN(0, 1), IN(1), K(9, 1), CMP(14, 0, 2), AR(4, 1, 1), SEL(3, 4, 1)], 1, 10),
292]
293
294RUST_GOLDEN = {
295 'add': 'pub fn calc(i0: i64, i1: i64) -> i64 { i0 + i1 }\n',
296 'wmul': 'pub fn calc(i0: i64, i1: i64) -> i64 { i0.wrapping_mul(i1) }\n',
297 'lt': 'pub fn calc(i0: i64, i1: i64) -> i64 { if i0 < i1 { i1 - i0 } else { i0 - i1 } }\n',
298 'const': 'pub fn calc() -> i64 { 5i64 }\n',
299 'not-bool': 'pub fn calc(i0: i64, i1: i64) -> bool { !(i0 < i1) }\n',
300 'negconst': 'pub fn calc(i0: i64) -> i64 { if i0 <= (-5i64) { -9223372036854775808i64 } else { i0.wrapping_add('
301 '(-9223372036854775808i64)) } }\n',
302}
303
304
305def arity(ops):
306 return sum(1 for r in ops if r['op'] == 9)
307
308
309def ptypes(ops):
310 t = {}
311 for r in ops:
312 if r['op'] == 9:
313 t[r['imm']] = r['t']
314 return [t[i] for i in range(len(t))]
315
316
317# ------------------------------------------------------------------ runners
318class Ctx:
319 def __init__(self, a, work):
320 self.a, self.work, self.n = a, work, 0
321 self.oracle_cache = {}
322
323 def tmp(self, label):
324 self.n += 1
325 d = self.work / ('%04d-%s' % (self.n, label))
326 d.mkdir(parents=True)
327 return d
328
329 def compile_run(self, cmd, d, vs, n):
330 rc, out, err = V.run(cmd, timeout=300)
331 if rc != 0:
332 return None, 'compile exit %s: %s' % (rc, err.decode(errors='replace')[:400])
333 rc, out, err = V.run([d / 'run'], V.pack_vectors(vs, n), timeout=300)
334 if rc != 0:
335 return None, 'run exit %s' % rc
336 rows = out.decode().split('\n')[:-1]
337 if len(rows) != len(vs):
338 return None, 'row count %d != %d' % (len(rows), len(vs))
339 return [tuple(int(x) for x in r.split()) for r in rows], None
340
341 def c_oracle(self, src, n, vs):
342 key = (src, tuple(vs))
343 if key in self.oracle_cache:
344 return self.oracle_cache[key]
345 d = self.tmp('c-oracle')
346 (d / 'unit.c').write_text(src)
347 ps = ', '.join(['int64_t'] * n) or 'void'
348 args = ', '.join('(int64_t)v[%d]' % i for i in range(n))
349 (d / 'driver.c').write_text(ORACLE_DRIVER % {'ps': ps, 'k': n, 'args': args})
350 res = self.compile_run([self.a.cc] + GCC_ORACLE + [d / 'unit.c', d / 'driver.c', '-o', d / 'run'], d, vs, n)
351 self.oracle_cache[key] = res
352 return res
353
354 def rust_run(self, rs_text, types, rtype, vs, setting='D'):
355 d = self.tmp('rust-' + setting)
356 n = len(types)
357 args = ', '.join(('v[%d] as i64' if t == 5 else 'v[%d]') % i for i, t in enumerate(types))
358 bits = {1: 'x', 5: 'x as u64', 6: 'x as u64'}[rtype]
359 (d / 'unit.rs').write_text(rs_text + RUST_DRIVER % {'k': n, 'args': args, 'bits': bits})
360 return self.compile_run([self.a.rustc] + RUST_SETTINGS[setting] + [d / 'unit.rs', '-o', d / 'run'], d, vs, n)
361
362 def native(self, om_text, n, vs, sym='omega_calc'):
363 d = self.tmp('native')
364 om = om_text.encode() if isinstance(om_text, str) else om_text
365 (d / 'unit.om').write_bytes(om)
366 rc, binary, err = V.run([self.a.omc], om, timeout=120)
367 if rc != 0 or not binary:
368 return None, 'omc exit %s: %s' % (rc, err.decode(errors='replace')[:300])
369 frame = om + b'\0' + b'%08d' % len(binary) + binary
370 rc, binding, err = V.run([self.a.bridge_native], frame, timeout=120)
371 if rc != 0 or not binding:
372 return None, 'bridge generator exit %s' % rc
373 (d / 'binding.c').write_bytes(binding)
374 (d / 'caller.c').write_text(V.native_driver(sym, n))
375 return self.compile_run([self.a.cc, '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', d / 'binding.c',
376 d / 'caller.c', '-o', d / 'run'], d, vs, n)
377
378
379ORACLE_DRIVER = r'''#include <stdint.h>
380#include <stdio.h>
381#include <unistd.h>
382#include <sys/wait.h>
383int64_t calc(%(ps)s);
384int main(void)
385{
386 uint64_t n, v[6] = {0};
387 if (fread(&n, 8, 1, stdin) != 1)
388 return 2;
389 for (uint64_t j = 0; j < n; j++) {
390 if (%(k)d && fread(v, 8, %(k)d, stdin) != %(k)d)
391 return 2;
392 int fd[2];
393 if (pipe(fd) != 0)
394 return 2;
395 fflush(stdout);
396 pid_t p = fork();
397 if (p < 0)
398 return 2;
399 if (p == 0) {
400 close(fd[0]);
401 uint64_t u = (uint64_t)calc(%(args)s);
402 if (write(fd[1], &u, 8) != 8)
403 _exit(3);
404 _exit(0);
405 }
406 close(fd[1]);
407 uint64_t u = 0;
408 ssize_t got = read(fd[0], &u, 8);
409 close(fd[0]);
410 int st = 0;
411 if (waitpid(p, &st, 0) != p)
412 return 2;
413 if (WIFEXITED(st) && WEXITSTATUS(st) == 0 && got == 8)
414 printf("0 %%llu\n", (unsigned long long)u);
415 else
416 printf("1 0\n");
417 }
418 return 0;
419}
420'''
421
422RUST_DRIVER = r'''
423use std::io::Read;
424fn main() {
425 std::panic::set_hook(Box::new(|_| {}));
426 let mut b = Vec::new();
427 std::io::stdin().read_to_end(&mut b).unwrap();
428 let n = u64::from_le_bytes(b[0..8].try_into().unwrap()) as usize;
429 let k: usize = %(k)d;
430 for j in 0..n {
431 let base = 8 + 8 * k * j;
432 let v: Vec<u64> = (0..k).map(|i| u64::from_le_bytes(b[base + 8 * i..base + 8 * i + 8].try_into().unwrap())).collect();
433 let _ = &v;
434 match std::panic::catch_unwind(|| calc(%(args)s)) {
435 Ok(x) => println!("0 {}", %(bits)s),
436 Err(_) => println!("1 0"),
437 }
438 }
439}
440'''
441
442
443def sa(ctx, build, mode, data):
444 return V.run([build / 'sa'], bytes([mode]) + data, timeout=60)
445
446
447# ------------------------------------------------------------------ direction checks
448class Run:
449 def __init__(self, label):
450 self.label, self.ok, self.fail, self.counts = label, 0, [], {}
451
452 def check(self, cls, cond, what):
453 self.counts[cls] = self.counts.get(cls, 0) + 1
454 if cond:
455 self.ok += 1
456 else:
457 self.fail.append('%s %s: %s' % (self.label, cls, what))
458 return cond
459
460
461def c_import_check(ctx, tool, quick=False, out=None):
462 """Every positive C fixture: import, v3 codec decode/replay, reference == gcc UBSan oracle. Every refusal
463 row: the exact exit. Returns (Run, {id: (env, ops, vs, oracle rows)})."""
464 R_ = Run('c-import')
465 units = {}
466 cov = {}
467 for cid, n, body, extra in C_POS:
468 src = csrc(n, body)
469 rc, env, err = V.run(tool, src.encode())
470 if not R_.check('positive', rc == 0 and env, '%s exit %s %s' % (cid, rc, err[:120])):
471 if quick:
472 return R_, units
473 continue
474 rc, dec, _ = sa(ctx, ctx.a.s2build, 2, env)
475 R_.check('positive', rc == 0 and dec == env, '%s v3 decode exit %s' % (cid, rc))
476 rc, rep, _ = sa(ctx, ctx.a.s2build, 5, env)
477 R_.check('positive', rc == 0 and rep == src.encode(), '%s provenance replay exit %s' % (cid, rc))
478 hdr, ops = records(env)
479 R_.check('positive', (hdr['ver'], hdr['lang'], hdr['prof'], hdr['rt'], hdr['abi']) == (3, 1, 10, 0, 1),
480 '%s header %s' % (cid, hdr))
481 vs = vectors(n, cid, extra)
482 orc, why = ctx.c_oracle(src, n, vs)
483 if not R_.check('oracle', orc is not None, '%s gcc oracle: %s' % (cid, why)):
484 continue
485 c = set()
486 bad = None
487 for v, o in zip(vs, orc):
488 ref = evaluate(ops, v, c)
489 if not same(ref, o):
490 bad = (v, ref, o)
491 break
492 cls = 'overflow' if any(o[0] for o in orc) else 'boundary'
493 R_.check(cls, bad is None, '%s vector %s reference %s oracle %s' % ((cid,) + bad if bad else (cid, 0, 0, 0)))
494 cov[cid] = (ops, c)
495 units[cid] = (env, ops, vs, orc, src)
496 if quick and R_.fail:
497 return R_, units
498 for cid, text, want in C_REFUSE:
499 rc, o, e = V.run(tool, text.encode())
500 cls = 'malformed' if want in (65, 72) else 'unsupported'
501 R_.check(cls, rc == want and o == b'', '%s exit %s want %s' % (cid, rc, want))
502 if quick and R_.fail:
503 return R_, units
504 # Function name (amendment A8): any C identifier of at most 63 bytes outside the reserved sets; the
505 # semantic identity does not depend on it, and every accepted source compiles under gcc.
506 body = 'a < b ? b - a : a - b'
507 rc, e0, _ = V.run(tool, csrc(2, body).encode())
508 rc0, id0, _ = sa(ctx, ctx.a.s2build, 3, e0) if rc == 0 else (rc, b'', b'')
509 for name in ['Absdiff_2', '_x', 'x', 'omega_f', 'calc2', 'int_add', 'INT64', 'MAX_C2', 'size', 'n' * 63]:
510 src = csrc(2, body).replace('calc(', name + '(', 1)
511 rc, env, _ = V.run(tool, src.encode())
512 rc2, ident, _ = sa(ctx, ctx.a.s2build, 3, env) if rc == 0 else (rc, b'', b'')
513 d = ctx.tmp('c-name')
514 (d / 'unit.c').write_text(src)
515 rc3, _, err3 = V.run([ctx.a.cc, '-std=c17', '-Wall', '-Wextra', '-Werror', '-c', d / 'unit.c', '-o',
516 d / 'unit.o'])
517 R_.check('name', rc == 0 and rc0 == 0 and rc2 == 0 and ident == id0 and rc3 == 0,
518 'name %r import %s identity %s gcc %s' % (name, rc, ident == id0, rc3))
519 if quick and R_.fail:
520 return R_, units
521 for name in ['n' * 64, 'int8_t', 'size_t', 'INT64_MAX', 'UINT64_C', 'INT_WIDTH', 'INTMAX_MIN', '__x', '_Foo',
522 'main', 'bool', 'true', 'typeof', 'return', 'int64_t', '_Bool']:
523 src = csrc(2, body).replace('calc(', name + '(', 1)
524 rc, o, _ = V.run(tool, src.encode())
525 R_.check('unsupported', rc == 71 and o == b'', 'name %r exit %s want 71' % (name, rc))
526 if quick and R_.fail:
527 return R_, units
528 if out is not None:
529 # Coverage: every comparison outcome and both arms of every select occur on some vector.
530 miss = []
531 for cid, (ops, c) in cov.items():
532 for k, r in enumerate(ops):
533 if 10 <= r['op'] <= 16 and not ({(k, 0), (k, 1)} <= c):
534 miss.append('%s#%d' % (cid, k))
535 out['coverage_missing'] = miss
536 R_.check('coverage', not miss, 'uncovered outcomes %s' % miss)
537 out['overflow_error_vectors'] = sum(sum(o[0] for o in u[3]) for u in units.values())
538 out['vectors'] = sum(len(u[2]) for u in units.values())
539 return R_, units
540
541
542def all_units(ctx, cunits):
543 """(id, env, ops, vectors) for every C import result and every hand-built v3 unit (codec-accepted)."""
544 out = []
545 for cid, (env, ops, vs, orc, src) in cunits.items():
546 out.append((cid, env, ops, vs))
547 for hid, ops, lang, prof in HAND:
548 env = env_of(sem(ops, lang, prof))
549 rc, _, err = sa(ctx, ctx.a.s2build, 2, env)
550 if rc != 0:
551 raise AssertionError('hand unit %s refused by the v3 codec: %s %s' % (hid, rc, err))
552 n = arity(ops)
553 out.append((hid, env, ops, vectors(n, hid)))
554 return out
555
556
557def export_refusals():
558 v1 = V.envelope(V.build_sem([(9, U, U, 0), (9, U, U, 1), (2, 0, 1, 0)]))
559 big = [IN(0)]
560 for i in range(1, 40):
561 big.append(AR(2, i - 1, i - 1, 5))
562 ok = env_of(sem([IN(0), IN(1), AR(2, 0, 1)]))
563 return [
564 ('v1-unit', v1, 68),
565 ('garbage', b'not an envelope', 65),
566 ('empty', b'', 65),
567 ('truncated', ok[:-3], 65),
568 ('bad-record', env_of(sem([IN(0), R(18, 5, 0, 0)])), 65),
569 ('lang-mismatch', env_of(sem([IN(0), IN(1), AR(2, 0, 1)], lang=2, prof=10)), 68),
570 ('too-long', env_of(sem(big)), 67),
571 ('oversize', ok + b'\0' * 8200, 65),
572 ]
573
574
575def rust_call(tool, env, name=None, raw=False):
576 """The public command takes [NAME]; a raw mutant binary takes the c-export style frame directly."""
577 if raw:
578 nm = (name or '').encode()
579 return V.run(tool, bytes([len(nm)]) + nm + env)
580 return V.run(tool + ([name] if name is not None else []), env)
581
582
583def has_attr6(ops):
584 return any(r['op'] in (2, 3, 4) and r['t'] == 5 and r['at'] == 6 for r in ops)
585
586
587def matrix_rows(R_, uid, ops, vs, got, setting, expect_r_error=False):
588 """Check one setting's rows against the reference. D/RC: attribute 6 overflow is the error. R: the
589 two's-complement wrapped value (rows where the checked reference errors are counted as REFINEMENT).
590 expect_r_error is the mutated-expectation control: it demands the error from R as well."""
591 bad = None
592 refine = 0
593 for v, g in zip(vs, got):
594 chk = evaluate(ops, v)
595 ref = evaluate(ops, v, wrap6=(setting == 'R' and not expect_r_error))
596 if not same(ref, g):
597 bad = (v, ref, g)
598 break
599 if setting == 'R' and chk[0] == 1:
600 refine += 1
601 errs = sum(g[0] for g in got)
602 R_.counts['rows:' + setting] = R_.counts.get('rows:' + setting, 0) + len(got)
603 R_.counts['error:' + setting] = R_.counts.get('error:' + setting, 0) + errs
604 if refine:
605 R_.counts['refinement:' + setting] = R_.counts.get('refinement:' + setting, 0) + refine
606 cls = '%s:%s' % (setting, 'overflow' if errs or refine else 'boundary')
607 return R_.check(cls, bad is None, '%s %s vector %s reference %s rust %s' % (
608 (setting, uid) + bad if bad else (setting, uid, 0, 0, 0)))
609
610
611def rust_check(ctx, tool, units, quick=False, raw=False, settings=('D',)):
612 R_ = Run('rust')
613 results = {}
614 for uid, env, ops, vs in units:
615 rc, rs, err = rust_call(tool, env, raw=raw)
616 if not R_.check('positive', rc == 0 and rs, '%s exit %s %s' % (uid, rc, err[:120])):
617 if quick:
618 return R_, results
619 continue
620 text = rs.decode()
621 if uid in RUST_GOLDEN:
622 R_.check('golden', text == RUST_GOLDEN[uid], '%s text %r' % (uid, text))
623 per = {}
624 for s in settings:
625 got, why = ctx.rust_run(text, ptypes(ops), ops[-1]['t'], vs, s)
626 if not R_.check('positive', got is not None, '%s %s rustc: %s' % (s, uid, why)):
627 continue
628 matrix_rows(R_, uid, ops, vs, got, s)
629 per[s] = got
630 if len(settings) > 1 and not has_attr6(ops) and len(per) == len(settings):
631 # Attribute 5 (wrapping_*) and comparison-only units: the build setting must not matter.
632 R_.check('attr5-identical', all(per[s] == per[settings[0]] for s in settings),
633 '%s differs across %s' % (uid, settings))
634 if 'D' in per:
635 results[uid] = per
636 if quick and R_.fail:
637 return R_, results
638 for rid, env, want in export_refusals():
639 rc, o, e = rust_call(tool, env, raw=raw)
640 R_.check('malformed' if want == 65 else 'unsupported', rc == want and o == b'',
641 '%s exit %s want %s' % (rid, rc, want))
642 if quick and R_.fail:
643 return R_, results
644 # NAME (amendment A8): any C identifier of at most 63 bytes that is not a Rust keyword.
645 uid, env, ops, vs = units[0]
646 base = RUST_GOLDEN[uid]
647 for name in ['absdiff', 'Foo_1', '_x', 'main', 'union', 'n' * 63]:
648 rc, o, _ = rust_call(tool, env, name, raw)
649 want = base.replace('pub fn calc(', 'pub fn %s(' % name, 1)
650 if R_.check('name', rc == 0 and o.decode() == want, 'NAME %r exit %s %r' % (name, rc, o[:60])):
651 d = ctx.tmp('rust-name')
652 (d / 'lib.rs').write_bytes(o)
653 rc2, _, err2 = V.run([ctx.a.rustc, '--edition', '2021', '--crate-type', 'lib', '-A', 'warnings',
654 d / 'lib.rs', '-o', d / 'lib.rlib'])
655 R_.check('name', rc2 == 0, 'NAME %r rustc %s' % (name, err2[:120]))
656 if quick and R_.fail:
657 return R_, results
658 for name in ['fn', '_', 'self', 'Self', 'async', 'gen', '1x', 'a-b', 'é', 'n' * 64, 'x' * 255]:
659 rc, o, _ = rust_call(tool, env, name, raw)
660 R_.check('unsupported', rc == 64 and o == b'', 'NAME %r exit %s' % (name, rc))
661 if quick and R_.fail:
662 return R_, results
663 return R_, results
664
665
666def lower_check(ctx, tool, units, quick=False):
667 R_ = Run('native')
668 for uid, env, ops, vs in units:
669 rc, om, err = V.run(tool, env)
670 if not R_.check('positive', rc == 0 and om.startswith(b'note omega.universal.lower.s2.v1 semantic '),
671 '%s lower exit %s %s' % (uid, rc, err[:120])):
672 if quick:
673 return R_
674 continue
675 rc2, ident, _ = sa(ctx, ctx.a.s2build, 3, env)
676 R_.check('positive', rc2 == 0 and om.split(b'\n', 1)[0].endswith(ident.hex().encode()),
677 '%s semantic identity note' % uid)
678 got, why = ctx.native(om, arity(ops), vs)
679 if not R_.check('native', got is not None, '%s native: %s' % (uid, why)):
680 if quick:
681 return R_
682 continue
683 bad = None
684 for v, g in zip(vs, got):
685 ref = evaluate(ops, v)
686 if g[0] not in (0, 1) or not same(ref, g):
687 bad = (v, ref, g)
688 break
689 R_.check('native', bad is None, '%s vector %s reference %s native %s' % ((uid,) + bad if bad else (uid, 0, 0, 0)))
690 if quick and R_.fail:
691 return R_
692 uid, env, ops, vs = units[0]
693 rc, om, _ = V.run(tool + ['isum'], env)
694 got, why = ctx.native(om, arity(ops), vs, 'omega_isum') if rc == 0 else (None, 'exit %s' % rc)
695 R_.check('native', got is not None and all(same(evaluate(ops, v), g) for v, g in zip(vs, got)),
696 'NAME isum: %s' % why)
697 for name in ['1x', 'wadd', 'u', 'p', 'v', 'sbits', 'long', 'a-b', 'x' * 64]:
698 rc, o, _ = V.run(tool + [name], env)
699 R_.check('unsupported', rc == 64 and o == b'', 'NAME %r exit %s' % (name, rc))
700 for rid, env2, want in export_refusals():
701 if rid in ('too-long',):
702 continue
703 rc, o, _ = V.run(tool, env2)
704 want2 = 68 if want == 68 else 65
705 R_.check('malformed' if want2 == 65 else 'unsupported', rc == want2 and o == b'',
706 '%s exit %s want %s' % (rid, rc, want2))
707 return R_
708
709
710def compose_check(ctx, cunits, rust_results, settings=MATRIX):
711 """C -> c-i64-import -> rust-i64-export -> rustc against the C oracle, per build setting. D and RC equal
712 the oracle on every vector (UBSan error = panic). R equals it wherever C is defined; where the C oracle
713 reports signed overflow (undefined behaviour in C17) R must return exactly the wrapped reference value:
714 a REFINEMENT, counted separately, never an equality with the C error."""
715 R_ = Run('compose')
716 for cid, (env, ops, vs, orc, src) in cunits.items():
717 per = rust_results.get(cid, {})
718 for s in settings:
719 got = per.get(s)
720 if not R_.check('%s:composition' % s, got is not None, '%s %s no Rust result' % (s, cid)):
721 continue
722 bad = None
723 for v, o, g in zip(vs, orc, got):
724 if s == 'R' and o[0] == 1:
725 w = evaluate(ops, v, wrap6=True)
726 if g != w:
727 bad = (v, o, g)
728 break
729 R_.counts['R:refinement'] = R_.counts.get('R:refinement', 0) + 1
730 elif not same(o, g):
731 bad = (v, o, g)
732 break
733 R_.check('%s:composition' % s, bad is None,
734 '%s %s vector %s C %s Rust %s' % ((s, cid) + bad if bad else (s, cid, 0, 0, 0)))
735 return R_
736
737
738def control_check(ctx, tool, units):
739 """Negative controls; each must FAIL its check. (i) mutated expectation: R is required to report the
740 attribute 6 error. (ii) mutated unit: attribute 6 exported as wrapping_add, checked under D and RC."""
741 out = []
742 byid = {u[0]: u for u in units}
743 uid, env, ops, vs = byid['add']
744 rc, rs, _ = rust_call(tool, env)
745 text = rs.decode() if rc == 0 else ''
746 got, why = ctx.rust_run(text, ptypes(ops), ops[-1]['t'], vs, 'R')
747 probe = Run('control')
748 ok = got is not None and matrix_rows(probe, uid, ops, vs, got, 'R', expect_r_error=True)
749 out.append({'control': 'R-reports-error-expectation', 'observed': 'PASS' if ok else 'FAIL',
750 'by': probe.fail[:1] or [why]})
751 mut = text.replace('i0 + i1', 'i0.wrapping_add(i1)')
752 for s in ('D', 'RC'):
753 probe = Run('control')
754 got, why = ctx.rust_run(mut, ptypes(ops), ops[-1]['t'], vs, s)
755 ok = mut != text and got is not None and matrix_rows(probe, uid, ops, vs, got, s)
756 out.append({'control': 'attr6-as-wrapping_add-%s' % s, 'observed': 'PASS' if ok else 'FAIL',
757 'by': probe.fail[:1] or [why]})
758 return out
759
760
761# ------------------------------------------------------------------ codec (v1/v2 differential, v3 rows)
762def codec_check(ctx):
763 R_ = Run('codec')
764 old, new = ctx.a.sa2 / 'sa', ctx.a.s2build / 'sa'
765 base = []
766 s1 = V.build_sem([(9, U, U, 0), (9, U, U, 1), (2, 0, 1, 0), (1, U, U, 7), (4, 2, 3, 0), (1, U, U, 0), (2, 4, 5, 0)])
767 base.append(V.envelope(s1))
768 rc, e, _ = V.run([ctx.a.c_import_v1], b'#include <stdint.h>\nuint64_t calc(uint64_t a, uint64_t b) { return a * b + 3ULL; }\n')
769 if rc == 0:
770 base.append(e)
771 for lang, prof in [(5, 7), (6, 8), (7, 9)]:
772 s = bytearray(V.build_sem([(9, U, U, 0), (1, U, U, 3), (3, 0, 1, 0)], lang=lang, prof=prof))
773 s[4] = 2
774 base.append(V.envelope(bytes(s)))
775 for lang, prof in [(3, 3), (3, 4), (4, 5)]:
776 base.append(V.envelope(V.build_sem([(9, U, U, 0), (2, 0, 0, 0)], lang=lang, prof=prof)))
777 corpus = list(base)
778 rnd = random.Random('S2-codec-corpus')
779 for e in base:
780 for pos in range(min(len(e), 13 + 44 + 40)):
781 for x in (0x01, 0x02, 0x80):
782 m = bytearray(e)
783 m[pos] ^= x
784 corpus.append(bytes(m))
785 for _ in range(40):
786 m = bytearray(e)
787 m[rnd.randrange(len(m))] = rnd.randrange(256)
788 corpus.append(bytes(m))
789 corpus.append(e[:-1])
790 corpus.append(e + b'\0')
791 diffs = 0
792 # A mutant whose OMSA version byte became 3 is a v3 input, outside the "v1/v2 unchanged" domain; the v3
793 # rows below cover that domain (e.g. v3-profile-1 refuses 68 where the v2 codec refuses 66).
794 v3dom = [e for e in corpus if len(e) > 17 and e[:4] == b'OMSB' and e[13:17] == b'OMSA' and e[17] == 3]
795 R_.counts['v3-domain-excluded'] = len(v3dom)
796 for e in corpus:
797 if len(e) > 17 and e[:4] == b'OMSB' and e[13:17] == b'OMSA' and e[17] == 3:
798 continue
799 for mode in range(0, 8):
800 data = (bytes([1, 0, 1, 0]) + e) if mode == 6 else e
801 a = sa(ctx, ctx.a.sa2, mode, data)
802 b = sa(ctx, ctx.a.s2build, mode, data)
803 if (a[0], a[1]) != (b[0], b[1]):
804 diffs += 1
805 if diffs <= 5:
806 R_.fail.append('codec v1/v2 differential mode %d: v2 %s v3 %s on %s' % (mode, a[0], b[0], e[:30].hex()))
807 R_.counts['v1v2-differential'] = R_.counts.get('v1v2-differential', 0) + 1
808 R_.ok += R_.counts['v1v2-differential'] - diffs
809 good = [IN(0), IN(1), AR(2, 0, 1), CMP(12, 0, 1), SEL(3, 2, 0)]
810 rows = [
811 ('v3-ok', sem(good), 0),
812 ('version-4', sem(good, ver=4), 66),
813 ('v3-profile-1', sem(good, prof=1), 68),
814 ('v2-profile-10', sem(good, ver=2), 68),
815 ('profile-16', sem(good, prof=16), 68),
816 ('lang-2-profile-10', sem(good, lang=2), 68),
817 ('runtime-1', sem(good, rt=1), 68),
818 ('abi-2', sem(good, abi=2), 68),
819 ('op-18', sem([IN(0), R(18, 5, 0, 0)]), 69),
820 ('op-0', sem([IN(0), R(0, 5, 0, 0)]), 69),
821 ('op-5-load', sem([IN(0), R(5, 5, 0, 0)]), 68),
822 ('type-7', sem([IN(0), R(2, 7, 6, 33, 0, 0)]), 70),
823 ('type-2', sem([IN(0), R(2, 2, 6, 33, 0, 0)]), 68),
824 ('effects', sem([IN(0), R(2, 5, 6, 33, 0, 0, ef=1)]), 71),
825 ('attr6-obl1', sem([IN(0), R(2, 5, 6, 1, 0, 0)]), 72),
826 ('attr5-obl33', sem([IN(0), R(2, 5, 5, 33, 0, 0)]), 72),
827 ('i64-attr1', sem([IN(0), R(2, 5, 1, 1, 0, 0)]), 70),
828 ('arith-imm', sem([IN(0), R(2, 5, 6, 33, 0, 0, imm=1)]), 65),
829 ('arith-forward', sem([IN(0), R(2, 5, 6, 33, 0, 2), IN(1)]), 70),
830 ('arith-type-mix', sem([IN(0), IN(1, 1), R(2, 5, 6, 33, 0, 1)]), 70),
831 ('bool-arith', sem([IN(0), CMP(10, 0, 0), R(2, 6, 0, 0, 1, 1)]), 70),
832 ('cmp-type-i64', sem([IN(0), R(12, 5, 0, 0, 0, 0)]), 70),
833 ('cmp-mixed', sem([IN(0), IN(1, 1), CMP(12, 0, 1)]), 70),
834 ('cmp-bool-operands', sem([IN(0), CMP(10, 0, 0), CMP(10, 1, 1)]), 70),
835 ('cmp-obl', sem([IN(0), R(12, 6, 0, 1, 0, 0)]), 72),
836 ('sel-cond-i64', sem([IN(0), SEL(0, 0, 0)]), 70),
837 ('sel-else-forward', sem([IN(0), CMP(10, 0, 0), SEL(1, 0, 3), IN(1)]), 70),
838 ('sel-else-type', sem([IN(0), IN(1, 1), CMP(10, 0, 0), SEL(2, 0, 1)]), 70),
839 ('sel-attr', sem([IN(0), CMP(10, 0, 0), R(16, 5, 5, 0, 1, 0, 0)]), 70),
840 ('not-b', sem([IN(0), CMP(10, 0, 0), R(17, 6, 0, 0, 1, 0)]), 70),
841 ('not-i64', sem([IN(0), NOT(0)]), 70),
842 ('bool-const-2', sem([R(1, 6, 0, 0, imm=2)]), 70),
843 ('i64-const-attr1', sem([R(1, 5, 1, 0, imm=2)]), 70),
844 ('u64-const-attr0', sem([R(1, 1, 0, 0, imm=2)]), 70),
845 ('bool-input', sem([IN(0, 6)]), 70),
846 ('input-slot-6', sem([IN(6)]), 67),
847 ('input-dup', sem([IN(0), IN(0)]), 70),
848 ('input-obl', sem([R(9, 5, 0, 0, imm=0)]), 72),
849 ('dialect', sem([R(9, 5, 0, 1, imm=0, d=2)]), 68),
850 ('op-version', sem([R(9, 5, 0, 1, imm=0, v=2)]), 66),
851 ]
852 for rid, s, want in rows:
853 rc, o, _ = sa(ctx, ctx.a.s2build, 2, env_of(s))
854 R_.check('v3-positive' if want == 0 else 'v3-refusal', rc == want, '%s exit %s want %s' % (rid, rc, want))
855 rc, _, _ = sa(ctx, ctx.a.sa2, 2, env_of(sem(good)))
856 R_.check('v3-refusal', rc == 66, 'v2 codec on a v3 unit exit %s want 66' % rc)
857 return R_
858
859
860# ------------------------------------------------------------------ tool-source mutants
861C_MUTANTS = [
862 ('wrap-as-plain', 'setf 5 5 1\nret emitop code a b 0 lo hi', 'setf 5 6 33\nret emitop code a b 0 lo hi'),
863 ('plain-add-as-wrap', 'right = term depth\nsetf 5 6 33', 'right = term depth\nsetf 5 5 1'),
864 ('plain-mul-as-wrap', 'right = primary depth\nsetf 5 6 33', 'right = primary depth\nsetf 5 5 1'),
865 ('lt-as-le', 'lexnext\nret 13\nend\nret 12', 'lexnext\nret 13\nend\nret 13'),
866 ('gt-as-ge', 'lexnext\nret 15\nend\nret 14', 'lexnext\nret 15\nend\nret 15'),
867 ('eq-as-ne', 'lexnext\nret 10', 'lexnext\nret 11'),
868 ('select-arms-swapped', 'ret emitop 16 c x y qlo qhi', 'ret emitop 16 c y x qlo qhi'),
869 ('compare-operands-swapped', 'c = emitop code left right 0 lo hi', 'c = emitop code right left 0 lo hi'),
870 ('wrap-sub-as-add', 'if eq k 45\ncode = 3\nend\nif eq k 42', 'if eq k 45\ncode = 2\nend\nif eq k 42'),
871 ('literal-limit', 'gt d 7', 'gt d 8'),
872 ('sub-as-add', 'if eq get Tk 0 45\ncode = 3', 'if eq get Tk 0 45\ncode = 2'),
873]
874RUST_MUTANTS = [
875 ('attr6-as-wrapping', 'ret and eq get Ot k 5 eq get Oat k 6', 'ret and eq get Ot k 5 eq get Oat k 5'),
876 ('lt-as-le', 'text Ycmp " == != < <= > >= "', 'text Ycmp " == != <= <= > >= "'),
877 ('eq-as-ne', 'text Ycmp " == != < <= > >= "', 'text Ycmp " != != < <= > >= "'),
878 ('select-arms-swapped', 'yemit get Ob k 1\nfor i ulong len Ysel3\nybyte ulong get Ysel3 i\nend\nyemit get Oi k 1',
879 'yemit get Oi k 1\nfor i ulong len Ysel3\nybyte ulong get Ysel3 i\nend\nyemit get Ob k 1'),
880 ('negative-sign-dropped', 'ybyte 45\nydec sub 0 v', 'ybyte 32\nydec sub 0 v'),
881 ('i64-suffix-as-u64', 'if eq t 5\nybyte 105\nelse', 'if eq t 5\nybyte 117\nelse'),
882 ('wrapping-add-sub-swapped', 'text Ymeth ".wrapping_add(.wrapping_sub(', 'text Ymeth ".wrapping_sub(.wrapping_add('),
883 ('plain-add-sub-swapped', 'text Yops " + - * "', 'text Yops " - + * "'),
884 ('not-dropped', 'ybyte 33\nyemit get Oa k 0', 'ybyte 32\nyemit get Oa k 0'),
885 ('normalization-kept', 'if ne get Oat y 5\nret y', 'if ne get Oat y 6\nret y'),
886]
887LOWER_MUTANTS = [
888 ('add-overflow-edge', 'if and lt b 0 ge r 0\\nret 1', 'if and lt b 0 gt r 0\\nret 1'),
889 ('mul-min-neg1', 'if eq b -9223372036854775808\\nret 1', 'if eq b -9223372036854775808\\nret 0'),
890 ('sub-overflow-sign', 'if and ge b 0 ge r 0\\nret 1', 'if and ge b 0 lt r 0\\nret 1'),
891 ('select-cond-poison-dropped', 'ofrag 35\nogp c\nogp x', 'ofrag 35\nogp x\nogp x'),
892 ('select-arms-swapped', 'oarm k c get Ob k\nofrag 17\noarm k c get Oi k', 'oarm k c get Oi k\nofrag 17\noarm k c get Ob k'),
893 ('compare-shifted', 'ofrag add get Oc k 19', 'ofrag add get Oc k 20'),
894 ('attr6-overflow-ignored', 'if eq get Oat k 6\nopp k\nofrag add c 24', 'if eq get Oat k 7\nopp k\nofrag add c 24'),
895 ('root-trap-inverted', 'ofrag 16\nofrag 30\nogp r', 'ofrag 16\nofrag 29\nogp r'),
896 ('wsub-operands-swapped', 'ret slong sub sbits a sbits b', 'ret slong sub sbits b sbits a'),
897 ('not-as-add', 'ofrag 40', 'ofrag 20'),
898 ('compare-poison-dropped', 'ofrag 35\nogp a\nogp get Ob k', 'ofrag 35\nogp get Ob k\nogp get Ob k'),
899]
900
901
902def build_mutant(ctx, name, src_rel, old, new):
903 m = json.loads((ctx.a.s2build / 'build.json').read_text())['artifacts'][name]
904 pin = m['compiler_sha256']
905 comp = ctx.a.omc191 if pin == SEED_OMC else ctx.a.omc
906 text = (ROOT / src_rel).read_text()
907 if text.count(old) != 1:
908 raise AssertionError('mutant anchor %r occurs %d times in %s' % (old, text.count(old), src_rel))
909 parts = []
910 for rel in m['inputs']:
911 parts.append(text.replace(old, new).encode() if rel == src_rel else (ROOT / rel).read_bytes())
912 program = b'\n'.join(parts) + b'\n'
913 rc, binary, err = V.run([comp], program, timeout=120)
914 if rc != 0 or binary[:4] != b'\x7fELF':
915 return None, 'compile exit %s: %s' % (rc, err.decode(errors='replace')[:200])
916 d = ctx.tmp('mutant-' + name)
917 exe = d / name
918 exe.write_bytes(binary)
919 exe.chmod(0o700)
920 return [exe], None
921
922
923def run_mutants(ctx, cunits, units):
924 res = []
925 plan = [('c-i64-import', 'src/adapters/c-i64-import.om', C_MUTANTS),
926 ('rust-i64-export', 'src/adapters/rust-i64-export.om', RUST_MUTANTS),
927 ('lower-s2', 'src/adapters/upper-lower-s2.om', LOWER_MUTANTS)]
928 for name, rel, muts in plan:
929 for mid, old, new in muts:
930 tool, why = build_mutant(ctx, name, rel, old, new)
931 if tool is None:
932 res.append({'tool': name, 'mutant': mid, 'killed': False, 'why': 'stillborn: ' + why})
933 continue
934 if name == 'c-i64-import':
935 r, _ = c_import_check(ctx, tool, quick=True)
936 elif name == 'rust-i64-export':
937 r, _ = rust_check(ctx, tool, units, quick=True, raw=True)
938 else:
939 r = lower_check(ctx, tool, units, quick=True)
940 res.append({'tool': name, 'mutant': mid, 'killed': bool(r.fail), 'by': r.fail[:1]})
941 return res
942
943
944# ------------------------------------------------------------------ main
945def main():
946 ap = argparse.ArgumentParser()
947 ap.add_argument('--omc', required=True)
948 ap.add_argument('--omc191', required=True)
949 ap.add_argument('--bridge-native', required=True)
950 ap.add_argument('--sa2', required=True, help='the v2 codec build directory (build/L832)')
951 ap.add_argument('--s2build', default=str(ROOT / 'build/S2'))
952 ap.add_argument('--c-import-v1', required=True)
953 ap.add_argument('--cc', default='gcc')
954 ap.add_argument('--rustc', default='rustc')
955 ap.add_argument('--out', required=True)
956 ap.add_argument('--log-dir', default='')
957 a = ap.parse_args()
958 for k in ('sa2', 's2build'):
959 setattr(a, k, Path(getattr(a, k)))
960 out = Path(a.out)
961 out.mkdir(parents=True, exist_ok=False)
962 rep = {'schema': 'omega.translation-s2.selftest.v1', 'spec': 'spec/universal/translation-s2-v1.md', 'tools': {}}
963 try:
964 for k, pin in (('omc', NATIVE_OMC), ('omc191', SEED_OMC)):
965 p = Path(getattr(a, k))
966 if not p.is_file() or sha(p.read_bytes()) != pin:
967 raise NotRun('%s is not the pinned compiler %s' % (k, pin[:8]))
968 rep['tools'][k] = {'path': str(p), 'sha256': pin}
969 for k in ('bridge_native', 'c_import_v1'):
970 p = Path(getattr(a, k))
971 if not p.is_file():
972 raise NotRun('missing ' + k)
973 rep['tools'][k] = {'path': str(p), 'sha256': sha(p.read_bytes())}
974 for k, p in (('sa2', a.sa2 / 'sa'), ('s2-sa', a.s2build / 'sa')):
975 if not p.is_file():
976 raise NotRun('missing ' + str(p))
977 rep['tools'][k] = {'path': str(p), 'sha256': sha(p.read_bytes())}
978 for k, argv in (('cc', [a.cc, '--version']), ('rustc', [a.rustc, '--version'])):
979 rc, o, _ = V.run(argv)
980 if rc != 0:
981 raise NotRun('oracle %s absent' % k)
982 rep['tools'][k] = o.decode().split('\n')[0]
983 rep['tools']['s2_build'] = json.loads((a.s2build / 'build.json').read_text())
984 except NotRun as e:
985 print('NOT_RUN', e)
986 (out / 'receipt.json').write_text(json.dumps({'status': 'NOT_RUN', 'why': str(e)}, indent=2) + '\n')
987 return 3
988 t0 = time.time()
989 ctx = Ctx(a, out / 'work')
990 tools = {k: [str(ROOT / 'tools/adapters' / k)] for k in ('c-i64-import', 'rust-i64-export', 'lower-s2')}
991 runs = []
992 runs.append(codec_check(ctx))
993 extra = {}
994 rc_run, cunits = c_import_check(ctx, tools['c-i64-import'], out=extra)
995 runs.append(rc_run)
996 units = all_units(ctx, cunits)
997 rr, rust_results = rust_check(ctx, tools['rust-i64-export'], units, settings=MATRIX)
998 runs.append(rr)
999 runs.append(lower_check(ctx, tools['lower-s2'], units))
1000 runs.append(compose_check(ctx, cunits, rust_results))
1001 controls = control_check(ctx, tools['rust-i64-export'], units)
1002 muts = run_mutants(ctx, cunits, units)
1003 fails = [f for r in runs for f in r.fail]
1004 per = {}
1005 for m in muts:
1006 per.setdefault(m['tool'], [0, 0])
1007 per[m['tool']][0] += 1
1008 per[m['tool']][1] += int(m['killed'])
1009 for tool, (n, k) in per.items():
1010 if n < 8 or k != n:
1011 fails.append('mutants %s: %d/%d killed (need all, >= 8)' % (tool, k, n))
1012 for c in controls:
1013 if c['observed'] != 'FAIL':
1014 fails.append('negative control %s passed (must fail)' % c['control'])
1015 matrix = {}
1016 for r in (rr, runs[-1]):
1017 for k, v in r.counts.items():
1018 if ':' in k:
1019 s = k.split(':')[1] if k.split(':')[0] in ('rows', 'error', 'refinement') else k.split(':')[0]
1020 matrix.setdefault(s, {})['%s.%s' % (r.label, k)] = v
1021 rep.update({
1022 'status': 'PASS' if not fails else 'FAIL',
1023 'checks': {r.label: {'ok': r.ok, 'failed': len(r.fail), 'by_class': r.counts} for r in runs},
1024 'c_import': extra, 'units': len(units), 'c_fixtures': len(cunits), 'hand_units': len(HAND),
1025 'mutants': muts, 'mutant_summary': {k: {'total': n, 'killed': kk} for k, (n, kk) in per.items()},
1026 'rust_settings': {s: RUST_SETTINGS[s] for s in MATRIX}, 'rust_matrix': matrix, 'controls': controls,
1027 'failures': fails[:50], 'seconds': round(time.time() - t0, 1),
1028 })
1029 text = json.dumps(rep, indent=2) + '\n'
1030 (out / 'receipt.json').write_text(text)
1031 if a.log_dir:
1032 Path(a.log_dir).mkdir(parents=True, exist_ok=True)
1033 (Path(a.log_dir) / ('s2-selftest-%s.json' % out.name)).write_text(text)
1034 for r in runs:
1035 print('%-9s ok %5d failed %3d %s' % (r.label, r.ok, len(r.fail), json.dumps(r.counts, sort_keys=True)))
1036 for tool, (n, k) in sorted(per.items()):
1037 print('mutants %-16s %d/%d killed' % (tool, k, n))
1038 for s in MATRIX:
1039 print('rust-setting %-2s %s' % (s, json.dumps(matrix.get(s, {}), sort_keys=True)))
1040 for c in controls:
1041 print('control %-32s observed %s %s' % (c['control'], c['observed'], (c['by'] or [''])[0]))
1042 for f in fails[:30]:
1043 print('FAIL', f)
1044 print('TRANSLATION-S2 %s receipt %s' % (rep['status'], out / 'receipt.json'))
1045 return 0 if not fails else 1
1046
1047
1048if __name__ == '__main__':
1049 sys.exit(main())