rt_exec.py 34 KB

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