check_framedisp.py 15 KB

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