audit_helpers.py 53 KB

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