nonvacuity.sh 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  1. #!/bin/sh
  2. # nonvacuity.sh -- prove the runtime checks can actually fail.
  3. #
  4. # A test that has never been seen red is not a test. This script breaks the
  5. # runtime on purpose, once per check, and asserts that the check goes red and
  6. # says something useful about the breakage. Then it restores the source and
  7. # asserts everything is green again.
  8. #
  9. # Each mutation below is a real bug that was in this file at some point, not an
  10. # invented one. That is the point: these are the mistakes we actually make
  11. # with 16-bit ModRM, so these are the ones the checks have to catch.
  12. #
  13. # audit_helpers.py name-versus-decode: catches a wrong ModRM that still
  14. # decodes cleanly, and both halves of a name that admits
  15. # an operand at all - `34 02' where the name promises
  16. # `34 01', and `35 01' where the row's opcode gate admits
  17. # only 34h. Both rows are new, and a row nobody has seen
  18. # reject anything accepts whatever it is shown.
  19. # audit_helpers.py coverage: catches a helper that has silently
  20. # dropped OUT of the audit, which is a green report about
  21. # a subject nobody looked at
  22. # run_com_tests.sh the .COM layout: catches a header that cannot be
  23. # located, a runtime size that disagrees with the image,
  24. # and an entry jump that starts in the wrong place
  25. # check_runtime.py golden: catches the same thing in the built
  26. # image
  27. # check_runtime.py decode sweep: catches a wrong instruction LENGTH
  28. # check_runtime.py branch targets: catches a wrong fixup
  29. # check_runtime.py entry goldens: catches a broken prologue
  30. # probe/modrm11.py the mod=11 table: catches the ModRM column itself
  31. # going wrong, which no amount of decoding will show
  32. # check_framedisp.py the BP disp rule: catches a displacement that reads
  33. # a different address than the symbol table named
  34. # tests/comimage.py the image layout: catches a sweep region built from a
  35. # literal instead of from two independent readings of the
  36. # file - the old RT_SZ went on reporting PASS while its
  37. # region began inside the runtime - and the layout itself
  38. # being written down a second time, now that one file
  39. # defines it and all three readers import it
  40. # rt_exec.py the BP contract: catches an entry that borrows BP to
  41. # reach its argument and does not hand it back. The bytes
  42. # are well formed, the golden is satisfied, the audit says
  43. # every helper emits what its name says, and the machine
  44. # triple-faults on the second call - so nothing short of
  45. # running it, or of stating the register contract
  46. # explicitly, can see it.
  47. # rt_exec.py the string entries: catches rdstr storing its first
  48. # character where the length byte belongs (a missing IncSi
  49. # puts `hello' back as 05 65 6c 6c 6f), and strstore
  50. # running LOOP with CX = 0 when the source is empty - 65536
  51. # iterations that wrap the segment and walk through the
  52. # driver's own case record. Both are same-size,
  53. # matrix-green slips that only a byte dump can see.
  54. # run_com_exec.py the frame rule: catches a local STRING packed with the
  55. # INTEGER rule, so its characters grow up over the saved BP
  56. # and the return address; readln into such a local then
  57. # runs the string's own bytes as an address. The fix moves
  58. # no well-formed instruction, so only execution - or the
  59. # size it pins in the compile matrix - can tell.
  60. # run_com_exec.py the string arms: catches the destination limit loaded
  61. # into AX instead of CX, the assignment pushes swapped so
  62. # the destination is read as its own source, and a string
  63. # read dispatched to the integer reader. Every one is the
  64. # right shape reading the wrong thing, and the MovCxi
  65. # helper is COMP in the audit, so no byte check can see it.
  66. # check_8086.py the 8086 opcodes: catches a conditional branch or a
  67. # SETcc emitted as `0F 8x'/`0F 9x', which are 386-only.
  68. # Nothing else here can: qemu-system-i386's lowest CPU
  69. # model is 486, where both are ordinary instructions, and
  70. # FCML's -m16 mode is a 386 too. Clause H additionally
  71. # catches the branch polarity being inverted, which is
  72. # still a legal opcode and therefore invisible to every
  73. # shape-based check.
  74. # run_com_exec.py behaviour: catches a*b that emits an ADD, `>'
  75. # and `>=' swapped, REPEAT..UNTIL that stops after one
  76. # pass, two procedures whose parameters collide, a left
  77. # operand overwritten by the right one's code (SaveLeft),
  78. # and a boolean `not' lowered as the integer one. Every
  79. # one of them sat in a fixture that COMPILED and was
  80. # never RUN, with every byte-level check green.
  81. # run_compile_tests.sh refusal: catches a boolean READ slipping
  82. # through to the runtime. TP3 refuses it with error 66
  83. # (TPSRC8 prderrtp; its runtime has no xrdbool), and
  84. # this compiler used to accept it and let rdbool store
  85. # a WORD into the one-byte variable. The mutation is
  86. # the one arm of IoCall's type dispatch that refuses it,
  87. # and only the COMPILE MATRIX can see a refusal: an ERR
  88. # fixture is never executed, so nothing that runs
  89. # programs on it can fail the check.
  90. # run_exec86.py behaviour (Exec86): catches the interpreter's OWN
  91. # reading of the machine: JE inverted in Exec86's Cond,
  92. # which swaps the two arms of every `=' in every program
  93. # while the emitted bytes, the sizes and every
  94. # byte-level check stay green. The image is fine; only
  95. # the thing reading it is wrong, so nothing that looks at
  96. # the image can fail this one.
  97. # runtest.py the R key: catches CmdRun poking nothing into
  98. # the interpreter at all, which faults on the first step
  99. # and prints "interpreter fault" instead of the guest's
  100. # answer. It is the only case here that needs a rebuilt
  101. # SHELL rather than a rebuilt compiler or runtime.
  102. #
  103. # The mod=11 cases do not need a rebuild -- they read the probe sources
  104. # directly -- so they are cheap, and they are the ones that matter most: the
  105. # table they guard is the one thing in this project that was wrong in the
  106. # documentation while the code was right, and a table that is wrong in the
  107. # code produces bytes that decode perfectly.
  108. #
  109. # Usage: tests/nonvacuity.sh (from shell/; leaves Runtime.mod restored)
  110. set -u
  111. cd "$(dirname "$0")/.." || exit 1
  112. GM2=/home/eric/bin/Modula2/Gm2/bin/gm2
  113. SAVED=../tmp/nonvacuity.Runtime.mod
  114. PROBE=../tmp/nonvacuity.rtprobe
  115. DUMP=../tmp/nonvacuity.dump
  116. # Exec86.mod is UNTRACKED, so unlike Runtime.mod git cannot put a botched
  117. # mutation back: the copy taken here is the only correct one in existence.
  118. # Shell.mod is tracked but is mutated by the R-key case below, and a trap that
  119. # restored only the sources would leave tpshell BUILT FROM the mutation - so
  120. # the trap rebuilds too. All three copies live in the project's own tmp/ and
  121. # are taken here, before the first mutation, rather than beside each case.
  122. #
  123. # comimage.py and comtest.py are the image layout and one of its three readers;
  124. # both are mutated by cases further down, and neither is recoverable from git
  125. # once the mutation is staged over - so they join the trap here for the same
  126. # reason, and an interrupted run cannot leave the layout half-written.
  127. mkdir -p ../tmp
  128. SAVED_E=../tmp/nonvacuity.Exec86.mod
  129. SAVED_SH=../tmp/nonvacuity.Shell.mod
  130. SAVED_CI=../tmp/nonvacuity.comimage.py
  131. SAVED_T=../tmp/nonvacuity.comtest.py
  132. cp Runtime.mod "$SAVED" || exit 1
  133. cp Exec86.mod "$SAVED_E" || exit 1
  134. cp Shell.mod "$SAVED_SH" || exit 1
  135. cp tests/comimage.py "$SAVED_CI" || exit 1
  136. cp tests/comtest.py "$SAVED_T" || exit 1
  137. restore_all () {
  138. cp "$SAVED" Runtime.mod
  139. cp "$SAVED_E" Exec86.mod
  140. cp "$SAVED_SH" Shell.mod
  141. cp "$SAVED_CI" tests/comimage.py
  142. cp "$SAVED_T" tests/comtest.py
  143. "$GM2" -fiso -c Runtime.mod >/dev/null 2>&1
  144. "$GM2" -fiso -c Exec86.mod >/dev/null 2>&1
  145. # The shell is rebuilt as well: a test that runs against a binary built
  146. # from a half-restored tree is reporting on the mutation, not on the code.
  147. make >/dev/null 2>&1
  148. }
  149. trap restore_all EXIT
  150. pass=0
  151. fail=0
  152. # mutate <file> <sed-expr> -- apply a deliberate breakage and INSIST it landed.
  153. #
  154. # Four cases in this file were already dead when first run, all the same way:
  155. # the helper they name had been renamed or reformatted since the case was
  156. # written, the sed matched nothing, the source was unchanged, and the check
  157. # correctly passed - so the harness reported "NOT NON-VACUOUS" and, worse, a
  158. # reader skimming the output could take "the check still passed" for a passing
  159. # test. A case that cannot fire is worse than no case: it is a claim of
  160. # coverage that was never tested.
  161. #
  162. # So the mutation is verified, not assumed. If the file is byte-identical
  163. # afterwards, that is reported as a FAILURE of the harness, naming the sed, and
  164. # the case is not run - because running it would only produce a meaningless
  165. # green. The message says what to do (fix the sed) rather than what it found.
  166. mutate () {
  167. mf=$1
  168. msed=$2
  169. cp "$mf" ../tmp/nonvacuity.mut.bak
  170. sed -i "$msed" "$mf"
  171. if cmp -s "$mf" ../tmp/nonvacuity.mut.bak; then
  172. echo " BROKEN CASE: the mutation did not change $mf"
  173. echo " sed: $msed"
  174. echo " the named code has probably been renamed or reformatted -"
  175. echo " fix this case, it is asserting nothing"
  176. fail=$((fail + 1))
  177. return 1
  178. fi
  179. return 0
  180. }
  181. # rebuild <label> -- re-emit the runtime and dump it
  182. rebuild () {
  183. "$GM2" -fiso -c Runtime.mod >/dev/null 2>&1 || return 1
  184. "$GM2" -fiso -o "$PROBE" tests/RtProbe.mod Runtime.o Posix.o \
  185. >/dev/null 2>&1 || return 1
  186. "$PROBE" > "$DUMP" || return 1
  187. return 0
  188. }
  189. # expect_red <label> <pattern> <checker-cmd...>
  190. # <pattern> is a grep the failure output must match, so a check cannot
  191. # "pass" by failing for some unrelated reason.
  192. expect_red () {
  193. label=$1
  194. want=$2
  195. shift 2
  196. if out=$("$@" 2>&1); then
  197. echo "NOT NON-VACUOUS: $label -- the check still passed"
  198. fail=$((fail + 1))
  199. elif ! printf '%s\n' "$out" | grep -qi "$want"; then
  200. echo "WRONG FAILURE: $label -- went red, but not for the stated reason"
  201. printf '%s\n' "$out" | sed 's/^/ /'
  202. fail=$((fail + 1))
  203. else
  204. echo " ok: $label"
  205. printf '%s\n' "$out" | grep -im1 "$want" | sed 's/^/ /'
  206. pass=$((pass + 1))
  207. fi
  208. }
  209. echo "== each mutation must turn the named check red"
  210. echo
  211. # --- 1. name-versus-decode -------------------------------------------
  212. # MovSiBx was `89 DC`, which is MOV SP,BX. Two bytes either way, decodes
  213. # cleanly, and no structural check can see it.
  214. cp "$SAVED" Runtime.mod
  215. mutate Runtime.mod 's|B (0DEH) END MovSiBx|B (0DCH) END MovSiBx|'
  216. expect_red "audit_helpers catches MovSiBx emitting MOV SP,BX" \
  217. "MovSiBx" python3 tests/audit_helpers.py
  218. # CmpSiBx had the identical mistake, which is how you know a single fix is
  219. # not enough -- the same misreading was written twice.
  220. cp "$SAVED" Runtime.mod
  221. mutate Runtime.mod 's|B (39H) ; B (0DEH) END CmpSiBx|B (39H) ; B (0DCH) END CmpSiBx|'
  222. expect_red "audit_helpers catches CmpSiBx emitting CMP SP,BX" \
  223. "CmpSiBx" python3 tests/audit_helpers.py
  224. # --- 2. golden, and entry goldens ------------------------------------
  225. # MovDlAl was `88 C0` = MOV AL,AL instead of MOV DL,AL. This is the case that
  226. # motivated runtime.golden: the sweep stayed in sync, every branch target
  227. # stayed on a boundary, no entry's first bytes moved, and the size did not
  228. # change. The target helper was MovAlDh when this case was written, which is
  229. # the fourth way a case here can rot - see the note on `mutate` below.
  230. cp "$SAVED" Runtime.mod
  231. mutate Runtime.mod 's|PROCEDURE MovDlAl ; BEGIN B (88H) ; B (0C2H)|PROCEDURE MovDlAl ; BEGIN B (88H) ; B (0C0H)|'
  232. rebuild
  233. expect_red "runtime.golden catches MOV AL,AL" \
  234. "mov al,al" python3 tests/check_runtime.py "$DUMP"
  235. # initmem opened with the mis-emitted MovSiAx, so its entry golden was the
  236. # thing that noticed the prologue was a no-op.
  237. cp "$SAVED" Runtime.mod
  238. mutate Runtime.mod 's|B (0F0H) END MovSiAx|B (0C0H) END MovSiAx|'
  239. rebuild
  240. expect_red "check_runtime catches a broken initmem prologue" \
  241. "mov ax,ax" python3 tests/check_runtime.py "$DUMP"
  242. # --- 3. decode sweep / length ----------------------------------------
  243. # StDiDl was `88 97` = [BX+disp16],DL: mod=10, so the instruction needs a
  244. # disp16 it was not given, and the sweep loses sync two bytes later.
  245. cp "$SAVED" Runtime.mod
  246. mutate Runtime.mod 's|PROCEDURE StDiDl ; BEGIN B (88H) ; B (15H)|PROCEDURE StDiDl ; BEGIN B (88H) ; B (97H)|'
  247. rebuild
  248. expect_red "decode sweep catches a mod=10 byte move with no displacement" \
  249. "mov byte ptr \[bx+5b5fh\],dl" python3 tests/check_runtime.py "$DUMP"
  250. # --- 4. branch targets ------------------------------------------------
  251. # FixUp measures a rel8 from the end of the instruction, one byte past the
  252. # displacement field. Drop the +1 and every short branch lands one byte into
  253. # its target, which for a 3-byte instruction means the middle of it. The
  254. # bytes themselves are all perfectly well formed -- only the fixups are
  255. # wrong -- so this is the one failure mode the golden cannot be expected to
  256. # catch on its own.
  257. cp "$SAVED" Runtime.mod
  258. mutate Runtime.mod 's|rel := (t + 100H - (fix \[i\].place + 1)) MOD 100H|rel := (t + 100H - fix [i].place) MOD 100H|'
  259. rebuild
  260. expect_red "branch check catches rel8 fixups measured from the wrong byte" \
  261. "not an instruction boundary" \
  262. python3 tests/check_runtime.py "$DUMP"
  263. echo
  264. echo "== everything restored and green again"
  265. cp "$SAVED" Runtime.mod
  266. if rebuild; then
  267. if python3 tests/audit_helpers.py >/dev/null 2>&1 &&
  268. python3 tests/check_runtime.py "$DUMP" >/dev/null 2>&1; then
  269. echo " ok: both checks pass on the restored source"
  270. pass=$((pass + 1))
  271. else
  272. echo "NOT RESTORED: a check is red after restoring Runtime.mod"
  273. fail=$((fail + 1))
  274. fi
  275. else
  276. echo "NOT RESTORED: the runtime would not rebuild"
  277. fail=$((fail + 1))
  278. fi
  279. echo
  280. echo "== the mod=11 table (probe/modrm11.py)"
  281. # These mutate the probe's own sources, not the runtime, so there is no
  282. # rebuild in the loop. SAVED_PY / SAVED_S are restored after each case.
  283. SAVED_PY=../tmp/nonvacuity.modrm11.py
  284. SAVED_S=../tmp/nonvacuity.modrm11.s
  285. cp tests/probe/modrm11.py "$SAVED_PY" || exit 1
  286. cp tests/probe/modrm11.s "$SAVED_S" || exit 1
  287. M11="python3 tests/probe/modrm11.py"
  288. restore_probe () {
  289. cp "$SAVED_PY" tests/probe/modrm11.py
  290. cp "$SAVED_S" tests/probe/modrm11.s
  291. }
  292. # 1. one cell of the table moved
  293. mutate tests/probe/modrm11.py 's|"Si", "Di"\]$|"Bp", "Di"]|'
  294. expect_red "anchor pins a moved table cell" \
  295. "anchor ADD SI, 2" $M11
  296. restore_probe
  297. # 2. the table this project actually shipped: AX dropped off the front and a
  298. # duplicate BX invented at the end, which shifts every code down by one
  299. mutate tests/probe/modrm11.py 's|^REG = .*$|REG = ["Cx", "Dx", "Bx", "Sp", "Bp", "Si", "Di", "Bx"]|'
  300. expect_red "the table shifted by one (AX dropped, BX duplicated)" \
  301. "anchor MOV SP, BP" $M11
  302. restore_probe
  303. # 3. the .s edited to contradict the table. This is the case that shows why
  304. # the hard-coded EXPECT bytes exist: the assembler encodes the new claim
  305. # correctly, so comparing the .s against `as` alone can never fail here.
  306. mutate tests/probe/modrm11.s 's|movw %sp, %di # reg 100|movw %bp, %di # reg 100|'
  307. expect_red "probe source edited away from the recorded bytes" \
  308. "expected 89 E7" $M11
  309. restore_probe
  310. # 4. the 8-bit list edited, which is a different table from the word one
  311. mutate tests/probe/modrm11.s 's|movb %al, %dl # 88 C2 -> DL := AL|movb %al, %bl # was DL|'
  312. expect_red "the 8-bit register list edited" \
  313. "expected 88 C2" $M11
  314. restore_probe
  315. # 5. an anchor's recorded byte corrupted, so the anchor can no longer
  316. # corroborate itself
  317. mutate tests/probe/modrm11.py 's|"8B EC", "8B E5"|"8B ED", "8B E5"|'
  318. expect_red "anchor byte no longer matches the emitted code" \
  319. "expected 8B ED" $M11
  320. restore_probe
  321. if $M11 >/dev/null 2>&1; then
  322. echo " ok: modrm11.py passes on the restored probe sources"
  323. pass=$((pass + 1))
  324. else
  325. echo "NOT RESTORED: modrm11.py is red after restoring its sources"
  326. $M11 2>&1 | sed 's/^/ /'
  327. fail=$((fail + 1))
  328. fi
  329. echo
  330. echo "== the BP displacement rule (check_framedisp.py)"
  331. # This one is about Compiler.mod rather than the runtime, and it needs the
  332. # whole toolchain rebuilt (comtest, not rtprobe), so it gets its own rebuild.
  333. SAVED_C=../tmp/nonvacuity.Compiler.mod
  334. cp Compiler.mod "$SAVED_C" || exit 1
  335. rebuild_compiler () {
  336. $GM2 -fiso -c Compiler.mod >/dev/null 2>&1 || return 1
  337. $GM2 -fiso -fgen-module-list=tests/ct.lst -o /dev/null \
  338. tests/ComTest.mod TextBuf.o Posix.o Compiler.o Runtime.o Linker.o \
  339. >/dev/null 2>&1
  340. $GM2 -fiso -fuse-list=tests/ct.lst -o comtest \
  341. tests/ComTest.mod TextBuf.o Posix.o Compiler.o Runtime.o Linker.o \
  342. >/dev/null 2>&1 || return 1
  343. return 0
  344. }
  345. # 1. the original bug: `off MOD 100H`, always disp8. Restores exactly the code
  346. # that was there before EmBpDisp existed. t28's [BP+128] read becomes
  347. # [BP-128], which is the failure this whole check is named after.
  348. python3 - "$SAVED_C" <<'PYEOF'
  349. import sys
  350. p = 'Compiler.mod'
  351. s = open(p).read()
  352. old = """BEGIN
  353. IF off <= 127 THEN
  354. Ebyte (46H) ; Ebyte (VAL (BYTE, off))
  355. ELSE
  356. Ebyte (86H) ; Eword (off)
  357. END
  358. END EmBpDisp ;"""
  359. new = """VAR disp : CARDINAL ;
  360. BEGIN
  361. disp := off MOD 100H ;
  362. Ebyte (46H) ; Ebyte (VAL (BYTE, disp))
  363. END EmBpDisp ;"""
  364. assert old in s, "EmBpDisp body not found -- update this mutation"
  365. open(p, 'w').write(s.replace(old, new))
  366. PYEOF
  367. if rebuild_compiler; then
  368. expect_red "displacement truncation reads a different address" \
  369. "no 8B access at \[BP+128\]" python3 tests/check_framedisp.py
  370. else
  371. echo " FAIL: the compiler would not rebuild with the truncation"
  372. fail=$((fail + 1))
  373. fi
  374. cp "$SAVED_C" Compiler.mod
  375. # 2. the other half of the rule: always use the 4-byte form, ignoring the
  376. # <= 127 case. This is over-cautious rather than wrong, so the checker must
  377. # still be happy -- which is worth asserting, because a check that only
  378. # ever fails on a smaller encoding is a check that pins one answer instead
  379. # of the rule.
  380. python3 - <<'PYEOF'
  381. p = 'Compiler.mod'
  382. s = open(p).read()
  383. old = """ IF off <= 127 THEN
  384. Ebyte (46H) ; Ebyte (VAL (BYTE, off))
  385. ELSE
  386. Ebyte (86H) ; Eword (off)
  387. END"""
  388. new = """ Ebyte (86H) ; Eword (off)"""
  389. assert old in s, "EmBpDisp branch not found -- update this mutation"
  390. open(p, 'w').write(s.replace(old, new))
  391. PYEOF
  392. if rebuild_compiler; then
  393. if python3 tests/check_framedisp.py >/dev/null 2>&1; then
  394. echo " ok: always-disp16 is accepted, so the check pins the rule"
  395. echo " and not one particular encoding"
  396. pass=$((pass + 1))
  397. else
  398. echo " FAIL: check_framedisp rejects a safe, over-long encoding"
  399. python3 tests/check_framedisp.py 2>&1 | sed 's/^/ /'
  400. fail=$((fail + 1))
  401. fi
  402. else
  403. echo " FAIL: the compiler would not rebuild with always-disp16"
  404. fail=$((fail + 1))
  405. fi
  406. cp "$SAVED_C" Compiler.mod
  407. if rebuild_compiler; then
  408. if python3 tests/check_framedisp.py >/dev/null 2>&1; then
  409. echo " ok: check_framedisp passes on the restored source"
  410. pass=$((pass + 1))
  411. else
  412. echo "NOT RESTORED: check_framedisp is red after restoring Compiler.mod"
  413. python3 tests/check_framedisp.py 2>&1 | sed 's/^/ /'
  414. fail=$((fail + 1))
  415. fi
  416. else
  417. echo "NOT RESTORED: the compiler would not rebuild"
  418. fail=$((fail + 1))
  419. fi
  420. # --- the region check_framedisp sweeps, and the one file it comes from -----
  421. echo
  422. echo "== the image layout, measured once (tests/comimage.py)"
  423. # check_framedisp.py decodes instructions over a REGION of the image, and a
  424. # wrong region does not stop it: the byte patterns it searches for are in the
  425. # image wherever they happen to be, and a decode that starts mid-instruction
  426. # reached the same offsets anyway. That is how RT_SZ = 391 - a literal that had
  427. # drifted from the runtime it described - went on reporting PASS while its sweep
  428. # began inside the runtime, part way through an instruction. Nothing in the
  429. # check could see where its own region began.
  430. #
  431. # So the region is two independent readings of the file - where the entry jump
  432. # says execution starts, and where the program header says the runtime ends -
  433. # and the two must AGREE or the region is undetermined. Both readings, and the
  434. # layout itself, live in tests/comimage.py, which is also where comtest.py and
  435. # the independent checker in run_com_tests.sh now get the copy each of them
  436. # used to keep: a duplicated constant that has silently drifted is not an
  437. # independent check, it is a second source of truth that lies, and it lies in
  438. # the direction of looking like the code under test is broken.
  439. #
  440. # None of this needs a rebuild - comimage.py is Python the checkers import -
  441. # so these cases are cheap, and they turn the READERS red one at a time.
  442. # 1. entry_target answers with the literal the region used to be built from.
  443. # The two readings now disagree, and there is no measured region to sweep.
  444. python3 - <<'PYEOF'
  445. p = 'tests/comimage.py'
  446. s = open(p).read()
  447. old = ' return ENT_SZ + int.from_bytes(d[1:ENT_SZ], "little", signed=True)'
  448. new = ' return ENT_SZ + 391 # the literal RT_SZ was'
  449. assert s.count(old) == 1, "entry_target's return not found -- update this mutation"
  450. open(p, 'w').write(s.replace(old, new))
  451. PYEOF
  452. expect_red "a sweep region that is not where execution starts is rejected" \
  453. "neither region is swept" python3 tests/check_framedisp.py
  454. cp "$SAVED_CI" tests/comimage.py
  455. # 2 and 3. The header's own equation, one byte out, so the header cannot be
  456. # located at all - the case where a checker that fell back on a remembered
  457. # offset would report a confident number instead. Two readers, two
  458. # different sentences: each must say in its own words that it does not know
  459. # where the program's code begins.
  460. python3 - <<'PYEOF'
  461. p = 'tests/comimage.py'
  462. s = open(p).read()
  463. old = ' if w(HDR_DS_WORD) != off + 0x1000 + LOAD_BIAS: # hdrDS'
  464. new = ' if w(HDR_DS_WORD) != off + 0x1000 + LOAD_BIAS + 1: # hdrDS'
  465. assert s.count(old) == 1, "the hdrDS equation not found -- update this mutation"
  466. open(p, 'w').write(s.replace(old, new))
  467. PYEOF
  468. expect_red "check_framedisp reports a header it cannot locate" \
  469. "no program header found" python3 tests/check_framedisp.py
  470. expect_red "check_8086 reports the same unlocatable header" \
  471. "could not locate the code region" python3 tests/check_8086.py
  472. cp "$SAVED_CI" tests/comimage.py
  473. # 4-7. The single copy itself, now that there is one. A second find_header,
  474. # a second HDR_SZ, a caller that reaches the helper through another
  475. # consumer instead of through comimage, and - the case that exists
  476. # because of rt_exec.py's "matched nothing" lesson - the definition the
  477. # audit counts. A rule that matches nothing looks exactly like a rule
  478. # that passes, so a deleted definition must be a red report rather than a
  479. # silent green one.
  480. python3 - <<'PYEOF'
  481. p = 'tests/comtest.py'
  482. s = open(p).read()
  483. old = 'def check_com(path, expected_src_len):'
  484. new = ('def find_header(d):\n'
  485. ' return None # a second copy of the helper\n'
  486. '\n\n'
  487. 'def check_com(path, expected_src_len):')
  488. assert s.count(old) == 1, "check_com not found -- update this mutation"
  489. open(p, 'w').write(s.replace(old, new))
  490. PYEOF
  491. expect_red "the audit reports a find_header copied out of comimage" \
  492. "comtest.py defines its own find_header" python3 tests/check_comimage.py
  493. cp "$SAVED_T" tests/comtest.py
  494. python3 - <<'PYEOF'
  495. p = 'tests/comtest.py'
  496. s = open(p).read()
  497. old = 'from comimage import (ENT_SZ, HDR_SZ, LOAD_BIAS, HEAD, HDR_DS_WORD,'
  498. new = ('HDR_SZ = 16 # a second copy of the layout\n'
  499. 'from comimage import (ENT_SZ, HDR_SZ, LOAD_BIAS, HEAD, HDR_DS_WORD,')
  500. assert s.count(old) == 1, "the comimage import not found -- update this mutation"
  501. open(p, 'w').write(s.replace(old, new))
  502. PYEOF
  503. expect_red "the audit reports a layout constant defined elsewhere" \
  504. "comtest.py defines its own HDR_SZ" python3 tests/check_comimage.py
  505. cp "$SAVED_T" tests/comtest.py
  506. python3 - <<'PYEOF'
  507. p = 'tests/comimage.py'
  508. s = open(p).read()
  509. old = 'def find_header(d):'
  510. new = 'def _find_header(d): # the definition is gone'
  511. assert s.count(old) == 1, "def find_header not found -- update this mutation"
  512. open(p, 'w').write(s.replace(old, new))
  513. PYEOF
  514. expect_red "the audit counts its own subject rather than matching nothing" \
  515. "defines find_header 0 times" python3 tests/check_comimage.py
  516. cp "$SAVED_CI" tests/comimage.py
  517. # 7. The import dropped while the CALLS stay - the shape a refactor makes when
  518. # one reader starts taking the helper from another reader instead. It would
  519. # NameError the moment comtest ran, but the audit says so first, and in the
  520. # vocabulary of the layout rather than in the vocabulary of Python: the
  521. # failure this is guarding is "two sources of truth", not "undefined name".
  522. python3 - <<'PYEOF'
  523. p = 'tests/comtest.py'
  524. s = open(p).read()
  525. old = ('from comimage import (ENT_SZ, HDR_SZ, LOAD_BIAS, HEAD, HDR_DS_WORD,\n'
  526. ' HDR_HEAP_WORD, find_header)')
  527. new = '# MUTATION: the shared import is gone, but the calls remain\n'
  528. assert s.count(old) == 1, "the comimage import not found -- update this mutation"
  529. open(p, 'w').write(s.replace(old, new))
  530. PYEOF
  531. expect_red "the audit reports a caller that does not take it from comimage" \
  532. "comtest.py calls find_header without importing it from comimage" \
  533. python3 tests/check_comimage.py
  534. cp "$SAVED_T" tests/comtest.py
  535. # Green again, on all three readers at once: the case above mutated the one
  536. # file all of them import, so restoring it has to satisfy each of them, not
  537. # just the one that was last run.
  538. for c in tests/check_framedisp.py tests/check_comimage.py tests/check_8086.py; do
  539. if python3 "$c" >/dev/null 2>&1; then
  540. echo " ok: $c passes on the restored sources"
  541. pass=$((pass + 1))
  542. else
  543. echo "NOT RESTORED: $c is red after restoring comimage.py and comtest.py"
  544. python3 "$c" 2>&1 | tail -3 | sed 's/^/ /'
  545. fail=$((fail + 1))
  546. fi
  547. done
  548. # --- 3. the operator bugs the nine dead fixtures were hiding ------------
  549. echo
  550. echo "== the bugs the never-executed fixtures were hiding"
  551. echo
  552. # A different KIND of case from everything above. The others break the code
  553. # and assert a byte-level check notices; these break the code and assert a
  554. # BEHAVIOURAL check notices, which is the only kind that could have found them.
  555. # Each of the original four shipped with a green compile matrix, a passing .COM
  556. # layout check, a passing golden and a passing emitter audit:
  557. #
  558. # OpMul = 1 `a * b` emitted ADD AX,CX. `*' and `+' both numbered
  559. # their operator 1, and BinOpEmit cannot see which
  560. # precedence level called it, so every multiplication
  561. # dispatched to the addition. The constant-folding arm was
  562. # correct, which is why `n * n' with n a CONST was right and
  563. # `a * a' with a a variable was not -- and t08_const is the
  564. # only fixture that ever multiplied.
  565. # 9Dh / 9FH `>' got SETGE and `>=' got SETG: swapped, one letter
  566. # apart in the mnemonic. Only a==b could see it.
  567. # JNZ -> body REPEAT..UNTIL looped back while the condition was TRUE,
  568. # which is WHILE, so the body ran once and stopped.
  569. #
  570. # They are mutated back to the original defect and run_com_exec.py must go red
  571. # on the exact fixture that pins the behaviour. The fourth (HideLocals) is a
  572. # scoping bug rather than an operator bug; it was hiding in the same place.
  573. #
  574. # Two joined them when the operand-lifetime and `not' fixes landed, each run
  575. # red by hand before it was written down here, and each with the same property
  576. # as the four above -- green everywhere except execution:
  577. #
  578. # SaveLeft's park `(p > q) or (q > p)' evaluated `(q > p) or (q > p)'. A
  579. # kind-2 value exists only in AX, and the right operand's
  580. # code is emitted before the two are ever brought together,
  581. # so without the push the left one is simply gone.
  582. # neglevel's split `not' on a boolean emitted the INTEGER `not', which left
  583. # 0FFFEh where a boolean belongs, and wrbool reads anything
  584. # non-zero as TRUE -- so `not (a = a)' answered TRUE and so
  585. # did every other `not'.
  586. mutate_compiler () { # reuse mutate's verified-change discipline on Compiler.mod
  587. mf=Compiler.mod
  588. msed=$1
  589. cp "$SAVED_C" ../tmp/nonvacuity.mut2.bak
  590. sed -i "$msed" "$mf"
  591. if cmp -s "$mf" ../tmp/nonvacuity.mut2.bak; then
  592. echo " BROKEN CASE: the mutation did not change Compiler.mod"
  593. echo " sed: $msed"
  594. echo " the named code has probably been renamed or reformatted -"
  595. echo " fix this case, it is asserting nothing"
  596. fail=$((fail + 1))
  597. return 1
  598. fi
  599. return 0
  600. }
  601. # The SETcc swap and the HideLocals removal are done in python rather than
  602. # with sed: both need to match source text containing `*` and `(` in a way that
  603. # is tedious and fragile as a regex, and a case whose only failure mode is a
  604. # malformed sed is a case that silently asserts nothing.
  605. #
  606. # And a python helper fails in a way sed does not: a syntax error in the helper
  607. # is a non-zero exit, `if mutate_foo; then` is simply false, and the case is
  608. # SKIPPED -- with no failure counted and nothing on stdout but whatever python
  609. # printed. That is how the SETcc case spent its first run: an apostrophe in an
  610. # assert message ("the `>' arm") closed the string early, python died, the
  611. # compiler was never broken, and the suite still reported 0 failed. A skipped
  612. # case and a passing case look the same in the total. So each helper below
  613. # fails LOUDLY: a non-zero exit from python is reported as a BROKEN CASE and
  614. # counted, never swallowed.
  615. #
  616. # Each one also counts its targets before replacing. `assert s != before' only
  617. # says the file changed; with two edits it would pass if just one of them
  618. # landed, and with two identical HideLocals call sites it would happily delete
  619. # the wrong one -- still a changed file, still a working compiler, still green
  620. # for the wrong reason.
  621. mutate_cc_swap () {
  622. if python3 - <<'PYX'
  623. p = 'Compiler.mod'
  624. s = open(p).read()
  625. GT = 'EmSetcc (9FH) ; (* > SETG *)' # the greater-than arm
  626. GE = 'EmSetcc (9DH) ; (* >= SETGE *)' # the greater-equal arm
  627. assert s.count(GT) == 1, 'expected 1 greater-than arm, found %d' % s.count(GT)
  628. assert s.count(GE) == 1, 'expected 1 greater-equal arm, found %d' % s.count(GE)
  629. s = s.replace(GT, GT.replace('9FH', '9DH'))
  630. s = s.replace(GE, GE.replace('9DH', '9FH'))
  631. open(p, 'w').write(s)
  632. PYX
  633. then
  634. return 0
  635. fi
  636. echo " BROKEN CASE: the SETcc swap did not apply"
  637. echo " the two EmSetcc arms are probably renamed or reformatted -"
  638. echo " fix this case, it is asserting nothing"
  639. fail=$((fail + 1))
  640. return 1
  641. }
  642. mutate_no_hidelocals () {
  643. if python3 - <<'PYX'
  644. p = 'Compiler.mod'
  645. s = open(p).read()
  646. # Two HideLocals calls exist. Only the body-exit one may go: deleting the
  647. # FORWARD one instead would still change the file, still rebuild, and still
  648. # leave t13_proc compiling, so the case would go green for the wrong reason.
  649. HL = ' HideLocals (nestMark) ; (* parameters and locals stop here *)\n'
  650. assert s.count(HL) == 1, 'expected 1 body-exit HideLocals, found %d' % s.count(HL)
  651. open(p, 'w').write(s.replace(HL, ''))
  652. PYX
  653. then
  654. return 0
  655. fi
  656. echo " BROKEN CASE: HideLocals was not removed"
  657. echo " the call or its comment has probably been reformatted -"
  658. echo " fix this case, it is asserting nothing"
  659. fail=$((fail + 1))
  660. return 1
  661. }
  662. cp "$SAVED_C" Compiler.mod
  663. if mutate_compiler 's|^ op := OpMul ; DropCh| op := OpAdd ; DropCh|'; then
  664. if rebuild_compiler; then
  665. expect_red "execution catches '*' emitting an ADD (t08_const, n*n)" \
  666. "t08_const" python3 tests/run_com_exec.py t08_const
  667. # t08 only ever multiplied two CONSTANTS, which is the one path that was
  668. # never wrong, because BinOpEmit folds it. So the case above is close
  669. # to vacuous: it proves the mutation changed the binary, not that the
  670. # emitted multiply is covered. The check that matters needs a
  671. # VARIABLE operand, and no shipped fixture has one -- which is why the
  672. # bug survived at all. So this writes a throwaway fixture that
  673. # multiplies a variable, runs it, and asserts the multiply is right.
  674. # The fixture is deleted afterwards; it is here to close the coverage
  675. # hole, not to become a permanent test (that is what a real fixture
  676. # with a `*' in it would be for).
  677. cat > tests/fixtures/zzmul.pas <<'ZZEOF'
  678. program zzmul;
  679. var a : integer ;
  680. begin
  681. a := 7 ;
  682. writeln (a * 6)
  683. end.
  684. ZZEOF
  685. printf '42\r\n' > tests/fixtures/zzmul.out
  686. expect_red "execution catches '*' on a VARIABLE (the unfolded path)" \
  687. "zzmul" python3 tests/run_com_exec.py zzmul
  688. rm -f tests/fixtures/zzmul.pas tests/fixtures/zzmul.out
  689. else
  690. echo " FAIL: the compiler would not rebuild with OpAdd for '*'"
  691. fail=$((fail + 1))
  692. fi
  693. fi
  694. cp "$SAVED_C" Compiler.mod
  695. cp "$SAVED_C" Compiler.mod
  696. if mutate_cc_swap; then
  697. if rebuild_compiler; then
  698. expect_red "execution catches '>' and '>=' swapped (t09_if)" \
  699. "t09_if" python3 tests/run_com_exec.py t09_if
  700. else
  701. echo " FAIL: the compiler would not rebuild with the SETcc swap"
  702. fail=$((fail + 1))
  703. fi
  704. fi
  705. cp "$SAVED_C" Compiler.mod
  706. cp "$SAVED_C" Compiler.mod
  707. if mutate_compiler 's| DropC (EmJcc (84H, L1)) ; (\* JZ -> body again \*)| zj := EmJcc (85H, L1) ;|'; then
  708. if rebuild_compiler; then
  709. expect_red "execution catches REPEAT..UNTIL exiting after one pass (t12)" \
  710. "t12_repeat" python3 tests/run_com_exec.py t12_repeat
  711. else
  712. echo " FAIL: the compiler would not rebuild with the JNZ repeat"
  713. fail=$((fail + 1))
  714. fi
  715. fi
  716. cp "$SAVED_C" Compiler.mod
  717. # The fourth: sibling procedures shared one parameter namespace, because a
  718. # finished procedure's symbols were left at a level Search still accepts.
  719. # Removing HideLocals puts two procedures' `a : integer' back in collision.
  720. cp "$SAVED_C" Compiler.mod
  721. if mutate_no_hidelocals; then
  722. if rebuild_compiler; then
  723. expect_red "a duplicate parameter in two procedures is a compile error again" \
  724. "ERROR 41" python3 tests/run_com_exec.py t13_proc
  725. else
  726. echo " FAIL: the compiler would not rebuild without HideLocals"
  727. fail=$((fail + 1))
  728. fi
  729. else
  730. echo " FAIL: could not remove HideLocals to test the scoping fix"
  731. fail=$((fail + 1))
  732. fi
  733. # M6: the LEFT operand, parked for the right one. kind 2 means "this value
  734. # exists in AX and nowhere else", and the right-hand operand's code is emitted
  735. # between recognizing the operator and using both operands - so without
  736. # SaveLeft's push the left value is overwritten before it is ever read, and
  737. # LoadPair's kind-4 shape can never trigger. `(p > q) or (q > p)' then
  738. # evaluates `(q > p) or (q > p)'. Every byte, every size and the whole compile
  739. # matrix stay green: nothing is malformed, the value is simply the wrong one.
  740. cp "$SAVED_C" Compiler.mod
  741. if python3 - <<'PYX'
  742. p = 'Compiler.mod'
  743. s = open(p).read()
  744. old = """BEGIN
  745. IF left.kind = 2 THEN
  746. EmPushAx () ;
  747. left.kind := 4 (* 4 = on the top of the stack *)
  748. END
  749. END SaveLeft ;"""
  750. new = """BEGIN
  751. (* MUTATION: the park is unreachable, so nothing survives the parse *)
  752. IF left.kind = 99 THEN
  753. EmPushAx () ;
  754. left.kind := 4
  755. END
  756. END SaveLeft ;"""
  757. assert s.count(old) == 1, 'SaveLeft body found %d times -- update this mutation' % s.count(old)
  758. open(p, 'w').write(s.replace(old, new))
  759. PYX
  760. then
  761. if rebuild_compiler; then
  762. expect_red "execution catches a left operand clobbered by the right one" \
  763. "t34_arith" python3 tests/run_com_exec.py t34_arith
  764. else
  765. echo " FAIL: the compiler would not rebuild without SaveLeft's push"
  766. fail=$((fail + 1))
  767. fi
  768. else
  769. echo " BROKEN CASE: the SaveLeft mutation did not apply"
  770. fail=$((fail + 1))
  771. fi
  772. cp "$SAVED_C" Compiler.mod
  773. # M7: the type split in TPSRC9's neglevel, wrong half. A boolean NOT lowered
  774. # as the INTEGER one leaves 0FFFEh/0FFFFh, and wrbool tests [BP+4] <> 0 - so
  775. # `not (a = a)' answers TRUE, and so does every other `not'. One instruction,
  776. # same length, same sizes, and the compile matrix cannot see it because both
  777. # halves emit well-formed code for a type the parser already accepted.
  778. cp "$SAVED_C" Compiler.mod
  779. if python3 - <<'PYX'
  780. p = 'Compiler.mod'
  781. s = open(p).read()
  782. old = """ IF r.cls = TBool THEN
  783. LoadAtom (r) ;
  784. EmXorAl01 () ;"""
  785. new = """ IF r.cls = TBool THEN
  786. LoadAtom (r) ;
  787. EmNotAx () ; (* MUTATION: integer NOT on a boolean *)"""
  788. assert s.count(old) == 1, 'the TBool arm of ParseNeg found %d times -- update this mutation' % s.count(old)
  789. open(p, 'w').write(s.replace(old, new))
  790. PYX
  791. then
  792. if rebuild_compiler; then
  793. expect_red "execution catches a boolean NOT lowered as an integer one" \
  794. "t35_not" python3 tests/run_com_exec.py t35_not
  795. else
  796. echo " FAIL: the compiler would not rebuild with EmNotAx for a boolean"
  797. fail=$((fail + 1))
  798. fi
  799. else
  800. echo " BROKEN CASE: the neglevel type-split mutation did not apply"
  801. fail=$((fail + 1))
  802. fi
  803. cp "$SAVED_C" Compiler.mod
  804. # Bug 36, argument order: the fix has FOUR independent halves - three parsers
  805. # that push each argument the moment it is parsed instead of after the whole
  806. # list, and the callee that reads its parameters backwards from BP+4 - and
  807. # t36_argclobber is the one fixture that tells them apart. Before these four
  808. # cases existed, its only proof was the pre-fix run quoted in the commit
  809. # message, which is a fact about the past rather than a check: it cannot be
  810. # re-derived, and nothing stops the four halves from drifting apart.
  811. #
  812. # Each revert below was run to a red BEFORE it was written here, and the four
  813. # fail on four DIFFERENT rows, which is what makes them four cases and not one
  814. # wearing four hats: the callee revert turns `5 3 7' into `7 3 5' (every
  815. # argument lands on its neighbour's parameter), the deferred ParseCallArgs
  816. # zeroes the rows built from computed arguments, ParseCall changes the
  817. # function call's result (19 -> 10) and IoCall changes the last write
  818. # (`FALSE 1' -> `TRUE 544', the first argument printed as the second
  819. # argument's value). A revert that left t36 green is reported by expect_red
  820. # as NOT NON-VACUOUS; a revert that did not land is a BROKEN CASE.
  821. # revert_procedure <name> -- put <name> back the way it was before bug 36 was
  822. # fixed, spliced out of the tree the fix landed on top of. The old code's
  823. # source of truth is the old code: quoting a copy of it in this file is a copy
  824. # that can drift from the tag it claims to reproduce, and a revert that
  825. # reproduces nothing is a case asserting nothing.
  826. revert_procedure () {
  827. python3 - "$1" <<'PYX'
  828. import subprocess, sys
  829. name = sys.argv[1]
  830. cur = open('Compiler.mod').read()
  831. r = subprocess.run(['git', 'show', 'v-TP3-IMAGELAYOUT:shell/Compiler.mod'],
  832. capture_output=True)
  833. assert r.returncode == 0, 'cannot read the pre-fix tree: %s' % r.stderr.decode()[:200]
  834. pre = r.stdout.decode()
  835. def span(text, where):
  836. # The DEFINITION, not the FORWARD declaration a few screens earlier: the
  837. # anchor runs to the end of the line, and a FORWARD line ends `FORWARD ;'
  838. # instead of nothing.
  839. a, b = 'PROCEDURE %s (idx : CARDINAL) ;\n' % name, 'END %s ;' % name
  840. na, nb = text.count(a), text.count(b)
  841. assert na == 1 and nb == 1, \
  842. '%s: %d definitions, %d ends in %s -- update this case' % (name, na, nb, where)
  843. i = text.index(a)
  844. j = text.index(b, i) + len(b)
  845. return text[i:j], i, j
  846. new, i, j = span(cur, 'Compiler.mod')
  847. old, _, _ = span(pre, 'the pre-fix tree')
  848. assert old != new, 'the pre-fix %s is identical to the current one' % name
  849. open('Compiler.mod', 'w').write(cur[:i] + old + cur[j:])
  850. PYX
  851. }
  852. # The callee half: no remap, so parameters are read in declaration order from
  853. # BP+4 while the arguments are pushed in parse order - the FIRST argument ends
  854. # up in the LAST parameter's slot, and one-argument calls (all of
  855. # Runtime.mod's own cases) cannot tell the two layouts apart.
  856. cp "$SAVED_C" Compiler.mod
  857. if python3 - <<'PYX'
  858. p = 'Compiler.mod'
  859. s = open(p).read()
  860. old = """ i := nestMark ;
  861. WHILE i < symTop DO
  862. symtab [i].off := parmOff + 2 - symtab [i].off ;
  863. INC (i)
  864. END ;
  865. """
  866. assert s.count(old) == 1, 'the ProcFunc parameter remap found %d times -- update this mutation' % s.count(old)
  867. open(p, 'w').write(s.replace(old, ''))
  868. PYX
  869. then
  870. if rebuild_compiler; then
  871. expect_red "t36 catches the callee laid out in declaration order (no remap)" \
  872. "t36_argclobber" python3 tests/run_com_exec.py t36_argclobber
  873. else
  874. echo " FAIL: the compiler would not rebuild without the parameter remap"
  875. fail=$((fail + 1))
  876. fi
  877. else
  878. echo " BROKEN CASE: the ProcFunc remap mutation did not apply"
  879. fail=$((fail + 1))
  880. fi
  881. cp "$SAVED_C" Compiler.mod
  882. # The caller half, site 1 of 3: a call used as a statement. The old code
  883. # read the whole list into args[] and pushed it backwards afterwards, so a
  884. # computed argument (which exists only in AX) was gone before the push loop
  885. # reached it.
  886. cp "$SAVED_C" Compiler.mod
  887. if revert_procedure ParseCallArgs; then
  888. if rebuild_compiler; then
  889. expect_red "t36 catches ParseCallArgs pushing after the whole list" \
  890. "t36_argclobber" python3 tests/run_com_exec.py t36_argclobber
  891. else
  892. echo " FAIL: the compiler would not rebuild with ParseCallArgs deferred"
  893. fail=$((fail + 1))
  894. fi
  895. else
  896. echo " BROKEN CASE: the ParseCallArgs revert did not apply"
  897. fail=$((fail + 1))
  898. fi
  899. cp "$SAVED_C" Compiler.mod
  900. # Site 2 of 3: the same call reached from ParseAtom, when a FUNCTION is
  901. # called inside an expression. A separate site, because it is a separate
  902. # procedure - and t36's `19' row is the only thing that notices this one.
  903. cp "$SAVED_C" Compiler.mod
  904. if revert_procedure ParseCall; then
  905. if rebuild_compiler; then
  906. expect_red "t36 catches ParseCall pushing after the whole list" \
  907. "t36_argclobber" python3 tests/run_com_exec.py t36_argclobber
  908. else
  909. echo " FAIL: the compiler would not rebuild with ParseCall deferred"
  910. fail=$((fail + 1))
  911. fi
  912. else
  913. echo " BROKEN CASE: the ParseCall revert did not apply"
  914. fail=$((fail + 1))
  915. fi
  916. cp "$SAVED_C" Compiler.mod
  917. # Site 3 of 3: write/writeln/read/readln, where the argument list is also
  918. # where an inline string literal gets its call. Reverting this procedure
  919. # also reverts the per-argument dispatch inside it (the BYTE read landed
  920. # here), which is harmless for t36 and is why the splice is the whole
  921. # procedure rather than the push alone: half a revert is a state the tree
  922. # was never in.
  923. cp "$SAVED_C" Compiler.mod
  924. if revert_procedure IoCall; then
  925. if rebuild_compiler; then
  926. expect_red "t36 catches IoCall printing the last argument's value" \
  927. "t36_argclobber" python3 tests/run_com_exec.py t36_argclobber
  928. else
  929. echo " FAIL: the compiler would not rebuild with IoCall's loops split"
  930. fail=$((fail + 1))
  931. fi
  932. else
  933. echo " BROKEN CASE: the IoCall revert did not apply"
  934. fail=$((fail + 1))
  935. fi
  936. cp "$SAVED_C" Compiler.mod
  937. # The boolean read (t38): TP3 refuses `readln (b)' with error 66 - prderrtp
  938. # rejects the whole class and the runtime has no xrdbool - and this compiler
  939. # used to accept it and dispatch to rdbool, which stores a WORD into the
  940. # one-byte variable, its second byte landing on the variable AFTER b (t37's
  941. # overflow, unobserved only because no fixture read a boolean). The fix is
  942. # one arm of IoCall's type dispatch, so the mutation restores exactly that
  943. # arm. The check is the COMPILE MATRIX rather than any run: an ERR fixture
  944. # is never executed, so nothing that runs programs on it can see a refusal.
  945. cp "$SAVED_C" Compiler.mod
  946. if python3 - <<'PYX'
  947. p = 'Compiler.mod'
  948. s = open(p).read()
  949. old = """ ELSIF acls = TBool THEN
  950. (* TP3 refuses boolean I/O: TPSRC8 prderrtp is error 66,
  951. "I/O not allowed here", and the runtime has no xrdbool
  952. at all. rdbool stores a WORD, so one byte of an
  953. accepted read would land on the variable AFTER b - the
  954. exact overflow t37_readbyte pins for a byte. TP3's
  955. answer to the whole class is the error; so is ours. *)
  956. Err (EIoHere) ;
  957. RETURN"""
  958. assert s.count(old) == 1, 'the boolean-read error arm found %d times -- update this mutation' % s.count(old)
  959. rep = """ ELSIF acls = TBool THEN
  960. ent := TU_RdBool"""
  961. open(p, 'w').write(s.replace(old, rep))
  962. PYX
  963. then
  964. if rebuild_compiler; then
  965. expect_red "t38 red when a boolean read dispatches to TU_RdBool" \
  966. "t38_readbool" tests/run_compile_tests.sh
  967. else
  968. echo " FAIL: the compiler would not rebuild with the boolean read accepted"
  969. fail=$((fail + 1))
  970. fi
  971. else
  972. echo " BROKEN CASE: the boolean-read mutation did not apply"
  973. fail=$((fail + 1))
  974. fi
  975. cp "$SAVED_C" Compiler.mod
  976. # The string variable (t39). A STRING is the first declared type bigger than
  977. # a word that this compiler accepts, and it is accepted in two places: DefVar
  978. # exempts TString from its `size > 2' catch-all so `var s : string [10]' can
  979. # exist at all, and the two arms below USE it once it does. The three
  980. # mutations are the three places the feature lives, each restored to the
  981. # exact pre-fix state (all three used to be ENoLib, or never existed):
  982. #
  983. # 1. the DEPARSE of assignment: before the fix, `s := 'hello'' fell out of
  984. # Assignment's size check. Removing the string arm puts it back there.
  985. # 2. the WRITE: before the fix, `writeln (s)' was refused by IoCall's
  986. # type dispatch. Restoring the refusal arm is removing the feature.
  987. # 3. the RUNTIME: wrstr's print loop is only as good as its length byte,
  988. # and only rt_exec.py can see a wrstr that reads no length at all.
  989. # 1. Assignment's string arm is gone, so `s := 'hello'' trips the old
  990. # `size > 2' refusal again. The arm is spliced out by its boundaries, not
  991. # by its text, so it cannot silently stop matching when the comment inside
  992. # is touched.
  993. cp "$SAVED_C" Compiler.mod
  994. if python3 - <<'PYX'
  995. p = 'Compiler.mod'
  996. s = open(p).read()
  997. a = s.index(' IF symtab [r.idx].cls = TString THEN')
  998. m = ' RETURN\n END ;\n IF symtab [r.idx].size > 2 THEN\n'
  999. i = s.index(m, a)
  1000. new = (' IF symtab [r.idx].cls = TString THEN\n'
  1001. ' Err (ENoLib) ; (* MUTATION: the arm is refused *)\n'
  1002. ' RETURN\n')
  1003. open(p, 'w').write(s[:a] + new + s[i + len(' RETURN\n'):])
  1004. PYX
  1005. then
  1006. if rebuild_compiler; then
  1007. expect_red "t39 red when the string-assignment arm is refused" \
  1008. "t39_strvar" tests/run_compile_tests.sh
  1009. else
  1010. echo " FAIL: the compiler would not rebuild with the string assignment refused"
  1011. fail=$((fail + 1))
  1012. fi
  1013. else
  1014. echo " BROKEN CASE: the string-assignment mutation did not apply"
  1015. fail=$((fail + 1))
  1016. fi
  1017. cp "$SAVED_C" Compiler.mod
  1018. # 2. The write arm of IoCall, restored to its pre-fix refusal.
  1019. cp "$SAVED_C" Compiler.mod
  1020. if python3 - <<'PYX'
  1021. p = 'Compiler.mod'
  1022. s = open(p).read()
  1023. old = """ EmPushVarAddr (symtab [arg.idx].local, symtab [arg.idx].off) ;
  1024. ent := TU_WrStr"""
  1025. assert s.count(old) == 1, 'the string-write arm found %d times -- update this mutation' % s.count(old)
  1026. rep = """ Err (ENoLib) ;
  1027. RETURN"""
  1028. open(p, 'w').write(s.replace(old, rep))
  1029. PYX
  1030. then
  1031. if rebuild_compiler; then
  1032. expect_red "t39 red when a string write is refused again (ENoLib)" \
  1033. "t39_strvar" tests/run_compile_tests.sh
  1034. else
  1035. echo " FAIL: the compiler would not rebuild with the string write refused"
  1036. fail=$((fail + 1))
  1037. fi
  1038. else
  1039. echo " BROKEN CASE: the string-write mutation did not apply"
  1040. fail=$((fail + 1))
  1041. fi
  1042. cp "$SAVED_C" Compiler.mod
  1043. # 3. The runtime half: wrstr never reads the length byte, so every string -
  1044. # "hello" and the empty one alike - prints nothing. The compiler, the
  1045. # golden and the audit all stay green; only executing the entry finds it.
  1046. cp "$SAVED" Runtime.mod
  1047. if python3 - <<'PYX'
  1048. p = 'Runtime.mod'
  1049. s = open(p).read()
  1050. old = """ MovBxBp4 ; (* BX := the caller's string address *)
  1051. XorCxCx ;
  1052. MovClBx ; (* CX := the length byte at [BX] *)"""
  1053. assert s.count(old) == 1, 'the wrstr length load found %d times -- update this mutation' % s.count(old)
  1054. rep = """ MovBxBp4 ; (* BX := the caller's string address *)
  1055. XorCxCx ; (* CX is never loaded: prints nothing *)"""
  1056. open(p, 'w').write(s.replace(old, rep))
  1057. PYX
  1058. then
  1059. if rebuild; then
  1060. expect_red "the runtime cases catch a wrstr that reads no length" \
  1061. "wrstr" python3 tests/rt_exec.py
  1062. else
  1063. echo " FAIL: the runtime would not rebuild with the length load dropped"
  1064. fail=$((fail + 1))
  1065. fi
  1066. else
  1067. echo " BROKEN CASE: the wrstr length-load mutation did not apply"
  1068. fail=$((fail + 1))
  1069. fi
  1070. cp "$SAVED" Runtime.mod
  1071. # Re-emit the object: the `rebuild` above compiled Runtime.o from the MUTATED
  1072. # source, and the restored-compiler check next links that object - without
  1073. # this recompile it would report on the mutation, not on the restored code.
  1074. "$GM2" -fiso -c Runtime.mod >/dev/null 2>&1 || {
  1075. echo " FAIL: Runtime.mod would not recompile after the restore"
  1076. fail=$((fail + 1))
  1077. }
  1078. if rebuild_compiler; then
  1079. if python3 tests/run_com_exec.py >/dev/null 2>&1; then
  1080. # No count: the matrix grows every time a fixture is added, and a
  1081. # number here would be right only until the next one.
  1082. echo " ok: every executed fixture passes on the restored compiler"
  1083. pass=$((pass + 1))
  1084. else
  1085. echo "NOT RESTORED: run_com_exec.py is red after restoring Compiler.mod"
  1086. python3 tests/run_com_exec.py 2>&1 | grep -i fail | head -3 | sed 's/^/ /'
  1087. fail=$((fail + 1))
  1088. fi
  1089. else
  1090. echo "NOT RESTORED: the compiler would not rebuild"
  1091. fail=$((fail + 1))
  1092. fi
  1093. echo
  1094. echo "== the string READ and ASSIGNMENT entries (t40, t41)"
  1095. # t39 above gave a STRING variable a frame and printed it. This milestone puts
  1096. # one on the RECEIVING end of the two operations that move data into a string
  1097. # and between two strings - readln(s)/read(s), and s := t - and each one is
  1098. # three things at once: a compiler arm that chooses a runtime entry, the
  1099. # convention that carries the limit, and the entry itself. The cases below
  1100. # break each of the six in turn. Every mutation is a fault, or a plausible
  1101. # neighbour of one, that was run to a red BY HAND before it was written here.
  1102. #
  1103. # The frame rule is the odd one out: it is not a new entry at all, but a
  1104. # pre-existing compiler bug that only this milestone could reach. A local
  1105. # STRING was packed with the INTEGER rule - the symbol took the pre-decrement
  1106. # locFree, so a string[5] local sat at BP-2 and its characters grew UP into
  1107. # BP+3, over the saved BP at [BP] and the return address at [BP+2]. `readln(s)'
  1108. # into such a local stored 'hello' over its own return address, and t40 then ran
  1109. # the string's own bytes as an address: Exec86 said `fault at IP=0x6F6C', which
  1110. # is 'l','o'. The fix packs locals top-anchored, so the first INTEGER (size 2)
  1111. # is still at -2 - byte for byte what the old rule produced - while a string[5]
  1112. # (size 6) goes to -6..-1, inside the frame. t39's size (217) and t40's
  1113. # behaviour are the two independent things that pin it.
  1114. # --- the two runtime entries ---------------------------------------------
  1115. # rdstr stored the first character where the length byte belongs, because the
  1116. # IncSi that steps SI past dest[0] was missing. The length byte then
  1117. # overwrote it: `hello' read back as 05 65 6c 6c 6f. Same length, same sizes,
  1118. # and the whole compile matrix stays green - only rt_exec.py's byte dump can
  1119. # see it.
  1120. cp "$SAVED" Runtime.mod
  1121. if python3 - <<'PYX'
  1122. p = 'Runtime.mod'
  1123. lines = open(p).read().split('\n')
  1124. out, i, n = [], 0, 0
  1125. while i < len(lines):
  1126. if lines[i].startswith(' IncSi ;') and 'dest + 1' in lines[i]:
  1127. out.append(' (* MUTATION: the IncSi that puts chars at dest+1 is gone *)')
  1128. i += 1
  1129. while i < len(lines) and not lines[i].rstrip().endswith('*)'):
  1130. i += 1
  1131. i += 1
  1132. n += 1
  1133. continue
  1134. out.append(lines[i])
  1135. i += 1
  1136. assert n == 1, 'the rdstr IncSi found %d times -- update this mutation' % n
  1137. open(p, 'w').write('\n'.join(out))
  1138. PYX
  1139. then
  1140. if rebuild; then
  1141. expect_red "rt_exec catches rdstr storing its first character at dest[0]" \
  1142. "rdstr reads a line into a string" python3 tests/rt_exec.py
  1143. else
  1144. echo " FAIL: the runtime would not rebuild with rdstr's IncSi removed"
  1145. fail=$((fail + 1))
  1146. fi
  1147. else
  1148. echo " BROKEN CASE: the rdstr IncSi mutation did not apply"
  1149. fail=$((fail + 1))
  1150. fi
  1151. cp "$SAVED" Runtime.mod
  1152. # strstore's empty-source guard. A source of length 0 sets CX := 0, and LOOP
  1153. # with CX = 0 runs 65536 times rather than zero - so `s := ''' copied 64K,
  1154. # wrapped the segment, and walked through the driver's own case record. That is
  1155. # why the pattern below matches the CASE, not a byte count: rt_exec.py reports
  1156. # this one as a malformed record, which is the honest shape of "the entry wrote
  1157. # where it had no business writing".
  1158. if python3 - <<'PYX'
  1159. p = 'Runtime.mod'
  1160. lines = open(p).read().split('\n')
  1161. out, i, n = [], 0, 0
  1162. while i < len(lines):
  1163. if lines[i].startswith(' Jcxz8 ("ss_done")'):
  1164. out.append(' (* MUTATION: the empty-source guard is gone *)')
  1165. i += 1
  1166. while i < len(lines) and not lines[i].rstrip().endswith('*)'):
  1167. i += 1
  1168. i += 1
  1169. n += 1
  1170. continue
  1171. out.append(lines[i])
  1172. i += 1
  1173. assert n == 1, 'the strstore Jcxz8 found %d times -- update this mutation' % n
  1174. open(p, 'w').write('\n'.join(out))
  1175. PYX
  1176. then
  1177. if rebuild; then
  1178. expect_red "rt_exec catches a strstore that runs LOOP with CX=0" \
  1179. "strstore copies an empty string" python3 tests/rt_exec.py
  1180. else
  1181. echo " FAIL: the runtime would not rebuild with the empty-source guard removed"
  1182. fail=$((fail + 1))
  1183. fi
  1184. else
  1185. echo " BROKEN CASE: the strstore empty-source guard mutation did not apply"
  1186. fail=$((fail + 1))
  1187. fi
  1188. cp "$SAVED" Runtime.mod
  1189. # Re-emit the object: `rebuild` above compiled Runtime.o from the MUTATED
  1190. # source, and the compiler rebuild below links that object - without this
  1191. # recompile the restored-compiler check at the end would report on the mutation.
  1192. "$GM2" -fiso -c Runtime.mod >/dev/null 2>&1 || {
  1193. echo " FAIL: Runtime.mod would not recompile after the restore"
  1194. fail=$((fail + 1))
  1195. }
  1196. # --- the frame rule -------------------------------------------------------
  1197. # The pre-fix layout, exactly: the symbol took locFree itself instead of its
  1198. # top, and the frame began at 0FFFEh. For INTEGER locals that is byte-for-byte
  1199. # the same -2, -4, ... the new rule produces, which is why the old rule survived
  1200. # so long unnoticed; for a STRING it puts characters where the return address
  1201. # is. Two independent readers go red together, so both are asserted: the
  1202. # compile matrix pins the LAYOUT (t39's code size drops 217 -> 215), and t40
  1203. # pins that the program RUNS (with the overlap its readln never sees the line
  1204. # terminator and the machine hangs).
  1205. cp "$SAVED_C" Compiler.mod
  1206. if python3 - <<'PYX'
  1207. p = 'Compiler.mod'
  1208. s = open(p).read()
  1209. a = '(locFree - size + 1) MOD 10000H'
  1210. assert s.count(a) == 2, 'the top-anchored base found %d times -- update this mutation' % s.count(a)
  1211. s = s.replace(a, 'locFree') # the old pre-decrement base
  1212. b = 'locFree := 0FFFFH ;'
  1213. assert s.count(b) == 2, 'the frame top found %d times -- update this mutation' % s.count(b)
  1214. s = s.replace(b, 'locFree := 0FFFEH ;') # the old starting point
  1215. open(p, 'w').write(s)
  1216. PYX
  1217. then
  1218. if rebuild_compiler; then
  1219. expect_red "the compile matrix catches a local string packed over the frame" \
  1220. "expected: OK 217" tests/run_compile_tests.sh
  1221. expect_red "t40 red when readln into a local string overwrites its return address" \
  1222. "never halted" python3 tests/run_com_exec.py t40_readln
  1223. else
  1224. echo " FAIL: the compiler would not rebuild with the old frame layout"
  1225. fail=$((fail + 1))
  1226. fi
  1227. else
  1228. echo " BROKEN CASE: the frame-layout revert did not apply"
  1229. fail=$((fail + 1))
  1230. fi
  1231. cp "$SAVED_C" Compiler.mod
  1232. # --- the compiler's arms --------------------------------------------------
  1233. # The limit both entries read is MOV CX,imm16. MOV AX,imm16 is one opcode away,
  1234. # the same length, and the audit's MovCxi row is COMP - "no single sequence to
  1235. # disassemble" - so nothing in the byte-level checks can tell them apart. Only
  1236. # execution can: t41's `s := t' truncates to 4 under CX and does not under AX.
  1237. # (t40 passes either way, because its CX happens to survive large enough for the
  1238. # five characters it reads - exactly the kind of luck a behavioural case is for.)
  1239. cp "$SAVED_C" Compiler.mod
  1240. if mutate_compiler 's| Ebyte (0B9H) ; Eword (imm)| Ebyte (0B8H) ; Eword (imm)|'; then
  1241. if rebuild_compiler; then
  1242. expect_red "t41 red when the destination limit is loaded into AX, not CX" \
  1243. "t41_strassign" python3 tests/run_com_exec.py t41_strassign
  1244. else
  1245. echo " FAIL: the compiler would not rebuild with MovCxi emitting MOV AX"
  1246. fail=$((fail + 1))
  1247. fi
  1248. fi
  1249. cp "$SAVED_C" Compiler.mod
  1250. # Assignment pushes the source first, then the destination, so the source sits
  1251. # at [BP+6] and the destination at [BP+4]. Swapped, strstore takes the
  1252. # destination as its own source - t41's `worl' rows become copies of what was
  1253. # already in the destination, which looks like it works and prints the wrong
  1254. # bytes.
  1255. cp "$SAVED_C" Compiler.mod
  1256. if python3 - <<'PYX'
  1257. p = 'Compiler.mod'
  1258. s = open(p).read()
  1259. src = (' EmPushVarAddr (symtab [src.idx].local,\n'
  1260. ' (symtab [src.idx].off + src.boff) MOD 10000H) ;\n'
  1261. ' EmPushVarAddr (symtab [r.idx].local,\n'
  1262. ' (symtab [r.idx].off + r.boff) MOD 10000H) ;')
  1263. dst = (' EmPushVarAddr (symtab [r.idx].local,\n'
  1264. ' (symtab [r.idx].off + r.boff) MOD 10000H) ;\n'
  1265. ' EmPushVarAddr (symtab [src.idx].local,\n'
  1266. ' (symtab [src.idx].off + src.boff) MOD 10000H) ;')
  1267. assert s.count(src) == 1, 'the assignment pushes found %d times -- update this mutation' % s.count(src)
  1268. open(p, 'w').write(s.replace(src, dst))
  1269. PYX
  1270. then
  1271. if rebuild_compiler; then
  1272. expect_red "t41 red when the assignment pushes are swapped" \
  1273. "t41_strassign" python3 tests/run_com_exec.py t41_strassign
  1274. else
  1275. echo " FAIL: the compiler would not rebuild with the pushes swapped"
  1276. fail=$((fail + 1))
  1277. fi
  1278. else
  1279. echo " BROKEN CASE: the assignment push-order mutation did not apply"
  1280. fail=$((fail + 1))
  1281. fi
  1282. cp "$SAVED_C" Compiler.mod
  1283. # The read dispatch's string arm. TU_RdStr and TU_RdInt sit next to each other
  1284. # in the same table and both take one address; TU_RdInt parses the line as a
  1285. # number, which stores nothing on `world', so readln(s) leaves s empty and the
  1286. # program prints a blank line. A refusal would at least say so; this arm looks
  1287. # like it worked and answers with the wrong bytes.
  1288. cp "$SAVED_C" Compiler.mod
  1289. if python3 - <<'PYX'
  1290. p = 'Compiler.mod'
  1291. s = open(p).read()
  1292. old = (' EmMovCxi ((symtab [arg.idx].size - 1) MOD 10000H) ;\n'
  1293. ' ent := TU_RdStr')
  1294. assert s.count(old) == 1, 'the string-read arm found %d times -- update this mutation' % s.count(old)
  1295. open(p, 'w').write(s.replace(old, old.replace('TU_RdStr', 'TU_RdInt')))
  1296. PYX
  1297. then
  1298. if rebuild_compiler; then
  1299. expect_red "t40 red when a string read dispatches to TU_RdInt" \
  1300. "t40_readln" python3 tests/run_com_exec.py t40_readln
  1301. else
  1302. echo " FAIL: the compiler would not rebuild with the read dispatch on TU_RdInt"
  1303. fail=$((fail + 1))
  1304. fi
  1305. else
  1306. echo " BROKEN CASE: the string-read dispatch mutation did not apply"
  1307. fail=$((fail + 1))
  1308. fi
  1309. cp "$SAVED_C" Compiler.mod
  1310. if rebuild_compiler; then
  1311. if python3 tests/run_com_exec.py >/dev/null 2>&1; then
  1312. echo " ok: every executed fixture passes on the restored sources"
  1313. pass=$((pass + 1))
  1314. else
  1315. echo "NOT RESTORED: run_com_exec.py is red after restoring the sources"
  1316. python3 tests/run_com_exec.py 2>&1 | grep -i fail | head -3 | sed 's/^/ /'
  1317. fail=$((fail + 1))
  1318. fi
  1319. else
  1320. echo "NOT RESTORED: the compiler would not rebuild"
  1321. fail=$((fail + 1))
  1322. fi
  1323. echo
  1324. echo "== the second execution oracle (run_exec86.py)"
  1325. # Everything above runs the image under qemu-system-i386. This one runs the
  1326. # SAME image inside shell/Exec86.mod, this project's own in-process 8086
  1327. # interpreter, and requires its output to agree with BOTH the hand-derived .out
  1328. # and qemu, byte for byte. Two execution checks that could only ever agree
  1329. # with each other would be one check: the point of this one is that it was
  1330. # written against the 8086's own reference rather than against qemu, whose
  1331. # lowest CPU model is a 486 and whose `0F 84' is an ordinary JZ.
  1332. #
  1333. # So the only mutation worth writing here is one qemu cannot make at all - the
  1334. # interpreter's own reading of the machine. Cond is that reading: nibble 4 is
  1335. # JE, and inverting it swaps the two arms of every `=' in every program. The
  1336. # emitted bytes, the sizes and the compile matrix are untouched, because
  1337. # nothing is emitted here - the fault is in who interprets it.
  1338. #
  1339. # Exec86.mod is recompiled explicitly rather than left to the harness:
  1340. # ensure_exec86run() notices the source changed and RELINKS, but does not
  1341. # recompile it, so a mutated source with a stale object would link the good
  1342. # interpreter straight back in and stay green - which is the trap its own
  1343. # docstring records, and the reason this case compiles first.
  1344. #
  1345. # SAVED_E itself was taken at the top of this file, next to the EXIT trap that
  1346. # puts it back.
  1347. if python3 - <<'PYX'
  1348. p = 'Exec86.mod'
  1349. s = open(p).read()
  1350. old = "| 4H : r := ZF"
  1351. new = "| 4H : r := NOT ZF (* MUTATION: JE inverted *)"
  1352. assert s.count(old) == 1, 'the JE arm of Cond found %d times -- update this mutation' % s.count(old)
  1353. open(p, 'w').write(s.replace(old, new))
  1354. PYX
  1355. then
  1356. if $GM2 -fiso -c Exec86.mod >/dev/null 2>&1; then
  1357. expect_red "the interpreter's own oracle catches JE inverted" \
  1358. "t33_cmpops" python3 tests/run_exec86.py t33_cmpops
  1359. else
  1360. echo " FAIL: Exec86.mod would not compile with JE inverted"
  1361. fail=$((fail + 1))
  1362. fi
  1363. else
  1364. echo " BROKEN CASE: the Cond JE mutation did not apply"
  1365. fail=$((fail + 1))
  1366. fi
  1367. cp "$SAVED_E" Exec86.mod
  1368. # And the check on the RESTORED interpreter, because a green above could also
  1369. # come from a mutation that never took and an object left mutated by a run
  1370. # that died in between.
  1371. if $GM2 -fiso -c Exec86.mod >/dev/null 2>&1; then
  1372. if python3 tests/run_exec86.py >/dev/null 2>&1; then
  1373. echo " ok: run_exec86 green on the restored interpreter"
  1374. pass=$((pass + 1))
  1375. else
  1376. echo "NOT RESTORED: run_exec86.py is red after restoring Exec86.mod"
  1377. python3 tests/run_exec86.py 2>&1 | grep -i "fail" | head -3 | sed 's/^/ /'
  1378. fail=$((fail + 1))
  1379. fi
  1380. else
  1381. echo "NOT RESTORED: Exec86.mod would not recompile"
  1382. fail=$((fail + 1))
  1383. fi
  1384. echo
  1385. echo "== the R key: compile, poke, run, report (runtest.py)"
  1386. # The only check in the project that exercises CmdRun. Everything above looks
  1387. # at bytes, or at what qemu says the image does; this one drives the shell
  1388. # through a pty the way a person would, presses R, and compares the GUEST's
  1389. # output against the fixture's hand-derived .out - so it fails on things no
  1390. # byte check can see and no file records either, because R writes no file at
  1391. # all (which is itself asserted).
  1392. #
  1393. # The mutation is the poke loop's count. With n = 0 nothing is copied into
  1394. # the interpreter, loadHi stays where Clear86 left it - 0100h - and Run86
  1395. # faults on its very first step, "execution left the loaded image", before the
  1396. # guest has executed a single instruction. That is fast and deterministic, which
  1397. # matters: the obvious alternative (poking the image somewhere else) leaves the
  1398. # machine executing zeros and buys a step-limit timeout instead of a finding.
  1399. cp "$SAVED_SH" Shell.mod
  1400. if python3 - <<'PYX'
  1401. p = 'Shell.mod'
  1402. s = open(p).read()
  1403. old = " n := LinkSize () ;"
  1404. new = " n := 0 ; (* MUTATION: nothing is poked *)"
  1405. assert s.count(old) == 1, 'the poke count in CmdRun found %d times -- update this mutation' % s.count(old)
  1406. open(p, 'w').write(s.replace(old, new))
  1407. PYX
  1408. then
  1409. if make > ../tmp/nonvacuity.make.log 2>&1; then
  1410. expect_red "the R check catches an image that was never poked" \
  1411. "AH=4Ch exit" python3 tests/runtest.py
  1412. else
  1413. echo " FAIL: the shell would not rebuild with the poke loop neutered"
  1414. tail -5 ../tmp/nonvacuity.make.log | sed 's/^/ /'
  1415. fail=$((fail + 1))
  1416. fi
  1417. else
  1418. echo " BROKEN CASE: the CmdRun poke mutation did not apply"
  1419. fail=$((fail + 1))
  1420. fi
  1421. cp "$SAVED_SH" Shell.mod
  1422. if make > ../tmp/nonvacuity.make.log 2>&1; then
  1423. if python3 tests/runtest.py >/dev/null 2>&1; then
  1424. echo " ok: runtest green on the restored shell"
  1425. pass=$((pass + 1))
  1426. else
  1427. echo "NOT RESTORED: runtest.py is red after restoring Shell.mod"
  1428. python3 tests/runtest.py 2>&1 | grep -i "fail" | head -3 | sed 's/^/ /'
  1429. fail=$((fail + 1))
  1430. fi
  1431. else
  1432. echo "NOT RESTORED: the shell would not rebuild"
  1433. tail -5 ../tmp/nonvacuity.make.log | sed 's/^/ /'
  1434. fail=$((fail + 1))
  1435. fi
  1436. echo
  1437. echo "== 8086 legality of the conditional lowering (check_8086.py)"
  1438. # This whole section exists because of a fault that every other check in the
  1439. # project was blind to, and being blunt about WHY is the point of listing it.
  1440. #
  1441. # EmJcc and EmSetcc emitted `0F 8x rel16' and `0F 9x rel8'. `0F' is a
  1442. # 386-and-later opcode prefix; the 8086 has none. So EVERY conditional branch
  1443. # and EVERY comparison in EVERY compiled program was an illegal instruction on
  1444. # the machine this compiler targets. And all of the following were green while
  1445. # it was: the compile matrix, the .COM layout checker, the runtime golden, the
  1446. # emitter audit, and the whole execution suite answering correctly under qemu.
  1447. #
  1448. # Two reasons, and the second is the one worth keeping:
  1449. # 1. qemu-system-i386 has no 8086 model. Its lowest is 486, where `0F 84' is
  1450. # a perfectly ordinary JZ. So the execution oracle CANNOT see this class
  1451. # of fault, ever.
  1452. # 2. FCML is this project's INDEPENDENT disassembler, and FCML's -m16 mode is
  1453. # a 386. The one tool whose job is to say "this is not a real instruction"
  1454. # was architecturally guaranteed to agree with the bug.
  1455. #
  1456. # So a check was needed that asks the question nothing else was asking. The
  1457. # five mutations below are the mutations that check has to catch, and each was
  1458. # run by hand and confirmed red BEFORE this section existed.
  1459. #
  1460. # M4 and M5 are the interesting pair. M4 is a fault this project actually
  1461. # introduced while fixing the above: EmJcc jumps TO its target, but the 8086
  1462. # shape steps OVER a 3-byte EJMP, so the naive port inverts every conditional
  1463. # in every program. It was caught by execution, not by any byte check. M5 is
  1464. # the partial version -- the inversion dropped for the IF and CASE sites only,
  1465. # kept for FOR -- and MEASURING that is what produced clause H, because the
  1466. # check was blind to M5 as first written: IF declares nibble 4, CASE declares
  1467. # 5, they negate into each other, and both are declared, so nothing complained
  1468. # while every conditional in every program took the wrong path. FOR declares
  1469. # C and F, whose negations D and E are declared for nothing at all, so the
  1470. # whole-suite version was caught by luck.
  1471. #
  1472. # Note these need `rebuild_compiler' only to refresh comtest; check_8086.py
  1473. # relinks the fixtures itself. Getting that wrong is how this section's first
  1474. # draft reported a mutation as VACUOUS: the build was skipped, a stale comtest
  1475. # ran the GOOD compiler, and the check passed. A helper that exits non-zero
  1476. # makes `if mutate_x; then' false and the case is silently skipped, which looks
  1477. # exactly like a pass -- so rebuild_compiler is checked, not assumed.
  1478. # M1: the original defect, restored verbatim.
  1479. cp "$SAVED_C" Compiler.mod
  1480. if python3 - <<'PYX'
  1481. p = 'Compiler.mod'
  1482. s = open(p).read()
  1483. old = """ Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)
  1484. Ebyte (03H) ; (* rel8: step over the 3-byte EJMP *)
  1485. RETURN EmJmpNear (target) (* target = 0 => forward, see above *)"""
  1486. new = """ Ebyte (0FH) ; Ebyte (cc) ; Eword (0) ;
  1487. IF target = 0 THEN
  1488. RETURN nPatch
  1489. END ;
  1490. RETURN 0"""
  1491. assert s.count(old) == 1, 'EmJcc body found %d times -- update this mutation' % s.count(old)
  1492. open(p, 'w').write(s.replace(old, new))
  1493. PYX
  1494. then
  1495. if rebuild_compiler; then
  1496. expect_red "check_8086 catches a 0F 8x branch (the original bug)" \
  1497. "0F 84" python3 tests/check_8086.py
  1498. else
  1499. echo " FAIL: the compiler would not rebuild with the 0F branch"
  1500. fail=$((fail + 1))
  1501. fi
  1502. else
  1503. echo " BROKEN CASE: the 0F branch mutation did not apply"
  1504. fail=$((fail + 1))
  1505. fi
  1506. cp "$SAVED_C" Compiler.mod
  1507. # M2: the other original defect, SETcc plus the MOV AH,0 it needed.
  1508. cp "$SAVED_C" Compiler.mod
  1509. if python3 - <<'PYX'
  1510. p = 'Compiler.mod'
  1511. s = open(p).read()
  1512. old = """ Ebyte (0B8H) ; Eword (1) ; (* MOV AX,#0001 *)
  1513. Ebyte (JccShort (cc)) ; (* taken when the comparison HOLDS *)
  1514. Ebyte (01H) ; (* rel8: step over the DEC AX *)
  1515. Ebyte (48H) (* DEC AX *)"""
  1516. new = """ Ebyte (0FH) ; Ebyte (cc) ; Ebyte (0C0H) ;
  1517. EmMovAh0 ()"""
  1518. assert s.count(old) == 1, 'EmSetcc body found %d times -- update this mutation' % s.count(old)
  1519. open(p, 'w').write(s.replace(old, new))
  1520. PYX
  1521. then
  1522. if rebuild_compiler; then
  1523. expect_red "check_8086 catches a 0F 9x SETcc (the original bug)" \
  1524. "0F 9F C0" python3 tests/check_8086.py
  1525. else
  1526. echo " FAIL: the compiler would not rebuild with the 0F SETcc"
  1527. fail=$((fail + 1))
  1528. fi
  1529. else
  1530. echo " BROKEN CASE: the 0F SETcc mutation did not apply"
  1531. fail=$((fail + 1))
  1532. fi
  1533. cp "$SAVED_C" Compiler.mod
  1534. # M4: the polarity inversion, everywhere. Note the expected text is clause H's,
  1535. # not a shape complaint: every byte here is a legal 8086 shape, which is the
  1536. # entire reason a separate clause had to be written.
  1537. cp "$SAVED_C" Compiler.mod
  1538. if python3 - <<'PYX'
  1539. p = 'Compiler.mod'
  1540. s = open(p).read()
  1541. old = ' Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)'
  1542. new = ' Ebyte (JccShort (cc)) ; (* MUTATION: inversion dropped *)'
  1543. assert s.count(old) == 1, 'EmJcc Ebyte found %d times -- update this mutation' % s.count(old)
  1544. open(p, 'w').write(s.replace(old, new))
  1545. PYX
  1546. then
  1547. if rebuild_compiler; then
  1548. expect_red "clause H catches the branch polarity inverted everywhere" \
  1549. "but reading the source says" python3 tests/check_8086.py
  1550. else
  1551. echo " FAIL: the compiler would not rebuild with the inversion dropped"
  1552. fail=$((fail + 1))
  1553. fi
  1554. else
  1555. echo " BROKEN CASE: the polarity mutation did not apply"
  1556. fail=$((fail + 1))
  1557. fi
  1558. cp "$SAVED_C" Compiler.mod
  1559. # M5: the same inversion dropped for the IF and CASE sites ONLY. This one is
  1560. # the reason clause H exists: it was run by hand and the check stayed GREEN,
  1561. # and FOR's C/F nibbles were the only reason the whole-suite version (M4)
  1562. # happened to be caught.
  1563. cp "$SAVED_C" Compiler.mod
  1564. if python3 - <<'PYX'
  1565. p = 'Compiler.mod'
  1566. s = open(p).read()
  1567. old = ' Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)'
  1568. new = """ IF (cc = 84H) OR (cc = 85H) THEN
  1569. Ebyte (JccShort (cc)) (* MUTATION: no inversion here *)
  1570. ELSE
  1571. Ebyte (JccShortInv (cc))
  1572. END ;"""
  1573. assert s.count(old) == 1, 'EmJcc Ebyte found %d times -- update this mutation' % s.count(old)
  1574. open(p, 'w').write(s.replace(old, new))
  1575. PYX
  1576. then
  1577. if rebuild_compiler; then
  1578. expect_red "clause H catches the inversion dropped for IF and CASE only" \
  1579. "t22_case" python3 tests/check_8086.py
  1580. else
  1581. echo " FAIL: the compiler would not rebuild with the partial inversion"
  1582. fail=$((fail + 1))
  1583. fi
  1584. else
  1585. echo " BROKEN CASE: the partial-inversion mutation did not apply"
  1586. fail=$((fail + 1))
  1587. fi
  1588. cp "$SAVED_C" Compiler.mod
  1589. # And the check on the RESTORED compiler, so a green above cannot come from a
  1590. # mutation that failed to take and left the real defect in place.
  1591. if rebuild_compiler; then
  1592. if python3 tests/check_8086.py >/dev/null 2>&1; then
  1593. echo " ok: check_8086 green on the restored compiler"
  1594. pass=$((pass + 1))
  1595. else
  1596. echo "NOT RESTORED: check_8086.py is red after restoring Compiler.mod"
  1597. python3 tests/check_8086.py 2>&1 | grep -m3 -- ' - ' | sed 's/^/ /'
  1598. fail=$((fail + 1))
  1599. fi
  1600. else
  1601. echo "NOT RESTORED: the compiler would not rebuild"
  1602. fail=$((fail + 1))
  1603. fi
  1604. echo
  1605. echo "== the emitter-name audit of Compiler.mod (audit_helpers.py)"
  1606. # These need no rebuild: the audit reads the SOURCE, not the built object, so
  1607. # they are the cheapest cases here and they cover the module the audit used
  1608. # not to look at at all. That is the point of the section: the audit reported
  1609. # "every helper agrees with its name" for a module it had never examined, and
  1610. # EmXchgAxCx was `93` (XCHG BX,AX) under a name that says XCHG AX,CX for the
  1611. # whole life of the project. Two of these five are for faults that were real.
  1612. SAVED_C2=../tmp/nonvacuity.Compiler.mod.2
  1613. SAVED_R2=../tmp/nonvacuity.Runtime.mod.2
  1614. cp Compiler.mod "$SAVED_C2" || exit 1
  1615. cp Runtime.mod "$SAVED_R2" || exit 1
  1616. restore_audit_sources () {
  1617. cp "$SAVED_C2" Compiler.mod
  1618. cp "$SAVED_R2" Runtime.mod
  1619. }
  1620. AUD="python3 tests/audit_helpers.py"
  1621. # 1. THE fault. 91h is XCHG AX,CX; 93h is XCHG BX,AX. Both are one byte, so
  1622. # the compile matrix never moved and the byte counts never moved.
  1623. cp "$SAVED_C2" Compiler.mod
  1624. mutate Compiler.mod 's|^ Ebyte (91H)$| Ebyte (93H)|'
  1625. expect_red "audit catches XchgAxCx emitting XCHG BX,AX" \
  1626. "exchanges Ax and Bx" $AUD
  1627. restore_audit_sources
  1628. # 2. the coverage check itself. A parameter list that find_helpers does not
  1629. # accept is exactly how the real emitter was missed, and the inventory is
  1630. # scanned separately on purpose so this can be caught. Without the
  1631. # independent scan this case is silent, because both lists would come from
  1632. # the same parser and agree that the helper does not exist.
  1633. cp "$SAVED_C2" Compiler.mod
  1634. mutate Compiler.mod 's|^PROCEDURE EmXchgAxCx () ;$|PROCEDURE EmXchgAxCx (why : CARDINAL) ;|'
  1635. expect_red "audit reports an emitter it cannot reach, rather than skipping it" \
  1636. "never examined it" $AUD
  1637. restore_audit_sources
  1638. # 3. EmXchgAxDx was named EmMoveAxDx, which said MOV where the bytes say XCHG.
  1639. # 93h here is XCHG AX,BX - one letter away, the exact class of mistake the
  1640. # name is supposed to make impossible.
  1641. cp "$SAVED_C2" Compiler.mod
  1642. mutate Compiler.mod 's|^ Ebyte (92H)$| Ebyte (93H)|'
  1643. expect_red "audit catches XchgAxDx emitting XCHG BX,AX" \
  1644. "XchgAxDx" $AUD
  1645. restore_audit_sources
  1646. # 4. CmpArgW0's [BP+2] written as the 386 SIB form, which decodes on a 8086 as
  1647. # [SI+24h]. A real bug: the runtime was clearing the wrong memory.
  1648. cp "$SAVED_R2" Runtime.mod
  1649. mutate Runtime.mod 's| B (83H) ; B (7EH) ; B (2) ; B (0) ;| B (83H) ; B (7CH) ; B (24) ; B (0) ; B (0) ;|'
  1650. expect_red "audit catches the [SI+24h] encoding of [BP+2]" \
  1651. "memory base is 'si" $AUD
  1652. restore_audit_sources
  1653. # 5. MovAxSp is POP then PUSH, because MOV AX,[SP] does not exist on an 8086.
  1654. # Dropping the POP leaves the stack one word short - a fault in the shape,
  1655. # not in a byte value.
  1656. cp "$SAVED_C2" Compiler.mod
  1657. python3 - <<'PYEOF'
  1658. p='Compiler.mod'; s=open(p).read()
  1659. a=" Ebyte (58H) ; (* POP AX *)\n"
  1660. assert s.count(a)==1, "EmMovAxSp POP line not found -- update this mutation"
  1661. open(p,'w').write(s.replace(a, ""))
  1662. PYEOF
  1663. expect_red "audit catches MovAxSp with its POP missing" \
  1664. "MovAxSp" $AUD
  1665. restore_audit_sources
  1666. # 6. The two-instruction shape: IDIV is CWD then IDIV, and dropping the CWD
  1667. # leaves an un-sign-extended dividend in DX:AX. Both are still present as
  1668. # a two-step spec, so a missing step has to be visible.
  1669. cp "$SAVED_C2" Compiler.mod
  1670. mutate Compiler.mod 's| Ebyte (99H) ; Ebyte (0F7H) ; Ebyte (0F9H)| Ebyte (0F7H) ; Ebyte (0F9H)|'
  1671. expect_red "audit catches IDiv without the CWD that extends the dividend" \
  1672. "IDivAxCx" $AUD
  1673. restore_audit_sources
  1674. # 7. The byte under EmXorAl01's name, and the row in PATTERNS that was added
  1675. # to admit it. `34 01' is XOR AL,#01 - the boolean NOT, and the one emitter
  1676. # in Compiler.mod with no ModRM byte at all. A grammar row nobody has ever
  1677. # seen reject anything cannot be trusted to accept only the truth, so here
  1678. # is the rejection: `34 02' is the same length, decodes just as cleanly, and
  1679. # `not x' would flip bit 1 instead of bit 0.
  1680. cp "$SAVED_C2" Compiler.mod
  1681. mutate Compiler.mod 's|^ Ebyte (34H) ; Ebyte (01H)| Ebyte (34H) ; Ebyte (02H)|'
  1682. expect_red "audit catches EmXorAl01 emitting xor al,#2 under a name saying #1" \
  1683. "XorAl01" $AUD
  1684. restore_audit_sources
  1685. # 7b. The other half of that row: the opcode gate. 34h is XOR AL,#imm and
  1686. # 35h is XOR AX,#imm - a word, not a byte, under a name that says AL. The
  1687. # row is pinned to {034h} on purpose, and a pin that has never been asked
  1688. # to hold is a pin. The report is the one thing the row above cannot
  1689. # produce: with no reading at all, the helper falls out of the grammar.
  1690. cp "$SAVED_C2" Compiler.mod
  1691. mutate Compiler.mod 's|^ Ebyte (34H) ; Ebyte (01H)| Ebyte (35H) ; Ebyte (01H)|'
  1692. expect_red "the opcode gate rejects XOR AX under an XOR AL name" \
  1693. "no name pattern accepts it" $AUD
  1694. restore_audit_sources
  1695. if $AUD >/dev/null 2>&1; then
  1696. echo " ok: the audit passes on both restored sources"
  1697. pass=$((pass + 1))
  1698. else
  1699. echo "NOT RESTORED: the audit is red after restoring the sources"
  1700. $AUD 2>&1 | sed 's/^/ /'
  1701. fail=$((fail + 1))
  1702. fi
  1703. echo
  1704. echo "== the BP contract rt_exec.py checks before it starts a machine"
  1705. # wrchar and wrbool both borrowed BP to reach their argument -- [SP] is not
  1706. # encodable in 16-bit mode -- and neither saved it. The driver's cursor into
  1707. # the case record lives in BP precisely because BP is the one register an entry
  1708. # may keep, so "wrchar borrowed it and did not give it back" sent the second
  1709. # call to a garbage address, the machine triple-faulted, and the run printed the
  1710. # record header twice and hung. Both the golden and the audit call that shape
  1711. # CORRECT: the bytes are well formed, every branch is on a boundary, the size
  1712. # is unchanged, and the decode says exactly what it says. So the rule is now
  1713. # checked directly, and these two cases are what make that check more than a
  1714. # claim.
  1715. #
  1716. # rt_exec.py needs the whole runtime rebuilt and then boots 36 machines, so this
  1717. # section is the slow one. The baseline comes first and is asserted: a case
  1718. # that mutates a red tree proves nothing.
  1719. SAVED_R3=../tmp/nonvacuity.Runtime.mod.3
  1720. cp Runtime.mod "$SAVED_R3" || exit 1
  1721. if rebuild; then
  1722. if python3 tests/rt_exec.py >/dev/null 2>&1; then
  1723. echo " ok: baseline - rt_exec.py passes on the unmutated runtime"
  1724. pass=$((pass + 1))
  1725. else
  1726. echo " FAIL: the baseline is already red, so the cases below prove"
  1727. echo " nothing - fix the baseline before reading them"
  1728. python3 tests/rt_exec.py 2>&1 | tail -3 | sed 's/^/ /'
  1729. fail=$((fail + 1))
  1730. fi
  1731. else
  1732. echo " FAIL: could not rebuild the runtime for the baseline"
  1733. fail=$((fail + 1))
  1734. fi
  1735. # 1. THE fault: drop the PUSH, exactly as EmitWrChar was written. This is the
  1736. # shape the behavioural case found, so the byte-level check must find it too
  1737. # -- a check that only the expensive test can trip is a check that has not
  1738. # been made to earn its place.
  1739. cp "$SAVED_R3" Runtime.mod
  1740. python3 - <<'PYEOF'
  1741. p = 'Runtime.mod'
  1742. s = open(p).read()
  1743. a = ' M ("wrchar") ;\n PushBp ; MovBpSp ;\n'
  1744. assert s.count(a) == 1, "EmitWrChar prologue not found exactly once"
  1745. open(p, 'w').write(s.replace(a, ' M ("wrchar") ;\n MovBpSp ;\n'))
  1746. PYEOF
  1747. if rebuild; then
  1748. expect_red "the BP contract catches wrchar borrowing BP unsaved" \
  1749. "borrows BP but does not open with" python3 tests/rt_exec.py
  1750. else
  1751. echo " FAIL: the runtime would not rebuild with the PUSH removed"
  1752. fail=$((fail + 1))
  1753. fi
  1754. cp "$SAVED_R3" Runtime.mod
  1755. # 2. The mirror image: push it and never pop it. A different one-instruction
  1756. # omission with the same consequence for a caller, and the reason the rule
  1757. # asks for the 5D and not just the 55.
  1758. cp "$SAVED_R3" Runtime.mod
  1759. mutate Runtime.mod 's|^ MovSpBp ; PopBp ;$| MovSpBp ;|'
  1760. if rebuild; then
  1761. expect_red "the BP contract catches a BP that is pushed and never popped" \
  1762. "pushes BP but never pops it" python3 tests/rt_exec.py
  1763. else
  1764. echo " FAIL: the runtime would not rebuild with the POP removed"
  1765. fail=$((fail + 1))
  1766. fi
  1767. cp "$SAVED_R3" Runtime.mod
  1768. # 3. The scan's other silent failure: a rule that matches nothing looks exactly
  1769. # like a rule that passes. The pattern the check looks for is changed to one
  1770. # the blob does not contain -- MOV BP,DI, which the runtime has no reason to
  1771. # emit -- so the check has examined thirteen entries and matched nothing and
  1772. # MUST say so rather than report a clean sweep. This is the general shape of
  1773. # the fault this project keeps making: a check whose SUBJECT has drifted
  1774. # reports a confident answer about the wrong thing.
  1775. cp "$SAVED_R3" Runtime.mod
  1776. SAVED_X=../tmp/nonvacuity.rt_exec.py
  1777. cp tests/rt_exec.py "$SAVED_X" || exit 1
  1778. mutate tests/rt_exec.py 's|^MOV_BP_SP = b"\\x8b\\xec" .*$|MOV_BP_SP = b"\\x8b\\xed" # MOV BP,DI: never emitted|' \
  1779. expect_red "a check that matched nothing is a failure, not a pass" \
  1780. "matched nothing" python3 tests/rt_exec.py
  1781. cp "$SAVED_X" tests/rt_exec.py
  1782. if rebuild; then
  1783. if python3 tests/rt_exec.py >/dev/null 2>&1; then
  1784. echo " ok: rt_exec.py passes on the restored source"
  1785. pass=$((pass + 1))
  1786. else
  1787. echo "NOT RESTORED: rt_exec.py is red after restoring Runtime.mod"
  1788. python3 tests/rt_exec.py 2>&1 | tail -3 | sed 's/^/ /'
  1789. fail=$((fail + 1))
  1790. fi
  1791. else
  1792. echo "NOT RESTORED: the runtime would not rebuild"
  1793. fail=$((fail + 1))
  1794. fi
  1795. # 4. The GOLDEN and the entry goldens, which are the other half of the same
  1796. # rule. rt_exec.py states the contract; check_runtime.py pins the bytes.
  1797. # They are separate mechanisms and the case below is what shows the golden
  1798. # one works on its own -- a re-baseline of runtime.golden would otherwise
  1799. # have absorbed the new prologues silently, and the next person to bless it
  1800. # would have no way to know the PUSH and POP were ever missing.
  1801. cp "$SAVED_R3" Runtime.mod
  1802. python3 - <<'PYEOF'
  1803. p = 'Runtime.mod'
  1804. s = open(p).read()
  1805. a = ' M ("wrchar") ;\n PushBp ; MovBpSp ;\n MovAlArg4 ;\n MovSpBp ; PopBp ;\n'
  1806. assert s.count(a) == 1, "EmitWrChar frame not found exactly once"
  1807. open(p, 'w').write(s.replace(a, ' M ("wrchar") ;\n MovBpSp ;\n MovAlArg2 ;\n MovSpBp ;\n'))
  1808. PYEOF
  1809. if rebuild; then
  1810. expect_red "the entry golden catches wrchar without its PUSH BP" \
  1811. "entry wrchar starts 8B EC" python3 tests/check_runtime.py "$DUMP"
  1812. else
  1813. echo " FAIL: the runtime would not rebuild with wrchar's frame removed"
  1814. fail=$((fail + 1))
  1815. fi
  1816. cp "$SAVED_R3" Runtime.mod
  1817. echo
  1818. echo "== the .COM layout check, and the runtime size it now measures"
  1819. # The checker used to RESTATE the runtime's size as a literal. It had drifted
  1820. # from the runtime it described, so the header was read out of the code stream
  1821. # and EVERY linked fixture "failed" on it - a whole file of "failures" that were
  1822. # not findings at all. A duplicated constant that has drifted does not fail
  1823. # loudly; it re-reports the same falsehood, in which the real failures hide.
  1824. # The size is now MEASURED from the image.
  1825. #
  1826. # These cases corrupt a real emitted .COM and require the checker to notice.
  1827. # They need the images, so they are built once and copied; the checker has a
  1828. # --check-only mode for exactly this, because its scratch directory is normally
  1829. # deleted on exit and a check that has only ever seen the truth is not a check.
  1830. KEEPDIR=../tmp/nonvacuity.com
  1831. rm -rf "$KEEPDIR"
  1832. TP_COM_KEEP=1 tests/run_com_tests.sh >../tmp/nonvacuity.com.log 2>&1
  1833. KEEP=$(sed -n 's/^TP_COM_KEEP=1: images left in //p' \
  1834. ../tmp/nonvacuity.com.log | tail -1)
  1835. if [ -z "$KEEP" ] || [ ! -d "$KEEP" ]; then
  1836. echo " FAIL: could not obtain emitted .COM images for the layout cases"
  1837. fail=$((fail + 1))
  1838. else
  1839. COMCHK="tests/run_com_tests.sh --check-only"
  1840. # 0. The baseline. Every case below is a claim that a specific assertion
  1841. # turns red, and none of them means anything if the copies of untouched
  1842. # images already fail. (The stale RT_SZ produced exactly that: a whole
  1843. # file of "failures" that were not findings.) So this is asserted first,
  1844. # and a failure here is reported as a broken baseline rather than a red
  1845. # test.
  1846. #
  1847. # The baseline is also WHERE THE HEADER OFFSET COMES FROM. Cases 1 and 2
  1848. # used to carry it as the literal 435 and 439, which were ENT_SZ + the
  1849. # runtime size at the time -- 432. Two 4-byte changes to the runtime
  1850. # later, both cases were editing the wrong bytes: 435 had become four
  1851. # bytes inside the runtime itself, so case 1 had stopped testing "the
  1852. # header cannot be found" and had started testing "the checker also
  1853. # notices you scribbled on the code", and case 2 had become a no-op
  1854. # that wrote the header where it already was. Both still went red, for
  1855. # reasons the messages did not name, which is the whole problem: a
  1856. # hard-coded offset is a claim about the world that expires silently.
  1857. #
  1858. # So the offset is read back out of the checker's own report on the
  1859. # untouched images, and the expected numbers below are ARITHMETIC ON IT.
  1860. # If the runtime grows again, these cases still test what they say.
  1861. rm -rf "$KEEPDIR"; mkdir -p "$KEEPDIR"
  1862. cp "$KEEP"/*.COM "$KEEP"/raw.txt "$KEEPDIR"/
  1863. BASE_OUT=$($COMCHK "$KEEPDIR" 2>&1)
  1864. if [ $? -eq 0 ]; then
  1865. echo " ok: baseline - untouched copies of the real images all pass"
  1866. pass=$((pass + 1))
  1867. else
  1868. echo " FAIL: the baseline is already red, so the cases below prove"
  1869. echo " nothing - fix the baseline before reading them"
  1870. printf '%s\n' "$BASE_OUT" | grep FAIL | head -3 | sed 's/^/ /'
  1871. fail=$((fail + 1))
  1872. fi
  1873. BASE_RT=$(printf '%s\n' "$BASE_OUT" \
  1874. | sed -n 's/.*measured runtime size: \([0-9][0-9]*\) bytes.*/\1/p' \
  1875. | head -1)
  1876. if [ -z "$BASE_RT" ]; then
  1877. echo " FAIL: the checker did not report the runtime size it measured,"
  1878. echo " so the cases below cannot find the header to edit"
  1879. fail=$((fail + 1))
  1880. BASE_RT=0
  1881. fi
  1882. # The layout constants are ENT_SZ 3 and HDR_SZ 16 (tests/comimage.py), so the
  1883. # header sits at hdrOff = 3 + rtSz and the entry jump's displacement must be
  1884. # (hdrOff + 16) - 3. The wanted number is therefore computed from the header
  1885. # OFFSET, not from rtSz: the two differ by 3, and getting that backwards
  1886. # produces a plausible-looking expectation three bytes out, which is how
  1887. # this case came to expect "want 452" and then be reported as not proving
  1888. # what it said.
  1889. BASE_OFF=$((3 + BASE_RT))
  1890. # Case 2 claims a runtime four bytes LONGER, so the header - and with it the
  1891. # demanded jump target - moves four bytes further on.
  1892. SHIFTED_WANT=$((BASE_OFF + 4 + 16 - 3))
  1893. echo " (measured runtime size $BASE_RT, header at image offset $BASE_OFF)"
  1894. # 1. Break hdrDS so it no longer ties the header to its own offset. The
  1895. # header must become UNFINDABLE and be reported as such - a checker that
  1896. # fell back to a remembered offset would report a confident number here,
  1897. # which is the failure mode the measurement was introduced to remove.
  1898. rm -rf "$KEEPDIR"; mkdir -p "$KEEPDIR"
  1899. cp "$KEEP"/*.COM "$KEEP"/raw.txt "$KEEPDIR"/
  1900. python3 - "$KEEPDIR/t01_minimal.COM" "$BASE_OFF" <<'PYEOF'
  1901. import sys
  1902. p, off = sys.argv[1], int(sys.argv[2])
  1903. d = bytearray(open(p, 'rb').read())
  1904. d[off + 4:off + 6] = (0x1234).to_bytes(2, 'little') # hdrDS, no longer self-consistent
  1905. open(p, 'wb').write(bytes(d))
  1906. PYEOF
  1907. expect_red "a header that cannot be located is reported, not assumed" \
  1908. "no program header found" $COMCHK "$KEEPDIR"
  1909. # 2. A complete, self-consistent header four bytes later, so the measured
  1910. # runtime size becomes $((BASE_RT + 4)) instead of $BASE_RT. This is the
  1911. # positive half of the same check: the derivation must FOLLOW the file,
  1912. # and the entry jump assertion - expressed in terms of the measurement -
  1913. # must follow it too, demanding $SHIFTED_WANT rather than $((BASE_OFF + 16 - 3)).
  1914. #
  1915. # hdrCS is copied from the header already in the file rather than written
  1916. # as a literal. It used to be the literal 464+100h, which was the image
  1917. # length when the image was 720 bytes; four bytes of runtime later it was
  1918. # 464+100h against a 724-byte image, so this case was ALSO failing on
  1919. # hdrCS, for a reason three lines below the one it was written to test.
  1920. rm -rf "$KEEPDIR"; mkdir -p "$KEEPDIR"
  1921. cp "$KEEP"/*.COM "$KEEP"/raw.txt "$KEEPDIR"/
  1922. python3 - "$KEEPDIR/t01_minimal.COM" "$BASE_OFF" "$SHIFTED_WANT" <<'PYEOF'
  1923. import sys
  1924. p, off, want = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
  1925. d = bytearray(open(p, 'rb').read())
  1926. hdrCS = int.from_bytes(d[off + 2:off + 4], 'little') # unchanged: still the image end
  1927. off += 4
  1928. ds = off + 0x1000 + 0x100
  1929. w = [1, hdrCS, ds, ds + 4, 0, 0, 0, 0]
  1930. for i, x in enumerate(w):
  1931. d[off + 2 * i:off + 2 * i + 2] = x.to_bytes(2, 'little')
  1932. open(p, 'wb').write(bytes(d))
  1933. PYEOF
  1934. expect_red "the measured runtime size follows the image ($BASE_RT -> $((BASE_RT + 4)))" \
  1935. "want $SHIFTED_WANT" $COMCHK "$KEEPDIR"
  1936. # 3. The entry jump's opcode. One byte, and the only assertion in the
  1937. # project that can see where execution STARTS.
  1938. rm -rf "$KEEPDIR"; mkdir -p "$KEEPDIR"
  1939. cp "$KEEP"/*.COM "$KEEP"/raw.txt "$KEEPDIR"/
  1940. python3 - "$KEEPDIR/t01_minimal.COM" <<'PYEOF'
  1941. import sys
  1942. p = sys.argv[1]
  1943. d = bytearray(open(p, 'rb').read())
  1944. d[0] = 0xEA
  1945. open(p, 'wb').write(bytes(d))
  1946. PYEOF
  1947. expect_red "the entry jump must be E9, not a near JMP" \
  1948. "not the E9 of the entry jump" $COMCHK "$KEEPDIR"
  1949. # 4. The entry jump's target, moved one instruction earlier. A .COM that
  1950. # lands in the middle of the prologue runs, prints something and exits
  1951. # cleanly, so no size or structure check can see this.
  1952. rm -rf "$KEEPDIR"; mkdir -p "$KEEPDIR"
  1953. cp "$KEEP"/*.COM "$KEEP"/raw.txt "$KEEPDIR"/
  1954. python3 - "$KEEPDIR/t01_minimal.COM" <<'PYEOF'
  1955. import sys
  1956. p = sys.argv[1]
  1957. d = bytearray(open(p, 'rb').read())
  1958. d[1:3] = (100).to_bytes(2, 'little')
  1959. open(p, 'wb').write(bytes(d))
  1960. PYEOF
  1961. expect_red "the entry jump must land on the first instruction" \
  1962. "entry jump rel16=100" $COMCHK "$KEEPDIR"
  1963. rm -rf "$KEEPDIR"
  1964. fi
  1965. echo
  1966. echo "non-vacuity: $pass ok, $fail failed"
  1967. [ "$fail" -eq 0 ]