check_framedisp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python3
  2. """check_framedisp.py -- guard the [BP+off] displacement encoding.
  3. The compiler addresses a procedure's frame through BP, and there are two ways
  4. to encode an offset:
  5. 8B 46 d8 mod=01 rm=110 MOV AX,[BP+disp8]
  6. 8B 86 lo hi mod=10 rm=110 MOV AX,[BP+disp16]
  7. Both are well-formed, both decode cleanly, and only one of them reads the
  8. variable the symbol table named. Nothing else in the build can tell them
  9. apart, so this asserts the choice.
  10. The bug
  11. -------
  12. EmLoadVar, EmStoreVar and EmPushVarAddr all used to compute
  13. disp := off MOD 100H
  14. and always emit the disp8 form. That is the correct LOW BYTE for any
  15. displacement, and locals are allocated downward from 0FFFEh, so their offsets
  16. are negative -- and disp8 0FEh is -2, which is right. The old code was
  17. therefore accidentally correct across -32768..+127, which is where almost
  18. every variable lives, and every existing fixture kept its exact bytes.
  19. It went wrong at +128: disp8 80h is -128 and not +128, so a read of
  20. [BP+128] became a read of [BP-128]. Procedure PARAMETERS are laid out
  21. upward from BP+4, so the 63rd parameter of a procedure is at 4 + 62*2 = 128
  22. and the 63rd word of every call's argument block was read from the wrong
  23. side of BP. Nobody had hit it because no fixture declared that many
  24. parameters, and because a program with no local variables has no BP-relative
  25. access at all -- so the whole BP path had zero coverage.
  26. The rule now enforced
  27. ---------------------
  28. EmBpDisp picks disp8 for off <= 127 and disp16 otherwise, where `off` is
  29. taken as a 16-bit value. Note that every offset above 32767 is *negative* as
  30. a displacement, so "otherwise" covers all of them; there is no overflow case
  31. and no 32767 ceiling. Both fixtures below therefore have every frame access
  32. encoded in the 4-byte form, and this check requires that form to be present
  33. and the 3-byte form to be ABSENT for those offsets -- so restoring the old
  34. `off MOD 100H` turns the test red.
  35. The expected offsets are computed here from the frame-layout rules rather
  36. than copied from the compiler's output, so this is a cross-check and not a
  37. restatement of what the compiler happens to do:
  38. locals locFree starts at 0FFFEh and the NEW SYMBOL IS GIVEN THE
  39. PRE-DECREMENT VALUE, so the first local of a procedure is at
  40. 0FFFEh = -2, the second at 0FFFCh = -4, and so on down.
  41. parameters parmOff starts at 4 and grows by 2 per parameter, so
  42. parameter k is at 4 + 2*(k-1).
  43. The region this check reads
  44. ---------------------------
  45. A displacement only means something about the instruction that contains it, so
  46. this check sweeps the program's OWN instructions, from the first one to the
  47. end of the image. Two different things in the file say where the first one
  48. is, and they are read separately:
  49. the entry jump `E9 rel16' at file offset 0, so execution begins at
  50. ENT_SZ + rel16 (Compiler.Inittur)
  51. the program found by its own signature (comimage.find_header); the
  52. header program code follows the header immediately
  53. They must agree. They are not the same measurement -- one is a jump target,
  54. the other is a self-consistency equation over header words -- so their
  55. agreement is evidence, and a disagreement means the region is undetermined,
  56. which this check reports instead of sweeping something anyway.
  57. Until this section was written the region was a literal: RT_SZ = 391, next to
  58. a comment saying it tracked Runtime.RT_Size(). It had drifted, the runtime
  59. having grown past it, so the sweep began inside the RUNTIME, part way through
  60. an instruction -- and the check passed. It passed because nothing in it could
  61. see where its own region began: the byte patterns are found wherever they are
  62. in the image, and a decode sweep that starts mid-instruction happened to reach
  63. the same offsets. A wrong input that produces the right answers is still a
  64. wrong input, and it stops being right the first time the layout moves.
  65. Fixtures
  66. --------
  67. t27_localvar.pas five locals, assigned and read back. Covers the negative
  68. half of the range, which is where every real variable is.
  69. t28_farparam.pas seventy declared parameters, of which the call passes
  70. sixteen (the call site caps arguments at 16). p63 and p70
  71. are at +128 and +142, the first offsets the disp8 form
  72. cannot represent.
  73. t28 is executed as well as compiled, and that distinction matters for what its
  74. .out file may assert. `g := p16 + p1' is deterministic (1 + 16 = 17) and is
  75. the printed value. `unused := p63 + p70' reads stack garbage, because a call
  76. caps at 16 arguments and p17..p70 are never passed; it is computed and
  77. discarded, and its value is deliberately NOT in the .out file. A fixture that
  78. printed it would be asserting a number that depends on what the caller left on
  79. the stack, which is a test of the harness rather than of the compiler. What
  80. t28 establishes for p63/p70 is the ENCODING, which is the thing that was
  81. wrong. Do not read t28 as a claim that a 70-argument call works.
  82. Usage: check_framedisp.py [-v] (from shell/)
  83. """
  84. import os
  85. import subprocess
  86. import sys
  87. import tempfile
  88. HERE = os.path.dirname(os.path.abspath(__file__))
  89. SHELL = os.path.dirname(HERE)
  90. sys.path.insert(0, HERE)
  91. import disasm16 # noqa: E402
  92. # Where the program header is, where the entry jump lands, and how big the
  93. # header is. This check used to write the runtime's size down as RT_SZ = 391
  94. # beside a comment claiming it tracked Runtime.RT_Size(), and swept from
  95. # ENT_SZ + RT_SZ - which is inside the RUNTIME, part way through an
  96. # instruction, and nowhere near the program's first instruction. It still
  97. # passed, for the two reasons a wrong region always passes: the byte patterns
  98. # below are in the image wherever they happen to be, and the decode sweep
  99. # reached the same answers from a start point that nothing in the check could
  100. # tell was wrong. So the region is now measured from the file AND asserted to
  101. # agree with itself in main(), because a check whose own input is wrong reports
  102. # confidently about bytes the program never executes.
  103. import comimage # noqa: E402
  104. COMTEST = os.path.join(SHELL, "comtest")
  105. # (fixture, opcode, [signed offsets])
  106. # Each offset is checked three ways: the decoded displacement set must contain
  107. # it, the 4-byte mod=10 encoding of it must be present in the image, and the
  108. # 3-byte mod=01 encoding of the same offset must be ABSENT. The last of those
  109. # is the one that goes red if `off MOD 100H` ever comes back.
  110. def expected_local_offsets(count):
  111. """locFree starts at 0FFFEh; the symbol takes the pre-decrement value, so
  112. the first local is at -2. Signed, because that is what a displacement
  113. is."""
  114. return [-(2 + 2 * i) for i in range(count)]
  115. def expected_param_offsets(index):
  116. """parmOff starts at 4 and grows by 2 per parameter."""
  117. return 4 + 2 * (index - 1)
  118. CASES = [
  119. # t27: `vN := const` then `g := v1 + ... + v5`. Each local is stored once
  120. # and loaded once, so each offset appears under both 89 (store) and 8B
  121. # (load).
  122. ("t27_localvar", "89", expected_local_offsets(5)),
  123. ("t27_localvar", "8B", expected_local_offsets(5)),
  124. # t28: `unused := p63 + p70` -- read but never printed, see the note above.
  125. ("t28_farparam", "8B", [expected_param_offsets(63),
  126. expected_param_offsets(70)]),
  127. ]
  128. def link_fixtures(work):
  129. """compile and link the two fixtures, returning {name: image bytes}"""
  130. names = ["t27_localvar", "t28_farparam"]
  131. paths = [os.path.join(HERE, "fixtures", n + ".pas") for n in names]
  132. p = subprocess.run([COMTEST],
  133. input=("\n".join(paths) + "\n").encode(),
  134. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
  135. cwd=work)
  136. # ComTest writes the .COM next to the CWD, under the fixture's basename
  137. out = {}
  138. for n in names:
  139. f = os.path.join(work, n + ".COM")
  140. if not os.path.exists(f):
  141. sys.stderr.write(p.stdout.decode("utf-8", "replace"))
  142. raise SystemExit("FAIL: %s.COM was not written" % n)
  143. with open(f, "rb") as fh:
  144. out[n] = fh.read()
  145. return out
  146. def bp_operands(code):
  147. """every instruction in `code` that is an 8r/9r with a [BP+disp] operand,
  148. as (opcode, modrm, disp_value, offset)"""
  149. got = []
  150. off = 0
  151. while off < len(code):
  152. t, n = disasm16.decode(code[off:], off)
  153. if n == 0:
  154. break
  155. op = code[off]
  156. if op in (0x8A, 0x8B, 0x88, 0x89, 0x8D) and n >= 3 \
  157. and code[off + 1] in (0x46, 0x86):
  158. modrm = code[off + 1]
  159. if modrm == 0x46: # mod=01 rm=110 -> disp8
  160. disp = code[off + 2]
  161. if disp > 127:
  162. disp -= 256
  163. else: # mod=10 rm=110 -> disp16
  164. disp = int.from_bytes(code[off + 2:off + 4], "little",
  165. signed=True)
  166. got.append(("%02X" % op, modrm, disp))
  167. off += n
  168. return got
  169. def main(argv):
  170. verbose = "-v" in argv
  171. if not os.path.exists(COMTEST):
  172. print("FAIL: %s not built; run tests/run_com_tests.sh first" % COMTEST)
  173. return 1
  174. problems = []
  175. work = tempfile.mkdtemp(prefix="framedisp.")
  176. try:
  177. images = link_fixtures(work)
  178. finally:
  179. subprocess.run(["rm", "-rf", work])
  180. for fixture, want_op, offsets in CASES:
  181. img = images[fixture]
  182. # The region this check sweeps, measured twice from the file: where the
  183. # entry jump says execution starts, and where the program header says
  184. # the runtime ends. Those are different facts read from different
  185. # bytes, so a check that knows only one of them cannot tell that its
  186. # region is wrong -- which is exactly what happened while this was a
  187. # literal: the sweep began inside the runtime and reported PASS. The
  188. # two must agree or there is no measured place to start, and a guess
  189. # would be reported here as a fact about the compiler.
  190. entry = comimage.entry_target(img)
  191. hdr = comimage.find_header(img)
  192. if entry is None:
  193. problems.append("%s: no entry jump at file offset 0, so the image "
  194. "says nothing about where the program's code "
  195. "begins and this check would have to guess"
  196. % fixture)
  197. continue
  198. if hdr is None:
  199. problems.append("%s: no program header found, so the end of the "
  200. "runtime is unknown and this check would have to "
  201. "guess where the program's code begins" % fixture)
  202. continue
  203. if entry != hdr + comimage.HDR_SZ:
  204. problems.append("%s: the entry jump lands on %d but the program "
  205. "header ends at %d -- the two measurements of "
  206. "where the program's code begins disagree, so "
  207. "neither region is swept" % (fixture, entry,
  208. hdr + comimage.HDR_SZ))
  209. continue
  210. code = img[entry:]
  211. op = int(want_op, 16)
  212. mine = [d for (o, _, d) in bp_operands(code) if o == want_op]
  213. if verbose:
  214. print("%s opcode %s [BP+..] accesses found: %s"
  215. % (fixture, want_op, ["%+d" % d for d in mine]))
  216. for off in offsets:
  217. u = off & 0xFFFF
  218. # 1. the displacement really is the one the layout rule predicts
  219. if off not in mine:
  220. problems.append("%s: no %s access at [BP%+d] (offsets seen: "
  221. "%s)" % (fixture, want_op, off,
  222. ", ".join("%+d" % d for d in mine)))
  223. continue
  224. # 2. and it is encoded in the 4-byte mod=10 form ...
  225. want = bytes([op, 0x86, u & 0xFF, (u >> 8) & 0xFF])
  226. if want not in code:
  227. problems.append("%s: expected the bytes %s for [BP%+d] and "
  228. "they are not in the image"
  229. % (fixture, want.hex(" ").upper(), off))
  230. # 3. ... and NOT in the 3-byte mod=01 form, which EmBpDisp
  231. # reserves for offsets <= 127. This is the assertion that
  232. # fails if the old `off MOD 100H` truncation returns. Note
  233. # the two failure modes are not the same severity, so they
  234. # are reported differently: for a positive offset above 127
  235. # the disp8 form reads a DIFFERENT address, while for a
  236. # negative offset it reads the right one in fewer bytes.
  237. bad = bytes([op, 0x46, u & 0xFF])
  238. if bad in code:
  239. landed = (u & 0xFF) - 256 if (u & 0xFF) > 127 else (u & 0xFF)
  240. if landed != off:
  241. problems.append(
  242. "%s: [BP%+d] is encoded as %s, a disp8 that reads "
  243. "[BP%+d] instead -- a different address"
  244. % (fixture, off, bad.hex(" ").upper(), landed))
  245. else:
  246. problems.append(
  247. "%s: [BP%+d] is encoded as %s, a disp8 form that "
  248. "EmBpDisp reserves for offsets <= 127 (it would read "
  249. "the right address, but by a different rule)"
  250. % (fixture, off, bad.hex(" ").upper()))
  251. print("frame displacement: %d local offsets (negative) and %d parameter "
  252. "offsets (+128, +142) encoded as mod=10/disp16"
  253. % (len(expected_local_offsets(5)), 2))
  254. if problems:
  255. print("FAIL: %d problem(s)" % len(problems))
  256. for p in problems:
  257. print(" - %s" % p)
  258. return 1
  259. print("PASS: every [BP+off] outside -128..+127 uses the 4-byte form, and "
  260. "no offset")
  261. print(" is truncated to a disp8 that would read a different address")
  262. return 0
  263. if __name__ == "__main__":
  264. sys.exit(main(sys.argv))