rt_exec.py 31 KB

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