omega-bridge
Omega-first language interoperability: checked conversion backends and native language bindings
Brought by drakestapleton
omega-bridge / tests / seeded_views.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Bit-exact seeded typed views/arrays, public float ABI and refusal/mutant controls. |
| 3 | |
| 4 | Pinned source semantics: omega-mv e5b32567 seed/omc/omc.om twid/tlog, |
| 5 | ldop/stop, fintr; OMEGESE.md 9.3/9.4 and Float values. |
| 6 | WolframLanguageEvaluator: {2^16,2^20,2^32-1} -> {65536,1048576,4294967295}. |
| 7 | Expected floating results come from executing the pinned compiler, never Python FP. |
| 8 | """ |
| 9 | import ctypes as C |
| 10 | import hashlib |
| 11 | import os |
| 12 | from pathlib import Path |
| 13 | import random |
| 14 | import re |
| 15 | import subprocess |
| 16 | import tempfile |
| 17 | |
| 18 | ROOT = Path(__file__).resolve().parents[1] |
| 19 | PIN = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f" |
| 20 | OMC = Path(os.environ["OMEGA_SEEDED_OMC"]) |
| 21 | assert hashlib.sha256(OMC.read_bytes()).hexdigest() == PIN |
| 22 | |
| 23 | |
| 24 | def run(cmd, data=None, ok=0): |
| 25 | p = subprocess.run([str(x) for x in cmd], input=data, capture_output=True, timeout=300) |
| 26 | assert p.returncode == ok, (cmd, p.returncode, p.stderr.decode(errors="replace")) |
| 27 | return p.stdout |
| 28 | |
| 29 | |
| 30 | def convert(src, mode="c"): |
| 31 | with tempfile.TemporaryDirectory(prefix="omega-seeded-source-") as td: |
| 32 | path = Path(td) / "unit.om" |
| 33 | path.write_text(src) |
| 34 | return run([ROOT / "tools/bridge-seeded", mode, path]) |
| 35 | |
| 36 | |
| 37 | def cc(src, out, shared=False, compiler=None): |
| 38 | p = out.with_suffix(".c") |
| 39 | p.write_bytes(src) |
| 40 | flags = ["-shared", "-fPIC", "-DOMEGA_LIBRARY"] if shared else [] |
| 41 | run([compiler or os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", *flags, p, "-o", out]) |
| 42 | |
| 43 | |
| 44 | def storage_codegen(generated, work): |
| 45 | """Use the emitted helpers, not hand-written stand-ins, for the GCC -O2 regression.""" |
| 46 | compiler = os.environ.get("CC", "cc") |
| 47 | if "aarch64" not in run([compiler, "-dumpmachine"]).decode(): |
| 48 | print("NOT_RUN fixed-width AArch64 codegen: CC is not an AArch64 compiler") |
| 49 | return |
| 50 | |
| 51 | def violations(code, name): |
| 52 | lines = code.decode().splitlines() |
| 53 | helpers = [] |
| 54 | for prefix in ("static unsigned o_width(", "static __int128 o_value(", |
| 55 | "static uint64_t o_norm(", "static uint64_t o_get(", "static void o_put("): |
| 56 | selected = [line for line in lines if line.startswith(prefix)] |
| 57 | assert len(selected) == 1, prefix |
| 58 | helpers.extend(selected) |
| 59 | probes = [] |
| 60 | for typ in (3, 4, 5): |
| 61 | probes.append(f"uint64_t probe_load{typ}(const void*p,uint64_t n,uint64_t i)" |
| 62 | f"{{return o_get(p,n,i,{typ});}}") |
| 63 | probes.append(f"void probe_store{typ}(void*p,uint64_t n,uint64_t i,uint64_t v)" |
| 64 | f"{{o_put(p,n,i,v,{typ});}}") |
| 65 | source = work / (name + ".c") |
| 66 | assembly = source.with_suffix(".s") |
| 67 | source.write_text("#include <stdint.h>\n" |
| 68 | "void o_trap(int) __attribute__((noreturn));\n" |
| 69 | + "\n".join(helpers + probes) + "\n") |
| 70 | run([compiler, "-O2", "-S", source, "-o", assembly]) |
| 71 | text = assembly.read_text() |
| 72 | bad = [] |
| 73 | for typ, bits in ((3, 16), (4, 32), (5, 64)): |
| 74 | for operation, instruction in (("load", "ldr"), ("store", "str")): |
| 75 | symbol = f"probe_{operation}{typ}" |
| 76 | match = re.search(rf"(?ms)^{symbol}:\n(.*?)^\s*\.size\s+{symbol},", text) |
| 77 | assert match, ("missing assembly function", symbol) |
| 78 | body = match.group(1) |
| 79 | opcode = instruction + ("h" if bits == 16 else "") |
| 80 | register = "x" if bits == 64 else "w" |
| 81 | if (len(re.findall(rf"(?m)^\s*{opcode}\s+{register}\d+,", body)) != 1 |
| 82 | or re.search(r"\b(?:ldrb|strb)\b", body)): |
| 83 | bad.append(symbol) |
| 84 | return bad |
| 85 | |
| 86 | assert not violations(generated, "storage-codegen"), "fixed-width accesses were not scalarized" |
| 87 | # Restore the reported byte loop: the assembly contract must reject it. |
| 88 | copies = (b"if(w==8)v=b[0];else if(w==16){uint16_t x;__builtin_memcpy(&x,b,2);v=x;}" |
| 89 | b"else if(w==32){uint32_t x;__builtin_memcpy(&x,b,4);v=x;}" |
| 90 | b"else if(w==64)__builtin_memcpy(&v,b,8);") |
| 91 | assert generated.count(copies) == 1 |
| 92 | loop = b"for(unsigned j=0;j<w/8;j++)v|=(uint64_t)b[j]<<(j*8);" |
| 93 | assert violations(generated.replace(copies, loop), "storage-byte-loop-mutant") |
| 94 | print("PASS fixed-width GCC -O2 loads/stores; byte-loop codegen mutant killed") |
| 95 | |
| 96 | |
| 97 | PROGRAM = """fn inc16 a view ushort 1024 b edit ushort 1024 to void |
| 98 | for i ulong 1024 |
| 99 | put b i add get a i 1 |
| 100 | end |
| 101 | ret |
| 102 | end |
| 103 | fn inc32 a view uint 1024 b edit uint 1024 to void |
| 104 | for i ulong 1024 |
| 105 | put b i add get a i 1 |
| 106 | end |
| 107 | ret |
| 108 | end |
| 109 | fn copy32 a view f32 1024 b edit f32 1024 to void |
| 110 | for i ulong 1024 |
| 111 | put b i get a i |
| 112 | end |
| 113 | ret |
| 114 | end |
| 115 | fn word out edit uchar 20480 off ulong value uint to void |
| 116 | for j ulong 4 |
| 117 | shift = uint mul j 8 |
| 118 | part = and shr value shift 255 |
| 119 | put out add off j uchar part |
| 120 | end |
| 121 | ret |
| 122 | end |
| 123 | fn readword input view uchar 4096 off ulong to uint |
| 124 | x = uint 0 |
| 125 | for j ulong 4 |
| 126 | p = add off j |
| 127 | v = uint get input p |
| 128 | shift = uint mul j 8 |
| 129 | x = or x shl v shift |
| 130 | end |
| 131 | ret x |
| 132 | end |
| 133 | fn process16 input view uchar 4096 output edit uchar 20480 to void |
| 134 | a = new ushort 1024 0 |
| 135 | b = new ushort 1024 0 |
| 136 | for i ulong 1024 |
| 137 | x = readword view input mul i 4 |
| 138 | put a i ushort and x 65535 |
| 139 | end |
| 140 | inc16 view a b |
| 141 | for i ulong 1024 |
| 142 | word output mul i 20 uint get b i |
| 143 | end |
| 144 | ret |
| 145 | end |
| 146 | fn process32 input view uchar 4096 output edit uchar 20480 to void |
| 147 | a = new uint 1024 0 |
| 148 | b = new uint 1024 0 |
| 149 | for i ulong 1024 |
| 150 | put a i readword view input mul i 4 |
| 151 | end |
| 152 | inc32 view a b |
| 153 | for i ulong 1024 |
| 154 | word output add mul i 20 4 get b i |
| 155 | end |
| 156 | ret |
| 157 | end |
| 158 | fn processf input view uchar 4096 output edit uchar 20480 to void |
| 159 | a = new f32 1024 0.0f32 |
| 160 | b = new f32 1024 0.0f32 |
| 161 | for i ulong 1024 |
| 162 | put a i bitcast f32 readword view input mul i 4 |
| 163 | end |
| 164 | copy32 view a b |
| 165 | for i ulong 1024 |
| 166 | off = mul i 20 |
| 167 | word output add off 8 bitcast uint get b i |
| 168 | word output add off 12 bitcast uint add get b i 1.0f32 |
| 169 | word output add off 16 bitcast uint fsqrt get b i |
| 170 | end |
| 171 | ret |
| 172 | end |
| 173 | fn main to int |
| 174 | input = new uchar 4096 0 |
| 175 | output = new uchar 20480 0 |
| 176 | more = true |
| 177 | while more |
| 178 | have = ulong 0 |
| 179 | while lt have 4096 |
| 180 | n = read 0 input have sub 4096 have |
| 181 | if lt n 0 |
| 182 | ret 9 |
| 183 | end |
| 184 | if eq n 0 |
| 185 | if ne have 0 |
| 186 | ret 8 |
| 187 | end |
| 188 | more = false |
| 189 | break |
| 190 | end |
| 191 | have = add have ulong n |
| 192 | end |
| 193 | if more |
| 194 | process16 view input output |
| 195 | process32 view input output |
| 196 | processf view input output |
| 197 | sent = ulong 0 |
| 198 | while lt sent 20480 |
| 199 | n = write 1 output sent sub 20480 sent |
| 200 | if le n 0 |
| 201 | ret 7 |
| 202 | end |
| 203 | sent = add sent ulong n |
| 204 | end |
| 205 | end |
| 206 | end |
| 207 | ret 0 |
| 208 | end |
| 209 | """ |
| 210 | |
| 211 | |
| 212 | def main(): |
| 213 | with tempfile.TemporaryDirectory(prefix="omega-seeded-views-") as td: |
| 214 | w = Path(td) |
| 215 | # Exhaustive u16 followed by exactly 2^20 deterministic random u32 bit patterns. |
| 216 | # The same words are bitcast to f32, not converted through a host float. |
| 217 | edges = [0, 0x80000000, 1, 0x80000001, 0x007fffff, 0x00800000, |
| 218 | 0x7f7fffff, 0xff7fffff, 0x7f800000, 0xff800000, |
| 219 | 0x7f800001, 0x7fc12345, 0xff800001, 0xffc12345, 0xffffffff] |
| 220 | rng = random.Random(0xE5B32567) |
| 221 | words = list(range(65536)) + edges + [rng.getrandbits(32) for _ in range(1048576)] |
| 222 | words.extend([0] * (-len(words) % 1024)) |
| 223 | data = b"".join(x.to_bytes(4, "little") for x in words) |
| 224 | binary = w / "oracle" |
| 225 | binary.write_bytes(run([OMC], PROGRAM.encode())) |
| 226 | binary.chmod(0o755) |
| 227 | expected = run([binary], data) |
| 228 | generated = convert(PROGRAM) |
| 229 | storage_codegen(generated, w) |
| 230 | host = w / "host" |
| 231 | cc(generated, host) |
| 232 | actual = run([host], data) |
| 233 | assert actual == expected, "typed arrays/rounding/sqrt differ from pinned omc" |
| 234 | print("PASS exhaustive-u16=65536 random-u32-f32=1048576 edge-bits=15") |
| 235 | x86 = w / "x86" |
| 236 | cc(generated, x86, compiler="x86_64-linux-gnu-gcc") |
| 237 | assert run([os.environ.get("QEMU_X86_64", "qemu-x86_64"), "-L", "/usr/x86_64-linux-gnu", x86], data) == expected |
| 238 | print("PASS x86 emulated C identical on complete typed-view and fsqrt stream") |
| 239 | # Corrupt each new feature independently. Every comparison must detect it. |
| 240 | mutations = { |
| 241 | "ushort-load": (b"__builtin_memcpy(&x,b,2);v=x;", b"__builtin_memcpy(&x,b,2);v=x^(t==3);"), |
| 242 | "uint-store": (b"uint32_t x=(uint32_t)v;__builtin_memcpy(b,&x,4);", b"uint32_t x=(uint32_t)(v^(t==4));__builtin_memcpy(b,&x,4);"), |
| 243 | "f32-store": (b"uint32_t x=(uint32_t)v;__builtin_memcpy(b,&x,4);", b"uint32_t x=(uint32_t)(v&(t==11?~UINT64_C(1):UINT64_MAX));__builtin_memcpy(b,&x,4);"), |
| 244 | "fsqrt": (b"case 20:z=o_sqrt32(x);break;", b"case 20:z=x;break;"), |
| 245 | } |
| 246 | for name, (old, new) in mutations.items(): |
| 247 | assert generated.count(old) == 1, (name, "mutation site") |
| 248 | exe = w / name |
| 249 | cc(generated.replace(old, new), exe) |
| 250 | assert run([exe], data) != expected, (name, "survived") |
| 251 | print("PASS killed", name) |
| 252 | # Compile-time out-of-range index is error 21 for every new view type. |
| 253 | for typ in ("ushort", "uint", "f32"): |
| 254 | src = f"fn bad a view {typ} 2 to {typ}\nret get a 2\nend\n" |
| 255 | path = w / ("refuse-" + typ + ".om") |
| 256 | path.write_text(src) |
| 257 | p = subprocess.run([ROOT / "tools/bridge-seeded", "c", path], capture_output=True) |
| 258 | assert p.returncode and not p.stdout and b"error 21" in p.stderr, (typ, p.stderr) |
| 259 | print("PASS refused out-of-range", typ) |
| 260 | # Seeded function-only units cannot access the global pool (error 9). |
| 261 | # Exercise global storage in a program instead of bypassing that gate. |
| 262 | for typ, literal, cast in (("ushort", "65535", "ulong"), ("uint", "4294967295", "ulong"), ("f32", "-0.0f32", "ulong bitcast uint")): |
| 263 | src = f"""global bank {typ} 2 |
| 264 | fn main to int |
| 265 | put bank 0 {literal} |
| 266 | put bank 1 get bank 0 |
| 267 | bits = {cast} get bank 1 |
| 268 | out = new uchar 8 0 |
| 269 | for j ulong 8 |
| 270 | shift = mul j 8 |
| 271 | put out j uchar and shr bits shift 255 |
| 272 | end |
| 273 | n = write 1 out 0 8 |
| 274 | ret 0 |
| 275 | end |
| 276 | """ |
| 277 | oracle = w / ("global-" + typ) |
| 278 | oracle.write_bytes(run([OMC], src.encode())) |
| 279 | oracle.chmod(0o755) |
| 280 | host = w / ("global-host-" + typ) |
| 281 | cc(convert(src), host) |
| 282 | assert run([host]) == run([oracle]), typ |
| 283 | print("PASS standalone global array", typ) |
| 284 | # All public view checks include true element width, exact count and result overlap. |
| 285 | for typ, ct, literal in (("ushort", C.c_uint16, "0"), ("uint", C.c_uint32, "0"), ("f32", C.c_uint32, "0.0f32")): |
| 286 | src = f"fn probe a view {typ} 2 b edit {typ} 2 i ulong to {typ}\nput b 0 get a i\nret get a i\nend\n" |
| 287 | libpath = w / (typ + ".so") |
| 288 | cc(convert(src), libpath, True) |
| 289 | lib = C.CDLL(str(libpath)) |
| 290 | fn = lib.omega_probe |
| 291 | fn.restype = C.c_uint32 |
| 292 | fn.argtypes = [C.c_void_p, C.c_void_p, C.c_uint64, C.c_void_p, C.c_uint64, C.c_uint64] |
| 293 | a, b = (ct * 2)(), (ct * 2)() |
| 294 | result = C.c_uint64(0x0123456789abcdef) |
| 295 | assert fn(C.byref(result), a, 2, b, 2, 2) == 3 |
| 296 | assert result.value == 0x0123456789abcdef |
| 297 | assert fn(C.byref(result), a, 1, b, 2, 0) == 32 |
| 298 | assert fn(C.byref(result), None, 2, b, 2, 0) == 32 |
| 299 | assert fn(C.byref(result), a, 2, a, 2, 0) == 32 |
| 300 | assert fn(C.cast(C.byref(a, C.sizeof(ct)), C.c_void_p), a, 2, b, 2, 0) == 32 |
| 301 | assert fn(C.byref(result), a, 2, C.byref(b, 1), 2, 0) == 32 |
| 302 | assert fn(C.byref(result, 1), a, 2, b, 2, 0) == 32 |
| 303 | assert fn(C.byref(result), C.c_void_p(-C.sizeof(ct)), 2, b, 2, 0) == 32 |
| 304 | assert fn(C.byref(result), a, 2, b, 2, 0) == 0 |
| 305 | print("PASS runtime bounds/count/null/alias/overlap/recovery", typ) |
| 306 | for typ, ct, bits in (("f32", C.c_uint32, edges), ("f64", C.c_uint64, [0, 0x8000000000000000, 1, 0x7ff0000000000000, 0x7ff8000000012345])): |
| 307 | src = f"fn identity x {typ} to {typ}\nret x\nend\n" |
| 308 | so = w / (typ + "scalar.so") |
| 309 | ctype = C.c_float if typ == "f32" else C.c_double |
| 310 | cc(convert(src), so, True) |
| 311 | fn = C.CDLL(str(so)).omega_identity |
| 312 | fn.argtypes = [C.POINTER(ctype), ctype] |
| 313 | fn.restype = C.c_uint32 |
| 314 | for value in bits: |
| 315 | arg = ctype.from_buffer_copy(ct(value)) |
| 316 | out = ctype() |
| 317 | assert fn(C.byref(out), arg) == 0 |
| 318 | assert ct.from_buffer_copy(out).value == value |
| 319 | # Mutant changes result-width marshalling; typed result bit oracle kills it. |
| 320 | code = convert(src) |
| 321 | old = b"o_put(result,1,0,_result," + (b"11" if typ == "f32" else b"12") + b")" |
| 322 | assert code.count(old) == 1 |
| 323 | bad = code.replace(old, old.replace(b"_result", b"(_result^1)")) |
| 324 | cc(bad, so.with_name(typ + "mutant.so"), True) |
| 325 | mf = C.CDLL(str(so.with_name(typ + "mutant.so"))).omega_identity |
| 326 | mf.argtypes, mf.restype = fn.argtypes, fn.restype |
| 327 | out = ctype() |
| 328 | assert mf(C.byref(out), ctype()) == 0 and ct.from_buffer_copy(out).value != 0 |
| 329 | print("PASS typed scalar and killed ABI mutant", typ) |
| 330 | print("SEEDED-VIEWS PASS") |
| 331 | |
| 332 | |
| 333 | if __name__ == "__main__": |
| 334 | main() |