130 lines
5.4 KiB
Python
130 lines
5.4 KiB
Python
"""Private input generation and independent protocol oracle; candidate is a subprocess."""
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
MASK = 0xffffffff
|
|
|
|
def digest(words):
|
|
value = 2166136261
|
|
for word in words:
|
|
for shift in range(0, 32, 8):
|
|
value = ((value ^ ((word >> shift) & 255)) * 16777619) & MASK
|
|
return value
|
|
|
|
def model(commands):
|
|
words=[0]*96
|
|
words[1],words[2],words[8]=10,2,1
|
|
output=[]
|
|
def find(ident):
|
|
return next((16+i*8 for i in range(8) if words[16+i*8] and words[17+i*8]==ident),None)
|
|
def clear(pos):
|
|
words[pos:pos+8]=[0]*8
|
|
words[7]-=1
|
|
def send(pos):
|
|
words[pos+3]=(words[0]+words[1])&MASK
|
|
words[pos+6]+=1
|
|
words[pos+7]=words[8]
|
|
words[8]=(words[8]+1)&MASK or 1
|
|
words[3]+=1
|
|
for line in commands:
|
|
fields=line.split('#')[0].split()
|
|
try:
|
|
kind=fields[0];args=[int(v,0) for v in fields[1:]]
|
|
assert len(args)=={'Z':3,'A':3,'N':2,'T':1,'C':1,'Q':1}[kind] and all(0<=v<=MASK for v in args)
|
|
except (ValueError,KeyError,AssertionError,IndexError):
|
|
output.append(None);continue
|
|
rc=value=detail=0
|
|
if kind=='Z':
|
|
if not 1<=args[1]<=1000000 or args[2]>3:rc=-1
|
|
else:
|
|
words=[0]*96
|
|
words[0:3]=args
|
|
words[8]=1
|
|
value,detail=args[:2]
|
|
elif kind=='N':
|
|
pos=next((16+i*8 for i in range(8) if not words[16+i*8]),None)
|
|
if not args[0] or find(args[0]) is not None or pos is None:rc=-1
|
|
else:
|
|
words[pos:pos+8]=[1,args[0],words[10]+1,0,0,args[1],0,0]
|
|
words[10]+=1;words[7]+=1;send(pos)
|
|
value,detail=words[pos+7],(pos-16)//8
|
|
elif kind=='T':
|
|
if args[0]>0x7fffffff:rc=-1
|
|
else:
|
|
words[0]=(words[0]+args[0])&MASK
|
|
for pos in range(16,80,8):
|
|
if words[pos] and ((words[0]-words[pos+3])&MASK)<0x80000000:
|
|
if words[pos+4]>=words[2]:words[5]+=1;clear(pos)
|
|
else:words[pos+4]+=1;send(pos)
|
|
value,detail=words[0],words[7]
|
|
elif kind=='A':
|
|
pos=find(args[0])
|
|
if pos is None or args[1]!=words[pos+7] or args[2]!=(words[pos+5]^0xa5a5a5a5):
|
|
words[6]+=1;rc=-1
|
|
else:
|
|
value,detail=words[pos+5],words[pos+6]
|
|
words[4]+=1;clear(pos)
|
|
else:
|
|
pos=find(args[0])
|
|
if pos is None:rc=-1
|
|
elif kind=='Q':value,detail=words[pos+7],words[pos+4]
|
|
else:
|
|
value,detail=words[pos+1],words[pos+6]
|
|
words[9]+=1;clear(pos)
|
|
output.append((rc,value,detail,words.copy()))
|
|
return output
|
|
|
|
|
|
def main():
|
|
private = json.loads(Path(__file__).with_name('cases.json').read_text())
|
|
commands = private['cases']
|
|
expected = model(commands)
|
|
root = Path(tempfile.mkdtemp(prefix='service-desk-'))
|
|
for name, content in private['context'].items():
|
|
(root / name).write_text(content)
|
|
(root / 'service.c').write_bytes((Path(sys.argv[1]) / 'service.c').read_bytes())
|
|
build = subprocess.run(['gcc', '-std=c11', '-O2', '-Wall', '-Wextra', '-Werror', 'main.c', 'input.c', 'output.c', 'history.c', 'service.c', '-o', 'probe'], cwd=root, capture_output=True, text=True, timeout=30)
|
|
if build.returncode:
|
|
print('BUILD_FAIL ' + build.stderr[-1500:])
|
|
return 1
|
|
inputs = '\n'.join(commands) + '\n'
|
|
# Inputs and expected observations are prepared before any untrusted execution.
|
|
# The trusted parent never accesses shared scratch after starting the candidate.
|
|
for mode in ([], ['--json'], ['--brief'], ['--json', '--brief']):
|
|
result = subprocess.run([str(root / 'probe')] + mode, cwd=root, input=inputs, capture_output=True, text=True, timeout=15)
|
|
if result.returncode:
|
|
print('RUN_FAIL ' + str(result.returncode))
|
|
return 1
|
|
sys.stderr.write(result.stderr[-1000:])
|
|
wanted = []
|
|
for sequence, item in enumerate(expected, 1):
|
|
if item is None:
|
|
wanted.append({'sequence':sequence,'input_error':True} if '--json' in mode else 'I '+str(sequence))
|
|
continue
|
|
rc, value, detail, words = item
|
|
if '--json' in mode:
|
|
obj = dict(sequence=sequence, rc=rc, value=value, detail=detail, digest=digest(words))
|
|
if '--brief' not in mode:
|
|
obj['words'] = words
|
|
wanted.append(obj)
|
|
else:
|
|
numbers = [sequence,rc,value,detail] + ([] if '--brief' in mode else words) + [digest(words)]
|
|
wanted.append('O '+' '.join(map(str,numbers)))
|
|
try:
|
|
actual = [json.loads(line) for line in result.stdout.splitlines()] if '--json' in mode else result.stdout.splitlines()
|
|
except ValueError:
|
|
print('INVALID_JSON')
|
|
return 1
|
|
if actual != wanted:
|
|
index = next((i for i,(a,b) in enumerate(zip(actual,wanted)) if a!=b),min(len(actual),len(wanted)))
|
|
print('MISMATCH mode={} command={} actual={} expected={}'.format(mode,index+1,actual[index:index+1],wanted[index:index+1]))
|
|
return 1
|
|
print('PASS')
|
|
return 0
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|