142 lines
6.5 KiB
Python
142 lines
6.5 KiB
Python
"""Private mathematical range/state oracle; subprocesses return raw observations."""
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
|
|
def byte_at(seed, address):
|
|
value = seed ^ (address & 0xffffffff) ^ (((address >> 32) * 2654435761) & 0xffffffff)
|
|
value ^= value >> 16
|
|
value = value * 2246822519 & 0xffffffff
|
|
value ^= value >> 13
|
|
return value & 255
|
|
|
|
|
|
def preview(seed, address, length):
|
|
value = 2166136261
|
|
for index in range(min(length, 64)):
|
|
value = ((value ^ byte_at(seed, address + index)) * 16777619) & 0xffffffff
|
|
return value
|
|
|
|
|
|
def model(cases):
|
|
capacity, seed, reserved = 1024, 0, 0
|
|
counters = [0, 0, 0, 0]
|
|
slots = [[0] * 5 for _ in range(8)]
|
|
text, objects = [], []
|
|
expected_count = {'Z': 2, 'O': 3, 'S': 4, 'R': 4, 'C': 1, 'Q': 1}
|
|
for number, case in enumerate(cases, 1):
|
|
fields = case['line'].split()
|
|
try:
|
|
kind = fields[0]
|
|
args = [int(value, 0) for value in fields[1:]]
|
|
assert len(args) == expected_count[kind] and all(0 <= value <= 0xffffffff for value in args)
|
|
except (KeyError, ValueError, AssertionError):
|
|
text.append('I ' + str(number))
|
|
objects.append(dict(sequence=number, input_error=True))
|
|
continue
|
|
rc = value = detail = digest = 0
|
|
found = next((i for i, item in enumerate(slots) if item[0] and item[1] == args[0]), None)
|
|
empty = next((i for i, item in enumerate(slots) if not item[0]), None)
|
|
if kind == 'Z':
|
|
capacity, seed = args
|
|
reserved = 0
|
|
counters = [0, 0, 0, 0]
|
|
slots = [[0] * 5 for _ in range(8)]
|
|
value, detail = args
|
|
elif kind == 'O':
|
|
ident, origin, length = args
|
|
if not ident or empty is None or found is not None or origin + length > capacity or origin > capacity or reserved + length > capacity:
|
|
rc = -1
|
|
else:
|
|
slots[empty] = [1, ident, origin, length, 0]
|
|
reserved += length
|
|
counters[0] += 1
|
|
value, detail = empty, length
|
|
elif kind == 'S':
|
|
parent, child, offset, length = args
|
|
duplicate = any(item[0] and item[1] == child for item in slots)
|
|
if found is None or not child or duplicate or empty is None or offset > slots[found][3] or offset + length > slots[found][3] or reserved + length > capacity:
|
|
rc = -1
|
|
else:
|
|
slots[empty] = [1, child, slots[found][2] + offset, length, parent]
|
|
reserved += length
|
|
counters[0] += 1
|
|
value, detail = empty, length
|
|
elif found is None:
|
|
rc = -1
|
|
elif kind == 'R':
|
|
ident, offset, count, width = args
|
|
extent = count * width
|
|
if width not in (1, 2, 4, 8, 16) or offset > slots[found][3] or offset + extent > slots[found][3]:
|
|
rc = -1
|
|
else:
|
|
value, detail = extent, min(extent, 64)
|
|
digest = preview(seed, slots[found][2] + offset, extent)
|
|
counters[2] += 1
|
|
elif kind == 'Q':
|
|
value, detail, digest = slots[found][2:]
|
|
elif kind == 'C':
|
|
if any(item[0] and item[4] == args[0] for item in slots):
|
|
rc = -1
|
|
else:
|
|
value, detail = slots[found][3], found
|
|
reserved -= value
|
|
slots[found] = [0] * 5
|
|
counters[1] += 1
|
|
if rc:
|
|
counters[3] += 1
|
|
counters = [item & 0xffffffff for item in counters]
|
|
active = sum(item[0] for item in slots)
|
|
values = [number, rc, value, detail, digest, capacity, seed, reserved] + counters + [active] + [field for slot in slots for field in slot]
|
|
text.append('O ' + ' '.join(map(str, values)))
|
|
objects.append(dict(sequence=number, result=dict(rc=rc, value=value, detail=detail, hash=digest), capacity=capacity, seed=seed, reserved=reserved, counters=dict(zip(('opens', 'closes', 'reads', 'rejects'), counters)), active_count=active, slots=[dict(zip(('active', 'id', 'origin', 'length', 'parent'), slot)) for slot in slots]))
|
|
return text, objects
|
|
|
|
|
|
def main():
|
|
candidate = Path(sys.argv[1])
|
|
private = json.loads(Path(__file__).with_name('cases.json').read_text())
|
|
wanted_text, wanted_json = model(private['cases'])
|
|
inputs = '\n'.join(case['line'] for case in private['cases']) + '\n'
|
|
root = Path(tempfile.mkdtemp(prefix='window-reader-'))
|
|
for name, contents in private['context'].items():
|
|
root.joinpath(name).write_text(contents)
|
|
for name in ('range.c', 'session.c'):
|
|
root.joinpath(name).write_bytes(candidate.joinpath(name).read_bytes())
|
|
built = subprocess.run(['gcc', '-std=c11', '-O2', '-g', '-Wall', '-Wextra', '-Werror', 'main.c', 'input.c', 'observation.c', 'json.c', 'range.c', 'session.c', '-o', 'window-reader'], cwd=root, capture_output=True, text=True, timeout=30)
|
|
if built.returncode:
|
|
print('BUILD_FAIL ' + built.stderr[-1000:])
|
|
return 1
|
|
# The complete input and both expected output representations already exist in memory.
|
|
# No root reads/writes of shared scratch occur after executing a candidate.
|
|
text_result = subprocess.run([str(root / 'window-reader')], cwd=root, input=inputs, capture_output=True, text=True, timeout=15)
|
|
json_result = subprocess.run([str(root / 'window-reader'), '--json'], cwd=root, input=inputs, capture_output=True, text=True, timeout=15)
|
|
for mode, result in (('text', text_result), ('json', json_result)):
|
|
if result.returncode:
|
|
print('RUN_FAIL {} {}'.format(mode, result.returncode))
|
|
return 1
|
|
# Ordinary diagnostic logging is allowed and kept on the private grader side.
|
|
sys.stderr.write(result.stderr[-2000:])
|
|
actual = text_result.stdout.splitlines()
|
|
if actual != wanted_text:
|
|
first = next((i for i, pair in enumerate(zip(actual, wanted_text)) if pair[0] != pair[1]), min(len(actual), len(wanted_text)))
|
|
print('OBSERVATION_MISMATCH command={} actual={} expected={}'.format(first + 1, actual[first:first+1], wanted_text[first:first+1]))
|
|
return 1
|
|
try:
|
|
actual_json = [json.loads(line) for line in json_result.stdout.splitlines()]
|
|
except ValueError:
|
|
print('JSON_INVALID')
|
|
return 1
|
|
if actual_json != wanted_json:
|
|
print('JSON_OBSERVATION_MISMATCH')
|
|
return 1
|
|
print('PASS')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|