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 / seed / modules / tests / check.py

255 lines · 18349 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent module integration and mutation oracle. No production dependency."""
3import hashlib, os, pathlib, struct, subprocess, sys, tempfile
4P=pathlib.Path
5repo=P(__file__).resolve().parents[3]
6compiler=P(sys.argv[1]).resolve()
7seed=repo/'seed/out/omc'
8out=P(sys.argv[2]).resolve() if len(sys.argv)>2 else P(tempfile.mkdtemp(prefix='ommodules-'))
9out.mkdir(parents=True,exist_ok=True)
10sha=lambda b:hashlib.sha256(b).hexdigest()
11u=lambda b,p:struct.unpack_from('<Q',b,p)[0]
12def put(b,p,n): struct.pack_into('<Q',b,p,n)
13comp=sha(compiler.read_bytes())
14source=b'om2\n'+(repo/'seed/ng/sha256.om').read_bytes()+(repo/'seed/modules/driver.om').read_bytes()
15def compile_driver(src,path):
16 r=subprocess.run([seed],input=src,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
17 assert r.returncode==0,r.stderr.decode();path.write_bytes(r.stdout);path.chmod(0o755)
18compile_driver(source,out/'ommod')
19driver=out/'ommod'
20subprocess.run(['cc','-Wall','-Wextra','-Werror','-O2',str(repo/'seed/modules/tests/caller.c'),str(repo/'seed/modules/tests/caller.S'),'-o',str(out/'caller')],check=True)
21store=out/'store';store.mkdir(exist_ok=True)
22passed=[]
23def ok(label):passed.append(label);print('PASS',label,flush=True)
24def run(args,expected=0,exe=None):
25 r=subprocess.run([exe or driver,*map(str,args)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30)
26 assert r.returncode==expected,(args,r.returncode,expected,r.stdout,r.stderr)
27 return r
28profile='debug'
29def build(name,text):
30 p=out/(name+'.om');p.write_text(text)
31 h=sha(p.read_bytes());r=run(['build',compiler,comp,profile,'aarch64-linux',store,p,h])
32 artifact=r.stdout.decode().strip().split()[-1]
33 assert len(artifact)==64
34 blob=(store/(artifact+'.mod')).read_bytes();assert sha(blob)==artifact
35 assert blob[:8]==b'OMMOD001' and blob[8:72]==comp.encode() and blob[72:136]==h.encode()
36 key=sha(b'OMMOD001'+comp.encode()+h.encode()+struct.pack('<QQ',int(profile=='release'),1))
37 assert (store/(key+'.ref')).read_text()==artifact
38 return dict(name=name,path=p,hash=h,artifact=artifact,key=key,blob=blob)
39def linkargs(m,dest,kind='program',entry='answer',s=store):
40 return ['link',s,comp,profile,'aarch64-linux',m['hash'],m['artifact'],kind,entry,dest]
41def execute(m,want,entry='answer'):
42 p=out/(m['name']+'.elf');run(linkargs(m,p,entry=entry));r=subprocess.run([p]);assert r.returncode==want,(m['name'],r.returncode,want)
43 return p
44leaf=build('leaf','om2\nfn helper to int\nret 40\nend\nexport fn answer to int\nret add helper 2\nend\n')
45execute(leaf,42);ok('native leaf ELF')
46root=build('root',f'om2\nimport dep {leaf["hash"]} answer\nfn helper to int\nret 1\nend\nexport fn answer to int\nret add dep helper\nend\n')
47execute(root,43);ok('separate native modules and private name isolation')
48root2=build('root2',f'om2\nimport dep {leaf["hash"]} answer\nexport fn answer to int\nret add dep 2\nend\n')
49execute(root2,44);assert (store/(leaf['artifact']+'.mod')).read_bytes()==leaf['blob'];ok('same byte-identical dependency reused by two roots')
50# Direct single-unit output is the independent execution oracle.
51mono=b'om2\nfn helper to int\nret 40\nend\nfn dep to int\nret add helper 2\nend\nfn main to int\nret add dep 1\nend\n'
52r=subprocess.run([compiler],input=mono,stdout=subprocess.PIPE,stderr=subprocess.PIPE);assert r.returncode==0,r.stderr
53p=out/'monolithic';p.write_bytes(r.stdout);p.chmod(0o755);assert subprocess.run([p]).returncode==43;ok('single-unit differential oracle')
54r=run(['build',compiler,comp,profile,'aarch64-linux',store,root['path'],root['hash']]);assert r.stdout==f'CACHE {root["artifact"]}\n'.encode();ok('cache identity equality')
55# strace verifies there is no compiler exec on a cache hit, even though the executable is hashed.
56trace=out/'cache.strace'
57subprocess.run(['strace','-f','-e','trace=execve,execveat','-o',trace,str(driver),'build',str(compiler),comp,profile,'aarch64-linux',str(store),str(root['path']),root['hash']],check=True,stdout=subprocess.PIPE)
58assert trace.read_text().count('execve(')==1 and 'execveat(' not in trace.read_text();ok('cache performs no compiler execution')
59fp=out/'root.native';run(linkargs(root,fp,'function','-'))
60r=subprocess.run([out/'caller',fp,'0'],capture_output=True);assert r.returncode==0 and r.stdout==b'43\n';ok('function-mode independent native ABI caller')
61data=fp.read_bytes();assert data[-8:]==b'OMLINK01';ds=u(data,len(data)-16);dp=len(data)-16-ds
62assert u(data,dp)==1 and u(data,dp+24)==8 and u(data,dp+32)==0;ok('machine-readable export/stack descriptor')
63arr=build('array','om2\nexport fn sum a view ulong * to ulong\nret add get a 0 get a 3\nend\n')
64aroot=build('arrayroot',f'om2\nimport dep {arr["hash"]} sum\nexport fn sum a view ulong * to ulong\nret dep a\nend\n')
65ap=out/'array.native';run(linkargs(aroot,ap,'function','-'))
66r=subprocess.run([out/'caller',ap,'999'],capture_output=True);assert r.returncode==0 and r.stdout==b'14\n';ok('typed unsized-view import ABI')
67trap=build('trap','om2\nexport fn answer to int\nx = int 0\nret div 1 x\nend\n')
68execute(trap,102);tp=out/'trap.native';run(linkargs(trap,tp,'function','-'));assert subprocess.run([out/'caller',tp,'0']).returncode==102;ok('program and host-caller trap semantics')
69void=build('void','om2\nexport fn answer to void\nret\nend\n');execute(void,0);ok('void root returns zero')
70# Each negative must leave the final output absent.
71serial=0
72def refuse(args,label,exe=None):
73 global serial
74 serial+=1;p=out/f'negative-{serial}'
75 r=subprocess.run([exe or driver,*map(str,args(p))],capture_output=True,timeout=30)
76 assert 0<r.returncode<100,(label,r.returncode,r.stderr)
77 assert not p.exists(),label
78 ok(label)
79refuse(lambda p:['link',store,'0'*64,profile,'aarch64-linux',root['hash'],root['artifact'],'program','answer',p],'wrong compiler identity')
80refuse(lambda p:['link',store,comp,'release','aarch64-linux',root['hash'],root['artifact'],'program','answer',p],'profile mismatch')
81refuse(lambda p:['link',store,comp,profile,'x86linux',root['hash'],root['artifact'],'program','answer',p],'target mismatch')
82refuse(lambda p:linkargs({**root,'artifact':'0'*64},p),'root artifact digest mismatch')
83refuse(lambda p:linkargs(root,p,entry='helper'),'private entry refused')
84refuse(lambda p:['build',compiler,'0'*64,profile,'aarch64-linux',store,root['path'],root['hash']],'build authenticates compiler bytes')
85refuse(lambda p:['build',compiler,comp,profile,'aarch64-linux',store,root['path'],'0'*64],'build authenticates source snapshot')
86# Corruption without changing the content address must fail both link and cache reuse.
87payload=store/(root['artifact']+'.mod');bad=bytearray(root['blob']);bad[180]^=1
88payload.chmod(0o644);payload.write_bytes(bad)
89refuse(lambda p:linkargs(root,p),'payload corruption hash check')
90refuse(lambda p:['build',compiler,comp,profile,'aarch64-linux',store,root['path'],root['hash']],'cache corruption hash check')
91payload.write_bytes(root['blob']);payload.chmod(0o444)
92# Reference a structurally mutated object by its recomputed digest to reach parser checks.
93def objectinfo(m):
94 b=m['blob'];o=176+u(b,152);n=u(b,160);obj=b[o:o+n];p=u(obj,40);funcs=[]
95 for i in range(u(obj,48)):
96 start=p;np=u(obj,p+24);nl=u(obj,p+40);name=obj[p+48:p+48+nl];p=(p+48+nl+7)&~7;params=p;p+=np*40
97 funcs.append((start,params,name))
98 return o,obj,funcs,p
99def mutation(m,change,label,exe=None,count=True):
100 b=bytearray(m['blob']);o,obj,fs,calls=objectinfo(m);change(b,o,obj,fs,calls)
101 h=sha(b);(store/(h+'.mod')).write_bytes(b);ref=store/(m['key']+'.ref');ref.chmod(0o644);ref.write_text(h)
102 mm={**m,'artifact':h};serialname=out/('mut-'+str(len(passed))+'-'+h[:8])
103 try:
104 r=subprocess.run([exe or driver,*map(str,linkargs(mm,serialname))],capture_output=True,timeout=30)
105 assert 0<r.returncode<100,(label,r.returncode,r.stderr)
106 assert not serialname.exists(),label
107 if count:ok(label)
108 finally:ref.write_text(m['artifact']);ref.chmod(0o444)
109mutations=[
110 (lambda b,o,x,f,c:put(b,o+8,2),'bad object version'),
111 (lambda b,o,x,f,c:put(b,o+16,2),'bad object target'),
112 (lambda b,o,x,f,c:put(b,o+24,1),'bad object profile'),
113 (lambda b,o,x,f,c:put(b,o+48,2**64-1),'overflowed function count'),
114 (lambda b,o,x,f,c:put(b,o+56,2**64-1),'overflowed call count'),
115 (lambda b,o,x,f,c:put(b,o+72,1),'reserved header nonzero'),
116 (lambda b,o,x,f,c:put(b,o+c,175),'unaligned/outside relocation'),
117 (lambda b,o,x,f,c:put(b,o+c+8,2**64-1),'bad caller function index'),
118 (lambda b,o,x,f,c:put(b,o+c+16,2**64-1),'bad callee function index'),
119 (lambda b,o,x,f,c:put(b,o+f[0][0]+16,12),'import signature mismatch'),
120 (lambda b,o,x,f,c:struct.pack_into('<I',b,o+u(x,c),0x94000001),'wrong call instruction'),
121 (lambda b,o,x,f,c:put(b,o+c+24,8388608),'transitive stack overflow'),
122 (lambda b,o,x,f,c:put(b,o+f[1][0]+40,2**64-1),'overflowed name length'),
123]
124for change,label in mutations:mutation(root,change,label)
125# Local function call cycle: rewrite the call to target its own caller, keep opcode consistent.
126def cycle(b,o,x,fs,c):
127 ci=next(c+i*32 for i in range(u(x,56)) if u(x,c+i*32+16)!=0)
128 src=u(x,ci+8);put(b,o+ci+16,src);site=u(x,ci);dest=u(x,fs[src][0]+8)
129 struct.pack_into('<I',b,o+site,0x94000000|(((dest-site)//4)&0x3ffffff))
130mutation(root,cycle,'local call cycle refused')
131# Duplicate relocation record pointing at the first call.
132def duplicate(b,o,x,fs,c): b[o+c+32:o+c+40]=b[o+c:o+c+8]
133mutation(root,duplicate,'duplicate callsite refused')
134# Invalid scalar parameter and fresh import must not cross the typed boundary.
135mutation(aroot,lambda b,o,x,f,c:put(b,o+f[0][1],12),'void parameter refused')
136mutation(aroot,lambda b,o,x,f,c:put(b,o+f[0][1]+32,1),'fresh external parameter refused')
137# Truncations at header and metadata boundaries, keeping envelope lengths internally consistent.
138for cut in [0,8,175,len(objectinfo(root)[1])-1]:
139 def trunc(b,o,x,f,c,cut=cut):
140 del b[o+cut:o+len(x)];put(b,160,cut)
141 mutation(root,trunc,f'truncated object {cut}')
142# Symlink protection on store, dependency and output ancestors.
143linkstore=out/'storelink';linkstore.symlink_to(store,target_is_directory=True)
144refuse(lambda p:linkargs(root,p,s=linkstore),'symlink store refused')
145realout=out/'realout';realout.mkdir(exist_ok=True);linked=out/'linkedout';linked.symlink_to(realout,target_is_directory=True)
146refuse(lambda p:linkargs(root,linked/'must-not-exist'),'symlink output ancestor refused');assert not (realout/'must-not-exist').exists()
147existing=out/'existing';existing.write_bytes(b'untouched');r=subprocess.run([driver,*map(str,linkargs(root,existing))],capture_output=True);assert r.returncode==38 and existing.read_bytes()==b'untouched';ok('existing output never overwritten')
148# Native bytes for a dependency are exactly the independent compiler result.
149o,obj,_,_=objectinfo(leaf)
150r=subprocess.run([compiler],input=b'object\n'+leaf['path'].read_bytes(),capture_output=True)
151assert r.returncode==0 and obj==r.stdout;ok('stored payload equals independent separate compilation')
152# A replaced transitive identity cannot be silently followed.
153ref=store/(leaf['key']+'.ref');ref.chmod(0o644);ref.write_text(root2['artifact'])
154refuse(lambda p:linkargs(root,p),'changed transitive identity refused')
155ref.write_text(leaf['artifact']);ref.chmod(0o444)
156# Missing immutable content and nonregular sources refuse promptly.
157blobpath=store/(leaf['artifact']+'.mod');hidden=blobpath.with_suffix('.hidden');blobpath.rename(hidden)
158refuse(lambda p:linkargs(root,p),'missing transitive payload refused');hidden.rename(blobpath)
159fifo=out/'fifo';os.mkfifo(fifo)
160refuse(lambda p:['build',compiler,comp,profile,'aarch64-linux',store,fifo,leaf['hash']],'FIFO source refuses without waiting')
161# Recover a crash between immutable payload publication and its reference publication.
162ref=store/(root2['key']+'.ref');ref.unlink()
163r=run(['build',compiler,comp,profile,'aarch64-linux',store,root2['path'],root2['hash']])
164assert r.stdout==f'BUILT {root2["artifact"]}\n'.encode();ok('orphan payload publication recovered')
165# Missing/private imports are checked before invoking the compiler.
166for name,export in [('missing','absent'),('private','helper')]:
167 p=out/(name+'.om');p.write_text(f'om2\nimport dep {leaf["hash"]} {export}\nexport fn answer to int\nret dep\nend\n')
168 refuse(lambda dest,p=p:['build',compiler,comp,profile,'aarch64-linux',store,p,sha(p.read_bytes())],name+' import refused')
169# Independent module count beyond the legacy 64-unit builder boundary.
170leaves=[]
171for i in range(70):
172 leaves.append(build('wide'+str(i),f'om2\nnote unique {i}\nexport fn answer to int\nret {i}\nend\n'))
173wide=build('wide','om2\n'+''.join(f'import dep{i} {m["hash"]} answer\n' for i,m in enumerate(leaves))+'export fn answer to int\nret add dep0 dep69\nend\n')
174execute(wide,69);ok('71 native modules without legacy count cap')
175profile='release'
176rleaf=build('releaseleaf','om2 release\nexport fn answer to int\nret 17\nend\n')
177rroot=build('releaseroot',f'om2 release\nimport dep {rleaf["hash"]} answer\nexport fn answer to int\nret dep\nend\n')
178execute(rroot,17);ok('release profile native import')
179profile='debug'
180# Synthetic arithmetic boundaries. The real function text is extracted from driver.om and run in a tiny
181# harness; expectations come from exact Python integers. No case allocates near the boundary.
182import re,itertools
183MAX=2**63-1;TL=2**60-1
184def extract(text,name):
185 m=re.search(r'^fn %s .*?(?=^fn |\Z)'%name,text,re.S|re.M);assert m,name;return m.group(0)
186HEAD='om2\nglobal mb uchar *\nglobal mt ulong *\nglobal ms ulong 8\nglobal mw uchar 4\ntext err "x\\n"\n'
187def harness(text,main,names=('die','need','sizeadd','sizemul','growto','ba','ta')):
188 return (HEAD+''.join(extract(text,n) for n in names)+'fn main to int\n'+main+'\nend\n').encode()
189hdir=out/'arith';hdir.mkdir(exist_ok=True);hn=0
190def hrun(text,main,names=None,want=0):
191 global hn
192 hn+=1;exe=hdir/f'h{hn}'
193 r=subprocess.run([seed],input=harness(text,main,*( [names] if names else [])),stdout=subprocess.PIPE,stderr=subprocess.PIPE);assert r.returncode==0,(main,r.stderr)
194 exe.write_bytes(r.stdout);exe.chmod(0o755)
195 return subprocess.run([exe],capture_output=True,timeout=30).returncode
196def lit(n):return f'ulong {n}'
197def arith_cases():
198 cases=[]
199 va=[0,1,2,MAX-2,MAX-1,MAX,MAX+1,2**64-1]
200 for a,b in itertools.product(va,va):
201 ok=a<=MAX and b<=MAX and a+b<=MAX
202 cases.append((f'a = {lit(a)}\nb = {lit(b)}\nr = sizeadd a b\nneed eq r {lit(a+b) if ok else 0} 90\nret 0',0 if ok else 20,f'sizeadd {a} {b}'))
203 vm=[0,1,2,3,MAX//3,MAX//3+1,2**31,2**32,2**32+1,2**62-1,2**62,MAX,MAX+1,2**64-1]
204 for a,b in itertools.product(vm,vm):
205 ok=a*b<=MAX or a==0
206 want=lit(a*b) if ok else '0'
207 if a==0:want='ulong 0'
208 cases.append((f'a = {lit(a)}\nb = {lit(b)}\nr = sizemul a b\nneed eq r {want} 90\nret 0',0 if ok else 20,f'sizemul {a} {b}'))
209 for limit in [MAX,TL]:
210 vn=[0,1,limit-4097,limit-1,limit,limit+1,2**64-1];ve=[0,1,512,4096,limit-1,limit,2**64-1]
211 for n,e in itertools.product(vn,ve):
212 if n>limit:
213 cases.append((f'n = {lit(n)}\ne = {lit(e)}\nl = {lit(limit)}\nr = growto n e l\nret 0',20,f'growto refuses {n} limit {limit}'));continue
214 res=n+e if e<=limit-n else n
215 cases.append((f'n = {lit(n)}\ne = {lit(e)}\nl = {lit(limit)}\nr = growto n e l\nneed eq r {lit(res)} 90\nret 0',0,f'growto {n} {e} limit {limit}'))
216 # Arena reservations refuse before touching memory when used+request passes the fixed-width boundary.
217 pre='r = ta 1\nr = ba 1\n'
218 for used,n,fn,lim in [(1,MAX,'ba',MAX),(1,2**64-1,'ba',MAX),(MAX,1,'ba',MAX),(MAX-99,100,'ba',MAX),(1,TL,'ta',TL),(1,2**64-1,'ta',TL),(TL,1,'ta',TL),(5,TL-4,'ta',TL)]:
219 idx=0 if fn=='ba' else 1
220 cases.append((pre+f'u = {lit(used)}\nn = {lit(n)}\nput ms {idx} u\nr = {fn} n\nret 0',20,f'{fn} refuses used {used} request {n}'))
221 return cases
222cases=arith_cases();bad=[]
223for main,want,label in cases:
224 got=hrun(source.decode(),main)
225 if got!=want:bad.append((label,got,want))
226assert not bad,bad[:10]
227ok(f'{len(cases)} synthetic length-arithmetic boundary cases')
228# Small real growth path through ba/ta (no boundary allocation).
229assert hrun(source.decode(),'r = ta 1\nr = ba 1\np = ba 5000\nneed eq p 1 90\nput mb 5000 7\nq = ba 100000\nneed eq q 5001 91\nput mb 105000 9\nneed eq get mb 5000 7 92\nt = ta 100000\nneed eq t 1 93\nput mt 100000 5\nneed eq get mt 100000 5 94\nret 0')==0;ok('small arena growth path preserves data')
230# SHA-256 bit-length field is a real 64-bit wire boundary, refused before any read.
231shsrc=(repo/'seed/ng/sha256.om').read_text()
232def hashharness(n):
233 s=('om2\nglobal mb uchar *\nglobal mt ulong *\nglobal ms ulong 8\nglobal mw uchar 4\nglobal mh uchar 64\ntext err "x\\n"\n'+shsrc.replace('om2\n','',1)+''.join(extract(driver_text,x) for x in ['die','need','hash'])+f'fn main to int\nn = {lit(n)}\nhash 0 n\nret 0\nend\n')
234 return s.encode()
235driver_text=(repo/'seed/modules/driver.om').read_text()
236for n,want in [(2**61,20),(2**64-1,20),(2**63,20)]:
237 r=subprocess.run([seed],input=hashharness(n),stdout=subprocess.PIPE,stderr=subprocess.PIPE);assert r.returncode==0,r.stderr
238 e=hdir/f'hash{n}';e.write_bytes(r.stdout);e.chmod(0o755)
239 assert subprocess.run([e],capture_output=True).returncode==want,n
240ok('SHA-256 length field boundary refused')
241for old,label in [('need le b div 9223372036854775807 a 20','sizemul overflow'),('need le b sub 9223372036854775807 a 20','sizeadd overflow'),('need le n limit 20','growto limit'),('need le n sub 9223372036854775807 p 20','ba overflow'),('need le n sub 1152921504606846975 p 20','ta overflow')]:
242 mtext=source.decode();assert mtext.count(old)==1,old
243 mtext=mtext.replace(old,'note disabled arithmetic check')
244 killed=any(hrun(mtext,m)!=w for m,w,_ in cases)
245 assert killed,'surviving arithmetic mutant '+label
246 ok('caught arithmetic mutant '+label)
247# Independent, targeted implementation mutants must fail the corresponding negative assertion.
248mutants=[(b'need eq rw site want 32',b'note disabled relocation check',mutations[10]),(b'need le cost 8388608 37',b'note disabled stack check',mutations[11])]
249for idx,(old,new,(change,label)) in enumerate(mutants):
250 assert source.count(old)==1
251 exe=out/f'mutant-{idx}';compile_driver(source.replace(old,new),exe)
252 try:mutation(root,change,label+' mutant',exe,False)
253 except AssertionError:ok('caught implementation mutant '+str(idx))
254 else:raise AssertionError('surviving implementation mutant '+str(idx))
255print(f'MODULES PASS {len(passed)} compiler={comp} driver={sha(driver.read_bytes())} source={sha(source)}',flush=True)