rt_exec.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. #!/usr/bin/env python3
  2. """rt_exec.py -- call every 8086 runtime entry with a known argument, on qemu,
  3. and check what it does.
  4. The runtime (shell/Runtime.mod) is hand-assembled 8086, so "it built" says
  5. nothing about it. This says it *runs*. It used to run it on Unicorn, and
  6. Unicorn 2.1.4 mis-decodes 16-bit ModRM memory operands, so it failed 33 of 33
  7. and every one of those failures was the emulator's. A wrong oracle is worse
  8. than none: it cannot tell "my codegen is broken" from "the machine is broken".
  9. So the machine is now qemu-system-i386, driven through the same boot sector the
  10. .COM fixtures use (tests/exec/bootcom.s), and the expectations are unchanged
  11. except where they were demonstrably wrong -- see EXPECTATION FIXES below.
  12. .pas-free: RtProbe (base = RT_BASE) -> blob + entry offsets
  13. rt_exec.py -> 16-40 byte case record
  14. exec/rtdrv.s (assembled) -> a whole .COM image
  15. bootcom.s + qemu -> one framed record per case
  16. rt_exec.py -> parsed, compared
  17. tests/rt_exec.py --probe # the standalone runtime dump (base 0)
  18. tests/rt_exec.py --list # the case names
  19. tests/rt_exec.py --show # print what came out, assert nothing
  20. EXPECTATION FIXES -- two expectations were wrong, and both were wrong in the
  21. direction that made the HARNESS the suspect:
  22. * rdchar stores ONE byte (Runtime.EmitRdChar: `StDiDl' = MOV [DI], DL), so
  23. dumping a two-byte word and comparing it against ord(c) could never pass.
  24. The check was broken, the entry was right. The case now reports two bytes
  25. and expects the character followed by the 0xEE poison that is still there.
  26. * rdint at end of input does NOT store anything. TP3's xrdint returns to
  27. rnerr without touching the variable, and Runtime.EmitRdInt says so in its
  28. own comment ("^Z before any digit reaches rnend ... returns WITHOUT
  29. touching the variable"). The old expectation said the variable became 0.
  30. It stays at the poison, and that is the faithful answer.
  31. Everything else is the original expectation verbatim. The two `rdln' halves of
  32. the six rdint cases are merged into the same case as the value they follow: a
  33. readln that printed anything would change the same compared string, so the
  34. assertion is unchanged - one qemu boot per check instead of two.
  35. """
  36. import os
  37. import re
  38. import struct
  39. import subprocess
  40. import sys
  41. import tempfile
  42. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  43. from run_com_exec import (GM2, QEMU, build_boot_sector, build_floppy, # noqa: E402
  44. run_qemu, visible_output)
  45. HERE = os.path.dirname(os.path.abspath(__file__))
  46. SHELL = os.path.dirname(HERE)
  47. # --------------------------------------------------------------- the layout
  48. # RT_BASE is restated from exec/rtdrv.s on purpose: the driver needs the blob at
  49. # a known offset and Python needs to know where the driver thinks it is, so the
  50. # two are written down and then CHECKED against each other (see build_image).
  51. # A restated constant that is never compared is a constant waiting to lie.
  52. RT_BASE = 0x0200
  53. HDR = 0x0800
  54. DLEN = 32
  55. DATA = 0x0810
  56. STORE = 0x0840
  57. CASE = 0x0860
  58. CASE_SZ = 40
  59. # A .COM is loaded at CS:0100, and every address in the image is an image
  60. # offset. The load bias is therefore the difference between the two, and
  61. # putting it in one place here stops it being applied -- or forgotten -- in each
  62. # field. exec/rtdrv.s has its own .set of it, for the same reason it has its
  63. # own .set of the record offsets: two independent statements that are then
  64. # checked against each other by the fact that any disagreement stops the cases
  65. # from passing.
  66. LOAD_BIAS = 0x0100
  67. # The 8086 has a fixed 16-byte-case-record area in rtdrv.s, and the harness
  68. # asserts this window is still zeros. If the driver outgrows its space it
  69. # starts eating the runtime it is testing, which would be silent; this makes it
  70. # loud.
  71. DRIVER_TOP = 0x0180
  72. # The four framing bytes exec/rtdrv.s wraps each case's report in.
  73. SOH, STX, ETX, EOT = 0x01, 0x02, 0x03, 0x04
  74. # Entry selector order, as Runtime.def declares it. The names are used only to
  75. # be looked up in RtProbe's output, so renaming an entry in Runtime.mod makes
  76. # the lookup fail loudly instead of silently testing offset 0.
  77. ENTS = ["initmem", "progend", "stackchk", "wrint", "wrchar", "wrbool",
  78. "wrreal", "wrln", "rdint", "rdchar", "rdbool", "rdln", "halt",
  79. "wrtinl"]
  80. # A call slot's flags, as rtdrv.s reads them.
  81. F_STACK = 1 # the argument goes on the stack, popped by the caller
  82. F_AX = 2 # ...or in AX instead (initmem's convention)
  83. F_INL = 4 # wrtinl: the argument is at the return address, not on the stack
  84. # The byte patterns check_bp_contract looks for, and the rule they express:
  85. # "an entry that borrows BP opens with PUSH BP; MOV BP,SP and pops it again
  86. # before it returns" -- so an entry containing 8B EC anywhere must start with
  87. # 55 8B EC and must contain a 5D. See that function: the first half of that
  88. # rule is exact and the second is a screen, and the difference matters.
  89. PUSH_BP_MOV_BP_SP = b"\x55\x8b\xec" # PUSH BP ; MOV BP,SP
  90. MOV_BP_SP = b"\x8b\xec" # MOV BP,SP
  91. POP_BP = b"\x5d" # POP BP
  92. # --------------------------------------------------------------- RtProbe
  93. def ensure_rtprobe():
  94. """Build tests/RtProbe.mod, return its path.
  95. Timestamp-checked, for the reason run_com_exec.ensure_comtest documents:
  96. a probe older than the runtime it reports on is worse than no probe, and
  97. the failure it produces -- a blob with the wrong addresses in it -- is
  98. silent at the byte level and catastrophic at the behaviour level.
  99. """
  100. exe = os.path.join(HERE, "rtprobe")
  101. newer = ["Runtime.mod", "Runtime.def", "Runtime.o", "Posix.c",
  102. os.path.join("tests", "RtProbe.mod")]
  103. if os.path.exists(exe):
  104. t = os.path.getmtime(exe)
  105. if all(os.path.exists(os.path.join(SHELL, f))
  106. and os.path.getmtime(os.path.join(SHELL, f)) <= t
  107. for f in newer):
  108. return exe
  109. r = subprocess.run([GM2, "-fiso", "-o", exe, "tests/RtProbe.mod",
  110. "Runtime.o", "Posix.o"],
  111. capture_output=True, cwd=SHELL)
  112. if r.returncode != 0:
  113. sys.exit("building RtProbe failed:\n" + r.stderr.decode(errors="replace"))
  114. return exe
  115. def load_runtime(base):
  116. """Run RtProbe at `base`.
  117. Return (blob, {name: image-absolute offset}, code_end). `code_end` is the
  118. blob-relative offset where the code stops and the data area starts, and it
  119. is what bounds the last entry's bytes: without it the last entry's "does
  120. it contain MOV SP,BP" question would be answered partly by the data area,
  121. and a string or an entry-table word that happens to contain the pattern
  122. would turn a missing epilogue into a pass.
  123. """
  124. out = subprocess.run([ensure_rtprobe()], input=b"%d\n" % base,
  125. capture_output=True, check=True).stdout.decode(
  126. errors="replace")
  127. # RtProbe ends its lines CR LF, as a program of this vintage would. Every
  128. # pattern below is `$'-anchored, and Python's `$' in MULTILINE stops before
  129. # "\n" only -- so without this the first regex fails and the report blames
  130. # the probe for it.
  131. out = out.replace("\r\n", "\n")
  132. m = re.search(r"^base=(\d+)$", out, re.M)
  133. if m is None or int(m.group(1)) != base:
  134. sys.exit("RtProbe did not confirm base=%d:\n%s" % (base, out[:400]))
  135. size = int(re.search(r"^(\d+) bytes", out, re.M).group(1))
  136. cm = re.search(r"^code ends at (\d+)$", out, re.M)
  137. if cm is None:
  138. sys.exit("RtProbe did not say where the code ends:\n%s" % out[:400])
  139. code_end = int(cm.group(1))
  140. if not 0 < code_end <= size:
  141. sys.exit("RtProbe says the code ends at %d, which is not inside a "
  142. "%d byte blob" % (code_end, size))
  143. entries = {nm: int(v) for v, nm in
  144. re.findall(r"entry \d+ = (\d+)\s+\((\w+)\)", out)}
  145. missing = [e for e in ENTS if e not in entries]
  146. if missing:
  147. sys.exit("RtProbe did not report entries: %s" % ", ".join(missing))
  148. blob = bytearray()
  149. for line in out.splitlines():
  150. h = re.match(r"^[0-9A-F]{8} ((?:[0-9A-F]{2} )+)$", line)
  151. if h:
  152. blob += bytes.fromhex(h.group(1).replace(" ", ""))
  153. if len(blob) != size:
  154. sys.exit("parsed %d bytes of runtime, RtProbe says %d"
  155. % (len(blob), size))
  156. for nm, off in entries.items():
  157. if not base <= off < base + code_end:
  158. sys.exit("entry %s is at %d, outside the code area %d..%d -- the "
  159. "entry table and the blob disagree"
  160. % (nm, off, base, base + code_end))
  161. return bytes(blob), entries, code_end
  162. def probe():
  163. """The standalone dump run_all.sh's `runtime probe' step wants: base 0."""
  164. raw = subprocess.run([ensure_rtprobe()], input=b"0\n", capture_output=True,
  165. check=True).stdout
  166. sys.stdout.buffer.write(raw)
  167. return 0
  168. def check_bp_contract(blob, entries, base, code_end):
  169. """Every entry must hand BP back.
  170. The driver keeps its cursor into the case record in BP, because an entry is
  171. allowed to destroy every register except BP and SP. Two entries did not
  172. honour that: wrchar and wrbool borrowed BP to reach their argument -- [SP]
  173. is unencodable in 16-bit mode -- and returned without saving it. One
  174. multi-call case caught it, and only because it made four calls in a row; a
  175. new entry that borrowed BP the same way would be caught by nothing.
  176. So the rule is checked here, over the built blob, before any case runs.
  177. The rule is the runtime's own convention, in two halves, and the halves are
  178. NOT equally strong -- which is worth writing down rather than discovering:
  179. * "an entry that borrows BP must START with 55 8B EC" is EXACT. The
  180. prologue is the first thing the entry does, so a positional test
  181. cannot be fooled by anything.
  182. * "...and must contain a 5D somewhere" is a SCREEN, not a proof. 5D is
  183. POP BP, but it is also a perfectly ordinary displacement byte, and
  184. this code does not disassemble. Requiring the POP to be contiguous
  185. with something else does not rescue it either: wrbool legitimately
  186. closes its frame with POP BP after the INT 21h, and a rule that
  187. insisted on 89 EC 5D would have failed a correct entry -- a false
  188. alarm, which is worse here than a miss because it teaches a reader to
  189. distrust the check. So the honest position is: a push with no pop is
  190. CAUGHT unless some displacement in the entry happens to be 5Dh, and
  191. the argument displacements in this runtime are 2 and 4, so nothing can
  192. collide today. tests/nonvacuity.sh removes the POP as well as the
  193. PUSH and requires each to turn this red, so the screen is at least
  194. witnessed rather than assumed.
  195. Counting 55s and 5Ds to check frame BALANCE would be worse than either:
  196. 55 occurs as an immediate and 5D as a displacement, so the answer would
  197. come out wrong without the check ever looking wrong. For the same reason
  198. each entry's bytes stop at the next entry, or at `code_end` for the last
  199. one: running on into the data area would let a string satisfy either test.
  200. The counts it returns are the point as much as the verdict. A scan that
  201. matches nothing is indistinguishable from a scan that passes, and that has
  202. happened here before -- so zero borrowers is a failure, not a pass.
  203. Entries are counted by OFFSET, not by name: `progend' and `halt' are one
  204. entry with two names, and counting them twice would make the total here
  205. disagree with the number of things that can actually be wrong.
  206. """
  207. offs = sorted(set(entries.values()))
  208. scanned = borrowed = 0
  209. bad = []
  210. for i, a in enumerate(offs):
  211. lo = a - base
  212. hi = (offs[i + 1] - base) if i + 1 < len(offs) else code_end
  213. code = bytes(blob[lo:hi])
  214. scanned += 1
  215. if MOV_BP_SP not in code:
  216. continue
  217. borrowed += 1
  218. # The two halves are reported separately, because they are separate
  219. # faults with separate fixes and "it does not hand BP back" does not
  220. # say which of them happened.
  221. if not code.startswith(PUSH_BP_MOV_BP_SP):
  222. why = "borrows BP but does not open with 55 8B EC, so the "\
  223. "caller's BP is destroyed"
  224. elif POP_BP not in code:
  225. why = "pushes BP but never pops it, so the caller gets a "\
  226. "cursor two bytes off"
  227. else:
  228. continue
  229. names = sorted(n for n, v in entries.items() if v == a)
  230. bad.append("%s -- %s (image 0x%04X: %s)"
  231. % (",".join(names), why, a, code[:12].hex(" ")))
  232. if bad:
  233. sys.exit("these entries do not hand BP back, so a caller that keeps a "
  234. "cursor in BP -- which this driver does, and which is the whole "
  235. "reason BP is the one register an entry may keep -- loses it:\n"
  236. " %s" % "\n ".join(bad))
  237. if borrowed == 0:
  238. sys.exit("no entry borrows BP, so this check examined %d entries and "
  239. "matched nothing: it is not looking at what it claims to "
  240. "look at" % scanned)
  241. return scanned, borrowed
  242. # ------------------------------------------------------------------ the case
  243. def case_bytes(c, entries):
  244. """One 40 byte case record, exactly as exec/rtdrv.s reads it.
  245. The record is a second, independent statement of the same layout rtdrv.s
  246. carries in its .set block. The cases only pass if the two agree on every
  247. offset, which is the whole reason for writing it twice: a driver that
  248. silently read the wrong field would still boot, still run, and still print.
  249. """
  250. if len(c["in"]) > 8:
  251. sys.exit("case %s supplies %d input bytes; the record holds 8"
  252. % (c["name"], len(c["in"])))
  253. b = bytearray(CASE_SZ)
  254. struct.pack_into("<H", b, 0, c["dump"]) # OFF_DUMPLEN
  255. struct.pack_into("<H", b, 2, c["dumpadr"]) # OFF_DUMPADR
  256. b[4] = len(c["in"]) # OFF_INLEN
  257. b[5:5 + len(c["in"])] = c["in"] # OFF_INBUF
  258. b[13] = c["index"] # OFF_CASE
  259. calls = c["calls"]
  260. if len(calls) > 4:
  261. sys.exit("case %s has %d calls; the record holds 4"
  262. % (c["name"], len(calls)))
  263. struct.pack_into("<H", b, 14, len(calls)) # OFF_NCALLS
  264. for i, (ent, arg, mode) in enumerate(calls):
  265. o = 16 + 6 * i # SLOT0
  266. struct.pack_into("<H", b, o, entries[ent])
  267. struct.pack_into("<H", b, o + 2, arg)
  268. b[o + 4] = mode
  269. return bytes(b)
  270. def build_image(blob, rec):
  271. """Assemble exec/rtdrv.s into a complete .COM, and check it is the one
  272. we think it is.
  273. The three assertions are the point of this function. An image that is
  274. subtly not the image we intended would still boot, still run, and still
  275. print something -- the failure would look like a runtime bug.
  276. """
  277. if RT_BASE + len(blob) > HDR:
  278. sys.exit("the runtime is %d bytes: at RT_BASE=%04X it runs into the "
  279. "test scaffolding at %04X. Move the .org's in rtdrv.s."
  280. % (len(blob), RT_BASE, HDR))
  281. with tempfile.TemporaryDirectory() as td:
  282. open(os.path.join(td, "rtblob.bin"), "wb").write(blob)
  283. open(os.path.join(td, "rtcase.bin"), "wb").write(rec)
  284. src = os.path.join(HERE, "exec", "rtdrv.s")
  285. obj, raw = os.path.join(td, "r.o"), os.path.join(td, "r.bin")
  286. r = subprocess.run(["as", "--32", "-I", td, "-o", obj, src],
  287. capture_output=True)
  288. if r.returncode != 0:
  289. sys.exit("as failed on rtdrv.s:\n"
  290. + r.stderr.decode(errors="replace"))
  291. r = subprocess.run(["objcopy", "-O", "binary", obj, raw],
  292. capture_output=True)
  293. if r.returncode != 0:
  294. sys.exit("objcopy failed:\n" + r.stderr.decode(errors="replace"))
  295. img = open(raw, "rb").read()
  296. # E9 00 00: a near jump to offset 3 from offset 0, so the displacement is
  297. # 3 - (0 + 3) = 0. The driver is the first thing after the jump, which is
  298. # what makes the rel16 zero and therefore useless as a check on the target
  299. # -- the check that matters is the one below, that the blob landed where the
  300. # driver thinks it did.
  301. if img[0:3] != b"\xe9\x00\x00":
  302. sys.exit("rtdrv.s does not open with a 3-byte near JMP over itself: %s"
  303. % img[0:3].hex())
  304. if img[RT_BASE:RT_BASE + len(blob)] != blob:
  305. sys.exit("the blob is not at RT_BASE=%04X in the assembled image -- "
  306. "rtdrv.s and rt_exec.py disagree about the layout"
  307. % RT_BASE)
  308. gap = img[DRIVER_TOP:RT_BASE]
  309. if gap != b"\x00" * len(gap):
  310. sys.exit("the driver has outgrown its space: rtdrv.s no longer fits "
  311. "under %04X, so it is overwriting the runtime" % DRIVER_TOP)
  312. return img
  313. def parse_record(raw, want_index):
  314. """Split the serial output into (case index, printed, dumped) or raise.
  315. Nothing here is lenient. A driver that printed nothing, a truncated
  316. record, or a record for the wrong case are all failures with a reason, not
  317. a comparison against an empty string that happens to pass.
  318. """
  319. if not raw or raw[0] != SOH:
  320. raise AssertionError("no record header: the driver printed %r" % raw[:64])
  321. if len(raw) < 5 or raw[3] != STX:
  322. raise AssertionError("malformed record header %r" % raw[:16])
  323. idx = int(raw[1:3], 16)
  324. if idx != want_index:
  325. raise AssertionError("record is for case %02X, expected %02X"
  326. % (idx, want_index))
  327. if raw[-1] != EOT:
  328. raise AssertionError("record was never closed (EOT): the last call did "
  329. "not return, or the machine halted early")
  330. end = raw.index(ETX, 4)
  331. if end < 0:
  332. raise AssertionError("record has no ETX: the calls printed nothing and "
  333. "the driver never got past them")
  334. printed, dump = raw[4:end], raw[end + 1:-1]
  335. if len(dump) % 2 or not re.fullmatch(b"[0-9A-F]*", dump):
  336. raise AssertionError("the memory report %r is not hex" % dump)
  337. return idx, printed, bytes.fromhex(dump.decode())
  338. # ----------------------------------------------------------------- the cases
  339. def build_cases():
  340. """Every check, in the order the names are printed.
  341. Each case is a list of calls plus two expectations: the bytes the entry(s)
  342. printed, and the bytes that must be at `dumpadr' afterwards. `dump=0' means
  343. the case asserts nothing about memory, which is itself an assertion: the
  344. report is empty, so a case cannot quietly acquire a memory check it did not
  345. ask for.
  346. The addresses handed to an entry as its argument are MEMORY addresses, not
  347. image offsets -- that is the whole of LoadBias, and it is the difference
  348. between a read entry storing where the harness looks and storing one page
  349. lower where nothing checks it. V below is "the memory address of STORE",
  350. which is what every read case wants.
  351. """
  352. cs = []
  353. V = STORE + LOAD_BIAS
  354. def add(name, calls, out=b"", stdin=b"", dump=0, dumpbytes=b"",
  355. dumpadr=STORE, note=""):
  356. cs.append({"name": name, "calls": calls, "out": out, "in": stdin,
  357. "dump": dump, "dumpbytes": dumpbytes, "dumpadr": dumpadr,
  358. "note": note, "index": len(cs)})
  359. def s(ent, arg):
  360. return (ent, arg, F_STACK)
  361. def x(ent, arg):
  362. return (ent, arg, F_AX)
  363. def n(ent):
  364. return (ent, 0, 0)
  365. # initmem is handed the header in AX -- and the header's MEMORY address, not
  366. # its image offset. Given the image offset it reads the two words it wants
  367. # out of blank space, finds both zero, and clears nothing at all: a silent
  368. # no-op, which is the reason this case poisons the data area to AAH first.
  369. add("initmem zeroes globals",
  370. [x("initmem", HDR + LOAD_BIAS)], dump=DLEN, dumpadr=DATA,
  371. dumpbytes=b"\x00" * DLEN,
  372. note="the data area is poisoned to AA first, so a zero is a result")
  373. for v, why in [(0, "the one value where a signed/unsigned slip is invisible"),
  374. (1, ""), (-1, ""), (7, ""), (10, ""), (42, ""),
  375. (100, ""), (12345, ""), (-32768, "the sign bit"), (32767, "")]:
  376. add("wrint(%d)" % v, [s("wrint", v & 0xFFFF)],
  377. out=str(v).encode(), note=why)
  378. add("wrchar('A')", [s("wrchar", ord("A"))], out=b"A")
  379. add("wrchar('!')", [s("wrchar", ord("!"))], out=b"!")
  380. add("wrbool(0)", [s("wrbool", 0)], out=b"FALSE")
  381. add("wrbool(1)", [s("wrbool", 1)], out=b"TRUE")
  382. add("wrbool(2)", [s("wrbool", 2)], out=b"TRUE",
  383. note="any non-zero is true, as TP3's xwrb does")
  384. add("wrln", [n("wrln")], out=b"\r\n")
  385. add("stackchk returns", [n("stackchk")], out=b"",
  386. note="no output: the assertion is that control came back at all")
  387. add("writeln(42) writeln TRUE in one program",
  388. [s("wrint", 42), s("wrchar", ord(" ")), s("wrbool", 1), n("wrln")],
  389. out=b"42 TRUE\r\n",
  390. note="four calls back to back, so no register leaks between them")
  391. # rdint: the value, and then the rdln that must eat the rest of the line.
  392. for text, want in [(b" 42abc", 42), (b"-17 x", -17), (b"+5", 5),
  393. (b"0", 0), (b" 007", 7), (b"1234", 1234)]:
  394. add("rdint(%r) then rdln" % text,
  395. [s("rdint", V), n("rdln")], out=b"", stdin=text, dump=2,
  396. dumpbytes=struct.pack("<h", want),
  397. note="the delimiter must be left for rdln, which prints nothing")
  398. for c in "Q7":
  399. add("rdchar(%r)" % c, [s("rdchar", V)], out=b"", stdin=c.encode(),
  400. dump=2, dumpbytes=bytes([ord(c), 0xEE]),
  401. note="rdchar stores ONE byte, so the poison is still in byte 2")
  402. for c, want in [("T", 1), ("y", 1), ("1", 1), ("F", 0), ("n", 0), ("0", 0)]:
  403. add("rdbool(%r)" % c, [s("rdbool", V)], out=b"", stdin=c.encode(),
  404. dump=2, dumpbytes=struct.pack("<H", want))
  405. add("rdint at end of input leaves the variable alone",
  406. [s("rdint", V), n("rdln")], out=b"", stdin=b"", dump=2,
  407. dumpbytes=b"\xee\xee",
  408. note="TP3's xrdint returns to rnerr without storing; the poison stays")
  409. add("wrtinl reads its length and characters from the return address",
  410. [("wrtinl", 0, F_INL)], out=b"hello",
  411. note="the one entry whose argument is not a stack word")
  412. return cs
  413. def run_case(c, blob, entries, boot):
  414. rec = case_bytes(c, entries)
  415. img = build_image(blob, rec)
  416. with tempfile.TemporaryDirectory() as td:
  417. floppy = os.path.join(td, "f.img")
  418. open(floppy, "wb").write(build_floppy(boot, img, c["in"]))
  419. return run_qemu(floppy)
  420. def main(argv):
  421. if "--probe" in argv:
  422. return probe()
  423. cases = build_cases()
  424. if "--list" in argv:
  425. for c in cases:
  426. print(c["name"])
  427. return 0
  428. show = "--show" in argv
  429. only = [a for a in argv if not a.startswith("-")]
  430. blob, entries, code_end = load_runtime(RT_BASE)
  431. boot = build_boot_sector()
  432. # Before any machine is started: the contract the driver depends on.
  433. nscan, nborrow = check_bp_contract(blob, entries, RT_BASE, code_end)
  434. print(" %-52s PASS (%d entries scanned, %d borrow BP and hand it "
  435. "back)" % ("every entry preserves BP", nscan, nborrow))
  436. npass = 1
  437. nfail = 0
  438. for c in cases:
  439. if only and not any(o in c["name"] for o in only):
  440. continue
  441. # A marker byte inside an expectation would make the framing
  442. # ambiguous, so it is refused rather than mis-parsed.
  443. for b in (SOH, STX, ETX, EOT):
  444. if bytes([b]) in c["out"]:
  445. sys.exit("case %s: its expected output contains the framing "
  446. "byte %02X, which would be indistinguishable from the "
  447. "driver's own markers" % (c["name"], b))
  448. raw, rc, note = run_case(c, blob, entries, boot)
  449. if show:
  450. print(c["name"], "->", repr(visible_output(raw)))
  451. continue
  452. try:
  453. _, printed, dumped = parse_record(raw, c["index"])
  454. except AssertionError as e:
  455. print(" %-52s FAIL %s" % (c["name"], e))
  456. nfail += 1
  457. continue
  458. if printed != c["out"]:
  459. print(" %-52s FAIL printed %s, want %s"
  460. % (c["name"], visible_output(printed),
  461. visible_output(c["out"])))
  462. nfail += 1
  463. continue
  464. if dumped != c["dumpbytes"]:
  465. print(" %-52s FAIL +%04X = %s, want %s"
  466. % (c["name"], c["dumpadr"], dumped.hex() or "-",
  467. c["dumpbytes"].hex() or "-"))
  468. nfail += 1
  469. continue
  470. print(" %-52s PASS%s" % (c["name"],
  471. (" (" + c["note"] + ")") if c["note"] else ""))
  472. npass += 1
  473. if show:
  474. return 0
  475. print("\nruntime entries: %d passed, %d failed (of %d)"
  476. % (npass, nfail, npass + nfail))
  477. return 1 if nfail else 0
  478. if __name__ == "__main__":
  479. sys.exit(main(sys.argv[1:]))