audit_helpers.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. "MovBxImm": PARAM, "MovCxImm": PARAM, "MovDxImm": PARAM,
  89. "MovDl": PARAM, "MovAlD": PARAM, "MovAh": PARAM,
  90. "SubAl": PARAM, "CmpAl": PARAM, "AddDl": PARAM, "J8": COMP,
  91. "Jcc": COMP, "CmpCxV": PARAM,
  92. "B": DATA, "C8": DATA,
  93. },
  94. "Compiler.mod": {
  95. "AddSp": PARAM, "SubSp": PARAM, "Setcc": PARAM,
  96. "Call": COMP, "Jcc": COMP, "JmpNear": COMP,
  97. "BpDisp": COMP, "LoadVar": COMP, "StoreVar": COMP,
  98. "PushVarAddr": COMP, "MovAxi": COMP, "CmpAxi": COMP,
  99. },
  100. }
  101. # The Vx family is NOT here: those four are audited by audit_vx_helpers,
  102. # because their shape is fixed even though their immediate is a data offset.
  103. # They are named explicitly rather than filtered out of VX_KINDS so that this
  104. # table stands on its own and a name added to VX_KINDS later cannot silently
  105. # become unchecked - it would instead be reported, which is the point.
  106. _NONLINE_VX = ("LdBxVx", "MovBxVx", "MovDxVx", "StVxBx")
  107. def scan_emitters(src):
  108. """Yield (name, text) for every PROCEDURE, however it is written.
  109. The INVENTORY side of the coverage check, and deliberately as dumb as it
  110. can be: a name at the start of a line, and everything up to the next one.
  111. It does not check the parameter list, does not look for BEGIN, does not
  112. care where comments are, and cannot be defeated by the same mistake twice.
  113. The reason it exists at all is that the other list - the one the audit
  114. actually reads - is produced by find_helpers, which is a real parser and
  115. therefore fails on real inputs (a parameter list it did not expect, a
  116. comment in the wrong place). Comparing a parser against itself finds
  117. nothing; comparing it against a scan that cannot parse anything finds
  118. exactly the cases where the parser is the thing that is wrong.
  119. """
  120. heads = list(RE_ANY_PROC.finditer(src))
  121. for k, h in enumerate(heads):
  122. stop = heads[k + 1].start() if k + 1 < len(heads) else len(src)
  123. yield h.group(1), src[h.end():stop]
  124. def find_helpers(src):
  125. """Yield (name, body) for every PROCEDURE, in source order.
  126. A documented emitter must be auditable, so text between the header and
  127. BEGIN - which is where the explanatory comment belongs, and the only place
  128. it can be read next to the code it describes - is allowed through. A
  129. regex that permitted it had nested quantifiers and took exponential time
  130. on these files, so this splits on procedure HEADERS instead and takes the
  131. text up to the next header. That is linear, and it also cannot read one
  132. procedure's bytes as another's.
  133. The header regex is still strict about the parameter list (empty only),
  134. because that is what distinguishes an emitter from a real routine.
  135. """
  136. heads = list(RE_PROC_HEAD.finditer(src))
  137. for k, h in enumerate(heads):
  138. stop = heads[k + 1].start() if k + 1 < len(heads) else len(src)
  139. chunk = src[h.end():stop]
  140. m = re.search(r"\bBEGIN\b(.*)\bEND\s+%s\s*;" % re.escape(h.group(1)),
  141. chunk, re.DOTALL)
  142. if not m:
  143. continue
  144. yield h.group(1), m.group(1)
  145. # The H suffix is optional: the source mixes B (8AH) and B (0) for the same
  146. # kind of literal, and a byte written without H used to be silently dropped
  147. # from the audit, which made three helpers look like truncated prefixes.
  148. #
  149. # BOTH B (...) and Ebyte (...) are accepted. Runtime.mod spells a byte B(v)
  150. # and Compiler.mod spells the same thing Ebyte(v); the Em prefix is on the
  151. # *procedure* names there, not on the byte call, so the byte regex has to cover
  152. # both spellings or Compiler.mod's 22 emitters are silently skipped - which is
  153. # what happened, and how EmXchgAxCx stayed wrong for its whole life with
  154. # correct byte counts and a green compile matrix.
  155. RE_BYTE = re.compile(r"(?:\bB|\bEbyte)\s*\(\s*([0-9A-Fa-f]+)H?\s*\)")
  156. # Both modules emit bytes, so both must be swept. Compiler.mod is where the
  157. # procedure-skip jump, the FOR test ordering and EmXchgAxCx (93h = XCHG BX,AX
  158. # where the name says XCHG AX,CX) all live: bugs that break every two-variable
  159. # arithmetic and comparison in every program, invisible because the audit
  160. # looked at Runtime.mod and found nothing wrong there.
  161. MODULES = ["Runtime.mod", "Compiler.mod"]
  162. # --- name grammar -----------------------------------------------------
  163. #
  164. # An ordered table of (name regex, mnemonic, operand specs, allowed opcodes).
  165. #
  166. # Why the opcode column exists
  167. # ----------------------------
  168. # "MovDlSi" and "MovBpSp" are ambiguous from the name alone: SI and BP are
  169. # both in the register list and in the memory-base list. What settles it is
  170. # the opcode, and the rule is the asymmetry that makes 16-bit hand-assembly
  171. # so error-prone:
  172. #
  173. # 88 /r MOV r/m8, r8 reg is the SOURCE (store)
  174. # 89 /r MOV r/m16, r16 reg is the SOURCE (store)
  175. # 8A /r MOV r8, r/m8 reg is the DESTINATION (load)
  176. # 8B /r MOV r16, r/m16 reg is the DESTINATION (load)
  177. #
  178. # A byte move (8A/88) to or from a bare base register can only be a memory
  179. # access, because "mov dl, si" is not an instruction. A word move (8B/89)
  180. # could be either, so for word moves the register reading is tried first.
  181. # Encoding that rule in the table, rather than in pattern order alone, is what
  182. # stops a helper being "verified" against the wrong reading of its own name.
  183. #
  184. # Operand spec tokens:
  185. #
  186. # "r:Name" a bare register spelled Name (Ax, Al, Dx, Si, Ds, ...)
  187. # "i:N" the immediate N; the name spells it in DECIMAL
  188. # "ih:N" like i: but the name spells it in HEX (only Int, whose
  189. # vector 21h FCML prints as "21h" and which reads as decimal
  190. # 33 if you do not notice)
  191. # "m:Base" memory at [Base], with no displacement
  192. # "m:Base+D" memory at [Base + D]
  193. #
  194. # "Arg" is the emitter's alias for BP: on entry BP points at the return
  195. # address, so a word argument starts at [BP+2]. Naming it "Arg" rather than
  196. # "Bp" is what stops these being misread as [BP] accesses, and it is also
  197. # how the grammar knows to expect the +2.
  198. #
  199. # "Arg" is the frame in which the entry did NOT push BP, and it is the only
  200. # one where the argument is two bytes up: an entry that pushes BP first has
  201. # moved it to +4, which is a different name and a different byte
  202. # (MovAlArg2 / MovAlArg4, CmpArg2W0 / CmpArg4W0). A name that says only
  203. # "Arg" always means +2, with no exceptions -- the alternatives to spelling
  204. # the displacement out were a Modula-2 parameter, which this audit cannot
  205. # see, and a comment, which nothing checks.
  206. #
  207. # A name matching NO pattern is reported UNPARSED, which counts as a failure
  208. # on purpose: a helper the audit cannot read is a helper nobody is checking.
  209. REGS = ["Ax", "Bx", "Cx", "Dx", "Si", "Di", "Bp", "Sp",
  210. "Al", "Bl", "Cl", "Dl", "Ah", "Bh", "Ch", "Dh"]
  211. # Segment registers: the 8086 can only PUSH/POP them, never MOV to or from
  212. # one, so they need names of their own.
  213. SEGS = ["Ds", "Es", "Cs", "Ss"]
  214. JCCS = ["Je", "Jne", "Jz", "Jnz", "Jge", "Jnl", "Jle", "Jl", "Ja", "Jae",
  215. "Jb", "Jbe", "Jg", "Jns", "Js", "Jo", "Jno", "Jp", "Jnp", "Jcxz",
  216. "Jecxz", "Jrcxz", "Loop", "Loope", "Loopne"]
  217. _ALT = "|".join(REGS)
  218. _BASE = "Si|Di|Bx|Bp|Sp|Arg|Data"
  219. _STORE = (0x88, 0x89) # reg is the source
  220. _LOAD = (0x8A, 0x8B) # reg is the destination
  221. PATTERNS = [
  222. # --- no-operand and fixed-operand forms -------------------------
  223. (re.compile(r"^RetR?$"), "ret", [], None),
  224. (re.compile(r"^LeaveR?$"), "leave", [], None),
  225. (re.compile(r"^Int([0-9A-Fa-f]+)$"), "int", ["ih:%(1)s"], {0xCD}),
  226. (re.compile(r"^(Push|Pop)(%s)$" % "|".join(SEGS)),
  227. None, ["r:%(2)s"], None),
  228. (re.compile(r"^(Push|Pop)(%s)$" % _ALT), None, ["r:%(2)s"], None),
  229. # --- jumps: the target is a fixup, so only the mnemonic is checked
  230. (re.compile(r"^(%s)(8|16)?$" % "|".join(JCCS)), None, [], None),
  231. (re.compile(r"^Jmp(%s)$" % _ALT), "jmp", ["r:%(1)s"], {0xFF}),
  232. # --- MUL names one operand; 16-bit DIV names two because it always
  233. # divides DX:AX, so the decode has an AX the name has no room for
  234. (re.compile(r"^Mul(%s)$" % _ALT), "mul", ["r:%(1)s"], {0xF7}),
  235. (re.compile(r"^Div(%s)$" % _ALT), "div", ["r:Ax", "r:%(1)s"], {0xF7}),
  236. # --- store: name is St<base><reg>, decode puts the register last --
  237. (re.compile(r"^St(%s)(%s)$" % (_BASE, _ALT)),
  238. "mov", ["m:%(1)s", "r:%(2)s"], _STORE),
  239. # --- load through a bare base register: Ld<reg><base> ------------
  240. # The mirror of the St pattern above, and spelled Ld rather than Mov on
  241. # purpose. `8A 07` and `8A C3` are one byte apart and do opposite
  242. # things: LdAlBx reads the byte AT the pointer in BX, MovAlBl takes the
  243. # low byte OF BX. Naming the first "MovAlBx" put the two one letter
  244. # apart, and getch's pushback path used the wrong one - it read memory
  245. # 010Ah, the address of the character, instead of the character. So the
  246. # grammar is part of the safety: Ld* may only be spelled for a memory
  247. # source, which is what distinguishes it from Mov*<reg><lowreg>.
  248. (re.compile(r"^Ld(%s)(%s)$" % (_ALT, _BASE)),
  249. "mov", ["r:%(1)s", "m:%(2)s"], (0x8A, 0x8B)),
  250. # --- XCHG is symmetric, so the name's operand order carries no
  251. # information and must not be checked positionally. 87 /r is
  252. # XCHG r/m16, r16, so FCML always prints the r/m operand first:
  253. # 87 C7 - reg=AX, rm=DI - decodes as "xchg di,ax" whichever way the
  254. # author thought about it. What the audit is really for here is the
  255. # PAIR: XchgAxDi must not come out as XCHG AX,CX. So the two
  256. # registers are compared as a set (see the "rx:" handling below).
  257. (re.compile(r"^Xchg(%s)(%s)$" % (_ALT, _ALT)),
  258. "xchg", ["rx:%(1)s|%(2)s"], {0x87, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,
  259. 0x97}),
  260. # --- the accumulator-implicit XCHGs, 91h..97h, join the /r form -----
  261. # One byte, no ModRM, both registers fixed by the opcode. They are in
  262. # the same opcode set because the same `rx:` set comparison decides them,
  263. # and that comparison is exactly what catches 93h (XCHG BX,AX) under the
  264. # name XchgAxCx - the fault that broke every two-variable arithmetic
  265. # operation in every program. 90h is deliberately absent: it is NOP, and
  266. # FCML decodes it as "nop", not as an XCHG AX,AX.
  267. #
  268. # --- MOV r8, imm8 : B0+reg, and the AH-specific B4 form -----------
  269. # MOV AH,imm8 is B4 imm8, which is not B0+reg. The name says which
  270. # register, so the opcode is checked against it: B4 must be AH and B0+4
  271. # must not be. (The runtime's wrchar used to load the character with the
  272. # wrong register, so the store landed in AL-adjacent memory.)
  273. # B4 imm8 is MOV AH,imm8 and is NOT B0+reg, so AH and AL are listed
  274. # separately with their own opcodes rather than sharing one pattern that
  275. # would accept B4 under the name MovAl0.
  276. (re.compile(r"^MovAh(0|1)$"),
  277. "mov", ["r:Ah", "i:%(1)s"], {0xB4}),
  278. (re.compile(r"^MovAl(0|1)$"),
  279. "mov", ["r:Al", "i:%(1)s"], {0xB0}),
  280. # --- MUL/IMUL r/m16, accumulator implicit, /5 and /4 -----------------
  281. # The destination is AX:DX and the operand is the named register, so
  282. # "MulAxCx" means CX := CX, i.e. AX:DX := AX * CX. FCML prints only the
  283. # one explicit operand ("imul cx"), which is why the spec has one token.
  284. (re.compile(r"^Mul(%s)(%s)$" % (_ALT, _ALT)),
  285. "imul", ["r:%(2)s"], {0xF7}),
  286. # --- CmpArg<N>W0 : CMP WORD [BP+N],0 between MOV BP,SP / MOV SP,BP -----
  287. # An odd but exact shape: [SP] is not encodable, so the frame pointer is
  288. # borrowed for the one comparison and handed back untouched. The pair of
  289. # saves at the ends is what makes it correct, so the whole sequence is
  290. # checked - a missing MOV SP,BP would leave BP clobbered for the caller.
  291. #
  292. # The displacement is a CAPTURED GROUP, not a constant, and the name has to
  293. # spell it out. That is the rule that keeps CmpArg2W0 and CmpArg4W0
  294. # honest: they differ by one byte, and one byte is the difference between
  295. # reading a BOOLEAN and reading a character, so the name -- which is the
  296. # only thing this audit can read -- has to carry it. A single helper
  297. # taking the displacement as a Modula-2 parameter would decode correctly
  298. # under either name and be unchecked under both.
  299. (re.compile(r"^CmpArg(2|4)W0$"),
  300. None, [["mov", ["r:Bp", "r:Sp"]],
  301. ["cmp", ["m:Bp+%(1)s", "i:0"]],
  302. ["mov", ["r:Sp", "r:Bp"]]], {0x8B}),
  303. # --- a "Mov<reg>Sp" that is a POP/PUSH pair, not a memory access ----
  304. # MOV AX,[SP] does not exist on the 8086 at all, so the stack top is read
  305. # with POP and given back with PUSH: an observational no-op that leaves SP
  306. # where it found it. Named MovAxSp because that is the OPERATION, and the
  307. # two-step shape is recorded here because it is the only correct encoding.
  308. (re.compile(r"^Mov(%s)Sp$" % _ALT),
  309. None, [["pop", ["r:%(1)s"]], ["push", ["r:%(1)s"]]], None),
  310. # --- IDIV: CWD then IDIV r/m16, sign-extending into DX:AX ---------
  311. # A two-instruction shape, so the specs are a list of one list per
  312. # instruction. The CWD is not incidental: F7 /7 divides the 32-bit value
  313. # in DX:AX, and a signed dividend is only in DX:AX if CWD ran. Drop the
  314. # 99h and the divisor goes to the same place, so the pair is checked
  315. # together - which is the reason the sequence form exists.
  316. # FCML prints BOTH ends of a /r divide ("idiv ax, cx"), because the
  317. # accumulator is not implicit in the mnemonic the way it is for MUL, so
  318. # the spec needs two operands and the AX comes first.
  319. (re.compile(r"^I?Div(%s)(%s)$" % (_ALT, _ALT)),
  320. None, [["cwd", []], ["idiv", ["r:%(1)s", "r:%(2)s"]]], {0xF7}),
  321. # --- load a register from memory, with a displacement ------------
  322. # The displacement makes the name unambiguous, so any load opcode works.
  323. (re.compile(r"^Mov(%s)(%s)(\d+)$" % (_ALT, _BASE)),
  324. "mov", ["r:%(1)s", "m:%(2)s+%(3)s"], _LOAD),
  325. # --- two registers: MOV BP,SP / CMP SI,BX / XOR AX,AX / ADD DI,AX -
  326. # Tried before the bare-base reading below, because for a word move
  327. # "MovBpSp" means BP := SP and only "MovDlSi" means DL := [SI]. The two
  328. # readings cannot both match, because one demands a register operand
  329. # where the other demands a memory operand.
  330. # Xchg is NOT in this list. It has its own pattern above, which compares
  331. # the two registers as a SET because 87 /r is symmetric and FCML always
  332. # prints the r/m operand first - so the name's order carries no
  333. # information and must not be checked positionally. Listing Xchg here as
  334. # well gave it a second, ordered reading, and the audit then reported
  335. # "2 name readings fit the same bytes" for XchgAxCx: not a real ambiguity
  336. # in the code, but two overlapping rows in the grammar saying the same
  337. # thing. A grammar that can be satisfied two ways for one name is a
  338. # grammar that can be satisfied the wrong way.
  339. (re.compile(r"^(Mov|Cmp|Add|Sub|Xor|And|Or)(%s)(%s)$" % (_ALT, _ALT)),
  340. None, ["r:%(2)s", "r:%(3)s"], None),
  341. # --- byte move from a bare base register: necessarily memory ------
  342. # Restricted to 8A/88 on purpose: if this ever matched an 8B/89 it would
  343. # be a register move already claimed by the pattern above.
  344. (re.compile(r"^Mov(%s)(%s)$" % (_ALT, _BASE)),
  345. "mov", ["r:%(1)s", "m:%(2)s"], (0x8A, 0x88)),
  346. # --- immediate against a register --------------------------------
  347. (re.compile(r"^(Add|Sub|Cmp|Xor|And|Or)(%s)(\d+)$" % _ALT),
  348. None, ["r:%(2)s", "i:%(3)s"], {0x83}),
  349. # --- one register: INC CX / DEC SI / NOT DX / NEG AX ------------
  350. (re.compile(r"^(Inc|Dec|Not|Neg|Shl|Shr|Sar)(%s)$" % _ALT),
  351. None, ["r:%(2)s"], None),
  352. ]
  353. def register_word(tok):
  354. """Map an FCML operand token to a REGS/SEGS word, or None."""
  355. t = tok.strip().lower()
  356. if not t or t.startswith("word ptr ") or t.startswith("byte ptr "):
  357. return None
  358. t = t.split()[-1]
  359. for r in REGS + SEGS:
  360. if t == r.lower():
  361. return r
  362. return None
  363. def match_operand(spec, tok):
  364. """Does one FCML operand token satisfy one token spec? Returns None on
  365. success, or a human-readable reason on failure."""
  366. kind, arg = spec.split(":", 1)
  367. t = tok.strip()
  368. if kind in ("i", "ih"):
  369. # FCML prints an immediate as hex with an h suffix ("0h", "2h", "21h")
  370. raw = t.lower().rstrip("h")
  371. try:
  372. v = int(raw, 16)
  373. except ValueError:
  374. return "%r is not an immediate" % t
  375. want = int(arg, 16) if kind == "ih" else int(arg, 10)
  376. if v != want:
  377. return "immediate is %d, name says %d" % (v, want)
  378. return None
  379. if kind == "r":
  380. got = register_word(t)
  381. if got != arg:
  382. return "%r is not the register %s" % (t, arg)
  383. return None
  384. if kind == "m":
  385. base, _, disp = arg.partition("+")
  386. real = {"Arg": "bp", "Data": "si"}.get(base, base.lower())
  387. if base == "Arg" and not disp:
  388. disp = "2" # the first word argument lives at [BP+2]
  389. u = t.lower()
  390. u = re.sub(r"^(word|byte) ptr ", "", u)
  391. if not (u.startswith("[") and u.endswith("]")):
  392. return "%r is not a memory reference" % t
  393. body = u[1:-1]
  394. if not body.startswith(real):
  395. return "memory base is %r, name says [%s]" % (body, real)
  396. if not disp:
  397. if body != real:
  398. return ("memory is %r, name says [%s] with no displacement"
  399. % (body, real))
  400. return None
  401. got = body[len(real):].strip()
  402. m = re.fullmatch(r"\+\s*([0-9a-f]+)h?", got)
  403. if not m:
  404. return "displacement %r is not a number" % got
  405. if int(m.group(1), 16) != int(disp):
  406. return "displacement is %d, name says %s" \
  407. % (int(m.group(1), 16), disp)
  408. return None
  409. return "bad spec %r" % spec
  410. def operands_of(decode):
  411. """Split an FCML decode like "mov si,bx" or "cmp word ptr [bp+4h],0h"
  412. into operand tokens. Returns (mnemonic, [tokens])."""
  413. i = decode.find(" ")
  414. if i < 0:
  415. return decode.strip(), []
  416. return decode[:i].strip(), decode[i + 1:].split(",")
  417. # --- the Vx helpers, which the one-line grammar cannot see ---------------
  418. #
  419. # find_helpers takes a body spanning any number of lines, so a helper written
  420. # as
  421. #
  422. # PROCEDURE LdBxVx (delta : CARDINAL ) ;
  423. # BEGIN
  424. # B (8BH) ; B (01EH) ; Dd (delta)
  425. # END LdBxVx ;
  426. #
  427. # does not reach the one-line pass. That is a gap rather than a documented
  428. # exclusion, because these are exactly the helpers that are hard
  429. # to get right and easy to get subtly wrong:
  430. #
  431. # - the operand is a D_ data-block offset, so the immediate is a FIXUP.
  432. # Emitting W (delta) instead of Dd (delta) produces a byte-identical
  433. # instruction with the raw offset in it: `MOV BX,001Ch` for
  434. # `MOV BX,<D_PUSH>`, pointing into the entry JMP. That happened, and
  435. # the result was a hang rather than a crash.
  436. # - in 16-bit mode there is no [BX] memory form, so a data address has to
  437. # go through mod=00 / rm=110, which is ModRM 1E. rm=111 is [BX+SI], and
  438. # it decodes cleanly, so a wrong ModRM here is invisible to every other
  439. # check in the tree.
  440. # - LdBxVx and StVxBx are a load/store pair on the same word and MUST use
  441. # the same ModRM and the same fixup kind, or one of them silently
  442. # addresses something else.
  443. # - LdBxVx and MovBxVx differ only in the ModRM's mod field, i.e. "the word
  444. # at the address" versus "the address". Both mistakes above have been
  445. # made here, in this pair.
  446. #
  447. # So they get their own check, keyed on "Vx" - the operand word Runtime.mod
  448. # reserves for "a 16-bit absolute address into the data block" - and every one
  449. # of them is declared explicitly, so ADDING a Vx helper is a deliberate act:
  450. # an undeclared one is reported rather than ignored.
  451. #
  452. # The header, the body and the closing name are separated by `(.*?)` rather
  453. # than by `\s*`, because two of these helpers carry an explanatory comment
  454. # between the parameter list and BEGIN. A `\s*` there skips them silently -
  455. # which is the failure this whole check exists to prevent - so the pattern is
  456. # deliberately loose about whitespace and strict about the `END <name>`.
  457. RE_VX = re.compile(
  458. r"^PROCEDURE\s+(\w*Vx\w*)\s*\([^)]*\)\s*;.*?\bBEGIN\b(.*?)\bEND\s+\1\s*;",
  459. re.MULTILINE | re.DOTALL)
  460. # (opcode, shape). "address" = MOV reg,imm16: the register is in the opcode
  461. # and there is no ModRM. "load"/"store" = opcode + ModRM 1E + the
  462. # Dd-supplied immediate.
  463. VX_KINDS = {
  464. "MovBxVx": (0xBB, "address"), # MOV BX, Vx
  465. "MovDxVx": (0xBA, "address"), # MOV DX, Vx
  466. "LdBxVx": (0x8B, "load"), # MOV BX, WORD PTR [Vx]
  467. "StVxBx": (0x89, "store"), # MOV WORD PTR [Vx], BX
  468. }
  469. def audit_vx_helpers(src, mod, verbose):
  470. """Check the multi-line *Vx helpers. Returns (n_checked, problems)."""
  471. found = {}
  472. for m in RE_VX.finditer(src):
  473. found[m.group(1)] = m.group(2)
  474. problems = []
  475. # The count reported is the number of helpers ACTUALLY examined, not the
  476. # size of VX_KINDS. Those were the same number when only Runtime.mod was
  477. # swept, and printing the constant for Compiler.mod - which defines no Vx
  478. # emitter at all - made the report claim four subjects in a module that
  479. # has none. A count that does not change when the module does is a
  480. # cosmetic lie, and this report exists to be believed.
  481. checked = 0
  482. for name in sorted(set(found) | set(VX_KINDS)):
  483. # A *Vx helper is a Runtime.mod concept (the V* data word at a fixed
  484. # offset). Compiler.mod has none, so VX_KINDS is only a floor for the
  485. # module that is supposed to define them; asking Compiler.mod for four
  486. # Vx emitters it should not have produces four phantom failures.
  487. if mod != "Runtime.mod" and name in VX_KINDS and name not in found:
  488. continue
  489. if name not in VX_KINDS:
  490. problems.append("%s: a Vx helper with no declared kind - add it "
  491. "to VX_KINDS with its opcode and shape" % name)
  492. continue
  493. if name not in found:
  494. # The module is named rather than hardcoded: these four live in
  495. # Runtime.mod, and reporting them as missing from Compiler.mod
  496. # would be a false alarm about a module that has no business
  497. # defining them.
  498. problems.append("%s: declared in VX_KINDS but not defined in %s"
  499. % (name, mod))
  500. continue
  501. checked += 1
  502. body = found[name]
  503. want_op, shape = VX_KINDS[name]
  504. by = [int(b, 16) for b in RE_BYTE.findall(body)]
  505. hexs = " ".join("%02X" % b for b in by[:2])
  506. if not by or by[0] != want_op:
  507. problems.append("%s: starts %s, expected opcode %02X (%s)"
  508. % (name, hexs or "<nothing>", want_op, shape))
  509. continue
  510. # The two shapes need different numbers of literal bytes, and asking
  511. # for a ModRM on an address move is a false alarm: MOV reg,imm16
  512. # carries the register in the opcode and has no ModRM at all.
  513. if shape == "address":
  514. if len(by) != 1:
  515. problems.append("%s: emits %s, expected just the opcode - an "
  516. "address move is `MOV reg,imm16` and has no "
  517. "ModRM" % (name, hexs))
  518. continue
  519. elif len(by) < 2:
  520. problems.append("%s: emits %s, expected opcode and ModRM"
  521. % (name, hexs))
  522. continue
  523. elif by[1] != 0x1E:
  524. problems.append(
  525. "%s: ModRM is %02X, expected 1E. 16-bit mode has no [BX] "
  526. "form, so a data address must use mod=00 / rm=110; rm=111 "
  527. "is [BX+SI] and decodes cleanly, so nothing else would "
  528. "notice" % (name, by[1]))
  529. continue
  530. if "Dd" not in body:
  531. problems.append(
  532. "%s: does not call Dd, so the D_ offset is emitted raw "
  533. "instead of as a fixup - the instruction will be "
  534. "byte-correct and point at the wrong place" % name)
  535. continue
  536. if re.search(r"\bW\s*\(", body):
  537. problems.append("%s: calls W as well as Dd - the offset must be "
  538. "placed by Dd alone" % name)
  539. continue
  540. if verbose:
  541. print("%-20s %-16s %s (%s, Dd fixup)"
  542. % (name, hexs, shape,
  543. "no ModRM" if shape == "address" else "mod=00 rm=110"))
  544. return checked, problems
  545. def sweep(src, mod, verbose):
  546. """Audit every one-line emitter helper in one module. Returns
  547. (n_ok, n_unparsed, n_bad, problems)."""
  548. n_ok = n_unparsed = n_bad = 0
  549. problems = []
  550. seen = set()
  551. # EmitData is a documented EXCLUSION, not a gap: its B(...) calls are DATA
  552. # (the D_ block), not instructions, so running the code buffer through a
  553. # disassembler produces nonsense like "add [bx+si],al" and a DECODE ERROR.
  554. # It is listed here rather than left implicit, because an exclusion that is
  555. # not written down is indistinguishable from a helper nobody audited.
  556. #
  557. # Its D_ offsets are asserted against this block by check_runtime.py's
  558. # golden, so "excluded from the name audit" is not "unchecked": the bytes
  559. # are pinned, only the name-to-opcode correspondence does not apply.
  560. excluded = {"EmitData"}
  561. if verbose:
  562. print("-- %s" % mod)
  563. print("name bytes FCML decode")
  564. for name, body in find_helpers(src):
  565. # Compiler.mod prefixes its emitters with Em. The name grammar is
  566. # shared with Runtime.mod and has no Em entries, so the prefix is
  567. # stripped here and the module name only ever appears in output. It
  568. # is stripped for PATTERNS matching and for the Vx pass alike, which
  569. # is why a single RE_BYTE and a single PATTERNS table can serve both
  570. # modules instead of two drifting copies.
  571. if mod != "Runtime.mod" and name.startswith("Em"):
  572. name = name[2:]
  573. seen.add(name)
  574. if name in excluded:
  575. continue
  576. by = [int(b, 16) for b in RE_BYTE.findall(body)]
  577. if not by:
  578. continue
  579. raw = bytes(by)
  580. # Disassemble; helpers are 1-2 bytes so one instruction is the norm,
  581. # but StCx / Shl / Div style helpers can be longer, so decode all.
  582. decodes = []
  583. off = 0
  584. while off < len(raw):
  585. text, length = disasm16.decode(raw[off:], off)
  586. if length == 0:
  587. decodes.append(("<DECODE ERROR>", ""))
  588. break
  589. decodes.append(operands_of(text or "?"))
  590. off += length
  591. hexs = " ".join("%02X" % b for b in raw)
  592. dec_text = "; ".join(d[0] + " " + ", ".join(d[1]) for d in decodes)
  593. if verbose:
  594. print("%-20s %-16s %s" % (name, hexs, dec_text))
  595. # A name can have more than one reading (MovBpSp: BP := SP, or
  596. # BP := [SP]). Take the first reading whose operand specs the decode
  597. # actually satisfies; if two readings both fit, the name is genuinely
  598. # ambiguous and that is itself reported, because it would mean the
  599. # audit could be satisfied by the wrong one.
  600. reads = []
  601. nopattern = True
  602. for rx, pmnem, specs, ops in PATTERNS:
  603. mm = rx.match(name)
  604. if not mm:
  605. continue
  606. # The opcode gate applies to the FIRST byte. That is right for a
  607. # one-instruction helper, and wrong for a sequence, where the first
  608. # byte belongs to the setup step: IDivAxCx starts with 99h (CWD)
  609. # and its F7h /7 is the second instruction, so a first-byte gate
  610. # rejected the one helper whose opcode matters most. Skipping the
  611. # gate for a sequence loses nothing, because the sequence check
  612. # below compares every decoded mnemonic against its own spec.
  613. is_seq = (isinstance(specs, list) and specs
  614. and isinstance(specs[0], list))
  615. if ops is not None and not is_seq and by[0] not in ops:
  616. continue
  617. nopattern = False
  618. gmap = {str(i): g for i, g in enumerate(mm.groups(), 1)}
  619. mn = pmnem
  620. if mn is None:
  621. # A pattern with no capture group has no mnemonic to infer
  622. # from the name, and a pattern with none either names the
  623. # mnemonic outright (a sequence) or is checked by operands
  624. # alone. A group-less pattern with pmnem None is a grammar
  625. # bug, not a helper bug, so say so instead of crashing.
  626. if not mm.re.groups:
  627. reads.append((mm, None, specs,
  628. "pattern %r has no capture group and names "
  629. "no mnemonic" % rx.pattern))
  630. continue
  631. mn = mm.group(1).lower()
  632. elif "%(" in mn:
  633. mn = mn % gmap
  634. if len(decodes) != 1:
  635. # A pattern may describe a fixed SEQUENCE of instructions by
  636. # passing a list of specs, one per instruction - IDIV is the
  637. # only user (CWD, then IDIV r/m16), and without this it was
  638. # reported as "emits 2 instructions, name describes one",
  639. # which is a true observation and a useless one: the two
  640. # instructions are one operation and the pair is the thing
  641. # that has to be checked, because a lone F7 /7 divides by an
  642. # un-sign-extended dividend.
  643. if not is_seq or len(specs) != len(decodes):
  644. reads.append((mm, mn, specs,
  645. "emits %d instructions, name describes %s"
  646. % (len(decodes),
  647. len(specs) if is_seq else "one")))
  648. continue
  649. why = []
  650. for k, sub in enumerate(specs):
  651. smn, sspecs = sub
  652. gmnem, got = decodes[k]
  653. if gmnem != smn:
  654. why.append("step %d is %r, name says %s"
  655. % (k + 1, gmnem, smn))
  656. break
  657. if len(got) != len(sspecs):
  658. why.append("step %d: name asserts %d operand(s), "
  659. "FCML decoded %d"
  660. % (k + 1, len(sspecs), len(got)))
  661. break
  662. w = [x for x in
  663. (match_operand(s % gmap if "%(" in s else s, t)
  664. for s, t in zip(sspecs, got)) if x]
  665. if w:
  666. why.append("step %d: %s" % (k + 1, "; ".join(w)))
  667. break
  668. reads.append((mm, mn, specs, "; ".join(why) if why else None))
  669. continue
  670. gmnem, got = decodes[0]
  671. if gmnem != mn:
  672. reads.append((mm, mn, specs,
  673. "FCML decodes %r, name says %s" % (gmnem, mn)))
  674. continue
  675. if len(specs) == 1 and specs[0].startswith("rx:"):
  676. # XCHG: compare the two registers as a set, not in order.
  677. # This has to come before the operand-COUNT check, because
  678. # the "rx:" spec packs both registers into one token while
  679. # the decode has two operands - which is the whole point of
  680. # it.
  681. want = set((specs[0] % gmap)[3:].split("|"))
  682. got_regs = [register_word(t) for t in got]
  683. if len(got_regs) != 2 or None in got_regs:
  684. reads.append((mm, mn, specs,
  685. "XCHG needs two bare registers, decoded %s"
  686. % ", ".join(got)))
  687. continue
  688. if set(got_regs) != want:
  689. reads.append((mm, mn, specs,
  690. "exchanges %s, name says %s"
  691. % (" and ".join(sorted(got_regs)),
  692. " and ".join(sorted(want)))))
  693. continue
  694. reads.append((mm, mn, specs, None))
  695. continue
  696. if len(got) != len(specs):
  697. reads.append((mm, mn, specs,
  698. "name asserts %d operand(s), FCML decoded %d"
  699. % (len(specs), len(got))))
  700. continue
  701. why = [w for w in
  702. (match_operand(sp % gmap if "%(" in sp else sp, tok)
  703. for sp, tok in zip(specs, got)) if w]
  704. if why:
  705. reads.append((mm, mn, specs, "; ".join(why)))
  706. continue
  707. reads.append((mm, mn, specs, None))
  708. if nopattern:
  709. n_unparsed += 1
  710. problems.append("%s: no name pattern accepts it (emits %s %r) - "
  711. "extend PATTERNS or fix the name"
  712. % (name, hexs, dec_text))
  713. continue
  714. fitting = [r for r in reads if r[3] is None]
  715. if len(fitting) > 1:
  716. n_bad += 1
  717. problems.append("%s: %d name readings fit the same bytes - the "
  718. "name is ambiguous" % (name, len(fitting)))
  719. continue
  720. if not fitting:
  721. n_bad += 1
  722. problems.append("%s: %s" % (name, reads[0][3]))
  723. continue
  724. n_ok += 1
  725. n_vx, vx_problems = audit_vx_helpers(src, mod, verbose)
  726. problems.extend(vx_problems)
  727. n_vx_ok = n_vx - len(vx_problems)
  728. # Every PROCEDURE that EMITS BYTES must have been looked at. A helper
  729. # whose body the parser skipped is the failure mode that has bitten this
  730. # file three times now: the Em prefix, the missing parameter list, and a
  731. # comment in the wrong place - each time the suite stayed green while the
  732. # helper went unexamined and the reported subject count quietly dropped.
  733. #
  734. # The inventory is scanned INDEPENDENTLY of find_helpers, and that is the
  735. # whole design of this check. Deriving both lists from the same parser
  736. # makes it vacuous: any input that stops find_helpers from matching also
  737. # removes the helper from the inventory, so the two lists agree and the
  738. # check reports nothing - which is exactly the failure it exists to catch.
  739. # So the inventory is a separate, deliberately dumb scan: every
  740. # `PROCEDURE <name>` at the start of a line, with everything up to the
  741. # next one as its text. It makes no attempt to parse Modula-2, so it
  742. # cannot fail in the same way twice. A helper the audit cannot reach is
  743. # therefore in `declared` and not in `seen`, which is a finding.
  744. #
  745. # The filter is the byte-call regex, so a parser, a lexer or a symbol
  746. # lookup that emits nothing is not expected to be audited - only helpers
  747. # that actually put bytes in the code buffer. A helper that emitted bytes
  748. # under some spelling RE_BYTE does not know would be missed here too, which
  749. # is why RE_BYTE accepts both B(...) and Ebyte(...) and why a new spelling
  750. # has to be added there rather than relied on to be found by accident.
  751. strip = (lambda s: s[2:]) if mod != "Runtime.mod" else (lambda s: s)
  752. declared = {strip(nm) for nm, txt in scan_emitters(src)
  753. if RE_BYTE.search(txt)}
  754. # EmitData is a documented EXCLUSION, not a gap: its B(...) calls are DATA
  755. # (the D_ block), not instructions, so running the code buffer through a
  756. # disassembler produces nonsense like "add [bx+si],al" and a DECODE ERROR.
  757. # It is listed here rather than left implicit, because an exclusion that is
  758. # not written down is indistinguishable from a helper nobody audited.
  759. #
  760. # Its D_ offsets are asserted against this block by check_runtime.py's
  761. # golden, so "excluded from the name audit" is not "unchecked": the bytes
  762. # are pinned, only the name-to-opcode correspondence does not apply.
  763. excluded = {"EmitData"}
  764. strip = (lambda s: s[2:]) if mod != "Runtime.mod" else (lambda s: s)
  765. # The table is written in the names the audit uses (Runtime.mod's own
  766. # names, Compiler.mod's with the Em prefix already removed), so it is NOT
  767. # stripped again here. Stripping it twice turns "AddSp" into "dSp", which
  768. # matches nothing - and a wrong match here is the dangerous direction: the
  769. # entries would stop suppressing their helpers and the report would look
  770. # like a genuine finding rather than like a broken table.
  771. documented = set(NON_ONE_LINE.get(mod, {}))
  772. audited_elsewhere = ({strip(n) for n in _NONLINE_VX}
  773. if mod == "Runtime.mod" else set())
  774. unexamined = (declared - seen - {strip(e) for e in excluded}
  775. - documented - audited_elsewhere)
  776. for n in sorted(unexamined):
  777. problems.append("%s: emits bytes but the audit never examined it - "
  778. "the report would be green and the helper unchecked"
  779. % n)
  780. print("\n %s: %d one-line helpers audited, %d agree with their name, "
  781. "%d disagree, %d outside the grammar"
  782. % (mod, n_ok + n_unparsed + n_bad, n_ok, n_bad, n_unparsed))
  783. print(" %s: %d multi-line *Vx helpers audited, %d agree, %d problem(s)"
  784. % (mod, n_vx, n_vx_ok, len(vx_problems)))
  785. return n_ok + n_vx_ok, n_unparsed, n_bad, problems
  786. def main(argv):
  787. verbose = "-v" in argv
  788. files = [a for a in argv[1:] if not a.startswith("-")]
  789. # No argument means "audit every module that emits bytes", not
  790. # "audit Runtime.mod". The single-module default is why the audit was
  791. # green while EmXchgAxCx encoded XCHG BX,AX under a name that says
  792. # XCHG AX,CX - a fault that broke every two-variable arithmetic operation
  793. # in every program the compiler could produce.
  794. mods = [os.path.basename(f) for f in files] if files else list(MODULES)
  795. tot_ok = tot_unparsed = tot_bad = 0
  796. problems = []
  797. for mod in mods:
  798. path = os.path.join(SHELL, mod)
  799. if not os.path.exists(path):
  800. print("FAIL: no such module: %s" % path)
  801. return 1
  802. with open(path) as f:
  803. src = f.read()
  804. n_ok, n_unp, n_bad, pr = sweep(src, mod, verbose)
  805. tot_ok += n_ok
  806. tot_unparsed += n_unp
  807. tot_bad += n_bad
  808. problems.extend("%s: %s" % (mod, p) for p in pr)
  809. total = tot_ok + tot_unparsed + tot_bad
  810. print("\nAUDITED %d emitter helpers across %d module(s): %d agree with "
  811. "their name, %d disagree, %d outside the grammar"
  812. % (total, len(mods), tot_ok, tot_bad, tot_unparsed))
  813. if problems:
  814. print("FAIL: %d problem(s)" % len(problems))
  815. for p in problems:
  816. print(" - %s" % p)
  817. return 1
  818. print("PASS: every audited helper emits what its name says")
  819. return 0
  820. if __name__ == "__main__":
  821. sys.exit(main(sys.argv))