rt_exec.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 math
  37. import os
  38. import re
  39. import struct
  40. import subprocess
  41. import sys
  42. import tempfile
  43. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  44. from run_com_exec import (GM2, QEMU, build_boot_sector, build_floppy, # noqa: E402
  45. run_qemu, visible_output)
  46. HERE = os.path.dirname(os.path.abspath(__file__))
  47. SHELL = os.path.dirname(HERE)
  48. # --------------------------------------------------------------- the layout
  49. # RT_BASE is restated from exec/rtdrv.s on purpose: the driver needs the blob at
  50. # a known offset and Python needs to know where the driver thinks it is, so the
  51. # two are written down and then CHECKED against each other (see build_image).
  52. # A restated constant that is never compared is a constant waiting to lie.
  53. RT_BASE = 0x0190
  54. HDR = 0x1100
  55. DLEN = 32
  56. DATA = 0x1110
  57. STORE = 0x1140
  58. WSTR = 0x1150
  59. WSTR_EMPTY = 0x1158
  60. CASE = 0x1160
  61. CASE_SZ = 64
  62. RDSTR_DST = 0x11B0
  63. SST_HELLO = 0x11C0
  64. SST_LONG = 0x11D0
  65. SST_EMPTY = 0x11E0
  66. SST_DST = 0x11F0
  67. SST_CAT = 0x1200
  68. SST_CAT0 = 0x1210
  69. SST_WORLD = 0x1220
  70. AXOUT = 0x11A6 # the driver stores the last call's AX here
  71. FMTDEST = 0x1430 # a 64-byte string for the real_fmt cases
  72. ASCSRC = 0x1470 # the ASCIIZ strings for real_val
  73. REALDST = 0x0FA8
  74. # A .COM is loaded at CS:0100, and every address in the image is an image
  75. # offset. The load bias is therefore the difference between the two, and
  76. # putting it in one place here stops it being applied -- or forgotten -- in each
  77. # field. exec/rtdrv.s has its own .set of it, for the same reason it has its
  78. # own .set of the record offsets: two independent statements that are then
  79. # checked against each other by the fact that any disagreement stops the cases
  80. # from passing.
  81. LOAD_BIAS = 0x0100
  82. # The 8086 has a fixed 16-byte-case-record area in rtdrv.s, and the harness
  83. # asserts this window is still zeros. If the driver outgrows its space it
  84. # starts eating the runtime it is testing, which would be silent; this makes it
  85. # loud.
  86. DRIVER_TOP = 0x0180
  87. # The four framing bytes exec/rtdrv.s wraps each case's report in.
  88. SOH, STX, ETX, EOT = 0x01, 0x02, 0x03, 0x04
  89. # Entry selector order, as Runtime.def declares it. The names are used only to
  90. # be looked up in RtProbe's output, so renaming an entry in Runtime.mod makes
  91. # the lookup fail loudly instead of silently testing offset 0.
  92. ENTS = ["initmem", "progend", "stackchk", "wrint", "wrchar", "wrbool",
  93. "wrreal", "wrln", "rdint", "rdchar", "rdbool", "rdln", "halt",
  94. "wrtinl", "rdbyte", "wrstr", "rdstr", "strstore", "cmpstr", "strcat",
  95. "wrintw", "real_from_int", "real_add", "real_sub", "real_mul",
  96. "real_div", "real_cmp", "real_int", "real_fmt", "real_val",
  97. "real_write"]
  98. # A call slot's flags, as rtdrv.s reads them.
  99. F_STACK = 1 # the argument goes on the stack, popped by the caller
  100. F_AX = 2 # ...or in AX instead (initmem's convention)
  101. F_INL = 4 # wrtinl: the argument is at the return address, not on the stack
  102. F_STACK2 = 8 # two stack words: +6 pushed first (lands at [BP+6]), +2 second
  103. # (at [BP+4]) -- strstore's dest/src order
  104. F_CX = 16 # CX := the word at +8, the maximum length rdstr and strstore
  105. # both read from the register
  106. F_STACK3 = 32 # three stack words: +8 first, then +6, then +2, so +2 is
  107. # [BP+4], +6 is [BP+6] and +8 is [BP+8]
  108. # The byte patterns check_bp_contract looks for, and the rule they express:
  109. # "an entry that borrows BP opens with PUSH BP; MOV BP,SP and pops it again
  110. # before it returns" -- so an entry containing 8B EC anywhere must start with
  111. # 55 8B EC and must contain a 5D. See that function: the first half of that
  112. # rule is exact and the second is a screen, and the difference matters.
  113. PUSH_BP_MOV_BP_SP = b"\x55\x8b\xec" # PUSH BP ; MOV BP,SP
  114. MOV_BP_SP = b"\x8b\xec" # MOV BP,SP
  115. POP_BP = b"\x5d" # POP BP
  116. # --------------------------------------------------------------- RtProbe
  117. def ensure_rtprobe():
  118. """Build tests/RtProbe.mod, return its path.
  119. Timestamp-checked, for the reason run_com_exec.ensure_comtest documents:
  120. a probe older than the runtime it reports on is worse than no probe, and
  121. the failure it produces -- a blob with the wrong addresses in it -- is
  122. silent at the byte level and catastrophic at the behaviour level.
  123. """
  124. exe = os.path.join(HERE, "rtprobe")
  125. newer = ["Runtime.mod", "Runtime.def", "Runtime.o", "Posix.c",
  126. os.path.join("tests", "RtProbe.mod")]
  127. if os.path.exists(exe):
  128. t = os.path.getmtime(exe)
  129. if all(os.path.exists(os.path.join(SHELL, f))
  130. and os.path.getmtime(os.path.join(SHELL, f)) <= t
  131. for f in newer):
  132. return exe
  133. r = subprocess.run([GM2, "-fiso", "-o", exe, "tests/RtProbe.mod",
  134. "Runtime.o", "Posix.o"],
  135. capture_output=True, cwd=SHELL)
  136. if r.returncode != 0:
  137. sys.exit("building RtProbe failed:\n" + r.stderr.decode(errors="replace"))
  138. return exe
  139. def load_runtime(base):
  140. """Run RtProbe at `base`.
  141. Return (blob, {name: image-absolute offset}, code_end). `code_end` is the
  142. blob-relative offset where the code stops and the data area starts, and it
  143. is what bounds the last entry's bytes: without it the last entry's "does
  144. it contain MOV SP,BP" question would be answered partly by the data area,
  145. and a string or an entry-table word that happens to contain the pattern
  146. would turn a missing epilogue into a pass.
  147. """
  148. out = subprocess.run([ensure_rtprobe()], input=b"%d\n" % base,
  149. capture_output=True, check=True).stdout.decode(
  150. errors="replace")
  151. # RtProbe ends its lines CR LF, as a program of this vintage would. Every
  152. # pattern below is `$'-anchored, and Python's `$' in MULTILINE stops before
  153. # "\n" only -- so without this the first regex fails and the report blames
  154. # the probe for it.
  155. out = out.replace("\r\n", "\n")
  156. m = re.search(r"^base=(\d+)$", out, re.M)
  157. if m is None or int(m.group(1)) != base:
  158. sys.exit("RtProbe did not confirm base=%d:\n%s" % (base, out[:400]))
  159. size = int(re.search(r"^(\d+) bytes", out, re.M).group(1))
  160. cm = re.search(r"^code ends at (\d+)$", out, re.M)
  161. if cm is None:
  162. sys.exit("RtProbe did not say where the code ends:\n%s" % out[:400])
  163. code_end = int(cm.group(1))
  164. if not 0 < code_end <= size:
  165. sys.exit("RtProbe says the code ends at %d, which is not inside a "
  166. "%d byte blob" % (code_end, size))
  167. entries = {nm: int(v) for v, nm in
  168. re.findall(r"entry \d+ = (\d+)\s+\((\w+)\)", out)}
  169. missing = [e for e in ENTS if e not in entries]
  170. if missing:
  171. sys.exit("RtProbe did not report entries: %s" % ", ".join(missing))
  172. blob = bytearray()
  173. for line in out.splitlines():
  174. h = re.match(r"^[0-9A-F]{8} ((?:[0-9A-F]{2} )+)$", line)
  175. if h:
  176. blob += bytes.fromhex(h.group(1).replace(" ", ""))
  177. if len(blob) != size:
  178. sys.exit("parsed %d bytes of runtime, RtProbe says %d"
  179. % (len(blob), size))
  180. for nm, off in entries.items():
  181. if not base <= off < base + code_end:
  182. sys.exit("entry %s is at %d, outside the code area %d..%d -- the "
  183. "entry table and the blob disagree"
  184. % (nm, off, base, base + code_end))
  185. return bytes(blob), entries, code_end
  186. def probe():
  187. """The standalone dump run_all.sh's `runtime probe' step wants: base 0."""
  188. raw = subprocess.run([ensure_rtprobe()], input=b"0\n", capture_output=True,
  189. check=True).stdout
  190. sys.stdout.buffer.write(raw)
  191. return 0
  192. def check_bp_contract(blob, entries, base, code_end):
  193. """Every entry must hand BP back.
  194. The driver keeps its cursor into the case record in BP, because an entry is
  195. allowed to destroy every register except BP and SP. Two entries did not
  196. honour that: wrchar and wrbool borrowed BP to reach their argument -- [SP]
  197. is unencodable in 16-bit mode -- and returned without saving it. One
  198. multi-call case caught it, and only because it made four calls in a row; a
  199. new entry that borrowed BP the same way would be caught by nothing.
  200. So the rule is checked here, over the built blob, before any case runs.
  201. The rule is the runtime's own convention, in two halves, and the halves are
  202. NOT equally strong -- which is worth writing down rather than discovering:
  203. * "an entry that borrows BP must START with 55 8B EC" is EXACT. The
  204. prologue is the first thing the entry does, so a positional test
  205. cannot be fooled by anything.
  206. * "...and must contain a 5D somewhere" is a SCREEN, not a proof. 5D is
  207. POP BP, but it is also a perfectly ordinary displacement byte, and
  208. this code does not disassemble. Requiring the POP to be contiguous
  209. with something else does not rescue it either: wrbool legitimately
  210. closes its frame with POP BP after the INT 21h, and a rule that
  211. insisted on 89 EC 5D would have failed a correct entry -- a false
  212. alarm, which is worse here than a miss because it teaches a reader to
  213. distrust the check. So the honest position is: a push with no pop is
  214. CAUGHT unless some displacement in the entry happens to be 5Dh, and
  215. the argument displacements in this runtime are 2 and 4, so nothing can
  216. collide today. tests/nonvacuity.sh removes the POP as well as the
  217. PUSH and requires each to turn this red, so the screen is at least
  218. witnessed rather than assumed.
  219. Counting 55s and 5Ds to check frame BALANCE would be worse than either:
  220. 55 occurs as an immediate and 5D as a displacement, so the answer would
  221. come out wrong without the check ever looking wrong. For the same reason
  222. each entry's bytes stop at the next entry, or at `code_end` for the last
  223. one: running on into the data area would let a string satisfy either test.
  224. The counts it returns are the point as much as the verdict. A scan that
  225. matches nothing is indistinguishable from a scan that passes, and that has
  226. happened here before -- so zero borrowers is a failure, not a pass.
  227. Entries are counted by OFFSET, not by name: `progend' and `halt' are one
  228. entry with two names, and counting them twice would make the total here
  229. disagree with the number of things that can actually be wrong.
  230. """
  231. offs = sorted(set(entries.values()))
  232. scanned = borrowed = 0
  233. bad = []
  234. for i, a in enumerate(offs):
  235. lo = a - base
  236. hi = (offs[i + 1] - base) if i + 1 < len(offs) else code_end
  237. code = bytes(blob[lo:hi])
  238. scanned += 1
  239. if MOV_BP_SP not in code:
  240. continue
  241. borrowed += 1
  242. # The two halves are reported separately, because they are separate
  243. # faults with separate fixes and "it does not hand BP back" does not
  244. # say which of them happened.
  245. if not code.startswith(PUSH_BP_MOV_BP_SP):
  246. why = "borrows BP but does not open with 55 8B EC, so the "\
  247. "caller's BP is destroyed"
  248. elif POP_BP not in code:
  249. why = "pushes BP but never pops it, so the caller gets a "\
  250. "cursor two bytes off"
  251. else:
  252. continue
  253. names = sorted(n for n, v in entries.items() if v == a)
  254. bad.append("%s -- %s (image 0x%04X: %s)"
  255. % (",".join(names), why, a, code[:12].hex(" ")))
  256. if bad:
  257. sys.exit("these entries do not hand BP back, so a caller that keeps a "
  258. "cursor in BP -- which this driver does, and which is the whole "
  259. "reason BP is the one register an entry may keep -- loses it:\n"
  260. " %s" % "\n ".join(bad))
  261. if borrowed == 0:
  262. sys.exit("no entry borrows BP, so this check examined %d entries and "
  263. "matched nothing: it is not looking at what it claims to "
  264. "look at" % scanned)
  265. return scanned, borrowed
  266. # ------------------------------------------------------------------ the case
  267. def case_bytes(c, entries):
  268. """One CASE_SZ byte case record, exactly as exec/rtdrv.s reads it.
  269. The record is a second, independent statement of the same layout rtdrv.s
  270. carries in its .set block. The cases only pass if the two agree on every
  271. offset, which is the whole reason for writing it twice: a driver that
  272. silently read the wrong field would still boot, still run, and still print.
  273. """
  274. if len(c["in"]) > 8:
  275. sys.exit("case %s supplies %d input bytes; the record holds 8"
  276. % (c["name"], len(c["in"])))
  277. b = bytearray(CASE_SZ)
  278. struct.pack_into("<H", b, 0, c["dump"]) # OFF_DUMPLEN
  279. struct.pack_into("<H", b, 2, c["dumpadr"]) # OFF_DUMPADR
  280. b[4] = len(c["in"]) # OFF_INLEN
  281. b[5:5 + len(c["in"])] = c["in"] # OFF_INBUF
  282. struct.pack_into("<H", b, 13, c["index"]) # OFF_CASE (word)
  283. calls = c["calls"]
  284. if len(calls) > 4:
  285. sys.exit("case %s has %d calls; the record holds 4"
  286. % (c["name"], len(calls)))
  287. b[15] = len(calls) # OFF_NCALLS (byte)
  288. for i, (ent, arg, mode, arg2, cx) in enumerate(calls):
  289. o = 16 + 12 * i # SLOT0, SLOT_SZ = 12
  290. struct.pack_into("<H", b, o, entries[ent])
  291. struct.pack_into("<H", b, o + 2, arg & 0xFFFF)
  292. b[o + 4] = mode
  293. struct.pack_into("<H", b, o + 6, arg2 & 0xFFFF)
  294. struct.pack_into("<H", b, o + 8, cx & 0xFFFF)
  295. return bytes(b)
  296. def build_image(blob, rec):
  297. """Assemble exec/rtdrv.s into a complete .COM, and check it is the one
  298. we think it is.
  299. The three assertions are the point of this function. An image that is
  300. subtly not the image we intended would still boot, still run, and still
  301. print something -- the failure would look like a runtime bug.
  302. """
  303. if RT_BASE + len(blob) > HDR:
  304. sys.exit("the runtime is %d bytes: at RT_BASE=%04X it runs into the "
  305. "test scaffolding at %04X. Move the .org's in rtdrv.s."
  306. % (len(blob), RT_BASE, HDR))
  307. with tempfile.TemporaryDirectory() as td:
  308. open(os.path.join(td, "rtblob.bin"), "wb").write(blob)
  309. open(os.path.join(td, "rtcase.bin"), "wb").write(rec)
  310. src = os.path.join(HERE, "exec", "rtdrv.s")
  311. obj, raw = os.path.join(td, "r.o"), os.path.join(td, "r.bin")
  312. r = subprocess.run(["as", "--32", "-I", td, "-o", obj, src],
  313. capture_output=True)
  314. if r.returncode != 0:
  315. sys.exit("as failed on rtdrv.s:\n"
  316. + r.stderr.decode(errors="replace"))
  317. r = subprocess.run(["objcopy", "-O", "binary", obj, raw],
  318. capture_output=True)
  319. if r.returncode != 0:
  320. sys.exit("objcopy failed:\n" + r.stderr.decode(errors="replace"))
  321. img = open(raw, "rb").read()
  322. # E9 00 00: a near jump to offset 3 from offset 0, so the displacement is
  323. # 3 - (0 + 3) = 0. The driver is the first thing after the jump, which is
  324. # what makes the rel16 zero and therefore useless as a check on the target
  325. # -- the check that matters is the one below, that the blob landed where the
  326. # driver thinks it did.
  327. if img[0:3] != b"\xe9\x00\x00":
  328. sys.exit("rtdrv.s does not open with a 3-byte near JMP over itself: %s"
  329. % img[0:3].hex())
  330. if img[RT_BASE:RT_BASE + len(blob)] != blob:
  331. sys.exit("the blob is not at RT_BASE=%04X in the assembled image -- "
  332. "rtdrv.s and rt_exec.py disagree about the layout"
  333. % RT_BASE)
  334. gap = img[DRIVER_TOP:RT_BASE]
  335. if gap != b"\x00" * len(gap):
  336. sys.exit("the driver has outgrown its space: rtdrv.s no longer fits "
  337. "under %04X, so it is overwriting the runtime" % DRIVER_TOP)
  338. return img
  339. def parse_record(raw, want_index):
  340. """Split the serial output into (case index, printed, dumped) or raise.
  341. Nothing here is lenient. A driver that printed nothing, a truncated
  342. record, or a record for the wrong case are all failures with a reason, not
  343. a comparison against an empty string that happens to pass.
  344. """
  345. if not raw or raw[0] != SOH:
  346. raise AssertionError("no record header: the driver printed %r" % raw[:64])
  347. if len(raw) < 7 or raw[5] != STX:
  348. raise AssertionError("malformed record header %r" % raw[:16])
  349. idx = int(raw[1:5], 16)
  350. if idx != want_index:
  351. raise AssertionError("record is for case %04X, expected %04X"
  352. % (idx, want_index))
  353. if raw[-1] != EOT:
  354. raise AssertionError("record was never closed (EOT): the last call did "
  355. "not return, or the machine halted early")
  356. end = raw.index(ETX, 6)
  357. if end < 0:
  358. raise AssertionError("record has no ETX: the calls printed nothing and "
  359. "the driver never got past them")
  360. printed, dump = raw[6:end], raw[end + 1:-1]
  361. if len(dump) % 2 or not re.fullmatch(b"[0-9A-F]*", dump):
  362. raise AssertionError("the memory report %r is not hex" % dump)
  363. return idx, printed, bytes.fromhex(dump.decode())
  364. # ----------------------------------------------------------------- the cases
  365. def build_cases():
  366. """Every check, in the order the names are printed.
  367. Each case is a list of calls plus two expectations: the bytes the entry(s)
  368. printed, and the bytes that must be at `dumpadr' afterwards. `dump=0' means
  369. the case asserts nothing about memory, which is itself an assertion: the
  370. report is empty, so a case cannot quietly acquire a memory check it did not
  371. ask for.
  372. The addresses handed to an entry as its argument are MEMORY addresses, not
  373. image offsets -- that is the whole of LoadBias, and it is the difference
  374. between a read entry storing where the harness looks and storing one page
  375. lower where nothing checks it. V below is "the memory address of STORE",
  376. which is what every read case wants.
  377. """
  378. cs = []
  379. V = STORE + LOAD_BIAS
  380. def add(name, calls, out=b"", stdin=b"", dump=0, dumpbytes=b"",
  381. dumpadr=STORE, note=""):
  382. cs.append({"name": name, "calls": calls, "out": out, "in": stdin,
  383. "dump": dump, "dumpbytes": dumpbytes, "dumpadr": dumpadr,
  384. "note": note, "index": len(cs)})
  385. def s(ent, arg):
  386. return (ent, arg, F_STACK, 0, 0)
  387. def x(ent, arg):
  388. return (ent, arg, F_AX, 0, 0)
  389. def n(ent):
  390. return (ent, 0, 0, 0, 0)
  391. def i(ent):
  392. return (ent, 0, F_INL, 0, 0)
  393. def s2(ent, arg, arg2):
  394. """Two stack words: arg2 is pushed first (it lands at [BP+6]), arg
  395. second (at [BP+4]). real_from_int(src, dst) takes its source first."""
  396. return (ent, arg, F_STACK | F_STACK2, arg2, 0)
  397. def s3(ent, a, b, c):
  398. """Three stack words: c is pushed first (landing at [BP+8]), then b
  399. ([BP+6]), then a ([BP+4])."""
  400. return (ent, a, F_STACK | F_STACK3, b, c)
  401. def s2cx(ent, arg, arg2, cx):
  402. """Two stack words AND CX: arg2 is pushed first (it lands at [BP+6]),
  403. arg second (at [BP+4]), and CX carries the maximum length. strstore is
  404. the only entry that wants all three."""
  405. return (ent, arg, F_STACK | F_STACK2 | F_CX, arg2, cx)
  406. def scx(ent, arg, cx):
  407. """One stack word and CX, for rdstr: dest at [BP+4], limit in CX."""
  408. return (ent, arg, F_STACK | F_CX, 0, cx)
  409. # initmem is handed the header in AX -- and the header's MEMORY address, not
  410. # its image offset. Given the image offset it reads the two words it wants
  411. # out of blank space, finds both zero, and clears nothing at all: a silent
  412. # no-op, which is the reason this case poisons the data area to AAH first.
  413. add("initmem zeroes globals",
  414. [x("initmem", HDR + LOAD_BIAS)], dump=DLEN, dumpadr=DATA,
  415. dumpbytes=b"\x00" * DLEN,
  416. note="the data area is poisoned to AA first, so a zero is a result")
  417. for v, why in [(0, "the one value where a signed/unsigned slip is invisible"),
  418. (1, ""), (-1, ""), (7, ""), (10, ""), (42, ""),
  419. (100, ""), (12345, ""), (-32768, "the sign bit"), (32767, "")]:
  420. add("wrint(%d)" % v, [s("wrint", v & 0xFFFF)],
  421. out=str(v).encode(), note=why)
  422. # --- the 6-byte MBF real: integer -> real ---------------------------
  423. # The source word is passed in the case record's input bytes (CASE+5),
  424. # and the destination at STORE; both are memory addresses, as always.
  425. def mbf(v):
  426. """TP3's measured 6-byte Real for an integer (CALC-PORT.md)."""
  427. if v == 0:
  428. return bytes(6)
  429. neg = v < 0
  430. a = abs(v)
  431. k = a.bit_length() - 1
  432. e = 129 + k
  433. n = (a - (1 << k)) << (39 - k)
  434. b = bytearray([e]) + bytearray((n >> (8 * i)) & 0xFF
  435. for i in range(5))
  436. if neg:
  437. b[5] |= 0x80
  438. return bytes(b)
  439. def mbf_float(x):
  440. """The measured 6-byte MBF nearest to a fractional value."""
  441. if x == 0:
  442. return bytes(6)
  443. neg = x < 0
  444. a = abs(x)
  445. k = math.floor(math.log2(a))
  446. e = 129 + k
  447. n = int(round((a / (2.0 ** k) - 1.0) * (1 << 39)))
  448. if n >= (1 << 39):
  449. n = 0
  450. e += 1
  451. b = bytearray([e]) + bytearray((n >> (8 * i)) & 0xFF for i in range(5))
  452. if neg:
  453. b[5] |= 0x80
  454. return bytes(b)
  455. SRC = CASE + 5 + LOAD_BIAS
  456. for v in (0, 1, 2, 3, 5, 7, 42, 1000, 32767, -1, -2, -42, -32768):
  457. add("real_from_int(%d)" % v,
  458. [s2("real_from_int", STORE + LOAD_BIAS, SRC)],
  459. stdin=struct.pack("<h", v),
  460. dump=6, dumpbytes=mbf(v), dumpadr=STORE,
  461. note="the measured exponent bias is 129")
  462. # --- MBF addition and subtraction -----------------------------------
  463. # The driver preloads 12-byte blocks (a then b); real_add/real_sub take
  464. # the block's address, read both operands, and overwrite a with the result.
  465. BLOCKS = [(1, 2), (3, 5), (5, 3), (1, 1), (1000, 1), (-3, 2),
  466. (42, 1000), (32767, 1), (0, 5), (-3, -2),
  467. (6, 2), (10, 2), (15, 3), (1000, 2), (-6, 2), (6, -2),
  468. (-6, -2), (0, 5), (5, 2), (42, 6)]
  469. for bi, (a, b) in enumerate(BLOCKS):
  470. blk = 0x1230 + 16 * bi
  471. add("real_add(%d,%d)" % (a, b),
  472. [s("real_add", blk + LOAD_BIAS)],
  473. dump=6, dumpbytes=mbf(a + b), dumpadr=blk,
  474. note="the measured MBF bytes, the reference's readd")
  475. add("real_sub(%d,%d)" % (a, b),
  476. [s("real_sub", blk + LOAD_BIAS)],
  477. dump=6, dumpbytes=mbf(a - b), dumpadr=blk,
  478. note="the measured MBF bytes, the reference's resub")
  479. add("real_mul(%d,%d)" % (a, b),
  480. [s("real_mul", blk + LOAD_BIAS)],
  481. dump=6, dumpbytes=mbf(a * b), dumpadr=blk,
  482. note="the measured MBF bytes, the reference's remult")
  483. if b != 0 and a % b == 0:
  484. q = mbf(a // b)
  485. elif a == 5 and b == 2:
  486. q = bytes.fromhex("820000000020") # 2.5
  487. else:
  488. q = None
  489. if q is not None:
  490. add("real_div(%d,%d)" % (a, b),
  491. [s("real_div", blk + LOAD_BIAS)],
  492. dump=6, dumpbytes=q, dumpadr=blk,
  493. note="the measured MBF bytes, the reference's rediv")
  494. # --- recmp: AX := -1/0/+1 for a<b, a=b, a>b ------------------------
  495. # The driver stores every call's AX at AXOUT, so these cases can read the
  496. # result. The operand block is the same one the arithmetic cases use.
  497. seen = set()
  498. for bi, (a, b) in enumerate(BLOCKS):
  499. if (a, b) in seen:
  500. continue
  501. seen.add((a, b))
  502. blk = 0x1230 + 16 * bi
  503. want = (a > b) - (a < b)
  504. add("real_cmp(%d,%d)" % (a, b),
  505. [s("real_cmp", blk + LOAD_BIAS)],
  506. dump=2, dumpbytes=struct.pack("<H", want & 0xFFFF), dumpadr=AXOUT,
  507. note="the reference's recmp, returned as AX = -1/0/+1")
  508. # Fractional blocks, compared through the exponent/mantissa path.
  509. FRAC = [(3.7, 3.7), (3.9, 3.7), (-3.7, -3.9), (0.5, 0.25),
  510. (-0.5, 0.5), (12345.75, 12345.5), (2.5, 0.0), (-2.5, 0.0),
  511. (0.99, 0.0), (1.9, 0.0)]
  512. for fi, (a, b) in enumerate(FRAC):
  513. blk = 0x1370 + 16 * fi
  514. want = (a > b) - (a < b)
  515. add("real_cmp(%g,%g)" % (a, b),
  516. [s("real_cmp", blk + LOAD_BIAS)],
  517. dump=2, dumpbytes=struct.pack("<H", want & 0xFFFF), dumpadr=AXOUT,
  518. note="fractional magnitudes: the mantissa decides")
  519. add("real_cmp(2^40,0)",
  520. [s("real_cmp", 0x1410 + LOAD_BIAS)],
  521. dump=2, dumpbytes=struct.pack("<h", 1), dumpadr=AXOUT,
  522. note="the exponent alone decides")
  523. # --- reint: Int(real), in place --------------------------------------
  524. # a is the real; the block's b is unused. The expected bytes are the
  525. # measured MBF of trunc(a), because reint returns a REAL, not an integer
  526. # (TPSRC's xint pushes the six-byte result back).
  527. for bi, (a, b) in enumerate(BLOCKS):
  528. if a in (0, 1, -3, 32767):
  529. blk = 0x1230 + 16 * bi
  530. add("real_int(%d)" % a,
  531. [s("real_int", blk + LOAD_BIAS)],
  532. dump=6, dumpbytes=mbf(math.trunc(a)), dumpadr=blk,
  533. note="the integer part as a real, the reference's reint")
  534. for fi, (a, b) in enumerate(FRAC):
  535. blk = 0x1370 + 16 * fi
  536. add("real_int(%g)" % a,
  537. [s("real_int", blk + LOAD_BIAS)],
  538. dump=6, dumpbytes=mbf(math.trunc(a)), dumpadr=blk,
  539. note="the fraction is masked away; the sign and exponent stay")
  540. add("real_int(2^40)",
  541. [s("real_int", 0x1410 + LOAD_BIAS)],
  542. dump=6, dumpbytes=bytes.fromhex("A90000000000"), dumpadr=0x1410,
  543. note="exponent >= 0A8h is already integral and returns unchanged")
  544. # --- fmtreal: real_fmt writes a length-prefixed, left-padded field -----
  545. # CX = (decimals << 8) | width, [BP+4] = real, [BP+6] = destination.
  546. def fmt(name, blk, width, dec, text):
  547. add(name,
  548. [s2cx("real_fmt", blk + LOAD_BIAS, FMTDEST + LOAD_BIAS,
  549. (dec << 8) | width)],
  550. dump=1 + len(text), dumpbytes=bytes([len(text)]) + text,
  551. dumpadr=FMTDEST,
  552. note="the reference's fmtreal; dest[0] is the field length")
  553. add("real_fmt(from int 1)",
  554. [s2("real_from_int", STORE + LOAD_BIAS, SRC),
  555. s2cx("real_fmt", STORE + LOAD_BIAS, FMTDEST + LOAD_BIAS, 0)],
  556. stdin=struct.pack("<h", 1), dump=2, dumpbytes=bytes([1]) + b"1",
  557. dumpadr=FMTDEST, note="a known-good 1.0 from real_from_int")
  558. fmt("real_fmt(1:0:0)", 0x1230, 0, 0, b"1")
  559. fmt("real_fmt(0:0:0)", 0x12B0, 0, 0, b"0")
  560. fmt("real_fmt(3.7:0:2)", 0x1370, 0, 2, b"3.70")
  561. fmt("real_fmt(12345.75:12:2)", 0x13C0, 12, 2, b" 12345.75")
  562. fmt("real_fmt(0.5:6:3)", 0x13A0, 6, 3, b" 0.500")
  563. fmt("real_fmt(-3.7:0:1)", 0x1390, 0, 1, b"-3.7")
  564. fmt("real_fmt(0:5:2)", 0x12B0, 5, 2, b" 0.00")
  565. fmt("real_fmt(2.5:0:0)", 0x13D0, 0, 0, b"3")
  566. fmt("real_fmt(3.7:10:25)", 0x1370, 10, 25, b"3.7000E+00")
  567. # --- ascreal: real_val parses an ASCIIZ string ------------------------
  568. # A dump of AXOUT shows the returned offset, or FFFFh on a hard error.
  569. ASC_STRINGS = [b"3.5\0", b"-2.25\0", b"1E3\0", b"0.5\0",
  570. b"12345.75\0", b"3.5x\0", b"1E\0", b"1E40\0",
  571. b"\0", b".5\0", b"1.2.3\0", b"35\0", b"5E-1\0", b"5.\0", b"5.0\0", b"12345\0", b"1234575\0", b"1234.5\0", b"1000\0", b"123\0", b"1234\0", b"12340\0", b"12341\0", b"12341E0\0", b"12345E0\0"]
  572. WANT_OFF = [3, 5, 3, 3, 8, 3, 0xFFFF, 0xFFFF, 0, 2, 0xFFFF, 2, 4, 2, 3, 5, 7, 6, 4, 3, 4, 5, 5, 7, 7]
  573. off = 0
  574. for txt, want in zip(ASC_STRINGS, WANT_OFF):
  575. add("real_val(%r) offset" % txt[:-1],
  576. [s2("real_val", ASCSRC + off + LOAD_BIAS, STORE + LOAD_BIAS)],
  577. dump=2, dumpbytes=struct.pack("<H", want & 0xFFFF), dumpadr=AXOUT,
  578. note="AX = the first unparsed character, FFFFh on error")
  579. off += len(txt)
  580. # The parsed VALUE. On a hard error nothing is stored, and STORE is
  581. # poisoned with EEEE (its first two bytes are all the driver writes), so
  582. # those cases also prove the destination was left alone.
  583. VAL = [3.5, -2.25, 1000.0, 0.5, 12345.75, 3.5, None, None, 0.0, 0.5,
  584. None, 35.0, 0.5, 5.0, 5.0, 12345.0, 1234575.0, 1234.5,
  585. 1000.0, 123.0, 1234.0, 12340.0, 12341.0, 12341.0, 12345.0]
  586. off = 0
  587. for txt, v in zip(ASC_STRINGS, VAL):
  588. wantv = (b"\xEE\xEE" + bytes(4)) if v is None else mbf_float(v)
  589. add("real_val(%r) value" % txt[:-1],
  590. [s2("real_val", ASCSRC + off + LOAD_BIAS, STORE + LOAD_BIAS)],
  591. dump=6, dumpbytes=wantv, dumpadr=STORE,
  592. note="the packed MBF, or the untouched EEEE poison on error")
  593. off += len(txt)
  594. for bi, (a, b) in [(0, (12340, 5)), (1, (12340, 1))]:
  595. blk = 0x1500 + 16 * bi
  596. add("real_add(%d,%d)" % (a, b), [s("real_add", blk + LOAD_BIAS)],
  597. dump=6, dumpbytes=mbf(a + b), dumpadr=blk,
  598. note="a large value plus a small digit: the add core's alignment")
  599. for bi, a in [(2, 12341), (3, 12345), (4, 12340)]:
  600. blk = 0x1500 + 16 * bi
  601. add("real_mul(%d,1)" % a, [s("real_mul", blk + LOAD_BIAS)],
  602. dump=6, dumpbytes=mbf(a), dumpadr=blk,
  603. note="multiplying by 1.0 must be exact")
  604. # --- real_write: [BP+4]=decimals, [BP+6]=width, [BP+8]=real ----------
  605. def wr(name, blk, width, dec, text):
  606. add(name, [s3("real_write", dec, width, blk + LOAD_BIAS)], out=text,
  607. note="fmtreal's field, padded and printed by the entry itself")
  608. wr("real_write(3.7:0:2)", 0x1370, 0, 2, b"3.70")
  609. wr("real_write(3.7:10:2)", 0x1370, 10, 2, b" 3.70")
  610. wr("real_write(12345.75:12:2)", 0x13C0, 12, 2, b" 12345.75")
  611. wr("real_write(0.5:0:3)", 0x13A0, 0, 3, b"0.500")
  612. wr("real_write(-3.7:0:1)", 0x1390, 0, 1, b"-3.7")
  613. wr("real_write(2.5:0:0)", 0x13D0, 0, 0, b"3")
  614. wr("real_write(42:0:0)", 0x1290, 0, 0, b"42")
  615. wr("real_write(3.7:18:FFFF)", 0x1370, 18, 0xFFFF,
  616. b" 3.7000000000E+00")
  617. add("wrchar('A')", [s("wrchar", ord("A"))], out=b"A")
  618. add("wrchar('!')", [s("wrchar", ord("!"))], out=b"!")
  619. add("wrbool(0)", [s("wrbool", 0)], out=b"FALSE")
  620. add("wrbool(1)", [s("wrbool", 1)], out=b"TRUE")
  621. add("wrbool(2)", [s("wrbool", 2)], out=b"TRUE",
  622. note="any non-zero is true, as TP3's xwrb does")
  623. add("wrln", [n("wrln")], out=b"\r\n")
  624. add("stackchk returns", [n("stackchk")], out=b"",
  625. note="no output: the assertion is that control came back at all")
  626. add("writeln(42) writeln TRUE in one program",
  627. [s("wrint", 42), s("wrchar", ord(" ")), s("wrbool", 1), n("wrln")],
  628. out=b"42 TRUE\r\n",
  629. note="four calls back to back, so no register leaks between them")
  630. # rdint: the value, and then the rdln that must eat the rest of the line.
  631. for text, want in [(b" 42abc", 42), (b"-17 x", -17), (b"+5", 5),
  632. (b"0", 0), (b" 007", 7), (b"1234", 1234)]:
  633. add("rdint(%r) then rdln" % text,
  634. [s("rdint", V), n("rdln")], out=b"", stdin=text, dump=2,
  635. dumpbytes=struct.pack("<H", want & 0xFFFF),
  636. note="the delimiter must be left for rdln, which prints nothing")
  637. for c in "Q7":
  638. add("rdchar(%r)" % c, [s("rdchar", V)], out=b"", stdin=c.encode(),
  639. dump=2, dumpbytes=bytes([ord(c), 0xEE]),
  640. note="rdchar stores ONE byte, so the poison is still in byte 2")
  641. # rdbyte: the same reader as rdint, entered through its own frame, and the
  642. # whole point is the WIDTH of the store. A poison byte sits just past the
  643. # variable, so the word store rdint used would show up here as byte 2
  644. # turning into the high byte of the value instead of staying EE. -1 is
  645. # the case where the two disagree most visibly: the value is FFFF, so a
  646. # word store writes FF twice.
  647. for text, want in [(b"200", 200), (b"-1", 0xFF), (b"7", 7), (b"0", 0)]:
  648. add("rdbyte(%r) then rdln" % text,
  649. [s("rdbyte", V), n("rdln")], out=b"", stdin=text, dump=2,
  650. dumpbytes=bytes([want & 0xFF, 0xEE]),
  651. note="rdbyte stores ONE byte, so the poison is still in byte 2")
  652. for c, want in [("T", 1), ("y", 1), ("1", 1), ("F", 0), ("n", 0), ("0", 0)]:
  653. add("rdbool(%r)" % c, [s("rdbool", V)], out=b"", stdin=c.encode(),
  654. dump=2, dumpbytes=struct.pack("<H", want & 0xFFFF))
  655. add("rdint at end of input leaves the variable alone",
  656. [s("rdint", V), n("rdln")], out=b"", stdin=b"", dump=2,
  657. dumpbytes=b"\xee\xee",
  658. note="TP3's xrdint returns to rnerr without storing; the poison stays")
  659. add("rdbyte at end of input leaves the variable alone",
  660. [s("rdbyte", V), n("rdln")], out=b"", stdin=b"", dump=2,
  661. dumpbytes=b"\xee\xee",
  662. note="rdscan returns CX=2 on the ^Z path, so rdbyte stores nothing")
  663. add("wrtinl reads its length and characters from the return address",
  664. [i("wrtinl")], out=b"hello",
  665. note="the one entry whose argument is not a stack word")
  666. # wrstr is the other way round from wrtinl: its argument IS a stack word,
  667. # but a word that has to be a POINTER, so the string's bytes live in memory
  668. # instead of after the call. WSTR (seeded in rtdrv.s, restated here) is a
  669. # length byte and five characters - the same bytes wrtinl reads from the
  670. # code stream - so the two cases must print the same word. The argument
  671. # carries LOAD_BIAS because a runtime entry dereferences a MEMORY address,
  672. # not an image offset.
  673. add("wrstr prints the length byte's worth of characters",
  674. [s("wrstr", WSTR + LOAD_BIAS)], out=b"hello",
  675. note="the entry dereferences the stack word; the bytes are in memory")
  676. add("wrstr prints nothing for an empty string",
  677. [s("wrstr", WSTR_EMPTY + LOAD_BIAS)], out=b"",
  678. note="a length byte of 0 must print no characters at all")
  679. # --- rdstr: the entry behind readln(s)/read(s). Its argument is a stack
  680. # word (the destination address), it walks it with SI, and CX is the limit.
  681. # The destination is pre-filled with 0xEE in rtdrv.s, so every byte past the
  682. # stored length is a checked claim that the entry did not write it.
  683. add("rdstr reads a line into a string",
  684. [scx("rdstr", RDSTR_DST + LOAD_BIAS, 10)], out=b"", stdin=b"hello\n",
  685. dump=11, dumpbytes=bytes([5]) + b"hello" + b"\xee" * 5,
  686. dumpadr=RDSTR_DST,
  687. note="length byte then the characters; nothing past the length is written")
  688. add("rdstr truncates a line longer than CX",
  689. [scx("rdstr", RDSTR_DST + LOAD_BIAS, 3)], out=b"", stdin=b"abcdef\n",
  690. dump=5, dumpbytes=bytes([3]) + b"abc" + b"\xee",
  691. dumpadr=RDSTR_DST,
  692. note="CX is the limit; the rest of the line is left unread, not stored")
  693. add("rdstr stores length 0 for an empty line",
  694. [scx("rdstr", RDSTR_DST + LOAD_BIAS, 10)], out=b"", stdin=b"\n",
  695. dump=3, dumpbytes=bytes([0]) + b"\xee\xee", dumpadr=RDSTR_DST,
  696. note="the terminator is the first character, so only dest[0] is written")
  697. add("rdstr at end of input stores length 0",
  698. [scx("rdstr", RDSTR_DST + LOAD_BIAS, 10)], out=b"", stdin=b"",
  699. dump=3, dumpbytes=bytes([0]) + b"\xee\xee", dumpadr=RDSTR_DST,
  700. note="getch returns ^Z at end of input, a terminator like CR and LF")
  701. # --- strstore: `s := t' for two string variables. dest at [BP+4], source
  702. # at [BP+6], maximum in CX. The count is min(source length, CX), the source
  703. # is never written, and the destination tail past the new length is left
  704. # exactly as it was.
  705. add("strstore copies a whole string",
  706. [s2cx("strstore", SST_DST + LOAD_BIAS, SST_HELLO + LOAD_BIAS, 20)],
  707. out=b"", dump=8, dumpbytes=bytes([5]) + b"hello" + b"\xee" * 2,
  708. dumpadr=SST_DST,
  709. note="dest length and characters; the tail past them is still EE")
  710. add("strstore truncates to the destination maximum",
  711. [s2cx("strstore", SST_DST + LOAD_BIAS, SST_LONG + LOAD_BIAS, 4)],
  712. out=b"", dump=8, dumpbytes=bytes([4]) + b"abcd" + b"\xee" * 3,
  713. dumpadr=SST_DST,
  714. note="count := min(source length, CX); the source itself is not shortened")
  715. add("strstore copies an empty string",
  716. [s2cx("strstore", SST_DST + LOAD_BIAS, SST_EMPTY + LOAD_BIAS, 10)],
  717. out=b"", dump=4, dumpbytes=bytes([0]) + b"\xee" * 3, dumpadr=SST_DST,
  718. note="CX 0 must copy nothing -- LOOP would otherwise run 65536 times")
  719. add("strstore leaves the source alone",
  720. [s2cx("strstore", SST_DST + LOAD_BIAS, SST_LONG + LOAD_BIAS, 4)],
  721. out=b"", dump=9, dumpbytes=bytes([8]) + b"abcdefgh", dumpadr=SST_LONG,
  722. note="TP3 shortens a stack copy of the source; this entry writes none")
  723. # --- cmpstr: string compare, AX := -1 / 0 / +1 for left <, =, > right.
  724. # left is at [BP+6] and right at [BP+4] (the same order s2cx gives which
  725. # string goes where), so this compares 'hello' against 'abcdefgh'.
  726. #
  727. # The sign is NOT checked here, and cannot be: a case record dumps MEMORY,
  728. # and the driver does not capture AX after a call. What this case can say
  729. # is that the entry runs to RET without touching an operand - it is
  730. # read-only - and check_bp_contract separately proves it hands BP back. The
  731. # SIGN is pinned by t48_strcmp and t49_strcmp_lit, which run whole compiled
  732. # programs on qemu and print all six relations as booleans; a program is a
  733. # better observer of a return value than a record with no field for one.
  734. add("cmpstr compares 'hello' with 'abcdefgh' and writes neither",
  735. [s2cx("cmpstr", SST_LONG + LOAD_BIAS, SST_HELLO + LOAD_BIAS, 20)],
  736. out=b"", dump=6, dumpbytes=bytes([5]) + b"hello", dumpadr=SST_HELLO,
  737. note="the dump is the LEFT operand ([BP+6]); it must come back unchanged")
  738. # --- strcat: s := s + t. The same argument shape as strstore -- source
  739. # pushed first, destination at [BP+4], maximum in CX -- but the DESTINATION
  740. # is READ as well as written: dest[0] is the existing length, dest[0]+src[0]
  741. # is the new one, and the characters are copied to dest[1]+dest[0]. That is
  742. # why the destination is seeded: strstore may ignore its destination, but
  743. # 0xEE here would read as a length of 238 and raise the overflow error.
  744. #
  745. # The overflow EXIT cannot be a case: a record dumps memory after the calls
  746. # return, and the error path leaves through INT 21h AH=4C, so the record is
  747. # never closed. t55_strcat_overflow runs a whole compiled program and
  748. # checks the exit code instead - see run_com_exec.py and the .exit file.
  749. add("strcat appends the source to the destination",
  750. [s2cx("strcat", SST_CAT + LOAD_BIAS, SST_WORLD + LOAD_BIAS, 20)],
  751. out=b"", dump=11, dumpbytes=bytes([10]) + b"helloworld",
  752. dumpadr=SST_CAT,
  753. note="'hello' + 'world': the new length is the SUM of the two")
  754. add("strcat appends to an empty destination",
  755. [s2cx("strcat", SST_CAT0 + LOAD_BIAS, SST_WORLD + LOAD_BIAS, 20)],
  756. out=b"", dump=6, dumpbytes=bytes([5]) + b"world", dumpadr=SST_CAT0,
  757. note="a zero destination length is the ordinary case, not a special one")
  758. add("strcat of an empty source leaves the destination alone",
  759. [s2cx("strcat", SST_CAT + LOAD_BIAS, SST_EMPTY + LOAD_BIAS, 20)],
  760. out=b"", dump=8, dumpbytes=bytes([5]) + b"hello" + b"\xee" * 2,
  761. dumpadr=SST_CAT,
  762. note="a zero SOURCE length takes JCXZ; a LOOP would run 65536 times")
  763. add("strcat at the destination maximum does not overflow",
  764. [s2cx("strcat", SST_CAT + LOAD_BIAS, SST_WORLD + LOAD_BIAS, 10)],
  765. out=b"", dump=11, dumpbytes=bytes([10]) + b"helloworld",
  766. dumpadr=SST_CAT,
  767. note="sum == CX is allowed; only sum > CX is the error")
  768. return cs
  769. def run_case(c, blob, entries, boot):
  770. rec = case_bytes(c, entries)
  771. img = build_image(blob, rec)
  772. with tempfile.TemporaryDirectory() as td:
  773. floppy = os.path.join(td, "f.img")
  774. open(floppy, "wb").write(build_floppy(boot, img, c["in"]))
  775. return run_qemu(floppy)
  776. def main(argv):
  777. if "--probe" in argv:
  778. return probe()
  779. cases = build_cases()
  780. if "--list" in argv:
  781. for c in cases:
  782. print(c["name"])
  783. return 0
  784. show = "--show" in argv
  785. only = [a for a in argv if not a.startswith("-")]
  786. blob, entries, code_end = load_runtime(RT_BASE)
  787. boot = build_boot_sector()
  788. # Before any machine is started: the contract the driver depends on.
  789. nscan, nborrow = check_bp_contract(blob, entries, RT_BASE, code_end)
  790. print(" %-52s PASS (%d entries scanned, %d borrow BP and hand it "
  791. "back)" % ("every entry preserves BP", nscan, nborrow))
  792. npass = 1
  793. nfail = 0
  794. for c in cases:
  795. if only and not any(o in c["name"] for o in only):
  796. continue
  797. # A marker byte inside an expectation would make the framing
  798. # ambiguous, so it is refused rather than mis-parsed.
  799. for b in (SOH, STX, ETX, EOT):
  800. if bytes([b]) in c["out"]:
  801. sys.exit("case %s: its expected output contains the framing "
  802. "byte %02X, which would be indistinguishable from the "
  803. "driver's own markers" % (c["name"], b))
  804. raw, rc, note = run_case(c, blob, entries, boot)
  805. if show:
  806. print(c["name"], "->", repr(visible_output(raw)))
  807. continue
  808. try:
  809. _, printed, dumped = parse_record(raw, c["index"])
  810. except AssertionError as e:
  811. print(" %-52s FAIL %s" % (c["name"], e))
  812. nfail += 1
  813. continue
  814. if printed != c["out"]:
  815. print(" %-52s FAIL printed %s, want %s"
  816. % (c["name"], visible_output(printed),
  817. visible_output(c["out"])))
  818. nfail += 1
  819. continue
  820. if dumped != c["dumpbytes"]:
  821. print(" %-52s FAIL +%04X = %s, want %s"
  822. % (c["name"], c["dumpadr"], dumped.hex() or "-",
  823. c["dumpbytes"].hex() or "-"))
  824. nfail += 1
  825. continue
  826. print(" %-52s PASS%s" % (c["name"],
  827. (" (" + c["note"] + ")") if c["note"] else ""))
  828. npass += 1
  829. if show:
  830. return 0
  831. print("\nruntime entries: %d passed, %d failed (of %d)"
  832. % (npass, nfail, npass + nfail))
  833. return 1 if nfail else 0
  834. if __name__ == "__main__":
  835. sys.exit(main(sys.argv[1:]))