audit_helpers.py 54 KB

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