256 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Build frozen C candidates; compare raw observations with a Python RTU model."""
import random
import subprocess
import sys
import tempfile
from pathlib import Path
READONLY = {'Makefile': 'CC = gcc\nCFLAGS = -std=c11 -O2 -Wall -Wextra -Werror\n.PHONY: all clean\nall: rtu-demo\nrtu-demo: demo.c rtu.c rtu_timing.c crc16.c rtu.h\n\t$(CC) $(CFLAGS) demo.c rtu.c rtu_timing.c crc16.c -o $@\nclean:\n\trm -f rtu-demo\n', 'rtu.h': '#ifndef RTU_H\n#define RTU_H\n#include <stddef.h>\n#include <stdint.h>\n#define RTU_CAPACITY 64u\n#define RTU_CHAR_GAP 3u\n#define RTU_FRAME_GAP 7u\ntypedef enum { RTU_CONTINUE, RTU_INTER_GAP, RTU_FRAME_BOUNDARY } rtu_gap_t;\ntypedef void (*rtu_emit_fn)(void *, uint32_t, const uint8_t *, size_t);\ntypedef struct {\n uint32_t accepted, bad_crc, bad_length, timing_errors, overflows;\n} rtu_stats_t;\ntypedef struct {\n uint8_t bytes[RTU_CAPACITY];\n size_t used;\n uint32_t last_byte;\n unsigned active, dropping;\n rtu_stats_t stats;\n rtu_emit_fn emit;\n void *context;\n} rtu_receiver;\nuint16_t rtu_crc16(const uint8_t *data, size_t length);\nrtu_gap_t rtu_classify_gap(uint32_t previous, uint32_t now);\nvoid rtu_init(rtu_receiver *rx, rtu_emit_fn emit, void *context);\nvoid rtu_byte(rtu_receiver *rx, uint8_t byte, uint32_t tick);\nvoid rtu_poll(rtu_receiver *rx, uint32_t tick);\nrtu_stats_t rtu_get_stats(const rtu_receiver *rx);\n#endif\n', 'crc16.c': '#include "rtu.h"\nuint16_t rtu_crc16(const uint8_t *data, size_t length)\n{\n uint16_t crc = 0xffffu;\n for (size_t i = 0; i < length; ++i) {\n crc ^= data[i];\n for (unsigned bit = 0; bit < 8; ++bit)\n crc = (uint16_t)((crc >> 1) ^ ((crc & 1u) ? 0xa001u : 0u));\n }\n return crc;\n}\n', 'demo.c': '#include "rtu.h"\n#include <inttypes.h>\n#include <stdio.h>\nstatic unsigned operation;\nstatic void observe(void *context, uint32_t tick, const uint8_t *data, size_t length)\n{\n (void)context;\n printf("F %u %" PRIu32 " %zu", operation, tick, length);\n for (size_t i = 0; i < length; ++i) printf(" %02x", data[i]);\n putchar(\'\\n\');\n}\nint main(void)\n{\n rtu_receiver rx;\n char kind;\n uint32_t tick;\n unsigned byte;\n rtu_init(&rx, observe, NULL);\n while (scanf(" %c", &kind) == 1) {\n ++operation;\n if (kind == \'R\') rtu_init(&rx, observe, NULL);\n else if (kind == \'B\') {\n if (scanf("%" SCNu32 " %x", &tick, &byte) != 2 || byte > 255u) return 2;\n rtu_byte(&rx, (uint8_t)byte, tick);\n } else if (kind == \'P\') {\n if (scanf("%" SCNu32, &tick) != 1) return 2;\n rtu_poll(&rx, tick);\n } else return 2;\n rtu_stats_t s = rtu_get_stats(&rx);\n printf("S %u %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 "\\n",\n operation, s.accepted, s.bad_crc, s.bad_length, s.timing_errors, s.overflows);\n }\n return 0;\n}\n', 'README.md': "# RTU 时间戳接收器\n\n构建:`make`(gcc,C11,`-O2 -Wall -Wextra -Werror`)。运行:`./rtu-demo`。\n所有输入均离线提供,不需要串口、板卡、线程或真实时钟。\n评分构建限 15 秒,每个驱动进程最多 20000 个操作、运行限 10 秒。\n\n## 输入与原始观察\n\nstdin 每行一种操作:`R` 重置;`B <十进制uint32 tick> <两位十六进制字节>`;\n`P <十进制uint32 tick>` 轮询。均为格式正确输入,R 建立新的时间轴;其余操作的 tick 按模 2^32 前进,\n可同 tick,活动期间当前 tick 到最近字节的模差不超过 2^31-1;统计计数不溢出。\nEOF 不触发隐式 flush。\n每次操作(包括 R)编号从 1 递增,回调先打印\n`F <操作号> <触发完成的tick> <不含CRC的长度> <逐字节两位小写hex>`,\n随后打印 `S <操作号> <accepted> <bad_crc> <bad_length> <timing_errors> <overflows>`。\n输出仅由 demo 观察器完成,库函数不得自行打印;正常退出为 0。\n\n## 接口合同(条款 T1–T9)\n\nT1. 保持 rtu.h 中全部签名。`rtu_init` 清空正在接收的段和五个计数,\n保存回调及 context;`rtu_get_stats` 仅返回计数,不改变状态。\n回调参数中的字节在回调期间有效,传入原 context。\n\nT2. 所有时间单位均为整数 tick,gap = `(uint32_t)(now - previous)`。\n`rtu_classify_gap`:0..3 为 RTU_CONTINUE;4..6 为 RTU_INTER_GAP;\n7..2^31-1 为 RTU_FRAME_BOUNDARY。该分类器两个参数的模差保证在\n0..2^31-1 内;必须跨 uint32 回绕工作。\n\nT3. 第一个字节开始一个段。后续字节相对最近字节分类:gap <= 3 继续该段;\ngap >= 7 先在当前字节的 tick 完成旧段,再用当前字节开始新段。\n最后一个字节不能因“看起来已有CRC”而提前完成,段只能由足够长空闲完成。\n\nT4. 活动段收到 gap 为 4..6 的字节时,该整个段作废,timing_errors 只加 1,\n当前字节也丢弃;后续字节继续丢弃并更新最近字节 tick,直到 gap >= 7 或\n满足 T5 的 poll 才解除丢弃。丢弃期间不再增加 timing_errors,不校验 CRC/长度。\n\nT5. `rtu_poll` 不代表收到字节,不更新最近字节 tick,也不会因 gap 为 4..6\n制造错误。活动段且距最近字节 gap >= 7 时,在 poll 的 tick 完成并清空该段;\n否则完全不改变接收状态。空接收器重复 poll 不输出、不计错。\n\nT6. 容量为 64 字节,包括 CRC。收到第 65 个字节时,overflows 只加 1,\n整个段进入与 T4 相同的丢弃状态(无需再增加 timing_errors),不保留尾巴;\n若该字节已因 T3 开始新段,则不属于旧段溢出。\n\nT7. 完成未丢弃的段时,长度 1..3 仅 bad_length 加 1;长度 4..64 才校验\nCRC-16/Modbus(初值 0xffff,逐位右移,多项式 0xa001,无最终异或),\nCRC 为最后两个字节,低字节在先。CRC 错误仅 bad_crc 加 1。\nCRC 正确仅 accepted 加 1,并恰好调用一次回调,移除两个 CRC 字节,\n其余字节原序返回。不按地址/功能码过滤任何字节值。\n\nT8. 完成、CRC/长度错误、超时清空、时间污染、溢出后,后续独立有效段都必须\n恢复正常;错误计数只按 T4/T6/T7 增加。R 丢弃未完成段而不产生错误。\n\nT9. 最终仅评分 rtu.c 和 rtu_timing.c。其余工程文件为只读上下文。评分会用\n原样上下文重新构建、输入更多符合本合同的事件序列;不要依赖持久文件、\n网络、隐藏评分器或固定样例输出。\n\n## 复现与自测\n\n以下帧 CRC 为 40 21,段在最后一次 poll 完成;期望一个 F,随后 accepted=1:\n\n```sh\nmake\nprintf 'B 100 01\\nB 101 03\\nB 102 40\\nB 103 21\\nP 110\\n' | ./rtu-demo\n```\n\n还应自行测试 gap 恰好 3/7、uint32 回绕、poll 后继续接收、污染段后连续有效段,\n以及最大长度与溢出。\n"}
def crc(data):
value = 65535
for byte in data:
value ^= byte
for _ in range(8):
value = (value // 2) ^ (40961 if value % 2 else 0)
return value
def frame(payload):
checksum = crc(payload)
return list(payload) + [checksum % 256, checksum // 256]
def cases():
rng = random.Random(0x52545531)
events = []
clock = 0
def reset(start):
nonlocal clock
events.append(('R',))
clock = start & 0xffffffff
def byte(value, gap=1):
nonlocal clock
clock = (clock + gap) & 0xffffffff
events.append(('B', clock, value))
def poll(gap):
nonlocal clock
clock = (clock + gap) & 0xffffffff
events.append(('P', clock))
def send(data, gap=1):
for value in data:
byte(value, gap)
# Public normal path, exact maximum, all byte values and modulo wrap.
for start in (90, 0xfffffff9, 0x7ffffffc):
for size in (2, 3, 15, 62):
for spacing in (0, 1, 3):
reset(start)
send(frame([rng.randrange(256) for _ in range(size)]), spacing)
poll(7)
poll(0)
poll(7)
# Consecutive frames: a byte is also the completion event for its predecessor.
for boundary in (7, 8, 100, 0x7fffffff):
reset(0xfffffff0)
send(frame([0, 255, rng.randrange(256)]))
following = frame([255, 0, rng.randrange(256), 17])
byte(following[0], boundary)
send(following[1:])
poll(7)
# Poll neither refreshes the byte timer nor marks inter-character errors.
reset(123)
send(frame([9, 0, 255]))
poll(4)
poll(2)
poll(1)
reset(0xfffffffb)
data = frame([2, 16, 8, 4])
byte(data[0], 0)
poll(2)
byte(data[1], 1)
send(data[2:])
poll(7)
# Polling an empty receiver and resetting a pending or poisoned segment.
reset(400)
poll(0)
poll(0x7fffffff)
byte(8, 1)
events.append(('R',))
poll(7)
send(frame([3, 6]))
poll(7)
# Reset also discards a poisoned segment without a second error.
reset(0xfffffff0)
byte(1, 0)
byte(2, 5)
events.append(('R',))
send(frame([3, 7]))
poll(7)
# Short length classes, every CRC-byte corruption, and immediate recovery.
for size in (1, 2, 3):
reset(rng.randrange(1 << 32))
send([rng.randrange(256) for _ in range(size)])
poll(7)
send(frame([rng.randrange(256), 4]))
poll(7)
for offset in (-2, -1):
reset(0xfffffffa)
bad = frame([0, 2, 4, 6, 8])
bad[offset] ^= 1 << rng.randrange(8)
send(bad)
poll(7)
send(frame([19, 3]))
poll(7)
# Once a segment has a 4..6 gap, even a valid suffix is discarded.
for illegal_gap in (4, 5, 6):
for recovery in ('poll', 'byte'):
reset(0xfffffffc)
send([7, 8])
byte(9, illegal_gap)
send(frame([rng.randrange(256), 3]), 0)
byte(1, 4)
poll(6)
if recovery == 'poll':
poll(1)
send(frame([3, 17]))
else:
next_frame = frame([5, 6, rng.randrange(256)])
byte(next_frame[0], 1)
send(next_frame[1:])
poll(7)
# Poll at 4 does not move the byte origin; next byte at delta 6 poisons.
reset(17)
byte(1, 0)
poll(4)
byte(2, 2)
send(frame([3, 4]))
poll(7)
send(frame([5, 6]))
poll(7)
# Capacity includes CRC. Long segments poison once, then recover.
for excess in (1, 2, 70):
reset(0xfffffff0)
send([rng.randrange(256) for _ in range(64 + excess)], 0)
send(frame([8, 9]), 0)
byte(7, 5)
poll(7)
send(frame([11, 12, 13]))
poll(7)
# Mixed deterministic streams exercise reset, delayed flush, noise, back-to-back frames.
reset(0xffffffe0)
for _ in range(80):
mode = rng.randrange(5)
payload = [rng.randrange(256) for _ in range(rng.choice((2, 4, 8, 31, 62)))]
data = frame(payload)
if mode == 0:
data[-1] ^= 128
send(data, rng.choice((0, 1, 3)))
if mode == 1:
byte(rng.randrange(256), rng.choice((4, 5, 6)))
send(frame([rng.randrange(256), rng.randrange(256)]))
if mode == 2:
poll(3)
poll(3)
poll(1)
elif mode == 3:
byte(rng.randrange(256), 7)
poll(7)
else:
poll(rng.choice((7, 8, 20)))
# EOF alone must not deliver or count a pending frame.
reset(0xfffffffe)
send(frame([0, 255]))
return events
def expected(events):
observations = []
counts = [0] * 5
segment = None
reason = None
last_byte = 0
def close(index, tick):
nonlocal segment, reason
if reason is None:
if len(segment) < 4:
counts[2] += 1
else:
payload, wire = segment[:-2], segment[-2] + segment[-1] * 256
if crc(payload) != wire:
counts[1] += 1
else:
counts[0] += 1
observations.append('F %d %d %d %s' %
(index, tick, len(payload), ' '.join('%02x' % b for b in payload)))
segment = None
reason = None
for index, event in enumerate(events, 1):
kind = event[0]
if kind == 'R':
counts = [0] * 5
segment = None
reason = None
else:
tick = event[1]
delta = (tick - last_byte) % (1 << 32)
if segment is not None and delta >= 7:
close(index, tick)
if kind == 'B':
if segment is None:
segment = []
elif delta > 3 and reason is None:
reason = 'timing'
counts[3] += 1
last_byte = tick
if reason is None:
segment.append(event[2])
if len(segment) > 64:
reason = 'capacity'
counts[4] += 1
observations.append('S %d %s' % (index, ' '.join(map(str, counts))))
return observations
def main():
candidate = Path(sys.argv[1])
events = cases()
wanted = expected(events)
stdin = ''.join(('R\n' if e[0] == 'R' else 'P %d\n' % e[1]
if e[0] == 'P' else 'B %d %02x\n' % (e[1], e[2])) for e in events)
scratch = Path(tempfile.mkdtemp(prefix='rtu-grade-'))
for name, contents in READONLY.items():
(scratch / name).write_text(contents)
for name in ('rtu.c', 'rtu_timing.c'):
(scratch / name).write_bytes((candidate / name).read_bytes())
built = subprocess.run(['make', '-s'], cwd=scratch, capture_output=True, text=True, timeout=15)
if built.returncode:
print('build failed')
return 1
# All scratch writes, candidate reads, source assembly and input preparation are complete.
# No scratch access or automatic cleanup is allowed after this untrusted child starts.
completed = subprocess.run([str(scratch / 'rtu-demo')], cwd=scratch, input=stdin,
capture_output=True, text=True, timeout=10)
if completed.returncode:
print('candidate process failed')
return 1
got = completed.stdout.splitlines()
for index in range(max(len(got), len(wanted))):
actual = got[index] if index < len(got) else '<missing>'
correct = wanted[index] if index < len(wanted) else '<extra>'
if actual != correct:
print('observation %d mismatch: got %s; expected %s' % (index + 1, actual, correct))
return 1
print('PASS')
return 0
if __name__ == '__main__':
raise SystemExit(main())