audit_helpers.py 54 KB

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