rt_exec.py 37 KB

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