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

253 lines · 11950 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Bounded/unsized runtime views: independent C reference, host and emulated x86.
3
4WolframLanguageEvaluator: {2^64-1,Table[{z,Quotient[2^64-1,z],
5Quotient[2^64-1,z]+1},{z,{1,2,4,8}}]} -> {18446744073709551615,
6{{1,18446744073709551615,18446744073709551616},
7{2,9223372036854775807,9223372036854775808},
8{4,4611686018427387903,4611686018427387904},
9{8,2305843009213693951,2305843009213693952}}}.
10The reference uses unsigned division before multiplication, then half-open ranges.
11No test dereferences a synthetic pointer. Both sides use real storage for accesses.
12"""
13import os
14from pathlib import Path
15import subprocess
16import tempfile
17
18from seeded_views import run, cc, storage_codegen
19
20ROOT = Path(__file__).resolve().parents[1]
21
22
23def convert(source, work, runtime=True, mode="c"):
24 path = work / "source.om"
25 path.write_text(source)
26 return run([ROOT / "tools/bridge-seeded", *(["--runtime-views"] if runtime else []), mode, path])
27
28
29def unit(typ, unsized):
30 shape = "*" if unsized else "256"
31 return ("om2\n" if unsized else "") + f"""fn extent a view {typ} {shape} to ulong
32ret len a
33end
34fn probe a view {typ} {shape} b edit {typ} {shape} i ulong to ulong
35if eq i 18446744073709551615
36ret extent view a
37end
38if eq i 0
39put b 0 get a 0
40else
41put b i get a i
42end
43ret len b
44end
45"""
46
47
48RUNNER = r"""
49#include <stdint.h>
50#include <stddef.h>
51#include <stdio.h>
52#include <string.h>
53#include <stdlib.h>
54#include "unit.h"
55#define CHECK(x) do { if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;} }while(0)
56static int valid(const void*p,uint64_t n){
57 uintptr_t a=(uintptr_t)p;
58 if(n>UINTPTR_MAX/WIDTH)return 0;
59 if(CAP && n>CAP)return 0;
60 if(!n)return 1;
61 return p && a%WIDTH==0 && a<=UINTPTR_MAX-n*WIDTH;
62}
63static int overlap(const void*a,uint64_t an,const void*b,uint64_t bn){
64 if(!an||!bn)return 0;
65 uintptr_t x=(uintptr_t)a,y=(uintptr_t)b;
66 return x<y+bn*WIDTH && y<x+an*WIDTH;
67}
68static unsigned reference(uint64_t*r,const void*a,uint64_t an,void*b,uint64_t bn,uint64_t i){
69 if(!valid(a,an)||!valid(b,bn)||overlap(a,an,b,bn))return 32;
70 if(i==UINT64_MAX){*r=an;return 0;}
71 if(i>=an||i>=bn)return 3;
72 memcpy((unsigned char*)b+i*WIDTH,(const unsigned char*)a+i*WIDTH,WIDTH);
73 *r=bn;return 0;
74}
75int main(void){
76 _Alignas(8) unsigned char bank[8192],expect[8192];
77 uint64_t actual=77,want=77;
78 memset(bank,0xa5,sizeof bank);memset(expect,0xa5,sizeof expect);
79 memset(bank+4096,0x5a,4096);memset(expect+4096,0x5a,4096);
80 uint64_t counts[]={0,1,2,255,256,257,UINT64_MAX,UINT64_MAX/WIDTH,UINT64_MAX/WIDTH+ (WIDTH!=1)};
81 for(unsigned j=0;j<sizeof(counts)/sizeof(counts[0]);++j){
82 uint64_t n=counts[j];
83 unsigned s=reference(&want,expect,n,expect+4096,n,UINT64_MAX);
84 unsigned t=omega_probe(&actual,bank,n,bank+4096,n,UINT64_MAX);
85 CHECK(s==t);if(!s)CHECK(want==actual);
86 }
87 for(uint64_t n=0;n<=256;++n){
88 uint64_t indices[]={0,n,n?n-1:0,UINT64_MAX};
89 for(unsigned j=0;j<4;++j){
90 actual=want=77;
91 unsigned s=reference(&want,expect,n,expect+4096,n,indices[j]);
92 unsigned t=omega_probe(&actual,bank,n,bank+4096,n,indices[j]);
93 CHECK(s==t);CHECK(want==actual);CHECK(!memcmp(bank,expect,sizeof bank));
94 }
95 }
96 /* Empty views are no ranges, including NULL and an interior misaligned pointer. */
97 CHECK(omega_probe(&actual,NULL,0,NULL,0,UINT64_MAX)==0&&actual==0);
98 CHECK(omega_probe(&actual,bank+1,0,bank,1,UINT64_MAX)==0);
99 CHECK(omega_probe(&actual,bank,1,bank+1,0,UINT64_MAX)==0);
100 CHECK(omega_probe(&actual,NULL,1,bank,1,UINT64_MAX)==32);
101 CHECK(omega_probe(&actual,bank,1,NULL,1,UINT64_MAX)==32);
102 if(WIDTH>1)CHECK(omega_probe(&actual,bank+1,1,bank+4096,1,UINT64_MAX)==32);
103 CHECK(omega_probe(&actual,bank,1,bank,1,UINT64_MAX)==32);
104 CHECK(omega_probe(&actual,bank,2,bank+WIDTH,1,UINT64_MAX)==32);
105 CHECK(omega_probe(&actual,bank,1,bank+WIDTH,1,UINT64_MAX)==0);
106 /* Distinguish read bounds from write bounds: the other access remains valid. */
107 CHECK(omega_probe(&actual,bank,1,bank+4096,2,1)==3);
108 CHECK(omega_probe(&actual,bank,2,bank+4096,1,1)==3);
109 CHECK(omega_probe((uint64_t*)bank,bank,1,bank+4096,1,UINT64_MAX)==32);
110 CHECK(omega_probe(NULL,bank,0,bank,0,UINT64_MAX)==32);
111 CHECK(omega_probe(&actual,(void*)(UINTPTR_MAX-(WIDTH-1)),1,bank,0,UINT64_MAX)==32);
112 if(!CAP){
113 /* Maximum nonwrapping range disjoint from live result storage; no access. */
114 uintptr_t base=(uintptr_t)&actual+sizeof actual;
115 uint64_t n=(UINTPTR_MAX-base)/WIDTH;
116 CHECK(omega_probe(&actual,(void*)base,n,NULL,0,UINT64_MAX)==0&&actual==n);
117 CHECK(omega_probe(&actual,(void*)base,n+1,NULL,0,UINT64_MAX)==32);
118 if(WIDTH>1)CHECK(omega_probe(&actual,(void*)(uintptr_t)WIDTH,UINT64_MAX/WIDTH+1,NULL,0,UINT64_MAX)==32);
119 }
120 puts("RUNTIME-VIEW REFERENCE PASS");return 0;
121}
122"""
123
124
125def execute(code, header, work, typ, cap, name, compiler="cc", runner=(), success=True):
126 (work / "unit.h").write_bytes(header)
127 source = work / (name + ".c")
128 generated = work / (name + "-unit.c")
129 source.write_text(f"#define WIDTH {dict(uchar=1,ushort=2,uint=4,ulong=8,f32=4)[typ]}\n#define CAP {cap}\n" + RUNNER)
130 generated.write_bytes(code)
131 binary = work / name
132 run([compiler, "-std=gnu11", "-O2", "-ffp-contract=off", "-Wall", "-Wextra", "-Werror", "-DOMEGA_LIBRARY", generated, source, "-o", binary])
133 p = subprocess.run([*runner, str(binary)], capture_output=True, timeout=300)
134 if success:
135 assert p.returncode == 0, (name,p.returncode,p.stderr.decode())
136 assert p.stdout.endswith(b"RUNTIME-VIEW REFERENCE PASS\n")
137 else:
138 assert p.returncode != 0, (name,"mutant survived")
139 return p
140
141
142def main():
143 with tempfile.TemporaryDirectory(prefix="omega-runtime-views-") as td:
144 w=Path(td)
145 for typ in ("uchar","ushort","uint","ulong","f32"):
146 for unsized in (False,True):
147 source=unit(typ,unsized)
148 code=convert(source,w)
149 header=convert(source,w,mode="h")
150 cap=0 if unsized else 256
151 name=typ+("-unsized" if unsized else "-bounded")
152 execute(code,header,w,typ,cap,name)
153 execute(code,header,w,typ,cap,name+"-x86","x86_64-linux-gnu-gcc",[os.environ.get("QEMU_X86_64","qemu-x86_64"),"-L","/usr/x86_64-linux-gnu"])
154 print("PASS host/reference and x86 EMULATED",name)
155 if typ=="uint" and unsized:
156 mutants={
157 "bounds-get":(b"if(i>=n)o_trap(3);unsigned w=",b"if(0)o_trap(3);unsigned w=",1),
158 "bounds-put":(b"if(i>=n)o_trap(3);unsigned w=",b"if(0)o_trap(3);unsigned w=",2),
159 "declared-overlap":(b"p1_n*4",b"256*4",None),
160 "null":(b"if(!p)return 0;",b"if(0)return 0;",None),
161 "overflow":(b"if(n>UINTPTR_MAX/z)return 0;",b"if(0)return 0;",None),
162 }
163 for m,(old,new,occurrence) in mutants.items():
164 assert old in code,m
165 if occurrence:
166 pieces=code.split(old)
167 assert len(pieces)==3
168 mutated=old.join(pieces[:occurrence])+new+old.join(pieces[occurrence:])
169 else:
170 mutated=code.replace(old,new)
171 execute(mutated,header,w,typ,cap,"mutant-"+m,success=False)
172 print("PASS killed",m)
173 storage_codegen(code,w)
174 # Fixed profile still requires exactly the declared shape.
175 source=unit("uint",False)
176 code=convert(source,w,runtime=False)
177 assert b"o_rbuf(" not in code
178 so=w/"fixed.so";cc(code,so,True)
179 import ctypes as C
180 fn=C.CDLL(str(so)).omega_probe
181 fn.argtypes=[C.c_void_p,C.c_void_p,C.c_uint64,C.c_void_p,C.c_uint64,C.c_uint64]
182 fn.restype=C.c_uint32
183 a=(C.c_uint32*256)();b=(C.c_uint32*256)();result=C.c_uint64()
184 assert fn(C.byref(result),a,1,b,1,C.c_uint64(-1).value)==32
185 assert fn(C.byref(result),a,256,b,256,C.c_uint64(-1).value)==0
186 # Readonly/readonly aliases remain admitted, with helper count forwarding.
187 ro="om2\nfn extent a view uint * to ulong\nret len a\nend\nfn same a view uint * b view uint * to ulong\nret extent view b\nend\n"
188 rocode=convert(ro,w);cc(rocode,w/"ro.so",True)
189 rf=C.CDLL(str(w/"ro.so")).omega_same
190 rf.argtypes=[C.c_void_p,C.c_void_p,C.c_uint64,C.c_void_p,C.c_uint64];rf.restype=C.c_uint32
191 assert rf(C.byref(result),a,1,a,2)==0 and result.value==2
192 many = "fn many a view uint 256 b edit uint 256 c edit uint 256 d edit uint 256 e view uint 256 to ulong\nput b 0 get a 0\nput c 0 get e 0\nput d 0 19\nret len a\nend\n"
193 manycode=convert(many,w);cc(manycode,w/"many.so",True)
194 mf=C.CDLL(str(w/"many.so")).omega_many
195 mf.argtypes=[C.c_void_p]+[C.c_void_p,C.c_uint64]*5;mf.restype=C.c_uint32
196 c=(C.c_uint32*1)();d=(C.c_uint32*1)()
197 a[0]=27
198 assert mf(C.byref(result),a,1,b,1,c,1,d,1,a,1)==0
199 assert result.value==1 and b[0]==27 and c[0]==27 and d[0]==19
200 negatives = [
201 "om2 diag\nfn bad a view uint * to ulong\nret len a\nend\n",
202 "om2 fmt\nfn bad a view uint * to ulong\nret len a\nend\n",
203 "om2\nfn fixed a view uint 2 to ulong\nret len a\nend\nfn bad a view uint * to ulong\nret fixed view a\nend\n",
204 "om2\nfn mutate a edit uint * to ulong\nret len a\nend\nfn bad a view uint * to ulong\nret mutate a\nend\n",
205 "om2\nfn bad a view uint * b view uint * c view uint * d ulong to ulong\nret d\nend\n",
206 ]
207 for source in negatives:
208 path=w/"unsupported.om";path.write_text(source)
209 for mode in ("c","h"):
210 p=subprocess.run([ROOT/"tools/bridge-seeded","--runtime-views",mode,path],capture_output=True)
211 assert p.returncode and not p.stdout,(source,mode,p.returncode)
212 for source in ("fn bad a view uint 2 to uint\nret get a 2\nend\n", "fn bad a view uint * to ulong\nret len a\nend\n", "om2\nfn bad a view uint * to ulong\nret rotr len a 1\nend\n"):
213 path=w/"refusal.om";path.write_text(source)
214 for mode in ("c","h"):
215 p=subprocess.run([ROOT/"tools/bridge-seeded","--runtime-views",mode,path],capture_output=True)
216 assert p.returncode and not p.stdout,(source,mode,p.returncode)
217 pathsrc = "om2\nfn pathlen a view uchar * to ulong\nfor i ulong len a\nif eq get a i 0\nret i\nend\nend\nret len a\nend\n"
218 pathcode=convert(pathsrc,w);pathheader=convert(pathsrc,w,mode="h")
219 (w/"path.c").write_bytes(pathcode);(w/"path.h").write_bytes(pathheader)
220 (w/"path-ref.c").write_text(r'''
221#include <stdint.h>
222#include <stdio.h>
223#include <string.h>
224#include "path.h"
225int main(void){
226 unsigned char data[257];uint64_t got=99;
227 if(omega_pathlen(&got,NULL,0)||got!=0)return 1;
228 if(omega_pathlen(&got,NULL,1)!=32)return 2;
229 for(uint64_t n=0;n<=256;++n){
230 for(uint64_t split=0;split<=n;++split){
231 memset(data,'x',sizeof data);data[split]=0;
232 const unsigned char *p=memchr(data,0,n);
233 uint64_t want=p?(uint64_t)(p-data):n;
234 if(omega_pathlen(&got,data,n)||got!=want)return 3;
235 }
236 }
237 puts("PASS bounded NUL scan reference, including absent/outside-bound terminators");
238 return 0;
239}
240''')
241 for compiler,runner,label in [
242 ("cc",[],"host"),
243 ("x86_64-linux-gnu-gcc",[os.environ.get("QEMU_X86_64","qemu-x86_64"),"-L","/usr/x86_64-linux-gnu"],"x86"),
244 ]:
245 binary=w/("path-"+label)
246 run([compiler,"-std=gnu11","-O2","-Wall","-Wextra","-Werror","-DOMEGA_LIBRARY",w/"path.c",w/"path-ref.c","-o",binary])
247 print(run([*runner,binary]).decode().strip(),label)
248 print("PASS fixed-count compatibility, readonly aliases, pinned syntax and unsupported-subset refusals")
249 print("SEEDED-RUNTIME-VIEWS PASS")
250
251
252if __name__=="__main__":
253 main()