run_com_tests.sh 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/bin/bash
  2. # Build and run the .COM linker harness (tests/ComTest.mod), then verify every
  3. # .COM it produced with an INDEPENDENT checker.
  4. #
  5. # The independent pass matters: ComTest computes the expectations from the same
  6. # Compiler state it is testing, so a bug in the compiler would be invisible to
  7. # it. The Python pass re-derives what the file must contain - the runtime's
  8. # first bytes, a zero gap, a size that covers the data area - from the
  9. # constants only, and cross-checks.
  10. set -u
  11. D=/home/eric/Projets/Projets-Modula2/MyWork/TP3-comp/shell
  12. GM2=/home/eric/bin/Modula2/Gm2/bin/gm2
  13. cd "$D" || exit 9
  14. FLAGS="-fiso"
  15. # build logs go beside the tree (TP3-comp/tmp), never in /tmp
  16. mkdir -p ../tmp
  17. # --check-only DIR -- skip the build and the link, and run only the
  18. # independent Python checker over the .COM files already in DIR (plus a
  19. # hand-written raw.txt in the same shape the linker emits).
  20. #
  21. # This exists for non-vacuity, and it is the only reason to make it. The
  22. # checker normally runs over a scratch directory that the EXIT trap deletes,
  23. # so there is no way to hand it a DELIBERATELY WRONG .COM and see whether it
  24. # notices. A check that has only ever been shown the truth is not a check:
  25. # it could be reporting the truth about every file because it says nothing at
  26. # all. tests/nonvacuity.sh uses this to feed it a corrupted image and
  27. # require the named assertion to go red.
  28. CHECK_ONLY=""
  29. if [ "${1:-}" = "--check-only" ]; then
  30. CHECK_ONLY=${2:-}
  31. shift 2
  32. fi
  33. echo "== support modules =="
  34. if [ -n "$CHECK_ONLY" ]; then
  35. echo "check-only mode: not rebuilding, not linking"
  36. OUT="$CHECK_ONLY"
  37. [ -d "$OUT" ] || { echo "RESULT: FAIL (no such directory: $OUT)"; exit 1; }
  38. else
  39. [ -f Posix.o ] || cc -c Posix.c || exit 1
  40. for m in TextBuf Compiler Runtime Linker; do
  41. $GM2 $FLAGS -c $m.mod >../tmp/cm_c_$m 2>&1 \
  42. || { echo "COMPILE_FAIL $m"; grep -m5 "error:" ../tmp/cm_c_$m; exit 1; }
  43. done
  44. $GM2 $FLAGS -c tests/ComTest.mod >../tmp/cm_c_ComTest 2>&1 \
  45. || { echo "COMPILE_FAIL ComTest"; grep -m5 "error:" ../tmp/cm_c_ComTest; exit 1; }
  46. rm -f tests/ct.lst comtest
  47. $GM2 $FLAGS -fgen-module-list=tests/ct.lst -o /dev/null \
  48. tests/ComTest.mod TextBuf.o Posix.o Compiler.o Runtime.o Linker.o \
  49. >../tmp/cm_p1 2>&1
  50. p1=$?
  51. $GM2 $FLAGS -fuse-list=tests/ct.lst -o comtest \
  52. tests/ComTest.mod TextBuf.o Posix.o Compiler.o Runtime.o Linker.o \
  53. >../tmp/cm_p2 2>&1
  54. p2=$?
  55. if [ $p2 -ne 0 ]; then
  56. echo "LINK_FAIL p1_rc=$p1 p2_rc=$p2"
  57. grep -E "error:|undefined" ../tmp/cm_p2 | head -10
  58. exit 1
  59. fi
  60. echo "comtest built (p1_rc=$p1, phase 1 rc=1 is the expected rollup)"
  61. # .COM files are written beside the harness, so run it in a scratch dir
  62. OUT=$(mktemp -d) || exit 9
  63. # TP_COM_KEEP=1 leaves the scratch dir behind, for tests/nonvacuity.sh to
  64. # corrupt a copy of a real image and hand it back through --check-only. The
  65. # alternative - rebuilding the whole toolchain inside the non-vacuity script
  66. # to produce one throwaway byte - is slow for no benefit, and the point of
  67. # the case is the CHECKER's sensitivity, not the compiler's.
  68. if [ "${TP_COM_KEEP:-0}" = "1" ]; then
  69. echo "TP_COM_KEEP=1: images left in $OUT"
  70. else
  71. trap 'rm -rf "$OUT"' EXIT
  72. fi
  73. cd "$OUT" || exit 9
  74. ls "$D"/tests/fixtures/*.pas | "$D"/comtest > "$OUT/raw.txt" 2>&1
  75. sed 's/^.*fixtures\///' "$OUT/raw.txt"
  76. echo "----------------------------------------------------------------"
  77. nok=$(grep -c " OK com=" "$OUT/raw.txt")
  78. nerr=$(grep -c " ERROR " "$OUT/raw.txt")
  79. nbad=$(grep -cE "WRITE_COM_FAILED|CANNOT" "$OUT/raw.txt")
  80. echo "linked: $nok .COM files, $nerr fixtures rejected at compile time, $nbad harness failures"
  81. if [ "$nbad" -ne 0 ]; then
  82. echo "RESULT: FAIL (harness could not link every compiling fixture)"
  83. exit 1
  84. fi
  85. fi
  86. # ---- independent verification of the bytes on disk ------------------------
  87. python3 - "$OUT" <<'PYEOF'
  88. import sys, os, re, glob
  89. out = sys.argv[1]
  90. # ENT_SZ and HDR_SZ are the layout constants, and they are RESTATED here on
  91. # purpose: the checker must not ask the code under test what the answer is.
  92. #
  93. # RT_SZ is different, and it is NOT restated. It used to be a literal, and it
  94. # was WRONG - 391, against a runtime of 432 bytes - so the header was read at
  95. # offset 394 instead of 435 and every one of the 30 .COM files "failed" on a
  96. # header full of code bytes. A duplicated constant that has silently drifted
  97. # is not an independent check; it is a second source of truth that lies, and
  98. # it lies in the direction of looking like the compiler is broken.
  99. #
  100. # So the runtime's size is MEASURED, from the .COM itself: the runtime is the
  101. # region between the entry jump and the program header, and the header is
  102. # found by its own signature rather than by an assumed offset (hdrFlag = 1,
  103. # with the code END and the data base where the layout says they are). If
  104. # the runtime ever changes size, this follows automatically; if the LAYOUT
  105. # changes, the header stops being found and the checker says so instead of
  106. # quietly measuring the wrong thing.
  107. #
  108. # The measurement is still independent of the compiler - it reads the emitted
  109. # file, not a Modula-2 variable - so it cannot be satisfied by the code under
  110. # test agreeing with itself. tests/check_runtime.py pins the size explicitly,
  111. # which is where a deliberate size change should be noticed.
  112. RT_SZ = None # measured per .COM by find_header, below
  113. # The image starts with a three-byte JMP at offset 0 -- see the layout comment
  114. # in Compiler.Inittur. It has to be there: a .COM is entered at file offset
  115. # 0, and until the jump existed this checker ASSERTED that the runtime was at
  116. # offset 0, which is precisely the bug. A checker that pins a wrong invariant
  117. # is worse than no checker, because it makes the wrong thing look tested.
  118. ENT_SZ = 3 # E9 lo hi
  119. HDR_SZ = 16 # 5 header words + 3 buffer words, see Compiler
  120. # RTSZ (image offset of the program header), PROLOG (RTSZ + HDR_SZ, where the
  121. # entry jump must land) and DATAB (RTSZ + 1000h, the compiler's data base) are
  122. # all DERIVED PER FILE by find_header below, not written down here. They used
  123. # to be module constants built on the restated RT_SZ, which is the bug this
  124. # whole block exists to remove: every one of them was wrong by 41 bytes, and
  125. # a checker that is consistently wrong in a simple direction does not fail -
  126. # it re-reports the same false 30 failures, in which the real ones hide.
  127. # The load bias: DOS puts a .COM's first byte at CS:0100, and CS = DS, so an
  128. # image offset K lives at DS:(K + 0100h). Every ABSOLUTE address in the
  129. # image must carry it; relative encodings (the entry jump, every CALL) must
  130. # not, since both operands shift together. Restated here so that the header
  131. # checks below compare against the addresses the program will actually use,
  132. # and so that the +0100h in them is a decision this checker made rather than
  133. # an accident of the compiler's. See Runtime.LoadBias.
  134. #
  135. # This is the THIRD bias of the same family in this file, and the subtlest:
  136. # the entry jump (a jump that landed on the end of the code), the RT_Entry
  137. # offsets (CALLs that landed inside a neighbouring runtime entry) and this
  138. # one (absolute addresses that landed 0100h low, inside the runtime) all
  139. # produce a program that STARTS, RUNS and PRINTS something. Only running it
  140. # finds this one; the byte checks are all satisfied by an address that is
  141. # consistently 0100h wrong.
  142. LOAD_BIAS = 0x100
  143. # initmem's prologue, which is the runtime's only reader of the program
  144. # header. The displacements +4 and +6 below are the whole point of this
  145. # constant: the header word checks further down read hdrDS at +4 and hdrHeap
  146. # at +6, and initmem has to read the SAME two words or it clears the wrong
  147. # range. It used to read +8 (hdrMax, which the compiler patches to 0), so it
  148. # zeroed nothing at all, and nothing here noticed -- the emitted loop was
  149. # perfectly well formed, it just never ran. Asserting the bytes and the
  150. # header offsets together is what closes that gap.
  151. #
  152. # It is the FIRST ELEVEN BYTES OF THE RUNTIME, so it sits at image offset
  153. # ENT_SZ, not 0.
  154. HEAD = '8B F0 8B 54 04 8B 4C 06' # 11 bytes of initmem, see below
  155. HDR_DS_WORD = 4 # header word holding the data base
  156. HDR_HEAP_WORD = 6 # header word holding the data end
  157. # Byte 4 of HEAD is the displacement of initmem's MOV DX,[SI+?], and byte 7
  158. # the displacement of its MOV CX,[SI+?]. The checks below read the header
  159. # words at HDR_DS_WORD and HDR_HEAP_WORD, so tying those two displacements to
  160. # the same two constants is what makes the runtime and the compiler agree by
  161. # construction rather than by coincidence.
  162. assert [int(HEAD.split()[4], 16), int(HEAD.split()[7], 16)] == \
  163. [HDR_DS_WORD, HDR_HEAP_WORD], \
  164. 'initmem no longer reads the two header words this checker verifies'
  165. raw = open(os.path.join(out, 'raw.txt')).read()
  166. rows = re.findall(r'(\S+\.pas)\s+OK\s+com=(\d+)\s+image=(\d+)\s+data=(\d+)\s+nonzeroInGap=(\d+)', raw)
  167. if not rows:
  168. print('RESULT: FAIL (no linked fixtures found in output)')
  169. sys.exit(1)
  170. def find_header(d):
  171. """Locate the program header by its own signature. Returns its image
  172. offset, or None.
  173. The header is eight words at image offset ENT_SZ + rtSz, and the layout
  174. says what they are (offsets here are BYTES into the header, which is why
  175. HDR_DS_WORD is 4 and not 2 - the words are 2 bytes each and 1-based by
  176. two, not by one):
  177. +0 1 hdrFlag, always 1
  178. +2 code end + bias hdrCS
  179. +4 data base + bias hdrDS, where data base = hdrOff + 1000h
  180. +6 data end + bias hdrHeap, which is hdrDS + dataBytes
  181. hdrDS ties the header to its OWN offset, so the offset is recoverable from
  182. the file without assuming a runtime size: hdrOff = hdrDS - 1000h - bias.
  183. A candidate is accepted only if hdrFlag is 1, hdrDS satisfies that
  184. equation, hdrHeap is above hdrDS (a heap below its own base is not a
  185. layout, it is a coincidence), and the runtime's known first bytes are
  186. where they belong. initmem is the ONLY code in the image that reads the
  187. header, so its bytes cannot themselves move: they are at ENT_SZ always.
  188. Measuring beats restating the size, and it is not a loss of independence:
  189. it reads the EMITTED FILE, so the compiler cannot satisfy it by agreeing
  190. with itself. tests/check_runtime.py is where the runtime's size is pinned
  191. deliberately, and this checker reports the size it measured on every run,
  192. so a change there is visible rather than absorbed.
  193. """
  194. head = bytes(int(x, 16) for x in HEAD.split())
  195. if d[ENT_SZ:ENT_SZ + len(head)] != head:
  196. return None # no runtime: nothing to measure
  197. for off in range(ENT_SZ, len(d) - HDR_SZ + 1):
  198. w = (lambda b: int.from_bytes(d[off + b:off + b + 2], 'little'))
  199. if w(0) != 1: # hdrFlag
  200. continue
  201. if w(HDR_DS_WORD) != off + 0x1000 + LOAD_BIAS: # hdrDS
  202. continue
  203. if w(HDR_HEAP_WORD) <= w(HDR_DS_WORD): # hdrHeap
  204. continue
  205. if w(2) - LOAD_BIAS < off + HDR_SZ: # hdrCS
  206. continue
  207. return off
  208. return None
  209. bad = 0
  210. last_rt = None
  211. for name, com, image, data, nzg in rows:
  212. com, image, data, nzg = int(com), int(image), int(data), int(nzg)
  213. # ComTest writes the .COM by BASENAME beside itself (it cannot graft a
  214. # directory onto a source path), so the checker must look for the bare
  215. # name, not the full source path the fixture was read from.
  216. path = os.path.join(out, os.path.basename(name)[:-4] + '.COM')
  217. errs = []
  218. if not os.path.exists(path):
  219. errs.append('no .COM file')
  220. d = b''
  221. else:
  222. d = open(path, 'rb').read()
  223. # Everything below is expressed in terms of where the header actually is,
  224. # measured from this file, rather than where a literal says it should be.
  225. hdrOff = find_header(d)
  226. if hdrOff is None:
  227. errs.append('no program header found: the layout this checker knows '
  228. 'how to look for is not the one in the file')
  229. RTSZ, PROLOG, DATAB = ENT_SZ, ENT_SZ + HDR_SZ, ENT_SZ + 0x1000
  230. else:
  231. RTSZ = hdrOff
  232. PROLOG = hdrOff + HDR_SZ
  233. DATAB = hdrOff + 0x1000
  234. if RTSZ != last_rt:
  235. last_rt = RTSZ
  236. print(' measured runtime size: %d bytes (header at image offset '
  237. '%d)' % (RTSZ - ENT_SZ, RTSZ))
  238. # The entry jump. This is the one assertion in the whole project that can
  239. # see where execution STARTS, because it is the only one that cares. It
  240. # has caught THREE real bugs, all in the same three bytes, and all of them
  241. # invisible to every other check here:
  242. #
  243. # 1. no jump at all, so a .COM began by executing the runtime's initmem
  244. # with whatever the loader left in AX;
  245. # 2. a jump to `pc`, one byte past the last instruction, into the
  246. # zero-filled code/data gap, where the CPU slides through
  247. # `ADD [BX+SI],AL` until it faults;
  248. # 3. a jump to RTSZ, which is the program HEADER - sixteen bytes of DATA
  249. # that the CPU then decodes as instructions. This one is the reason
  250. # the target is pinned to PROLOG and not to RTSZ: whether it works
  251. # depends entirely on how those sixteen bytes happen to decode, so
  252. # writeln('hi') ran correctly by sliding through them while t07 hung
  253. # on a LOCK-prefixed ADD with a displacement crossing a page. The
  254. # correct target is the first instruction, and there is no reason for
  255. # a checker to accept a range.
  256. if len(d) >= ENT_SZ:
  257. if d[0] != 0xE9:
  258. errs.append('byte 0 is %02X, not the E9 of the entry jump' % d[0])
  259. # The jump's displacement is measured from the end of the jump.
  260. want_rel = PROLOG - ENT_SZ
  261. got_rel = int.from_bytes(d[1:ENT_SZ], 'little')
  262. if got_rel != want_rel:
  263. errs.append('entry jump rel16=%d, want %d; it lands on image '
  264. 'offset %d, want %d (the first instruction, %d bytes '
  265. 'past the header - not the header at %d, and not the '
  266. 'end of the code at %d)'
  267. % (got_rel, want_rel, ENT_SZ + got_rel, PROLOG,
  268. HDR_SZ, RTSZ, image))
  269. # The runtime's own first bytes must follow the jump, and the jump must be
  270. # the only thing before them.
  271. if d[ENT_SZ:ENT_SZ + len(HEAD.split())].hex(' ').upper() != HEAD:
  272. errs.append('runtime not at offset %d (bytes there %s, want %s)'
  273. % (ENT_SZ,
  274. d[ENT_SZ:ENT_SZ + len(HEAD.split())].hex(' ').upper(),
  275. HEAD))
  276. if len(d) != com:
  277. errs.append('file is %d bytes, harness said %d' % (len(d), com))
  278. if DATAB + data != len(d):
  279. errs.append('size %d != dataBase+data %d' % (len(d), DATAB + data))
  280. # the gap between the image and the data area must be entirely zero
  281. gap = d[image:DATAB]
  282. if any(gap):
  283. errs.append('%d non-zero bytes in the code/data gap' % sum(1 for b in gap if b))
  284. if nzg != 0:
  285. errs.append('harness itself reported %d non-zero gap bytes' % nzg)
  286. # the program must start exactly where the runtime ends
  287. if image < RTSZ:
  288. errs.append('image %d shorter than the runtime %d' % (image, RTSZ))
  289. # the program header sits at offset rtSz, and its words must describe the
  290. # image that is actually in the file
  291. if len(d) > RTSZ + 8:
  292. hdr = d[RTSZ:RTSZ+16]
  293. flag = int.from_bytes(hdr[0:2], 'little')
  294. cs = int.from_bytes(hdr[2:4], 'little')
  295. ds = int.from_bytes(hdr[HDR_DS_WORD:HDR_DS_WORD+2], 'little')
  296. heap = int.from_bytes(hdr[HDR_HEAP_WORD:HDR_HEAP_WORD+2], 'little')
  297. if flag != 1:
  298. errs.append('hdrFlag=%d' % flag)
  299. # hdrCS is the end of the code, as a SEGMENT offset like every other
  300. # offset in the header, so the load bias comes off before comparing it
  301. # with the harness's `image` (= rtSz + code, already an image offset).
  302. # Adding RTSZ here would count the runtime twice.
  303. if cs - LOAD_BIAS != image:
  304. errs.append('hdrCS=%d, want %d (end of image, as a segment '
  305. 'offset)' % (cs, image + LOAD_BIAS))
  306. if ds != DATAB + LOAD_BIAS:
  307. errs.append('hdrDS=%d, want %d (= data base %d + load bias %d)'
  308. % (ds, DATAB + LOAD_BIAS, DATAB, LOAD_BIAS))
  309. if heap != DATAB + data + LOAD_BIAS:
  310. errs.append('hdrHeap=%d, want %d (= data base %d + %d + load bias %d)'
  311. % (heap, DATAB + data + LOAD_BIAS, DATAB, data,
  312. LOAD_BIAS))
  313. # initmem must read hdrDS and hdrHeap, not some other pair of header
  314. # words. (It read +8, hdrMax, which the compiler patches to 0, so
  315. # the range it cleared was empty and every global kept whatever the
  316. # loader left in it.)
  317. if [d[ENT_SZ + 4], d[ENT_SZ + 7]] != [HDR_DS_WORD, HDR_HEAP_WORD]:
  318. errs.append('initmem reads header words +%d/+%d, but the data '
  319. 'base and data end are at +%d/+%d'
  320. % (d[ENT_SZ + 4], d[ENT_SZ + 7],
  321. HDR_DS_WORD, HDR_HEAP_WORD))
  322. if errs:
  323. bad += 1
  324. print(' %-24s FAIL %s' % (os.path.basename(name)[:-4], '; '.join(errs)))
  325. else:
  326. print(' %-24s PASS %d bytes' % (os.path.basename(name)[:-4], com))
  327. print('----------------------------------------------------------------')
  328. print('independent .COM check: %d checked, %d failed' % (len(rows), bad))
  329. sys.exit(1 if bad else 0)
  330. PYEOF
  331. rc=$?
  332. [ "$rc" -eq 0 ] || exit 1
  333. echo "RESULT: ALL PASS"