nonvacuity.sh 94 KB

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