audit_helpers.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. #!/usr/bin/env python3
  2. """audit_helpers.py -- check that Runtime.mod's one-liner emitter procedures
  3. emit the instruction their name claims.
  4. Why this exists
  5. ---------------
  6. Runtime.mod hand-assembles 8086 by writing raw bytes. Most of it is wrapped
  7. up as one-line helpers:
  8. PROCEDURE MovSiBx ; BEGIN B (89H) ; B (0DCH) END MovSiBx ;
  9. and those names are the only documentation of what the bytes mean. That is
  10. exactly the setup for a silent, expensive mistake: write the right opcode and
  11. the wrong ModRM, and nothing complains. It happened twice here, in the same
  12. direction both times:
  13. MovSiBx emitted 89 DC -- which is MOV SP,BX, not MOV SI,BX
  14. CmpSiBx emitted 39 DC -- ditto, CMP SP,BX
  15. The comment next to CmpSiBx even spelled the ModRM out as "11 011 100" and
  16. still got it wrong, because 11 011 100 in mod=11 means rm=100=SP; SI is
  17. rm=100 only in mod=00, where it means [SI]. Both bugs shipped together into
  18. EmitWrInt, which then stored decimal digits through an SI register it had
  19. never initialised. The structural checks in check_runtime.py could not see
  20. any of this: the bytes decoded cleanly, the sweep stayed in sync, the branch
  21. targets were all on boundaries and none of the entry prologues moved. Only a
  22. *name* versus a *decode* comparison finds it, because only that knows what
  23. the author was trying to say.
  24. So: for every helper whose body is a literal byte list, disassemble those
  25. bytes with FCML and require the decode to match the name. The name grammar
  26. is deliberately narrow and mechanical:
  27. <Op><Dest><Src> e.g. MovSiBx, StDiAx, CmpSpBx, MovDlSi
  28. <Op><Reg> e.g. XorAxAx, NegAx, NotDx, IncSi, DecSi
  29. with Op in {Mov, Lea, St, Ld, Cmp, Add, Sub, Xor, And, Or, Not, Inc, Dec,
  30. Push, Pop, Int, Jmp, Jne, Jge, Jnl, Jle, Jl, Je, Jae, Jbe, Jb, Ja, JaE...}
  31. and the register/operand words below. A helper whose name does not parse is
  32. reported as UNPARSED rather than silently skipped -- a name the grammar does
  33. not understand is a name we are not checking, and that must be visible.
  34. This is a source-level check, so it needs no re-baselining: it is a function
  35. of the current source, and it gets stricter as more names are added to the
  36. grammar. It also runs without building anything.
  37. Usage: audit_helpers.py [MODULE.mod] # default ../Runtime.mod
  38. audit_helpers.py -v # print every helper, passing or not
  39. """
  40. import os
  41. import re
  42. import sys
  43. HERE = os.path.dirname(os.path.abspath(__file__))
  44. SHELL = os.path.dirname(HERE)
  45. sys.path.insert(0, HERE)
  46. import disasm16 # noqa: E402 (path set above)
  47. # An emitter may be declared with or without a parameter list, so the
  48. # parentheses are optional. This is not cosmetic: the version that required
  49. # `PROCEDURE Name ;` matched ZERO of Compiler.mod's 22 emitters, because they
  50. # are all declared `PROCEDURE EmName () ;`. So the audit reported "everything
  51. # agrees" for a module where it had examined nothing - a check that cannot fail
  52. # is not a check.
  53. RE_PROC_HEAD = re.compile(
  54. r"^PROCEDURE\s+(\w+)\s*(?:\(\s*\))?\s*;", re.MULTILINE)
  55. RE_ANY_PROC = re.compile(r"^PROCEDURE\s+(\w+)", re.MULTILINE)
  56. # --- what the one-line grammar deliberately does NOT reach ----------------
  57. #
  58. # The name audit checks procedures whose body is a list of CONSTANT bytes, so
  59. # that the bytes can be disassembled and compared against the name. Three
  60. # kinds of emitter cannot be checked that way, and all three are listed here
  61. # with their reason. A name in this table is a documented exclusion; a name
  62. # that is merely absent is a finding, and the coverage check below is what
  63. # tells the two apart.
  64. #
  65. # 1. PARAMETERISED operands -- a byte that is a parameter, not a literal.
  66. # `SubAl (v)` emits 2C v, which disassembles to "sub al, 0" whatever v is,
  67. # so the name can be checked only by also trusting the source order. The
  68. # grammar could learn this (the pattern Int([0-9A-Fa-f]+) already handles
  69. # the analogous case for INT); it does not yet, and until it does these are
  70. # unchecked BY THE AUDIT, not verified.
  71. # 2. COMPUTED or DISPATCHED bytes -- a ModRM chosen by a comparison, a
  72. # rel16 with a patch slot, a form that depends on which kind of variable it
  73. # is. There is no single byte sequence to disassemble.
  74. # 3. DATA, not code -- the B(...) calls here emit the D_ block, so running
  75. # them through a disassembler yields "add [bx+si],al" and a decode error.
  76. # tests/check_runtime.py pins these bytes against runtime.golden, so they
  77. # are pinned; only the name-to-opcode correspondence does not apply.
  78. #
  79. # Named per module because the same name can be a one-liner in one and not the
  80. # other. The Vx family in Runtime.mod is the reason a name is worth listing
  81. # separately: those four ARE audited, by audit_vx_helpers, because their shape
  82. # is fixed even though their immediate is a data offset.
  83. PARAM = "parameterised operand - the byte is an argument, not a literal"
  84. COMP = "computed or dispatched bytes - no single sequence to disassemble"
  85. DATA = "emits DATA (the D_ block), not instructions"
  86. NON_ONE_LINE = {
  87. "Runtime.mod": {
  88. # Real (MBF) entry helpers whose operands are data/field offsets or
  89. # immediates; each is a fixed sequence, pinned by rt_exec's MBF cases.
  90. "MovAxImm": COMP, "Jmp8": COMP, "AndDhImm": COMP,
  91. "StDiOffBx": COMP, "StDiOffDx": COMP,
  92. # The MBF core's parameterised moves and data-byte helpers. Each is
  93. # a fixed instruction/sequence; real_add/real_sub's 16 rt_exec cases
  94. # pin the behaviour (alignment, add/sub, normalisation, sign).
  95. "AdcBxImm": COMP, "AdcDxImm": COMP, "AddAhImm": COMP,
  96. "AndDataImm": COMP, "Call": COMP, "CmpClImm": COMP,
  97. "LdAlData": COMP, "LdClData": COMP, "LdCxDiOff": COMP,
  98. "LdCxSiOff": COMP, "LdDiDiOff": COMP, "LdDxSiOff": COMP,
  99. "LdSiDiOff": COMP, "MovClImm": COMP, "OrDhImm": COMP,
  100. "OrDiImm": COMP, "StDataCl": COMP, "StDataDi": COMP, "StDataImm": COMP,
  101. "SubClImm": COMP, "TestDhImm": COMP, "TestDataImm": COMP,
  102. "XorDhData": COMP, "XorDiData": COMP, "XorDataDh": COMP,
  103. "XorDataImm": COMP, "PushBp4": COMP,
  104. # remult/testexp helpers. The multiplication is pinned by rt_exec's
  105. # ten real_mul cases, including zero, cancellation and signs.
  106. "AdcBxData": COMP, "AdcDxData": COMP, "AddAhData": COMP,
  107. "AddAlImm": COMP, "AndChImm": COMP, "JccNear": COMP,
  108. "JmpNear": COMP, "MovDiData": COMP, "MovSiImm": COMP,
  109. "StDataAx": COMP, "StDataBx": COMP, "StDataCh": COMP,
  110. "StDataCx": COMP, "StDataDx": COMP, "StDataSi": COMP,
  111. # rediv's memory-operand compares/subtracts and result loads. The
  112. # displacement is a parameter, so the bytes cannot be disassembled as
  113. # a fixed sequence; rt_exec's fourteen real_div cases pin them.
  114. "CmpDxData": COMP, "CmpBxData": COMP, "CmpAhData": COMP,
  115. "MovCxData": COMP, "MovBxData": COMP, "MovDxData": COMP,
  116. "SbbBxData": COMP, "SbbDxData": COMP,
  117. "SubAhData": COMP, "StDataAl": COMP,
  118. "MovBxImm": PARAM, "MovCxImm": PARAM, "MovDxImm": PARAM,
  119. "MovDl": PARAM, "MovAlD": PARAM, "MovAh": PARAM,
  120. "MovDhImm": PARAM, "MovChImm": PARAM, "OrChImm": PARAM,
  121. "TestChImm": PARAM, "StSiImm": PARAM,
  122. # the fmtreal/ascreal data-offset and parameterised stores. Each is a
  123. # fixed sequence with a parameter/address, so there is no single set of
  124. # literal bytes to disassemble; rt_exec's exact-output cases pin them.
  125. "MovBxDataAddr": COMP, "MovSiData": COMP, "StDataByte": COMP,
  126. "MovBxByte": COMP, "MovBxOff1Byte": COMP, "TestDiOffImm": COMP,
  127. "XorDiOffImm": COMP, "LdBxDiOff": COMP, "LdDxDiOff": COMP,
  128. "LeaDiBxData": COMP, "MovAxData": COMP,
  129. "AddAxImm": COMP, "AddChImm": COMP, "AddClImm": COMP,
  130. "AndBlImm": COMP, "AndClImm": COMP, "CmpAxImm": COMP,
  131. "CmpBxByte": COMP, "CmpDxImm": COMP, "CmpSiData": COMP,
  132. "DecData": COMP, "AndAhImm": COMP, "AndAxImm": COMP,
  133. "CmpAhImm": COMP, "TestAhImm": COMP, "TestAxImm": COMP,
  134. "SubAl": PARAM, "CmpAl": PARAM, "AddDl": PARAM, "J8": COMP,
  135. "Jcc": COMP, "CmpCxV": PARAM,
  136. "B": DATA, "C8": DATA,
  137. # File control-block operations: a multi-instruction routine with
  138. # labels and raw DOS sequences, not a one-line ModRM helper. Its
  139. # bytes are pinned by rt_exec's file_assign case and the runtime
  140. # golden; the name grammar cannot read a whole routine.
  141. "EmitFileOps": COMP,
  142. },
  143. "Compiler.mod": {
  144. "FileIo": COMP, # typed-file INT 21h sequence; see EmFileIo
  145. "InlineCh": COMP, # emits a string blob, not one instruction
  146. "InlineCrLf": COMP, # emits a string blob, not one instruction
  147. "PushRealAddr": COMP, "PushRealSlot": COMP,
  148. "AsciiZLiteral": COMP, "XorByteGlob": COMP,
  149. "CopyRealTo": COMP,
  150. "AddSp": PARAM, "SubSp": PARAM, "Setcc": PARAM,
  151. "MovChImm": PARAM,
  152. "Call": COMP, "Jcc": COMP, "JmpNear": COMP,
  153. "BpDisp": COMP, "LoadVar": COMP, "StoreVar": COMP,
  154. "PushVarAddr": COMP, "MovAxi": COMP, "CmpAxi": COMP,
  155. "MovCxi": COMP, "LeaDi": COMP,
  156. # PushStrAddr is PushVarAddr's sibling one level up: it pushes the
  157. # ADDRESS of a whole-string operand, and a string LITERAL has no storage
  158. # to take the address of, so it emits the literal INLINE - a jump over
  159. # it, then <len><chars> - and pushes the address of those bytes. The
  160. # emitted sequence therefore depends on the operand: a variable is a
  161. # single EmPushVarAddr, a literal is two bytes of jump plus the string
  162. # itself. That is COMP, not PARAM (whose immediate varies but whose
  163. # opcode does not). Listed here rather than left out: an emitter the
  164. # name grammar cannot describe has to be written down, or the report is
  165. # green and the helper unchecked.
  166. "PushStrAddr": COMP,
  167. # SetBlob is PushStrAddr's sibling for sets: a set cannot fold to a
  168. # word, so its bytes travel inline - a JMP over them, then the bytes -
  169. # and the address of those bytes is the value. Like PushStrAddr the
  170. # emitted sequence depends on the operand (its length), so there is no
  171. # single sequence to disassemble; the LAYOUT it produces is pinned by
  172. # t61_setconst's .out instead.
  173. "SetBlob": COMP,
  174. # StrBlob is the string-literal blob on its own (factored out of
  175. # PushStrAddr so a string value parameter can copy from it); PushStrSlot
  176. # reserves a slot and copies a string value into it. Both emit data
  177. # behind a jump / a data-dependent byte loop, so there is no single
  178. # sequence to disassemble. The layouts they produce are pinned by the
  179. # string and string-parameter fixtures instead.
  180. "StrBlob": COMP,
  181. "PushStrSlot": COMP,
  182. # The CRT sequences (INT 10h) are one parameterised helper: several
  183. # instructions each, with no single name grammar. Listed, not left
  184. # implicit.
  185. "CrtSeq": COMP,
  186. # A VAR parameter's slot holds an ADDRESS. These three read and write
  187. # one level down: LoadVarInd fetches the pointer into BX and then the
  188. # byte/word at [BX]; StoreVarIndPrep parks the pointer in DI across the
  189. # right-hand side and StoreInd stores through it. The sequence depends
  190. # on the width (one byte or a word), so there is no single opcode to
  191. # name; t73_varparam's execution pins both widths, the local/global
  192. # address forms, passing one on, and READ through one.
  193. "LoadVarInd": COMP,
  194. "StoreVarIndPrep": COMP,
  195. "StoreInd": COMP,
  196. # The WITH/2-D field helpers. AddDiImm adds a record field's fixed
  197. # offset to an address already in DI; LdDiGlob and StDiGlob reload and
  198. # park that address in a data slot across a WITH body. Each is a fixed
  199. # 3-4 byte sequence whose operand is a data/field offset, and t77_with
  200. # pins the behaviour (2-D element, constant element, field offsets).
  201. "AddDiImm": COMP,
  202. "LdDiGlob": COMP,
  203. "StDiGlob": COMP,
  204. # Set-field helpers: store one constructor byte through DI
  205. # (StDiImm), and test one element's bit in a DI-addressed set
  206. # (LdAlDiOff + AndAlImm). t78_setfield pins both.
  207. "StDiImm": COMP,
  208. "LdAlDiOff": COMP,
  209. "AndAlImm": COMP,
  210. # A real copy through DI: one byte of the six.
  211. "StDiAlOff": COMP,
  212. # UpCase's byte tests and the 'a'..'z' fold.
  213. "CmpAlImm": COMP,
  214. "SubAlImm": COMP,
  215. # The run-time set bit test (`e in set'): shift/mask/index helpers.
  216. "MovClAl": COMP, "AndClImm": COMP,
  217. "MovBxi": COMP, "LeaBx": COMP, "MovBxDi": COMP,
  218. "AddBxAx": COMP, "LdAlBx": COMP, "MovDlImm": COMP,
  219. "AndAlDl": COMP,
  220. },
  221. }
  222. # The Vx family is NOT here: those four are audited by audit_vx_helpers,
  223. # because their shape is fixed even though their immediate is a data offset.
  224. # They are named explicitly rather than filtered out of VX_KINDS so that this
  225. # table stands on its own and a name added to VX_KINDS later cannot silently
  226. # become unchecked - it would instead be reported, which is the point.
  227. _NONLINE_VX = ("LdBxVx", "MovBxVx", "MovDxVx", "StVxBx")
  228. def scan_emitters(src):
  229. """Yield (name, text) for every PROCEDURE, however it is written.
  230. The INVENTORY side of the coverage check, and deliberately as dumb as it
  231. can be: a name at the start of a line, and everything up to the next one.
  232. It does not check the parameter list, does not look for BEGIN, does not
  233. care where comments are, and cannot be defeated by the same mistake twice.
  234. The reason it exists at all is that the other list - the one the audit
  235. actually reads - is produced by find_helpers, which is a real parser and
  236. therefore fails on real inputs (a parameter list it did not expect, a
  237. comment in the wrong place). Comparing a parser against itself finds
  238. nothing; comparing it against a scan that cannot parse anything finds
  239. exactly the cases where the parser is the thing that is wrong.
  240. """
  241. heads = list(RE_ANY_PROC.finditer(src))
  242. for k, h in enumerate(heads):
  243. stop = heads[k + 1].start() if k + 1 < len(heads) else len(src)
  244. yield h.group(1), src[h.end():stop]
  245. def find_helpers(src):
  246. """Yield (name, body) for every PROCEDURE, in source order.
  247. A documented emitter must be auditable, so text between the header and
  248. BEGIN - which is where the explanatory comment belongs, and the only place
  249. it can be read next to the code it describes - is allowed through. A
  250. regex that permitted it had nested quantifiers and took exponential time
  251. on these files, so this splits on procedure HEADERS instead and takes the
  252. text up to the next header. That is linear, and it also cannot read one
  253. procedure's bytes as another's.
  254. The header regex is still strict about the parameter list (empty only),
  255. because that is what distinguishes an emitter from a real routine.
  256. """
  257. heads = list(RE_PROC_HEAD.finditer(src))
  258. for k, h in enumerate(heads):
  259. stop = heads[k + 1].start() if k + 1 < len(heads) else len(src)
  260. chunk = src[h.end():stop]
  261. m = re.search(r"\bBEGIN\b(.*)\bEND\s+%s\s*;" % re.escape(h.group(1)),
  262. chunk, re.DOTALL)
  263. if not m:
  264. continue
  265. yield h.group(1), m.group(1)
  266. # The H suffix is optional: the source mixes B (8AH) and B (0) for the same
  267. # kind of literal, and a byte written without H used to be silently dropped
  268. # from the audit, which made three helpers look like truncated prefixes.
  269. #
  270. # BOTH B (...) and Ebyte (...) are accepted. Runtime.mod spells a byte B(v)
  271. # and Compiler.mod spells the same thing Ebyte(v); the Em prefix is on the
  272. # *procedure* names there, not on the byte call, so the byte regex has to cover
  273. # both spellings or Compiler.mod's 22 emitters are silently skipped - which is
  274. # what happened, and how EmXchgAxCx stayed wrong for its whole life with
  275. # correct byte counts and a green compile matrix.
  276. RE_BYTE = re.compile(r"(?:\bB|\bEbyte)\s*\(\s*([0-9A-Fa-f]+)H?\s*\)")
  277. # Both modules emit bytes, so both must be swept. Compiler.mod is where the
  278. # procedure-skip jump, the FOR test ordering and EmXchgAxCx (93h = XCHG BX,AX
  279. # where the name says XCHG AX,CX) all live: bugs that break every two-variable
  280. # arithmetic and comparison in every program, invisible because the audit
  281. # looked at Runtime.mod and found nothing wrong there.
  282. MODULES = ["Runtime.mod", "Compiler.mod"]
  283. # --- name grammar -----------------------------------------------------
  284. #
  285. # An ordered table of (name regex, mnemonic, operand specs, allowed opcodes).
  286. #
  287. # Why the opcode column exists
  288. # ----------------------------
  289. # "MovDlSi" and "MovBpSp" are ambiguous from the name alone: SI and BP are
  290. # both in the register list and in the memory-base list. What settles it is
  291. # the opcode, and the rule is the asymmetry that makes 16-bit hand-assembly
  292. # so error-prone:
  293. #
  294. # 88 /r MOV r/m8, r8 reg is the SOURCE (store)
  295. # 89 /r MOV r/m16, r16 reg is the SOURCE (store)
  296. # 8A /r MOV r8, r/m8 reg is the DESTINATION (load)
  297. # 8B /r MOV r16, r/m16 reg is the DESTINATION (load)
  298. #
  299. # A byte move (8A/88) to or from a bare base register can only be a memory
  300. # access, because "mov dl, si" is not an instruction. A word move (8B/89)
  301. # could be either, so for word moves the register reading is tried first.
  302. # Encoding that rule in the table, rather than in pattern order alone, is what
  303. # stops a helper being "verified" against the wrong reading of its own name.
  304. #
  305. # Operand spec tokens:
  306. #
  307. # "r:Name" a bare register spelled Name (Ax, Al, Dx, Si, Ds, ...)
  308. # "i:N" the immediate N; the name spells it in DECIMAL
  309. # "ih:N" like i: but the name spells it in HEX (only Int, whose
  310. # vector 21h FCML prints as "21h" and which reads as decimal
  311. # 33 if you do not notice)
  312. # "m:Base" memory at [Base], with no displacement
  313. # "m:Base+D" memory at [Base + D]
  314. #
  315. # "Arg" is the emitter's alias for BP: on entry BP points at the return
  316. # address, so a word argument starts at [BP+2]. Naming it "Arg" rather than
  317. # "Bp" is what stops these being misread as [BP] accesses, and it is also
  318. # how the grammar knows to expect the +2.
  319. #
  320. # "Arg" is the frame in which the entry did NOT push BP, and it is the only
  321. # one where the argument is two bytes up: an entry that pushes BP first has
  322. # moved it to +4, which is a different name and a different byte
  323. # (MovAlArg2 / MovAlArg4, CmpArg2W0 / CmpArg4W0). A name that says only
  324. # "Arg" always means +2, with no exceptions -- the alternatives to spelling
  325. # the displacement out were a Modula-2 parameter, which this audit cannot
  326. # see, and a comment, which nothing checks.
  327. #
  328. # A name matching NO pattern is reported UNPARSED, which counts as a failure
  329. # on purpose: a helper the audit cannot read is a helper nobody is checking.
  330. REGS = ["Ax", "Bx", "Cx", "Dx", "Si", "Di", "Bp", "Sp",
  331. "Al", "Bl", "Cl", "Dl", "Ah", "Bh", "Ch", "Dh"]
  332. # Segment registers: the 8086 can only PUSH/POP them, never MOV to or from
  333. # one, so they need names of their own.
  334. SEGS = ["Ds", "Es", "Cs", "Ss"]
  335. JCCS = ["Je", "Jne", "Jz", "Jnz", "Jge", "Jnl", "Jle", "Jl", "Ja", "Jae",
  336. "Jb", "Jbe", "Jg", "Jns", "Js", "Jo", "Jno", "Jp", "Jnp", "Jcxz",
  337. "Jecxz", "Jrcxz", "Loop", "Loope", "Loopne"]
  338. _ALT = "|".join(REGS)
  339. _ALT16 = "Ax|Bx|Cx|Dx|Si|Di|Bp|Sp"
  340. _BASE = "Si|Di|Bx|Bp|Sp|Arg|Data"
  341. _STORE = (0x88, 0x89) # reg is the source
  342. _LOAD = (0x8A, 0x8B) # reg is the destination
  343. PATTERNS = [
  344. # --- no-operand and fixed-operand forms -------------------------
  345. (re.compile(r"^RetR?$"), "ret", [], None),
  346. (re.compile(r"^LeaveR?$"), "leave", [], None),
  347. (re.compile(r"^Int([0-9A-Fa-f]+)$"), "int", ["ih:%(1)s"], {0xCD}),
  348. (re.compile(r"^(Push|Pop)(%s)$" % "|".join(SEGS)),
  349. None, ["r:%(2)s"], None),
  350. (re.compile(r"^(Push|Pop)(%s)$" % _ALT), None, ["r:%(2)s"], None),
  351. # --- jumps: the target is a fixup, so only the mnemonic is checked
  352. (re.compile(r"^(%s)(8|16)?$" % "|".join(JCCS)), None, [], None),
  353. (re.compile(r"^Jmp(%s)$" % _ALT), "jmp", ["r:%(1)s"], {0xFF}),
  354. # --- MUL names one operand; 16-bit DIV names two because it always
  355. # divides DX:AX, so the decode has an AX the name has no room for
  356. (re.compile(r"^Mul(%s)$" % _ALT), "mul", ["r:%(1)s"], {0xF7}),
  357. (re.compile(r"^Div(%s)$" % _ALT), "div", ["r:Ax", "r:%(1)s"], {0xF7}),
  358. # --- store: name is St<base><reg>, decode puts the register last --
  359. (re.compile(r"^St(%s)(%s)$" % (_BASE, _ALT)),
  360. "mov", ["m:%(1)s", "r:%(2)s"], _STORE),
  361. # --- load through a bare base register: Ld<reg><base> ------------
  362. # The mirror of the St pattern above, and spelled Ld rather than Mov on
  363. # purpose. `8A 07` and `8A C3` are one byte apart and do opposite
  364. # things: LdAlBx reads the byte AT the pointer in BX, MovAlBl takes the
  365. # low byte OF BX. Naming the first "MovAlBx" put the two one letter
  366. # apart, and getch's pushback path used the wrong one - it read memory
  367. # 010Ah, the address of the character, instead of the character. So the
  368. # grammar is part of the safety: Ld* may only be spelled for a memory
  369. # source, which is what distinguishes it from Mov*<reg><lowreg>.
  370. (re.compile(r"^Ld(%s)(%s)$" % (_ALT, _BASE)),
  371. "mov", ["r:%(1)s", "m:%(2)s"], (0x8A, 0x8B)),
  372. # --- XCHG is symmetric, so the name's operand order carries no
  373. # information and must not be checked positionally. 87 /r is
  374. # XCHG r/m16, r16, so FCML always prints the r/m operand first:
  375. # 87 C7 - reg=AX, rm=DI - decodes as "xchg di,ax" whichever way the
  376. # author thought about it. What the audit is really for here is the
  377. # PAIR: XchgAxDi must not come out as XCHG AX,CX. So the two
  378. # registers are compared as a set (see the "rx:" handling below).
  379. (re.compile(r"^Xchg(%s)(%s)$" % (_ALT, _ALT)),
  380. "xchg", ["rx:%(1)s|%(2)s"], {0x87, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,
  381. 0x97}),
  382. # 8-bit XCHG, 86 /r. The MBF intreal swaps DL and DH to move the low byte
  383. # of a 16-bit value into the exponent position.
  384. (re.compile(r"^Xchg(Al|Cl|Dl|Bl|Ah|Ch|Dh|Bh)(Al|Cl|Dl|Bl|Ah|Ch|Dh|Bh)$"),
  385. "xchg", ["rx:%(1)s|%(2)s"], {0x86}),
  386. # --- the accumulator-implicit XCHGs, 91h..97h, join the /r form -----
  387. # One byte, no ModRM, both registers fixed by the opcode. They are in
  388. # the same opcode set because the same `rx:` set comparison decides them,
  389. # and that comparison is exactly what catches 93h (XCHG BX,AX) under the
  390. # name XchgAxCx - the fault that broke every two-variable arithmetic
  391. # operation in every program. 90h is deliberately absent: it is NOP, and
  392. # FCML decodes it as "nop", not as an XCHG AX,AX.
  393. #
  394. # --- MOV r8, imm8 : B0+reg, and the AH-specific B4 form -----------
  395. # MOV AH,imm8 is B4 imm8, which is not B0+reg. The name says which
  396. # register, so the opcode is checked against it: B4 must be AH and B0+4
  397. # must not be. (The runtime's wrchar used to load the character with the
  398. # wrong register, so the store landed in AL-adjacent memory.)
  399. # B4 imm8 is MOV AH,imm8 and is NOT B0+reg, so AH and AL are listed
  400. # separately with their own opcodes rather than sharing one pattern that
  401. # would accept B4 under the name MovAl0.
  402. # --- shifts: by one, and by CL. The set membership test uses both:
  403. # D1 E8 (SHR AX,1) three times, and D2 E2 (SHL DL,CL) for the mask.
  404. # Shifts and rotates by one, byte and word. The MBF core shifts a 40-bit
  405. # mantissa with SHR/RCR and normalises with SHL/RCL.
  406. (re.compile(r"^(Shl|Shr|Rcl|Rcr|Rol|Ror|Sar)(%s)1$" % _ALT),
  407. None, ["r:%(2)s", "i:1"], {0xD0, 0xD1}),
  408. (re.compile(r"^Stc$"), "stc", [], {0xF9}),
  409. (re.compile(r"^Cmc$"), "cmc", [], {0xF5}),
  410. (re.compile(r"^Clc$"), "clc", [], {0xF8}),
  411. (re.compile(r"^Lahf$"), "lahf", [], {0x9F}),
  412. (re.compile(r"^Sahf$"), "sahf", [], {0x9E}),
  413. (re.compile(r"^LdChDiOff$"), "mov", ["r:Ch", "m:Di"], {0x8A}),
  414. (re.compile(r"^PushBp(4|6)$"), "push", ["m:Bp+%(1)s"], {0xFF}),
  415. (re.compile(r"^IncBxByte$"), "inc", ["m:Bx"], {0xFE}),
  416. (re.compile(r"^Adc(%s)(%s)$" % (_ALT16, _ALT16)),
  417. "adc", ["r:%(1)s", "r:%(2)s"], {0x11, 0x13}),
  418. (re.compile(r"^Sbb(%s)(%s)$" % (_ALT16, _ALT16)),
  419. "sbb", ["r:%(1)s", "r:%(2)s"], {0x18, 0x19, 0x1A, 0x1B}),
  420. (re.compile(r"^(Shl|Shr|Rcl|Rcr)(Al|Cl|Dl|Bl|Ah|Ch|Dh|Bh)Cl$"),
  421. None, ["r:%(2)s", "r:Cl"], {0xD2}),
  422. (re.compile(r"^Cbw$"), "cbw", [], {0x98}),
  423. (re.compile(r"^Imul(%s)$" % _ALT), "imul", ["r:%(1)s"], {0xF7}),
  424. # --- CMP reg,0 as a flag test (the 8086 has no OR reg,reg FCML can
  425. # decode here; CMP sets the same ZF/SF/CF for a non-negative reg) ---
  426. (re.compile(r"^CmpAl0$"), "cmp", ["r:Al", "i:0"], {0x3C}),
  427. (re.compile(r"^Cmp(Cl|Dl|Bl|Ah|Ch|Dh|Bh)0$"),
  428. "cmp", ["r:%(1)s", "i:0"], {0x80}),
  429. (re.compile(r"^MovAh(0|1)$"),
  430. "mov", ["r:Ah", "i:%(1)s"], {0xB4}),
  431. (re.compile(r"^MovAl(0|1)$"),
  432. "mov", ["r:Al", "i:%(1)s"], {0xB0}),
  433. # --- MUL/IMUL r/m16, accumulator implicit, /5 and /4 -----------------
  434. # The destination is AX:DX and the operand is the named register, so
  435. # "MulAxCx" means CX := CX, i.e. AX:DX := AX * CX. FCML prints only the
  436. # one explicit operand ("imul cx"), which is why the spec has one token.
  437. (re.compile(r"^Mul(%s)(%s)$" % (_ALT, _ALT)),
  438. "imul", ["r:%(2)s"], {0xF7}),
  439. # --- CmpArg<N>W0 : CMP WORD [BP+N],0 between MOV BP,SP / MOV SP,BP -----
  440. # An odd but exact shape: [SP] is not encodable, so the frame pointer is
  441. # borrowed for the one comparison and handed back untouched. The pair of
  442. # saves at the ends is what makes it correct, so the whole sequence is
  443. # checked - a missing MOV SP,BP would leave BP clobbered for the caller.
  444. #
  445. # The displacement is a CAPTURED GROUP, not a constant, and the name has to
  446. # spell it out. That is the rule that keeps CmpArg2W0 and CmpArg4W0
  447. # honest: they differ by one byte, and one byte is the difference between
  448. # reading a BOOLEAN and reading a character, so the name -- which is the
  449. # only thing this audit can read -- has to carry it. A single helper
  450. # taking the displacement as a Modula-2 parameter would decode correctly
  451. # under either name and be unchecked under both.
  452. (re.compile(r"^CmpArg(2|4)W0$"),
  453. None, [["mov", ["r:Bp", "r:Sp"]],
  454. ["cmp", ["m:Bp+%(1)s", "i:0"]],
  455. ["mov", ["r:Sp", "r:Bp"]]], {0x8B}),
  456. # --- a "Mov<reg>Sp" that is a POP/PUSH pair, not a memory access ----
  457. # MOV AX,[SP] does not exist on the 8086 at all, so the stack top is read
  458. # with POP and given back with PUSH: an observational no-op that leaves SP
  459. # where it found it. Named MovAxSp because that is the OPERATION, and the
  460. # two-step shape is recorded here because it is the only correct encoding.
  461. (re.compile(r"^Mov(%s)Sp$" % _ALT),
  462. None, [["pop", ["r:%(1)s"]], ["push", ["r:%(1)s"]]], None),
  463. # --- IDIV: CWD then IDIV r/m16, sign-extending into DX:AX ---------
  464. # A two-instruction shape, so the specs are a list of one list per
  465. # instruction. The CWD is not incidental: F7 /7 divides the 32-bit value
  466. # in DX:AX, and a signed dividend is only in DX:AX if CWD ran. Drop the
  467. # 99h and the divisor goes to the same place, so the pair is checked
  468. # together - which is the reason the sequence form exists.
  469. # FCML prints BOTH ends of a /r divide ("idiv ax, cx"), because the
  470. # accumulator is not implicit in the mnemonic the way it is for MUL, so
  471. # the spec needs two operands and the AX comes first.
  472. (re.compile(r"^I?Div(%s)(%s)$" % (_ALT, _ALT)),
  473. None, [["cwd", []], ["idiv", ["r:%(1)s", "r:%(2)s"]]], {0xF7}),
  474. # --- load a register from memory, with a displacement ------------
  475. # The displacement makes the name unambiguous, so any load opcode works.
  476. (re.compile(r"^Mov(%s)(%s)(\d+)$" % (_ALT, _BASE)),
  477. "mov", ["r:%(1)s", "m:%(2)s+%(3)s"], _LOAD),
  478. # --- two registers: MOV BP,SP / CMP SI,BX / XOR AX,AX / ADD DI,AX -
  479. # Tried before the bare-base reading below, because for a word move
  480. # "MovBpSp" means BP := SP and only "MovDlSi" means DL := [SI]. The two
  481. # readings cannot both match, because one demands a register operand
  482. # where the other demands a memory operand.
  483. # Xchg is NOT in this list. It has its own pattern above, which compares
  484. # the two registers as a SET because 87 /r is symmetric and FCML always
  485. # prints the r/m operand first - so the name's order carries no
  486. # information and must not be checked positionally. Listing Xchg here as
  487. # well gave it a second, ordered reading, and the audit then reported
  488. # "2 name readings fit the same bytes" for XchgAxCx: not a real ambiguity
  489. # in the code, but two overlapping rows in the grammar saying the same
  490. # thing. A grammar that can be satisfied two ways for one name is a
  491. # grammar that can be satisfied the wrong way.
  492. (re.compile(r"^(Mov|Cmp|Add|Sub|Xor|And|Or)(%s)(%s)$" % (_ALT, _ALT)),
  493. None, ["r:%(2)s", "r:%(3)s"], None),
  494. # --- byte move from a bare base register: necessarily memory ------
  495. # Restricted to 8A/88 on purpose: if this ever matched an 8B/89 it would
  496. # be a register move already claimed by the pattern above.
  497. (re.compile(r"^Mov(%s)(%s)$" % (_ALT, _BASE)),
  498. "mov", ["r:%(1)s", "m:%(2)s"], (0x8A, 0x88)),
  499. # --- immediate against a register --------------------------------
  500. (re.compile(r"^(Add|Sub|Cmp|Xor|And|Or)(%s)(\d+)$" % _ALT),
  501. None, ["r:%(2)s", "i:%(3)s"], {0x83}),
  502. # --- XOR AL,#imm8 is `34 ib': no ModRM byte at all, and only the
  503. # accumulator. The row above is pinned to 83 /r, which is the word
  504. # `op r, imm8' encoding, so `XorAl01' matched it and was rejected on
  505. # the opcode - leaving the helper with NO reading rather than a wrong
  506. # one, which is how the audit reported it. Narrow on purpose: 34 is
  507. # XOR AL, nothing else, so a name claiming `xor al, 1h' against any
  508. # other byte fails here. This is TPSRC9 neglevel's boolean NOT.
  509. (re.compile(r"^XorAl(\d+)$"),
  510. "xor", ["r:Al", "i:%(1)s"], {0x34}),
  511. # --- one register: INC CX / DEC SI / NOT DX / NEG AX ------------
  512. (re.compile(r"^(Inc|Dec|Not|Neg|Shl|Shr|Sar)(%s)$" % _ALT),
  513. None, ["r:%(2)s"], None),
  514. ]
  515. def register_word(tok):
  516. """Map an FCML operand token to a REGS/SEGS word, or None."""
  517. t = tok.strip().lower()
  518. if not t or t.startswith("word ptr ") or t.startswith("byte ptr "):
  519. return None
  520. t = t.split()[-1]
  521. for r in REGS + SEGS:
  522. if t == r.lower():
  523. return r
  524. return None
  525. def match_operand(spec, tok):
  526. """Does one FCML operand token satisfy one token spec? Returns None on
  527. success, or a human-readable reason on failure."""
  528. kind, arg = spec.split(":", 1)
  529. t = tok.strip()
  530. if kind in ("i", "ih"):
  531. # FCML prints an immediate as hex with an h suffix ("0h", "2h", "21h")
  532. raw = t.lower().rstrip("h")
  533. try:
  534. v = int(raw, 16)
  535. except ValueError:
  536. return "%r is not an immediate" % t
  537. want = int(arg, 16) if kind == "ih" else int(arg, 10)
  538. if v != want:
  539. return "immediate is %d, name says %d" % (v, want)
  540. return None
  541. if kind == "r":
  542. got = register_word(t)
  543. if got != arg:
  544. return "%r is not the register %s" % (t, arg)
  545. return None
  546. if kind == "m":
  547. base, _, disp = arg.partition("+")
  548. real = {"Arg": "bp", "Data": "si"}.get(base, base.lower())
  549. if base == "Arg" and not disp:
  550. disp = "2" # the first word argument lives at [BP+2]
  551. u = t.lower()
  552. u = re.sub(r"^(word|byte) ptr ", "", u)
  553. if not (u.startswith("[") and u.endswith("]")):
  554. return "%r is not a memory reference" % t
  555. body = u[1:-1]
  556. if not body.startswith(real):
  557. return "memory base is %r, name says [%s]" % (body, real)
  558. if not disp:
  559. if body != real:
  560. return ("memory is %r, name says [%s] with no displacement"
  561. % (body, real))
  562. return None
  563. got = body[len(real):].strip()
  564. m = re.fullmatch(r"\+\s*([0-9a-f]+)h?", got)
  565. if not m:
  566. return "displacement %r is not a number" % got
  567. if int(m.group(1), 16) != int(disp):
  568. return "displacement is %d, name says %s" \
  569. % (int(m.group(1), 16), disp)
  570. return None
  571. return "bad spec %r" % spec
  572. def operands_of(decode):
  573. """Split an FCML decode like "mov si,bx" or "cmp word ptr [bp+4h],0h"
  574. into operand tokens. Returns (mnemonic, [tokens])."""
  575. i = decode.find(" ")
  576. if i < 0:
  577. return decode.strip(), []
  578. return decode[:i].strip(), decode[i + 1:].split(",")
  579. # --- the Vx helpers, which the one-line grammar cannot see ---------------
  580. #
  581. # find_helpers takes a body spanning any number of lines, so a helper written
  582. # as
  583. #
  584. # PROCEDURE LdBxVx (delta : CARDINAL ) ;
  585. # BEGIN
  586. # B (8BH) ; B (01EH) ; Dd (delta)
  587. # END LdBxVx ;
  588. #
  589. # does not reach the one-line pass. That is a gap rather than a documented
  590. # exclusion, because these are exactly the helpers that are hard
  591. # to get right and easy to get subtly wrong:
  592. #
  593. # - the operand is a D_ data-block offset, so the immediate is a FIXUP.
  594. # Emitting W (delta) instead of Dd (delta) produces a byte-identical
  595. # instruction with the raw offset in it: `MOV BX,001Ch` for
  596. # `MOV BX,<D_PUSH>`, pointing into the entry JMP. That happened, and
  597. # the result was a hang rather than a crash.
  598. # - in 16-bit mode there is no [BX] memory form, so a data address has to
  599. # go through mod=00 / rm=110, which is ModRM 1E. rm=111 is [BX+SI], and
  600. # it decodes cleanly, so a wrong ModRM here is invisible to every other
  601. # check in the tree.
  602. # - LdBxVx and StVxBx are a load/store pair on the same word and MUST use
  603. # the same ModRM and the same fixup kind, or one of them silently
  604. # addresses something else.
  605. # - LdBxVx and MovBxVx differ only in the ModRM's mod field, i.e. "the word
  606. # at the address" versus "the address". Both mistakes above have been
  607. # made here, in this pair.
  608. #
  609. # So they get their own check, keyed on "Vx" - the operand word Runtime.mod
  610. # reserves for "a 16-bit absolute address into the data block" - and every one
  611. # of them is declared explicitly, so ADDING a Vx helper is a deliberate act:
  612. # an undeclared one is reported rather than ignored.
  613. #
  614. # The header, the body and the closing name are separated by `(.*?)` rather
  615. # than by `\s*`, because two of these helpers carry an explanatory comment
  616. # between the parameter list and BEGIN. A `\s*` there skips them silently -
  617. # which is the failure this whole check exists to prevent - so the pattern is
  618. # deliberately loose about whitespace and strict about the `END <name>`.
  619. RE_VX = re.compile(
  620. r"^PROCEDURE\s+(\w*Vx\w*)\s*\([^)]*\)\s*;.*?\bBEGIN\b(.*?)\bEND\s+\1\s*;",
  621. re.MULTILINE | re.DOTALL)
  622. # (opcode, shape). "address" = MOV reg,imm16: the register is in the opcode
  623. # and there is no ModRM. "load"/"store" = opcode + ModRM 1E + the
  624. # Dd-supplied immediate.
  625. VX_KINDS = {
  626. "MovBxVx": (0xBB, "address"), # MOV BX, Vx
  627. "MovDxVx": (0xBA, "address"), # MOV DX, Vx
  628. "LdBxVx": (0x8B, "load"), # MOV BX, WORD PTR [Vx]
  629. "StVxBx": (0x89, "store"), # MOV WORD PTR [Vx], BX
  630. }
  631. def audit_vx_helpers(src, mod, verbose):
  632. """Check the multi-line *Vx helpers. Returns (n_checked, problems)."""
  633. found = {}
  634. for m in RE_VX.finditer(src):
  635. found[m.group(1)] = m.group(2)
  636. problems = []
  637. # The count reported is the number of helpers ACTUALLY examined, not the
  638. # size of VX_KINDS. Those were the same number when only Runtime.mod was
  639. # swept, and printing the constant for Compiler.mod - which defines no Vx
  640. # emitter at all - made the report claim four subjects in a module that
  641. # has none. A count that does not change when the module does is a
  642. # cosmetic lie, and this report exists to be believed.
  643. checked = 0
  644. for name in sorted(set(found) | set(VX_KINDS)):
  645. # A *Vx helper is a Runtime.mod concept (the V* data word at a fixed
  646. # offset). Compiler.mod has none, so VX_KINDS is only a floor for the
  647. # module that is supposed to define them; asking Compiler.mod for four
  648. # Vx emitters it should not have produces four phantom failures.
  649. if mod != "Runtime.mod" and name in VX_KINDS and name not in found:
  650. continue
  651. if name not in VX_KINDS:
  652. problems.append("%s: a Vx helper with no declared kind - add it "
  653. "to VX_KINDS with its opcode and shape" % name)
  654. continue
  655. if name not in found:
  656. # The module is named rather than hardcoded: these four live in
  657. # Runtime.mod, and reporting them as missing from Compiler.mod
  658. # would be a false alarm about a module that has no business
  659. # defining them.
  660. problems.append("%s: declared in VX_KINDS but not defined in %s"
  661. % (name, mod))
  662. continue
  663. checked += 1
  664. body = found[name]
  665. want_op, shape = VX_KINDS[name]
  666. by = [int(b, 16) for b in RE_BYTE.findall(body)]
  667. hexs = " ".join("%02X" % b for b in by[:2])
  668. if not by or by[0] != want_op:
  669. problems.append("%s: starts %s, expected opcode %02X (%s)"
  670. % (name, hexs or "<nothing>", want_op, shape))
  671. continue
  672. # The two shapes need different numbers of literal bytes, and asking
  673. # for a ModRM on an address move is a false alarm: MOV reg,imm16
  674. # carries the register in the opcode and has no ModRM at all.
  675. if shape == "address":
  676. if len(by) != 1:
  677. problems.append("%s: emits %s, expected just the opcode - an "
  678. "address move is `MOV reg,imm16` and has no "
  679. "ModRM" % (name, hexs))
  680. continue
  681. elif len(by) < 2:
  682. problems.append("%s: emits %s, expected opcode and ModRM"
  683. % (name, hexs))
  684. continue
  685. elif by[1] != 0x1E:
  686. problems.append(
  687. "%s: ModRM is %02X, expected 1E. 16-bit mode has no [BX] "
  688. "form, so a data address must use mod=00 / rm=110; rm=111 "
  689. "is [BX+SI] and decodes cleanly, so nothing else would "
  690. "notice" % (name, by[1]))
  691. continue
  692. if "Dd" not in body:
  693. problems.append(
  694. "%s: does not call Dd, so the D_ offset is emitted raw "
  695. "instead of as a fixup - the instruction will be "
  696. "byte-correct and point at the wrong place" % name)
  697. continue
  698. if re.search(r"\bW\s*\(", body):
  699. problems.append("%s: calls W as well as Dd - the offset must be "
  700. "placed by Dd alone" % name)
  701. continue
  702. if verbose:
  703. print("%-20s %-16s %s (%s, Dd fixup)"
  704. % (name, hexs, shape,
  705. "no ModRM" if shape == "address" else "mod=00 rm=110"))
  706. return checked, problems
  707. def sweep(src, mod, verbose):
  708. """Audit every one-line emitter helper in one module. Returns
  709. (n_ok, n_unparsed, n_bad, problems)."""
  710. n_ok = n_unparsed = n_bad = 0
  711. problems = []
  712. seen = set()
  713. # EmitData is a documented EXCLUSION, not a gap: its B(...) calls are DATA
  714. # (the D_ block), not instructions, so running the code buffer through a
  715. # disassembler produces nonsense like "add [bx+si],al" and a DECODE ERROR.
  716. # It is listed here rather than left implicit, because an exclusion that is
  717. # not written down is indistinguishable from a helper nobody audited.
  718. #
  719. # Its D_ offsets are asserted against this block by check_runtime.py's
  720. # golden, so "excluded from the name audit" is not "unchecked": the bytes
  721. # are pinned, only the name-to-opcode correspondence does not apply.
  722. excluded = {"EmitData", "EmitFileOps"}
  723. if verbose:
  724. print("-- %s" % mod)
  725. print("name bytes FCML decode")
  726. for name, body in find_helpers(src):
  727. # Compiler.mod prefixes its emitters with Em. The name grammar is
  728. # shared with Runtime.mod and has no Em entries, so the prefix is
  729. # stripped here and the module name only ever appears in output. It
  730. # is stripped for PATTERNS matching and for the Vx pass alike, which
  731. # is why a single RE_BYTE and a single PATTERNS table can serve both
  732. # modules instead of two drifting copies.
  733. if mod != "Runtime.mod" and name.startswith("Em"):
  734. name = name[2:]
  735. seen.add(name)
  736. if name in excluded:
  737. continue
  738. by = [int(b, 16) for b in RE_BYTE.findall(body)]
  739. if not by:
  740. continue
  741. raw = bytes(by)
  742. # Disassemble; helpers are 1-2 bytes so one instruction is the norm,
  743. # but StCx / Shl / Div style helpers can be longer, so decode all.
  744. decodes = []
  745. off = 0
  746. while off < len(raw):
  747. text, length = disasm16.decode(raw[off:], off)
  748. if length == 0:
  749. decodes.append(("<DECODE ERROR>", ""))
  750. break
  751. decodes.append(operands_of(text or "?"))
  752. off += length
  753. hexs = " ".join("%02X" % b for b in raw)
  754. dec_text = "; ".join(d[0] + " " + ", ".join(d[1]) for d in decodes)
  755. if verbose:
  756. print("%-20s %-16s %s" % (name, hexs, dec_text))
  757. # A name can have more than one reading (MovBpSp: BP := SP, or
  758. # BP := [SP]). Take the first reading whose operand specs the decode
  759. # actually satisfies; if two readings both fit, the name is genuinely
  760. # ambiguous and that is itself reported, because it would mean the
  761. # audit could be satisfied by the wrong one.
  762. reads = []
  763. nopattern = True
  764. for rx, pmnem, specs, ops in PATTERNS:
  765. mm = rx.match(name)
  766. if not mm:
  767. continue
  768. # The opcode gate applies to the FIRST byte. That is right for a
  769. # one-instruction helper, and wrong for a sequence, where the first
  770. # byte belongs to the setup step: IDivAxCx starts with 99h (CWD)
  771. # and its F7h /7 is the second instruction, so a first-byte gate
  772. # rejected the one helper whose opcode matters most. Skipping the
  773. # gate for a sequence loses nothing, because the sequence check
  774. # below compares every decoded mnemonic against its own spec.
  775. is_seq = (isinstance(specs, list) and specs
  776. and isinstance(specs[0], list))
  777. if ops is not None and not is_seq and by[0] not in ops:
  778. continue
  779. nopattern = False
  780. gmap = {str(i): g for i, g in enumerate(mm.groups(), 1)}
  781. mn = pmnem
  782. if mn is None:
  783. # A pattern with no capture group has no mnemonic to infer
  784. # from the name, and a pattern with none either names the
  785. # mnemonic outright (a sequence) or is checked by operands
  786. # alone. A group-less pattern with pmnem None is a grammar
  787. # bug, not a helper bug, so say so instead of crashing.
  788. if not mm.re.groups:
  789. reads.append((mm, None, specs,
  790. "pattern %r has no capture group and names "
  791. "no mnemonic" % rx.pattern))
  792. continue
  793. mn = mm.group(1).lower()
  794. elif "%(" in mn:
  795. mn = mn % gmap
  796. if len(decodes) != 1:
  797. # A pattern may describe a fixed SEQUENCE of instructions by
  798. # passing a list of specs, one per instruction - IDIV is the
  799. # only user (CWD, then IDIV r/m16), and without this it was
  800. # reported as "emits 2 instructions, name describes one",
  801. # which is a true observation and a useless one: the two
  802. # instructions are one operation and the pair is the thing
  803. # that has to be checked, because a lone F7 /7 divides by an
  804. # un-sign-extended dividend.
  805. if not is_seq or len(specs) != len(decodes):
  806. reads.append((mm, mn, specs,
  807. "emits %d instructions, name describes %s"
  808. % (len(decodes),
  809. len(specs) if is_seq else "one")))
  810. continue
  811. why = []
  812. for k, sub in enumerate(specs):
  813. smn, sspecs = sub
  814. gmnem, got = decodes[k]
  815. if gmnem != smn:
  816. why.append("step %d is %r, name says %s"
  817. % (k + 1, gmnem, smn))
  818. break
  819. if len(got) != len(sspecs):
  820. why.append("step %d: name asserts %d operand(s), "
  821. "FCML decoded %d"
  822. % (k + 1, len(sspecs), len(got)))
  823. break
  824. w = [x for x in
  825. (match_operand(s % gmap if "%(" in s else s, t)
  826. for s, t in zip(sspecs, got)) if x]
  827. if w:
  828. why.append("step %d: %s" % (k + 1, "; ".join(w)))
  829. break
  830. reads.append((mm, mn, specs, "; ".join(why) if why else None))
  831. continue
  832. gmnem, got = decodes[0]
  833. if gmnem != mn:
  834. reads.append((mm, mn, specs,
  835. "FCML decodes %r, name says %s" % (gmnem, mn)))
  836. continue
  837. if len(specs) == 1 and specs[0].startswith("rx:"):
  838. # XCHG: compare the two registers as a set, not in order.
  839. # This has to come before the operand-COUNT check, because
  840. # the "rx:" spec packs both registers into one token while
  841. # the decode has two operands - which is the whole point of
  842. # it.
  843. want = set((specs[0] % gmap)[3:].split("|"))
  844. got_regs = [register_word(t) for t in got]
  845. if len(got_regs) != 2 or None in got_regs:
  846. reads.append((mm, mn, specs,
  847. "XCHG needs two bare registers, decoded %s"
  848. % ", ".join(got)))
  849. continue
  850. if set(got_regs) != want:
  851. reads.append((mm, mn, specs,
  852. "exchanges %s, name says %s"
  853. % (" and ".join(sorted(got_regs)),
  854. " and ".join(sorted(want)))))
  855. continue
  856. reads.append((mm, mn, specs, None))
  857. continue
  858. if len(got) != len(specs):
  859. reads.append((mm, mn, specs,
  860. "name asserts %d operand(s), FCML decoded %d"
  861. % (len(specs), len(got))))
  862. continue
  863. why = [w for w in
  864. (match_operand(sp % gmap if "%(" in sp else sp, tok)
  865. for sp, tok in zip(specs, got)) if w]
  866. if why:
  867. reads.append((mm, mn, specs, "; ".join(why)))
  868. continue
  869. reads.append((mm, mn, specs, None))
  870. if nopattern:
  871. n_unparsed += 1
  872. problems.append("%s: no name pattern accepts it (emits %s %r) - "
  873. "extend PATTERNS or fix the name"
  874. % (name, hexs, dec_text))
  875. continue
  876. fitting = [r for r in reads if r[3] is None]
  877. if len(fitting) > 1:
  878. n_bad += 1
  879. problems.append("%s: %d name readings fit the same bytes - the "
  880. "name is ambiguous" % (name, len(fitting)))
  881. continue
  882. if not fitting:
  883. n_bad += 1
  884. problems.append("%s: %s" % (name, reads[0][3]))
  885. continue
  886. n_ok += 1
  887. n_vx, vx_problems = audit_vx_helpers(src, mod, verbose)
  888. problems.extend(vx_problems)
  889. n_vx_ok = n_vx - len(vx_problems)
  890. # Every PROCEDURE that EMITS BYTES must have been looked at. A helper
  891. # whose body the parser skipped is the failure mode that has bitten this
  892. # file three times now: the Em prefix, the missing parameter list, and a
  893. # comment in the wrong place - each time the suite stayed green while the
  894. # helper went unexamined and the reported subject count quietly dropped.
  895. #
  896. # The inventory is scanned INDEPENDENTLY of find_helpers, and that is the
  897. # whole design of this check. Deriving both lists from the same parser
  898. # makes it vacuous: any input that stops find_helpers from matching also
  899. # removes the helper from the inventory, so the two lists agree and the
  900. # check reports nothing - which is exactly the failure it exists to catch.
  901. # So the inventory is a separate, deliberately dumb scan: every
  902. # `PROCEDURE <name>` at the start of a line, with everything up to the
  903. # next one as its text. It makes no attempt to parse Modula-2, so it
  904. # cannot fail in the same way twice. A helper the audit cannot reach is
  905. # therefore in `declared` and not in `seen`, which is a finding.
  906. #
  907. # The filter is the byte-call regex, so a parser, a lexer or a symbol
  908. # lookup that emits nothing is not expected to be audited - only helpers
  909. # that actually put bytes in the code buffer. A helper that emitted bytes
  910. # under some spelling RE_BYTE does not know would be missed here too, which
  911. # is why RE_BYTE accepts both B(...) and Ebyte(...) and why a new spelling
  912. # has to be added there rather than relied on to be found by accident.
  913. strip = (lambda s: s[2:]) if mod != "Runtime.mod" else (lambda s: s)
  914. declared = {strip(nm) for nm, txt in scan_emitters(src)
  915. if RE_BYTE.search(txt)}
  916. # EmitData is a documented EXCLUSION, not a gap: its B(...) calls are DATA
  917. # (the D_ block), not instructions, so running the code buffer through a
  918. # disassembler produces nonsense like "add [bx+si],al" and a DECODE ERROR.
  919. # It is listed here rather than left implicit, because an exclusion that is
  920. # not written down is indistinguishable from a helper nobody audited.
  921. #
  922. # Its D_ offsets are asserted against this block by check_runtime.py's
  923. # golden, so "excluded from the name audit" is not "unchecked": the bytes
  924. # are pinned, only the name-to-opcode correspondence does not apply.
  925. excluded = {"EmitData", "EmitFileOps"}
  926. strip = (lambda s: s[2:]) if mod != "Runtime.mod" else (lambda s: s)
  927. # The table is written in the names the audit uses (Runtime.mod's own
  928. # names, Compiler.mod's with the Em prefix already removed), so it is NOT
  929. # stripped again here. Stripping it twice turns "AddSp" into "dSp", which
  930. # matches nothing - and a wrong match here is the dangerous direction: the
  931. # entries would stop suppressing their helpers and the report would look
  932. # like a genuine finding rather than like a broken table.
  933. documented = set(NON_ONE_LINE.get(mod, {}))
  934. audited_elsewhere = ({strip(n) for n in _NONLINE_VX}
  935. if mod == "Runtime.mod" else set())
  936. unexamined = (declared - seen - {strip(e) for e in excluded}
  937. - documented - audited_elsewhere)
  938. for n in sorted(unexamined):
  939. problems.append("%s: emits bytes but the audit never examined it - "
  940. "the report would be green and the helper unchecked"
  941. % n)
  942. print("\n %s: %d one-line helpers audited, %d agree with their name, "
  943. "%d disagree, %d outside the grammar"
  944. % (mod, n_ok + n_unparsed + n_bad, n_ok, n_bad, n_unparsed))
  945. print(" %s: %d multi-line *Vx helpers audited, %d agree, %d problem(s)"
  946. % (mod, n_vx, n_vx_ok, len(vx_problems)))
  947. return n_ok + n_vx_ok, n_unparsed, n_bad, problems
  948. def main(argv):
  949. verbose = "-v" in argv
  950. files = [a for a in argv[1:] if not a.startswith("-")]
  951. # No argument means "audit every module that emits bytes", not
  952. # "audit Runtime.mod". The single-module default is why the audit was
  953. # green while EmXchgAxCx encoded XCHG BX,AX under a name that says
  954. # XCHG AX,CX - a fault that broke every two-variable arithmetic operation
  955. # in every program the compiler could produce.
  956. mods = [os.path.basename(f) for f in files] if files else list(MODULES)
  957. tot_ok = tot_unparsed = tot_bad = 0
  958. problems = []
  959. for mod in mods:
  960. path = os.path.join(SHELL, mod)
  961. if not os.path.exists(path):
  962. print("FAIL: no such module: %s" % path)
  963. return 1
  964. with open(path) as f:
  965. src = f.read()
  966. n_ok, n_unp, n_bad, pr = sweep(src, mod, verbose)
  967. tot_ok += n_ok
  968. tot_unparsed += n_unp
  969. tot_bad += n_bad
  970. problems.extend("%s: %s" % (mod, p) for p in pr)
  971. total = tot_ok + tot_unparsed + tot_bad
  972. print("\nAUDITED %d emitter helpers across %d module(s): %d agree with "
  973. "their name, %d disagree, %d outside the grammar"
  974. % (total, len(mods), tot_ok, tot_bad, tot_unparsed))
  975. if problems:
  976. print("FAIL: %d problem(s)" % len(problems))
  977. for p in problems:
  978. print(" - %s" % p)
  979. return 1
  980. print("PASS: every audited helper emits what its name says")
  981. return 0
  982. if __name__ == "__main__":
  983. sys.exit(main(sys.argv))