59 Commits
m6 .. m8
Author SHA1 Message Date
arti f340d74472 m8: default the full-loader exceptions to 2ine 2026-11-17 03:14:19 +00:00
arti 2a2efd61d7 m8: two-tier conformance harness (bare by default, loader exceptions) 2026-11-16 18:13:17 +00:00
arti 66d21ebc35 m8: add the 2ine OS/2 harness path and direct-loader default 2026-11-16 16:44:38 +00:00
arti 1315df5548 docs: m8 is the repository default branch 2026-11-16 15:59:53 +00:00
arti af0c5cb617 docs: tick the M8 plan 2026-11-16 12:18:22 +00:00
arti bb78a97313 M8.4: document the final M8 state and full gate sweep 2026-11-16 12:18:04 +00:00
arti e55287f218 M8.3: harden conformance evidence and mixed-provenance report 2026-11-16 06:57:35 +00:00
arti f9b51667c4 M8.3: extend conformance codegen classes and measure the i64 64/32 divide path 2026-11-16 06:30:37 +00:00
arti 5214938b6b tms-link: merge DWARF debug info from multiple translation units 2026-11-16 03:56:43 +00:00
arti dc7de6f3a7 tms-link: address M8 Task 1 review findings
Key archive member labels/placements by member offset so two same-named members cannot overwrite each other; add a dupnamed fixture asserting distinct address ranges. Treat an empty / index as absent, require ASCII decimal sizes, validate odd-member padding and final bounds, and dedupe index entries by member offset. Document the -l/archive ordering and the unit gate's FLIB_LIB/M4_SDK prerequisite (the real-LIB case is skipped with a reason when absent).

Accept the 1990 tools' metadata section bits (0x100/0x400) on allocated sections, which the M6 flib/rts members use, while still writing classic output flags.

Add M6_LINKER=tms-link to runtime.sh and i64.sh: after GSPA, link the same M6.OBJ + flib.lib/rts.lib with tms-link, compare allocated bytes/symbols to the GSPLNK oracle, and run the same MAME marker checks. M8 native-lib now compares tms-link's raw pre-coff-check image.

Add loud-path fixtures for index lies, BSD names, duplicate / and // tables, bad/missing padding, non-ASCII sizes and -l resolution failure; strengthen the no-index exclusion test; add 1990-flag and M5_NATIVE_LINKER docs.
2026-11-16 03:23:49 +00:00
arti 29c30ddcc6 tms-link: read ar archives and extract members selectively
Implement M8.1 native .lib linking: System V !<arch> parsing (/ symbol index, // long-name table, /N references, even-byte padding, loud malformed/truncated errors), in-memory member objects labelled lib(member), and extraction in the archive's own symbol-table order driven by currently undefined globals, iterated to a fixpoint without re-extracting a member. Duplicate definitions and unresolved references fail with object/member names.

Accept archive paths and -l/-lL in the CLI, preserve layout/map/debug behavior, and let scripts/m4/run.sh pass M4_NATIVE_LIBS/M4_NATIVE_RTS archives to tms-link. Relocation addends are now applied as signed 32-bit values (needed by the termtris rts.lib link).

Tests: tms-link archive fixtures and real flib extraction, m7 archive/-l parity, m5 native termtris with tms-link+rts.lib (dis34 match), m6 i64/runtime GSPLNK gates, and scripts/tests/m8/native-lib.sh (FLIB.LIB + RTS.LIB, MAME markers, GSPLNK byte/symbol parity).
2026-11-16 02:56:44 +00:00
arti dc94931eca docs: M8 scope and plan 2026-11-16 02:31:16 +00:00
arti 0f7353c21c docs: point the status line at the M7.4 code heads 2026-11-16 02:23:35 +00:00
arti 2157c24ef8 docs: m7 is the repository default branch 2026-11-16 02:23:23 +00:00
arti 1eaabaa6a0 M7.4: align the remaining COFF-repair comments 2026-11-15 15:56:00 +00:00
arti f471ab8c11 M7.4: soften the COFF-repair mechanism wording 2026-11-15 15:54:09 +00:00
arti 2835990a00 M7.4: make the COFF guard fail and correct the suite attribution 2026-11-15 15:46:35 +00:00
arti 3c024b93b9 docs: tick the M7.4 plan 2026-11-15 15:38:02 +00:00
arti 6e7d5bbe92 M7.4: document the final conformance/performance state
Record the full-suite method, settings, pins and exact counts
(c-torture 1692 = 1366/326/0/0; c-testsuite 220 = 210/10/0/0; all
1912 = 1576/336/0/0), the curated skip classes, the 112 honest pass
flips, the i64 DIVU fast path and its MAME frame measurement, the
conformance-loader COFF repair, and the shipped-tier counts.

Mark M7 complete, keep the M7.1/M7.2/M7.3 counts and limitations
(one debug TU, .lib not readable by tms-link, kept-debug not
loadable, hardware DEFERRED), and state the M7/M8 boundary. Add the
M7.1-M7.4 plan links and the M7.4 gate commands, and distinguish the
curated 48/172 c-testsuite tier from the full-corpus 210/10 result.
2026-11-15 15:37:19 +00:00
arti f8651fcb2f M7.4: triage and curate the full conformance suite 2026-11-15 13:39:28 +00:00
arti 65e6a6e6b8 M7.4: add the full-suite conformance driver and baseline 2026-11-15 08:34:25 +00:00
arti 1e3977132d M7.4: fix the i64div perf gate link, layout and result checks
The M4 default link command's 4 KiB prog region cannot hold the perf
driver's ~8.7 KiB .text, and the old markers at 018A8000 were inside that
.text.  Add a gate-local link command (prog = 40000h) and move the eight
markers to 01A20000, free RAM above the 4 KiB entry stack and inside the
declared ram region.

i64div-map-check.py parses both GSPLNK and tms-link maps and fails if the
marker cells overlap .text/.data/.bss, leave the region, or if a section
leaves its region.  The gate runs it on a host tms-link map and on the
GSPA/GSPLNK map from a link-only pass before MAME, with compile-only and
link-only stop modes for the no-DOSBox checks.

Require the exact deterministic phase checksums (fast 00000001:1E6F9AB4,
slow 00000000:007512AE, hosted and independently recomputed), and extend
the in-image self-check with large-magnitude fast cases: 0xFFFFFFFF/7,
-123/7 (-123 % 7 = -4) and INT32_MIN/3, so a wrong 32-bit quotient or
remainder fails before timing.  The gate documents that -O2 is an
optimizer baseline, not the i64 fast-path measurement.
2026-11-15 08:02:54 +00:00
arti e540db3ca9 M7.4: measure the i64 divide fast path in MAME frames
i64div.sh runs two equal-iteration i64 division workloads on the emulated
part: small operands whose high words are zero (the 32-bit DIVU fast path)
and operands with nonzero high words (the 64-step restoring loop).  The
driver's self-check first proves both paths produce the known M6 values;
the checksums are retained as evidence.

i64div-perf-check.lua polls the start and per-phase completion markers
once per MAME frame and requires the fast phase to complete in materially
fewer frames (slow_frames >= 8 * max(fast_frames,1), slow_frames >= 20).
A frame is a fixed emulated-cycle count, so the comparison is
reproducible.  The gate widens the loader budget to 200..4000 frames for
the slow phase; the M7 full-suite settings are untouched.

The script also has a compile-only preflight (tms-clang + llc, no
DOSBox/MAME) that checks the driver asm for the fast blocks, DIVU and the
slow loop.
2026-11-15 07:48:52 +00:00
arti 5f35a75a0a docs: M7.4 scope and plan 2026-11-15 07:34:12 +00:00
arti 54608c0e32 M7.3: keep hardware evidence and document the bootstrap knobs 2026-11-15 07:26:23 +00:00
arti 11693186bc docs: state the M7.3 gate-change scope precisely 2026-11-15 07:26:15 +00:00
arti ff4cf94176 docs: correct the M7.3 symbol table and evidence claims 2026-11-15 07:26:06 +00:00
arti c756b568ae docs: tick the M7.3 plan 2026-11-15 07:18:02 +00:00
arti 7d07fb787b M7.3: document the runtime/hardware state and rebase the JR fixture 2026-11-15 07:17:33 +00:00
arti 98561252ad M7.3: correct the hardware entry and unit assumptions 2026-11-15 05:16:55 +00:00
arti fe78805872 M7.3: add the real-hardware marker gate with MAME acceptance 2026-11-15 05:09:53 +00:00
arti cdf137f64b M7.3: do not write a byte for fputc(EOF) 2026-11-15 04:55:49 +00:00
arti 38fdeb2e28 M7.3: fix the stderr layout and empty-stream contract 2026-11-15 04:52:25 +00:00
arti 5757f056b0 M7.3: capture stderr as a second conformance stream 2026-11-15 03:55:01 +00:00
arti 9586ed21d1 M7.3: correct the xmore marker comments 2026-11-15 02:23:27 +00:00
arti a6379b206b M7.3: make the xmore flags honest (review round 2)
The ROM builders do not set A8, so markers 4 and 10 are no longer
presented as return values:

- property_called=1 and attrs_called=1 are plain post-call flags.  The
  gate requires the flag, states that the property has no server read-back
  (zero X errors is the only runtime check), and keeps the black margin
  as the real CWBackPixel proof.  Marker 14 pins the 160x120 fill
  geometry (0xA00078) so the margin sample cannot become vacuous.
- InternAtom wording: the display marker only proves the connection was
  live before the call; stage 14 cannot distinguish the intended _XSend
  block from a crash/wrong import.  The isolated probe is narrative entry
  evidence, not a gate check.
- XSetWindowAttributes attrs = {0}; replaces the unsigned int * zeroing
  loop.
- Fix the stale image_roundtrip stage-11 comment (text pixels now set
  stage 12).
- GC wording is 'source call sites; runtime entry not proven', not
  'proves call presence'.
2026-11-15 02:21:08 +00:00
arti 5716e3ca35 M7.3: strengthen the xmore gate evidence (review round 1)
Make the wider-Xlib evidence non-vacuous:

- Child starts with background 1; CWBackPixel=0 and a 160x120 fill leave a
  black margin sampled at screen (300,240).  XChangeWindowAttributes now
  returns a marker (10) and the margin is required; the attrs=1 negative
  control turns it white and fails the gate.
- Marker 4 is the XChangeProperty return (nonzero, not a read-back).
  Marker 11 counts the two explicit XChangeGC calls (presence + no X error;
  the ROM entry is a 2-arg cache flush).  XDrawString is proven by counting
  the set pixels of an XGetImage band (marker 12, 67 in the run).
- Marker 13 stores the live Display just before XInternAtom, so the skip
  cannot be a crash/wrong import; the gate/report state that entry is
  evidenced by the isolated probe.
- Zero the XSetWindowAttributes struct.
- Pin the six wider addresses as constants in validate-syms.sh.
- Print parent(...) instead of win(...) (parent-relative, not child).
- Correct the report's configure/p_img justification and add Fix round 1.
- scripts/m4/run.sh prints M7 MAME: PASS for an M7 marker line; M4 output
  is unchanged.
2026-11-15 02:00:32 +00:00
arti 0cab36a2b0 M7.3: wider VT1200 Xlib surface (xmore)
Add and validate XMapSubwindows, XChangeWindowAttributes,
XConfigureWindow, XInternAtom, XChangeProperty and XChangeGC from the
GUI_APPS table, extend x11m4.h with the X11R4 masks/structs and the ROM
call shapes, and add the xmore client plus its MAME gate.

xmore exercises a parent/child window, XMapSubwindows, the fixed-mask
move/resize ConfigureWindow, WM_NAME (predefined atom 39), CWBackPixel,
XChangeGC, XLoadFont/XDrawString, XFillRectangle, and a heap
XCreateImage/XPutImage/XGetImage/XPutImage/XDestroyImage round trip with
XSync.  Markers at 018A8000+n*20 show stage 14, image 0x13F and 0 errors.

XInternAtom is kept as the last call with an explicit 0xFFFFFFFF skip
marker: the ROM _XSend scatter path (0x3F9B44C0) that carries the name
does not complete in the loader harness (the same direct-send limit the
M4 xshow client records).  If it returns, the client uses the atom and
advances to stage 15.  The GC uses the server default font because the
ROM XLoadFont handle is rejected as GCFont (BadFont); XLoadFont itself is
still exercised and marked.

The M4 runner now accepts M4/M7 marker and PASS lines; M4 behavior is
unchanged.
2026-11-15 01:33:41 +00:00
arti e7f8252470 docs: M7.3 scope and plan 2026-11-15 00:31:17 +00:00
arti 3dccc4d188 docs: scope the M7.2 oracle acceptance to the tested M5 objects 2026-11-15 00:24:27 +00:00
arti e35cb154ce docs: tick the M7.2 plan 2026-11-15 00:16:54 +00:00
arti 8b0b0bcd11 m7.2: document the TI-COFF debug writer and tms-link 2026-11-15 00:14:09 +00:00
arti fefb1daba4 m7.2: prove barrier-synthesized !dbg in the debug gate
Extract the final -O0 @debug_ptr body and require !dbg on the
--bitptr/--lower-bitptr chain (mul, shl, ptrtoint, add, inttoptr) and on
every load/store through the computed pointer.  Line-table rows alone could
stay green if the barrier dropped locations only on the instructions it
synthesizes; this IR-level check fails in that case.

Refresh the stale gate header (three functions, -O2 smoke, indexed
.debug_addr, ptr=30) and note that the exact .debug_addr entry list is
deterministic at the current compiler but should be relaxed on a DWARF
emission change.
2026-11-14 23:01:05 +00:00
arti 46417f53ec m7.2: strengthen Task 3 debug/oracle/cinit gates
- debug.sh: add a pointer/array runtime-GEP function (debug_ptr) with
  asserted line rows/low PC, and build the same TU with tms-clang -g -O2
  through --bitptr/opt/--scale/--lower-bitptr/instcombine; require the
  -O2 object's .debug_* sections and dwarfdump its debug.c/function/low PC.
  Read .debug_addr entries by index and assert the CU low/high PC and
  .debug_line file index.
- oracle.sh: load both the GSPLNK and tms-link images in MAME with the same
  markers; require a minimum count and the names the checks depend on, and
  document the absolute/undefined C_EXT exclusion.
- cinit.sh: assert the object relocation (0x10, .bss/_cinit_target base,
  addend 0), compare the 28-byte optional header with GSPLNK, and link
  CINIT.O alone to exercise the synthesized public cinit symbol.
- tmscoff.py: point the order-relaxation comment at the Task 1 lit test that
  still pins the llc section order.
2026-11-14 22:54:19 +00:00
arti 0075e57c0d m7.2: add object/debug end-to-end gates
- oracle.sh: link the M5 native objects with GSPLNK and tms-link, require
  identical allocated bytes/public symbols through the independent reader,
  then run the tms-link image in MAME and decode _native_value with dis34.
- cinit.sh: a C TI .cinit record table (packed u16 count/u32 destination/
  data words) linked by tms-link, the termtris copy loop in MAME, cinit at
  the .cinit origin, the destination resolved to a bit address, and
  bytes/placement equal to GSPLNK.
- longname.sh: a 44-character public function defined in one TU and called
  from another, linked by tms-link, full name in the map, runs in MAME.
- debug.sh: tms-clang -g -> TI-COFF -> tms-link --keep-debug, .debug_*
  wrapped in a minimal ELF32 container and validated with llvm-dwarfdump
  (debug.c, line rows, low PC 0x314000, high_pc byte size, string names),
  plus the stripped image loading in MAME.
- tms-clang: pass -g through to clang; the bit-pointer passes preserve !dbg.
- tms-link: accept GSPA's .text/.data/.bss/.cinit order as well as llc's
  .text/.data/.cinit/.bss order (the real startup cinit.asm shape).
2026-11-14 22:21:03 +00:00
arti 38ab394c8b m7.2: tighten tms-link oracle and reader (fix round 1) 2026-11-14 21:50:03 +00:00
arti b21e762058 m7.2: add tools/tms-link native TI-COFF linker 2026-11-14 21:36:08 +00:00
arti d7209392f2 docs: M7.2 scope and plan 2026-11-14 20:36:32 +00:00
arti e09d85c99f docs: tick the M7.1 plan 2026-11-14 20:33:05 +00:00
arti ad6b39738a m7.1: close the final-review evidence gaps 2026-11-14 20:32:54 +00:00
arti 4110a24c23 m7.1: document the M7.1 state and refresh the generic manifest 2026-11-14 20:08:43 +00:00
arti f79eadfda1 m7.1: gate the odd-offset pointer and wide-integer .data cases 2026-11-14 18:13:16 +00:00
arti b0048b8151 m7.1: add the .data i64/aggregate/bitfield gate 2026-11-14 17:36:33 +00:00
arti 773dd7597e m7.1: cover the union and non-TMS stride controls 2026-11-14 16:55:45 +00:00
arti e1436ba112 m7.1: add the sub-byte stride diagnostic gate 2026-11-14 15:43:54 +00:00
arti b313de480b m7.1: keep narrowing base casts out of the barrier
Fix the fix-round regression: the base matcher stripped any zext/trunc,
so `(unsigned short)(unsigned)p + 24` lost its 16-bit truncation and
became `p + 24` at both -O0 and -O2.  stripWideningCasts now strips only
zext/sext and truncs to at least the 32-bit pointer width; a trunc below
i32 stops the match, leaving the shape unbarriered with its
`and 0xffff`/`and 0xff` intact (the base commit's value).

Allow widening sext on the base as well, closing the signed 64-bit
pointer-int shape: `(char *)((long long)(int)p + 24)` now becomes
`@__tms_bitptr(i32 24, ptr p)` instead of `getelementptr i8, p, 192`.
Use the fixed 32-bit TMS34010 pointer width rather than an absent module
DataLayout's 64-bit default, which misjudged a trunc to i32.

Add @narrow16/@narrow8/@narrow16and/@late64s to bitptr.ll (narrow shapes
must not emit a call), negative tests for the mismatched declaration,
body and non-call use fatal paths, a late64s M0 check with the late
positive scoped to @late itself, and narrow16/narrow8/late64s runtime
markers plus IR checks in the M7 gate.  Update the pointer-o2.sh header.
2026-11-14 13:57:48 +00:00
arti 9cf31b9b9b m7.1: barrier 64-bit pointer-int shapes
Extend --bitptr's raw inttoptr barrier through the zext/trunc clang emits
for a 64-bit pointer-int expression, so
`inttoptr(add(zext(ptrtoint p), i64 24))` becomes
`@__tms_bitptr(i32 24, ptr p)` instead of a post-scale `getelementptr
i8, p, 192`.  The pointer is 32-bit, so the addend is zext/truncated to
the low word.  The matcher also covers the reversed add operand order and
the sub form (negated addend).

Harden getBitPtrFn/lower_bitptr_calls: an existing @__tms_bitptr with a
mismatched signature or body, or a non-CallInst/mismatched use, now fails
loudly instead of leaving an undefined external.

Add @late64 (and sub/reversed/trunc) to bitptr.ll, assert the
nounwind readnone declaration, add a late64 M0 shape check (24, never
192) and a late64 runtime marker to the M7 gate.  Tighten the gate's
one-scale check to reject a second shl i32 in copy_back and to match
SLL 3/SLL 6 exactly (not SLL 31).  Update the stale M6 comments in
bitscale.cpp and the c-torture -O2 comment.
2026-11-14 13:14:56 +00:00
arti d3f411864d m7.1: add the -O2 bit-pointer semantic barrier
Replace the M6 pre-opt --scale with --bitptr: every source GEP (and an
inttoptr of a bit addend over a ptrtoint base) becomes an opaque
@__tms_bitptr(i32 bitoff, ptr base) call (nounwind readnone), so the
optimizer cannot canonicalize an already-bit offset back into a byte GEP
for the post-opt --scale to multiply by 8 again.

tms-clang -O2 is now clang -> --bitptr -> opt default<O2> -> --scale
(optimizer byte GEPs only) -> --lower-bitptr -> opt instcombine.  -O0 is
clang -> --bitptr -> --lower-bitptr.  --lower-bitptr restores
inttoptr(add(ptrtoint base, bitoff)); the final instcombine restores the
M0 int_diff 8/32 folding and the shim's emit_uint64 needs
instcombine<no-verify-fixpoint> for a known zext/nneg non-idempotent
shape.  Constant-expression GEPs keep the inttoptr/add form.

Remove the shim memmove constant-step workaround (natural d += n) and
add the M7 -O2 pointer gate (C driver at -O2, GSPA/GSPLNK, MAME, exact
markers/bytes and one-scale IR/asm evidence).  Update the M0 shape
checks for the final instcombine's bit-index `getelementptr i8, %p, 24`
late form (still 24 bits; the old 192 is rejected).
2026-11-14 12:26:40 +00:00
arti 91d42be168 docs: M7 scope and M7.1 plan 2026-11-14 11:39:14 +00:00
116 changed files with 16071 additions and 438 deletions

No files matched your search

+879 -163
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,103 @@
# TMS34010 M7.1 — Correctness and ABI Residuals Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Remove the remaining M6 correctness residuals: the `-O2` pointer over-scale, the sub-byte array/nested stride divergence, and the `.data` i64/aggregate/bitfield initializer gap, while keeping every M2–M6 gate green.
**Architecture:** The IR pipeline keeps the proven pre-opt bit scale, but replaces the scaled GEPs with opaque `@__tms_bitptr` calls so the optimizer cannot re-canonicalize them into already-bit GEPs. The post-opt pass scales only optimizer-created byte GEPs; a lowering pass then replaces the calls with `inttoptr(add(ptrtoint,...))` and a final instcombine restores the M0 folding. The sub-byte stride is diagnosed at compile time rather than silently byte-rounded. `.data` emission becomes recursive (i64, structs, unions, arrays, bitfields) in both raw and object modes.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `clang`, `tms-bitaddr`, `tms-clang`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §4.1–§4.2, §8 (M7.1), and the M6 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean`, branch `m7` (from m6 `bdc16ab8d4b6`); project work in `tms-c-compiler`, branch `m7` (from m6 `9dc8f28`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the native TI-COFF/GSPLNK path, the asm oracle, the `dwt` loader, and every M2–M6 gate green.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD for every task; commit per task; no push until the M7.1 final review is clean, then push `m7`.
- i64 `.data` words are little-endian (LSW first); the i64 argument/hidden-slot order stays MSW-first.
- Do not silently byte-round a sub-byte record stride: the diagnostic must be loud (default-on warning/error).
- Keep the narrow-load/store nonzero-offset guard from `bdc16ab8d4b6`.
## Review Focus
1. **The bitptr barrier.** Does the optimizer see opaque calls (no folding through them), does the post-opt pass scale only byte GEPs, does the lowering restore the M0 `int_diff = 8/32` shape, and is `p += n` correct at the default `-O2` with one scale?
2. **Sub-byte stride.** Does the diagnostic fire for the 1987 oracle `struct s arr[2]`/`struct nest`, not for byte-multiple records, and is the message actionable?
3. **`.data` exactness.** i64 word order, packed struct/bitfield bytes, unions/arrays, relocations, raw and object modes; no over-read/write; unsupported shapes stay loud.
4. **No M2–M6 regression** and the shim `memmove` workaround removed with the runtime gate proving the natural `d += n`.
---
### Task 1: The `-O2` bit-pointer semantic barrier
**Files:**
- Modify: `tools/tms-bitaddr/bitscale.cpp` (`--bitptr`, `--lower-bitptr`, tests)
- Modify: `tools/tms-bitaddr/tests/run.sh`, add `tests/bitptr.ll`
- Modify: `scripts/tms-clang` (pipeline)
- Modify: `scripts/tests/m5/conformance/shim.c` (remove the `memmove` workaround)
- Create: `scripts/tests/m7/pointer-o2.sh` (C gate)
- Test: `scripts/tests/m0/run.sh`, `scripts/tests/m6/runtime.sh`, the full M2–M6 gates
**Interfaces:**
- Consumes: the M6 pre-opt `--scale` + post-opt `--scale` pipeline and the known `p += n` over-scale.
- Produces: `@__tms_bitptr(i32 bitoff, ptr base)` (nounwind/readnone), `--bitptr`/`--lower-bitptr`, a pipeline that keeps opaque calls through `opt`, scales only post-opt byte GEPs, lowers the calls, and restores the M0 folding.
- [x] **Step 1: Write the failing tests.** Add `tests/bitptr.ll` to the `tms-bitaddr` suite: `--bitptr` turns `getelementptr i8, p, n` into a `@__tms_bitptr` call with the bit offset; `--lower-bitptr` turns it back into `inttoptr(add(ptrtoint p, n*8))`. Add `scripts/tests/m7/pointer-o2.sh`: a C driver with `char *p; p += n; *p = ...;` and the `memmove` overlap shape, compiled at `-O2`, linked with GSPA/GSPLNK, run in MAME, checking the correct bytes.
- [x] **Step 2: Run it red.** The current pipeline double-scales (`%bit.off = shl n,3` twice / `p + n*64` bits) and/or the shim workaround is required; the new gate fails.
- [x] **Step 3: Implement the barrier.** Add the `--bitptr`/`--lower-bitptr` modes; update `tms-clang` to clang → `--bitptr` → `opt` → `--scale` (post-opt byte GEPs) → `--lower-bitptr` → `opt -passes=instcombine` → output (at `-O0`: clang → `--bitptr` → `--lower-bitptr`); remove the shim `memmove` workaround (natural `d += n`).
- [x] **Step 4: Run green.** `scripts/tests/m7/pointer-o2.sh`, `scripts/tests/m0/run.sh` (`int_diff` 8/32, `late` 24), `scripts/tests/m6/runtime.sh` both levels, the full TMS34010 lit suite, and the M2–M6 gates.
- [x] **Step 5: Commit.** `tms-bitaddr` + `tms-clang` + shim + the gate.
### Task 2: Sub-byte array/nested stride diagnostic
**Files:**
- Modify: `clang/lib/Basic/Targets/TMS34010.cpp/.h` (target hook/flag if needed)
- Modify: `clang/lib/Sema/SemaType.cpp` / `SemaDecl.cpp` and `clang/include/clang/Basic/DiagnosticSemaKinds.td`
- Create: `clang/test/Sema/tms34010-subbyte-stride.c` (or the target test location)
- Create: `scripts/tests/m7/stride.sh`
- Test: the oracle `struct s { unsigned a:3; unsigned b:5; int c:4; unsigned d:20; unsigned e:4; }` and `struct nest { struct s a; int b; }`
**Interfaces:**
- Consumes: the M4/M6 packed record layout (36-bit content, 5-byte `sizeof`).
- Produces: a default-on diagnostic for arrays/nested members of records whose bit content is not a byte multiple, naming the byte-rounded and TI bit strides; no warning for byte-multiple records.
- [x] **Step 1: Write the failing test.** `stride.c` with `struct s arr[2];`, `struct nest n;`, and a byte-multiple control (e.g. `struct cross`); compile with `-Werror=tms34010-subbyte-stride`; the first run has no diagnostic (red).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Compute the record bit content (last field bit offset + width, recursively for nested fields) and diagnose an array element/nested field whose content is not a byte multiple. A warning is the acceptance; an implementation of the bit-content stride is optional only if sound.
- [x] **Step 4: Run green.** `stride.sh`; the Sema test; M4/M5/M6 layout/bitfield/aggregate gates.
- [x] **Step 5: Commit.**
### Task 3: `.data` i64/aggregate/bitfield initializers
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010AsmPrinter.cpp` (raw and object initializers)
- Create: `llvm/test/CodeGen/TMS34010/m7-data-initializers.ll`
- Create: `scripts/tests/m7/data.sh` (C + MAME, raw bytes)
- Test: the M5 object/native gates and the M6 runtime/conformance subset
**Interfaces:**
- Consumes: the M5 `.data` emitter (integers ≤32, f32/f64, pointers, byte arrays, zero).
- Produces: recursive struct/union/array/aggregate-zero emission and i64 two-word LSW-first emission in raw and object modes, with relocations; the existing unsupported-type diagnostics stay.
- [x] **Step 1: Write the failing test.** `m7-data-initializers.ll` and `data.sh` with `long long x = 0x1122334455667788;`, a packed struct, a bitfield struct, a union, an array of structs, and a pointer field; the current emitter rejects them (`M2 .data ...`).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Extend `emitDataInitializer` and `emitDataInitializerObject` recursively; i64 LSW-first; exact packed sizes; relocations; keep vectors/i128/unsupported loud.
- [x] **Step 4: Run green.** `data.sh` (raw bytes/MAME), the object path, `m5/native.sh`, `m5/object-smoke.sh`, the M6 runtime/conformance gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.1
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M2–M7.1 gate list
- [x] **Step 1: Update the docs** for the bitptr barrier, the stride diagnostic, `.data` coverage and the new gate counts; keep the M7.2–M7.4 boundary.
- [x] **Step 2: Run every gate** (M2–M6 full list + `scripts/tests/m7/*`; lit; conformance; generic).
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.1 removes the default-`-O2` correctness risk and the M6 `.data`/stride gaps. M7.2 owns debug info and the native linker; M7.3 the wider Xlib/stderr/hardware; M7.4 the full external suites and performance. The compiler repo is canonical; the project holds the harness, plans and gates.
@@ -0,0 +1,119 @@
# TMS34010 M7.2 — Object/Debug (Native Linker and TI-COFF Debug Info) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the M7.2 object/debug residuals: emit real debug information in the native TI-COFF object, and replace the GSPLNK dependency for the native path with `tools/tms-link`, including `.cinit` and public names longer than GSPA's 31-character limit, while keeping the GSPLNK output as the oracle.
**Architecture:** The MC object writer becomes a small TI-COFF **linker input** producer: optional `.cinit`, optional non-allocated `.debug_*` sections with long names, and the existing `.text`/`.data`/`.bss`. `llc` gains DWARF emission by setting `SupportsDebugInformation`; the asm path is unchanged because the compiler only emits debug for object output and existing IR has no `!dbg`. A new Python linker (`tools/tms-link`) reads those objects, lays out the four sections, resolves symbols and R-RELLONG fixups, and writes a position-dependent linked image the existing dwt loader accepts. Debug sections are stripped from the load image by default and kept with `--keep-debug` for `llvm-dwarfdump`.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `llvm-dwarfdump`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.2), §4.1–§4.2 (ABI) and §7.8 (tooling); the M7.1 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean` (branch `m7`, base the M7.1 push `065998da6f3c`); project work in `tms-c-compiler` (branch `m7`, base `e09d85c`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the asm oracle (GSPA/GSPLNK), the dwt loader, and every M2–M7.1 gate green.
- The default native gate must keep linking the M5/M6 objects with GSPLNK until the `tms-link` oracle gate proves byte equality; then the gates may link with `tms-link` where they exercise it, while at least one gate keeps GSPLNK as the oracle each run.
- `.cinit` is the TI init-record table (`u16 word count`, `u32 destination`, data words), not a raw image. Do not invent a second format.
- Debug info is object-path only. `-filetype=asm` must not gain `.loc`/`.debug_*` output that GSPA cannot assemble.
- Public names are not truncated on the object path; GSPA's 31-character truncation stays an asm-path limitation.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD; commit per task; no push until the M7.2 final review is clean.
## Review Focus
1. **TI-COFF exactness.** Section order, bit sizes, long names (`/offset`), `.cinit` flags, `.debug_*` flags 0, relocations in debug sections, optional header fields. Existing three-section objects must be byte-identical when no `.cinit`/debug is present.
2. **Debug validity.** `llvm-dwarfdump` reads the kept `.debug_*` sections after linking; line tables name the source and lines; low-PC values equal the linked addresses; the default image is stripped.
3. **Linker correctness.** Relocation addends (same-section `0xFFFF`, section-symbol and undefined-external forms), alignment/placement, duplicate/undefined symbols, long names, `.cinit` placement, map, and loader acceptance.
4. **Oracle equality.** `tms-link` vs GSPLNK: allocated section bytes and symbol addresses identical for the M5/M6 objects; no gate silently drops one side.
5. **No M2–M7.1 regression** and no asm-output change.
---
### Task 1: TI-COFF writer: `.cinit`, debug sections, long names
**Files:**
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCObjectWriter.{h,cpp}`
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCAsmInfo.cpp` (`SupportsDebugInformation`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (explicit `.cinit` section lowering if needed)
- Create: `llvm/test/CodeGen/TMS34010/m7-cinit-section.ll`, `m7-debug-info.ll`
- Test: the full TMS34010 lit suite; the M5 object/native gates unchanged
**Interfaces:**
- Consumes: the M7.1 writer (three sections, `/`-less names, bit sizes, R-RELLONG).
- Produces: optional `.cinit` (data flags `0x40`, after `.data`, only when non-empty), optional `.debug_*` sections (flags `0`, long names via the COFF string table), long section names in headers, and DWARF emission from `llc -filetype=obj` when the module has `!dbg`.
- [x] **Step 1: Write failing tests.** `m7-cinit-section.ll`: a global in `section ".cinit"` plus a normal function; `llc -filetype=obj` must produce a fourth section named `.cinit` with the correct bytes/relocation. `m7-debug-info.ll`: a function with `!dbg` locations; `llc -filetype=obj` must produce `.debug_line`/`.debug_info` (long names). A small parser (the project `coff.py` or a new `tools/tms-link/tmscoff.py`) asserts the sections; the current writer fails (`.cinit` has no representation; debug unknown).
- [x] **Step 2: Run red.** Both objects fail as expected; the three-section objects stay unchanged.
- [x] **Step 3: Implement.**
- Make the section list dynamic: `.text`, `.data`, `.cinit` (if present), `.bss`; emit section symbols/aux for each used section; keep `.text` required only when the module has code.
- Section headers: names >8 bytes become `/` + decimal string-table offset; build the string table before writing headers (symbols already share it). The string table starts with its own 4-byte size.
- Debug: set `SupportsDebugInformation = true`; accept non-empty sections whose names start with `.debug_` (and `.debug_*` from the DwarfDebug path), flags 0, with R-RELLONG relocations; keep unknown non-debug sections loud. Omit empty debug sections so existing objects stay three sections.
- Keep `-filetype=asm` free of DWARF: the asm path has no `!dbg` in every existing gate; document that debug is object-only. If AsmPrinter emits `.loc` with debug IR in asm mode, gate it off (target AsmPrinter check) rather than weakening GSPA acceptance.
- `.cinit` explicit section: ensure `__attribute__((section(".cinit")))` and `section ".cinit"` IR lower to an MC section named `.cinit`.
- [x] **Step 4: Run green.** New lit tests; full lit (107 + new); `m5/object-smoke.sh`, `m5/native.sh`, `m5/native-link.sh`; `m7/data.sh` (byte-identical objects); the three-section assertion in `m5/native-link.sh` stays.
- [x] **Step 5: Commit** (compiler + any project test parser).
### Task 2: `tools/tms-link` native linker
**Files:**
- Create: `tools/tms-link/tms-link` (Python 3 CLI), `tools/tms-link/tmscoff.py` (reader/writer)
- Create: `tools/tms-link/tests/run.sh` (+ fixtures)
- Create: `scripts/tests/m7/link.sh` (linker unit/self-test gate)
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` opt-in path; default GSPLNK)
**Interfaces:**
- Consumes: one or more relocatable TI-COFF objects (Task 1), the entry object, and the M4/M5 defaults (`.text` `018A0000`, `.bss` `01A00000`, `prog`/`ram`).
- Produces: `tms-link -o OUT [--map MAP] [--entry SYM] [--text ADDR] [--data ADDR] [--cinit ADDR] [--bss ADDR] [--keep-debug|--strip-debug] OBJ...`; a linked position-dependent COFF (`nreloc=0`, optional header populated), a map (`%08x %s` lines + `ENTRY POINT SYMBOL: "..."`), symbol resolution for long public names, `.cinit` placement after `.data`, and loud duplicate/undefined/unsupported-relocation errors.
- [x] **Step 1: Write failing tests.** Feed it two tiny relocatable objects produced by `llc` (one defining a global/function, one referencing it) plus a `.cinit` object; assert the linked section addresses, resolved fields, map lines, and `nreloc=0`. Feed it a duplicate definition, an undefined external and an R-RELWORD and require loud failures.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Reader: mirror `vendor/vt1200/dwt/loader/coff.py` (header, sections, long names, symbols with aux, relocations).
- Layout: `.text` at the text origin; `.data` immediately after (`align 16` bits); `.cinit` after `.data`; `.bss` at the bss origin. Sections are word-aligned; sizes stay in bits; `.bss` is virtual.
- Symbols: section symbols get the output paddr; defined globals get paddr + section-relative value; undefined externals resolve to the unique definition; locals are resolved from their section. Public long names are preserved byte-for-byte.
- Relocations: for each R-RELLONG, read the 32-bit field (the bit addend), resolve `S` from the symbol index (`0xFFFF` = the section base), write `S + addend`. Leave no relocations in the output.
- Optional header: magic `0x0108`, vstamp `199`, text/data/bss sizes and starts, entry symbol; match GSPLNK's shape.
- Debug: strip `.debug_*` by default; `--keep-debug` copies them with their relocations resolved against the linked addresses. Refuse more than one debug-bearing object in M7.2 with a clear message.
- Map: section allocation and global symbol addresses in a stable,
greppable form. Source-line ranges are the kept `.debug_*` data (`.debug_line`)
validated with `llvm-dwarfdump` in Task 3; the linker does not parse DWARF
for the text map.
- [x] **Step 4: Run green.** `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`; link `scripts/m5/native-link.c` + the GSPA entry object and compare allocated bytes/symbol addresses with GSPLNK.
- [x] **Step 5: Commit** (project; plus the `M4_LINKER` hook).
### Task 3: End-to-end object tests and the GSPLNK oracle
**Files:**
- Create: `scripts/tests/m7/oracle.sh` (both linkers, byte/symbol comparison, MAME)
- Create: `scripts/tests/m7/cinit.sh`, `scripts/m7/cinit-entry.asm`, `scripts/m7/cinit.c`
- Create: `scripts/tests/m7/longname.sh`, `scripts/m7/longname-a.c`, `scripts/m7/longname-b.c`
- Create: `scripts/tests/m7/debug.sh`, `scripts/m7/debug.c`, `scripts/m7/elf-debug-wrap.py` (test-only ELF wrapper for `llvm-dwarfdump`)
- Modify: `scripts/tms-clang` (`-g` pass-through) if needed
**Interfaces:**
- Consumes: Task 1's debug objects, Task 2's linker and `M4_LINKER` hook.
- Produces: gates that prove (a) `tms-link` == GSPLNK on the allocated image, (b) `.cinit` records are placed/relocated and the entry copies them in MAME, (c) a 40-character public function links and runs across two TUs, (d) the kept debug image validates with `llvm-dwarfdump` and the default image is stripped.
- [x] **Step 1: Write the failing gates.** `oracle.sh` links the M5 native objects both ways and requires identical `.text`/`.data`/`.bss` bytes and symbol values, plus the existing MAME markers. `cinit.sh` builds a C `.cinit` table, links with `tms-link`, and requires the entry's copy loop to write the expected words in MAME. `longname.sh` defines/calls a >31-character public symbol across two TUs. `debug.sh` compiles with `-g`, links `--keep-debug`, wraps the `.debug_*` sections in a minimal ELF container, and runs `llvm-dwarfdump` for the filename/line/address; it also asserts the default link has no debug sections and the image runs.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement the gates and any missing plumbing** (`tms-clang -g`, `M4_LINKER`, the ELF wrapper, the entry/cinit fixture). Keep each gate runnable alone and serial with MAME.
- [x] **Step 4: Run green.** All four gates, the M5 object/native gates and the M7.1 gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.2
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.2 list
- [x] **Step 1: Update the docs** for the debug format and validation path, the native linker (CLI, layout, map, `.cinit`, long names, strip/keep debug), the oracle comparison, the single-debug-TU limit, and the new counts. Correct the M6/M7.1 `.cinit`/debug/native-linker limitation text.
- [x] **Step 2: Run every gate** (M0, M2–M7.2; lit CodeGen + MC + clang Sema/CodeGen; GSPLNK oracle). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.2 makes the native path self-contained: `llc` objects carry `.cinit` and debug data, `tms-link` replaces GSPLNK for linking, and the GSPLNK image is the permanent oracle. M7.3 owns the wider Xlib surface, stderr capture and hardware; M7.4 the full external suites, performance and the final boundary. The compiler repo is canonical; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,113 @@
# TMS34010 M7.3 — Runtime and Hardware (Wider Xlib, stderr, Hardware Harness) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Widen the validated VT1200 Xlib surface and exercise it in MAME, add real stderr capture to the conformance harness, and deliver the real-hardware marker harness with its MAME-equivalent acceptance while the unit is unavailable.
**Architecture:** The Xlib surface stays ROM-import based: each new entry is validated against the v2.2 image with `validate-syms.sh`, declared in `scripts/m4/x11m4.h`, and used by a new client (`xmore`) that MAME runs through the existing loader. The conformance shim gains a second sink and length cell for `stderr`, with the runner/check-lua comparing it exactly. The hardware harness is a thin wrapper around the already-proven `dwt/loader/hostload.py --marker` path: it links the marker client at the real-unit origins, validates the same marker cells in MAME, and invokes hostload only when `VT1200_HOST` is set.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, GSPA/GSPLNK 2.00 under DOSBox, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.3), §7.7 (Xlib/ROM imports), §7.9; the M7.2 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.2 push `3dccc4d`); compiler unchanged (`3c39d1d82190`) unless a real target bug appears.
- Keep every M2–M7.2 gate green, the TI all-stack ABI, the asm oracle, the native path, and the default `m6` branch.
- New Xlib addresses must pass `scripts/m4/validate-syms.sh` (ROM range, 16-bit aligned, real prologue) and come from the Ghidra/dis34 table; never guess.
- stderr is a second stream: stdout bytes/markers stay byte-identical for existing tests; an empty stderr is the default.
- The hardware run is **DEFERRED**: the gate must pass without a unit (MAME-equivalent acceptance) and must not mark the milestone blocked. `VT1200_HOST` enables the real run.
- MAME + the loader are the acceptance environment. Run MAME gates serially.
- Red/green TDD; commit per task; no push until the M7.3 final review is clean.
## Review Focus
1. **Xlib correctness:** each new symbol address is justified and validated; the client uses the correct X11R4 argument shapes; markers prove the calls actually ran (not just returned); no X errors; existing xshow/termtris unchanged.
2. **stderr exactness:** separate buffer/length/magic, no aliasing with stdout, truncation semantics, runner comparison (`--expect-stderr` and `;stderr=`), empty default, and the selftest red cases.
3. **Hardware harness honesty:** the COFF uses the proven hardware origins, the marker cells match `hostload.py`, the MAME check reads the same cells, and the deferred path is explicit and non-blocking.
4. **No M2–M7.2 regression** and no change to the default linker/ABI.
---
### Task 1: Wider Xlib surface
**Files:**
- Modify: `symbols/vt1200-v22.syms` (new validated entries)
- Modify: `scripts/m4/x11m4.h` (prototypes/structs)
- Create: `scripts/m7/xmore.c`, `scripts/m7/xmore-check.lua`
- Create: `scripts/tests/m7/xlib.sh`
- Test: `scripts/m4/validate-syms.sh`, the existing xshow/termtris gates
**Interfaces:**
- Consumes: the v2.2 ROM import table and the M4 Xlib ABI (`Display`, `XImage`, events).
- Produces: validated `XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`, `XInternAtom`, `XChangeProperty`, `XChangeGC` entries (addresses from `vendor/vt1200/dwt/notes/GUI_APPS.md`), prototypes, and an `xmore` client whose markers prove subwindow mapping, configure, atom/property changes, GC change, text (`XLoadFont`/`XDrawString`), drawing, and a heap `XCreateImage`/`XGetImage`/`XPutImage`/`XDestroyImage` round trip with no X errors.
- [x] **Step 1: Write the failing gate.** `xlib.sh` compiles `xmore.c` with `tms-clang`/`llc`, links via the M4 harness, loads it in MAME, and requires markers (window, child, GC, atom, property, configure, image, errors=0) plus a screenshot pixel check; `validate-syms.sh` currently rejects the new symbols.
- [x] **Step 2: Run red.** `validate-syms.sh` fails on the missing entries; `xmore` does not link.
- [x] **Step 3: Implement.**
- Add the six addresses with the GUI_APPS evidence; run `validate-syms.sh`.
- Declare the prototypes (`XWindowChanges`/`CW*` bits, `XInternAtom`, `XChangeProperty`, `XChangeGC` values) in `x11m4.h` without disturbing the existing ABI assertions.
- Write `xmore.c`: one parent + child, `XMapSubwindows`, `XConfigureWindow` (move/resize), `XInternAtom("WM_NAME")`, `XChangeProperty`, `XChangeWindowAttributes` (background), `XChangeGC` (foreground), `XLoadFont`/`XDrawString`, draw a rectangle/image, `XCreateImage` on the heap, `XGetImage` a small region, `XPutImage`, `XDestroyImage`, `XSync`; markers at `0x018A8000 + n*0x20`; error handler counts X errors.
- If a call is genuinely unusable (e.g. `XGetImage` blocks on the emulated server), keep it in the surface/test with a documented skip marker rather than silently dropping it.
- [x] **Step 4: Run green.** `xlib.sh`, `validate-syms.sh`, the M4 xshow/termtris/symbols gates, and the M7.2/M6/M5 gates touched by the harness.
- [x] **Step 5: Commit.**
### Task 2: stderr capture
**Files:**
- Modify: `scripts/tests/m5/conformance/shim.c` (stderr stream, fprintf/fputs/fputc/fwrite)
- Modify: `scripts/tests/m5/conformance/conformance-check.lua` (err_len/err buffer)
- Modify: `scripts/tests/m5/conformance/run.sh` (`--expect-stderr`, `;stderr=` parsing/comparison)
- Modify: `scripts/tests/m5/conformance/selftest.sh` (empty/formatted/truncated stderr cases)
- Test: the conformance selftest, c-testsuite/c-torture smoke, the M6 runtime gate
**Interfaces:**
- Consumes: the shim's `CONF_OUT`/`CONF_LEN`/`CONF_MAGIC` result block.
- Produces: `stderr` as a real `FILE *` target with `fprintf`/`vfprintf`/`fputs`/`fputc`/`fwrite`, a second buffer (`01B30000`, 16 KiB) and length (`01B00060`), runner expectation support, and selftests proving exact comparison and truncation rejection.
- [x] **Step 1: Write failing tests.** Add selftest sources that write `fprintf(stderr, ...)`; the runner rejects `--expect-stderr` (unknown option) and the shim has no stderr.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Represent `stdout`/`stderr` as distinct sink descriptors; `printf` continues the stdout stream; stderr has its own buffer/length and the same 16 KiB cap.
- Implement the write surface (return value = untruncated length, bytes capped) and `fprintf` via the existing formatter; declare `stderr` in the shim and any headers.
- Extend the check lua to read `ERRLEN`/`ERR` and write `errlen=`/`err=`; extend the runner's spec parser and comparison, preserving `stdout` defaults.
- Selftests: empty stderr passes; expected formatted stderr passes/fails correctly; `errlen >= CAP` is rejected as truncation.
- [x] **Step 4: Run green.** conformance selftest, the c-testsuite/c-torture gates (no changed stdout), the M6 runtime gate.
- [x] **Step 5: Commit.**
### Task 3: Real-hardware harness with MAME-equivalent acceptance
**Files:**
- Create: `scripts/m7/hwmark.c` (or `.s`), `scripts/m7/hw-entry.asm`
- Create: `scripts/tests/m7/hardware.sh`, `scripts/m7/hw-check.lua`
- Test: the M4/M5 loader path; `dwt/loader/hostload.py` dry contract; no real unit required
**Interfaces:**
- Consumes: the proven hardware origins (`.text 018C0000`, `.data 018D0000`, `.bss 018D8000`) and `hostload.py`'s `MARKER_CELLS` (`018E0000` start, `018E0020` data=0xDEADBEEF, `018E0040` data2=0x12345678, `018E0060` bss=0, `018E0080` live counter).
- Produces: a marker COFF (linked with `tms-link` or GSPLNK), a MAME run that checks the same cells through the loader, and a guarded real-hardware invocation: `VT1200_HOST=... scripts/tests/m7/hardware.sh` runs `hostload.py --marker --coff ...`; without it the gate prints `HARDWARE: DEFERRED` and passes on the MAME evidence.
- [x] **Step 1: Write the failing gate.** `hardware.sh` requires the marker cells in MAME and prints the deferred marker; no marker client exists yet.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Build the marker client at the hardware origins (entry sets STK/FP, calls `_main`, writes the sentinels and a live counter; `.data` holds the sentinels).
- MAME: link/load/run the same COFF (loader.lua + `hw-check.lua`), assert the five cells and loader status 0.
- Real path: invoke `dwt/loader/hostload.py` with `--coff`, `--marker`, `--host "$VT1200_HOST"`, and an evidence directory; propagate its failures. Do not fake a hardware pass; without the host, `HARDWARE: DEFERRED`.
- Document the unit's MAC/IP/host assumptions and the deferred status.
- [x] **Step 4: Run green.** `hardware.sh` (MAME + deferred), the M4/M5 native gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.3
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.3 list
- [x] **Step 1: Update the docs** for the wider Xlib table and client, the stderr protocol (`01B00060`/`01B30000`), the hardware harness/origins/deferred status, and the new gate counts.
- [x] **Step 2: Run every gate** (M0, M2–M7.3; lit; clang; conformance; generic; validate-syms; xshow/termtris). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.3 completes the runtime surface and makes the hardware campaign reproducible while the unit is away. M7.4 owns the full external suites, performance and the final M7 boundary. The compiler repo is canonical for target code; this project repo holds the Xlib table, harness, plans and gates.
@@ -0,0 +1,97 @@
# TMS34010 M7.4 — Conformance, Performance and the M7 Boundary Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close M7 with the full pinned external corpora, an i64 divide/remainder fast path with measured evidence, and the final M7 docs/counts/limitations/M8 boundary.
**Architecture:** A full-suite driver runs every file in the two pinned corpora through the existing conformance classifier and runner with the fast native loader settings, records per-test pass/skip/failure-category, and proves no unclassified crashes. The i64 division outliner gains a branch: when both operands' high words are zero it uses one 32-bit `DIVU`/`DIVS` (via i32 div/rem in IR) instead of the 64-step restoring loop; signed forms reuse the absolute-value normalization. A frame/cycle-based gate measures the small-divisor workload against the loop path.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.4), §7.9; the M7.3 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.3 push `54608c0`); compiler work in `build/llvm-clean` (branch `m7`, `bbec928ba807`).
- Keep every M2–M7.3 gate green, the TI all-stack ABI, the native path, the asm oracle, and the default `m6` branch.
- Full-suite runs use the pinned corpora under `vendor/conformance` and the fast loader settings (`LOADER_AT=200`, `LOADER_END=1000`) in `native` mode; the default conformance gates keep their existing settings.
- A test that is classifier-supported but fails must get an honest per-test skip reason or a recorded failure category; never count a skip as a pass. No MAME/loader crash.
- The i64 fast path must preserve every M6 i64 semantic (signed truncation, remainder sign, divide-by-zero undefined) and the existing `m6-i64.ll` checks.
- No push until the M7.4 final review is clean; default stays `m6`.
## Review Focus
1. **Full-suite honesty:** all 1,692 + 220 files accounted for; classifier-supported pass/skip/failure categories exact; no crash counted as pass; the report/log retained.
2. **Fast path correctness:** the high-word check, zero divisor, signed normalization, 64-bit results, and the slow path unchanged; `m6-i64` and the runtime gate green.
3. **Measurement:** the perf gate compares the fast path against a genuine slow-path workload, not a compile-time constant fold; the metric is reproducible.
4. **No regression** and the final docs/boundary are accurate.
---
### Task 1: Full-suite harness and baseline run
**Files:**
- Create: `scripts/tests/m7/full-suite.sh` (driver + report)
- Create: `scripts/tests/m7/full-suite.skip` (generated/triaged skip reasons; Task 3 fills failures)
- Test: the existing conformance runner/classifier; c-testsuite/c-torture smoke
**Interfaces:**
- Consumes: `vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute/*.c` (1,692) and `vendor/conformance/c-testsuite/tests/single-exec/*.c` (220), `scripts/tests/m5/conformance/{run.sh,classify.sh}`.
- Produces: `full-suite.sh [--corpus c-torture|c-testsuite|all] [--jobs 1]` with `LOADER_AT=200 LOADER_END=1000`, `--mode native`, per-test `pass/skip/fail:<category>` rows, a summary (`total/pass/skip/fail/crash`), and a retained log/report; a nonzero exit only on a crash or an unclassified failure.
- [x] **Step 1: Write the failing driver.** It builds sorted full lists, runs the runner with `--classify --mode native --expect-status 0 --ignore-output` (c-torture) and the `.expected` comparison (c-testsuite), and prints a summary. The first run has no triage file and fails on the known failing tests.
- [x] **Step 2: Run a bounded sample red.** Pick 20 c-torture files and show pass/skip/fail; the failing ones are the red evidence.
- [x] **Step 3: Implement.** Run tests serially (MAME); classify skips; categorize failures (compile/diagnostic, loader status, mismatch, timeout) into a stable `fail:<category>` form; write `full-suite-results.tsv`, `full-suite-report.txt`, and the per-test logs under a work directory; never treat a skip as a pass. Keep the default conformance gates untouched.
- [x] **Step 4: Run the full c-testsuite (220) and start/complete the full c-torture (1,692).** Record exact counts; the run may take hours, so retain the log and resume from completed rows if interrupted (idempotent per id).
- [x] **Step 5: Commit** the driver (and the initial results summary).
### Task 2: i64 divide/remainder fast path
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`TMS34010LowerI64::lowerDivRem`)
- Modify: `llvm/test/CodeGen/TMS34010/m6-i64.ll` (fast-path checks) or create `m7-i64div-fast.ll`
- Create: `scripts/m7/i64div-perf.c`, `scripts/m7/i64div-perf-check.lua`, `scripts/tests/m7/i64div.sh`
- Test: `scripts/tests/m6/i64.sh`, the M6 runtime gate, `m6-i64.ll`
**Interfaces:**
- Consumes: the inline restoring-division outliner (`lowerDivRem`, 64 iterations) and the target `DIVU`/`DIVS`.
- Produces: a pre-check `(N >> 32) == 0 && (D >> 32) == 0`; on that path, `zext(udiv/urem (trunc N), (trunc D))` (32-bit `DIVU`) for unsigned, and for signed after the absolute-value normalization, with the same sign correction; the loop otherwise unchanged. A perf gate that measures a small-divisor workload (fast path) against a high-word-divisor workload (loop) using MAME frames/cycles or an equivalent instrumented counter.
- [x] **Step 1: Write failing tests.** `m7-i64div-fast.ll` requires the 32-bit `DIVU`/`DIVS` fast path (and the loop label still present); the perf gate requires the small-divisor workload to complete in materially fewer frames/iterations than the slow path. Current output has only the loop.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement** the fast path in `lowerDivRem`, keeping the zero-divisor undefined behavior, signed truncation and remainder sign; verify the IR/asm.
- [x] **Step 4: Run green.** The new lit test, the perf gate, `m6/i64.sh`, `m6/runtime.sh`, the M7.2/M7.3 gates.
- [x] **Step 5: Commit** (compiler + project).
### Task 3: Full-suite triage, skip curation and exact counts
**Files:**
- Modify: `scripts/tests/m7/full-suite.skip` (per-test honest reasons)
- Modify: `scripts/tests/m7/full-suite.sh` (summaries/categories)
- Create: `scripts/tests/m7/full-suite-report.txt` (retained)
- Test: the full-suite driver (idempotent resume), no crashes
**Interfaces:**
- Consumes: Task 1's per-test results.
- Produces: every failing test either fixed or skipped with a feature/curation reason; exact total/pass/skip/fail-category counts for both corpora; a retained report reproducible from the pins.
- [x] **Step 1: Triage** the failures by root cause; fix cheap target/driver issues; otherwise add a per-test `full-suite.skip` reason (one line each) and re-run only those.
- [x] **Step 2: Verify** the full results: no crash, no unclassified failure, every skip has a reason and is classifier-consistent.
- [x] **Step 3: Record the exact counts** and anomalies in the report.
- [x] **Step 4: Commit.**
### Task 4: Final M7 docs, full gates, final review, push M7.4/M7
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (M7 status)
- Test: the full M0/M2–M7.4 list
- [x] **Step 1: Update the docs** for the full-suite method/counts/skips, the i64 fast path and measurement, the complete M7 counts/limitations, and the M7/M8 boundary. Mark M7 complete (M8 owns multi-TU DWARF merging, `.lib` linking, hardware completion, remaining performance).
- [x] **Step 2: Run every gate** (M0, M2–M7.4; lit; clang; conformance; full suites; perf; generic). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.4 closes the conformance and performance surface and freezes the M7 boundary. M8 owns the remaining object/debug depth (multi-TU DWARF), `.lib` linking, the hardware run once the unit returns, and any further performance work.
@@ -0,0 +1,103 @@
# TMS34010 M8 — Native Archives, Multi-TU DWARF, Conformance Depth and Hardware Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the M7/M8 boundary: make `tms-link` read the 1990 TI-COFF archives so the native path no longer needs GSPLNK for `flib`/`rts`, merge debug information from multiple translation units, deepen the conformance pass rate and performance evidence, and close out M8 with the hardware status and boundary.
**Architecture:** `tms-link` gains an `ar` reader with iterative selective extraction over its existing TI-COFF object model, then a DWARF merge stage that rehomes section-relative offsets and relocations across objects. The conformance/perf work uses the existing full-suite driver and the i64 measurement harness. The hardware harness already exists; M8.4 only runs it if the unit is available and records the result.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m8`), `tms-clang`, `llc`, `tms-link`, TI COFF and `ar` archives, the dwt loader, MAME, `dis34`, `llvm-dwarfdump`, Python 3, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M8.1–M8.4); the M7 README/ledger boundary.
## Global Constraints
- M8 baseline: compiler `llvm-tms34010` `m7` at `e924e0c86343`, project `tms-c-compiler` `m7` at `0f7353c`; work on `m8` in both repos. `m7` remains the repository default unless the user asks; no force-push and no merge into `m0`–`m7`.
- Keep every M2–M7.4 gate green, the TI all-stack ABI, the asm/GSPLNK oracle, and the native loader contract (`nreloc=0` linked image).
- `.lib` archives are test/runtime inputs; do not vendor them. The 1990 `flib.lib`/`rts.lib` are System V `ar` (`!<arch>`) with TI-COFF members.
- Debug merging must keep section-relative DWARF offsets correct; the default load image stays debug-stripped and `--keep-debug` is the tool image.
- Full-suite accounting remains one row per file; no crash/unclassified result; skips always carry a reason.
- No push until the M8 final review is clean; then push `m8`.
## Review Focus
1. **Archive correctness:** `ar` header/member parsing, long names, symbol resolution, iterative extraction, duplicate/undefined behavior, determinism, GSPLNK parity.
2. **DWARF merge correctness:** CU/abbrev/str/line/addr offset rehoming, relocations, section-relative values, dwarfdump validation, single-TU compatibility, stripped load image unchanged.
3. **Conformance honesty:** full accounting, flipped classes recorded, no hidden passes, performance measurement causal.
4. **No regression** and the final boundary accurate.
---
### Task 1: Native `.lib` linking in `tms-link`
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `tools/tms-link/tests/` archive fixtures/cases
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` accepts `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`)
- Test: `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`, `scripts/tests/m5/native.sh`, `scripts/tests/m6/runtime.sh`, `scripts/tests/m6/i64.sh`
**Interfaces:**
- Consumes: `ar` archives with TI-COFF members (`build/m4-sdk/FLIB.LIB`, `RTS.LIB`), the existing object reader/linker, and the M4 hook.
- Produces: archive detection/reader; selective extraction of members that define currently-undefined symbols (iterated to a fixpoint); `-l`/path CLI support; duplicate definitions/undefined symbols/unsupported members loud; a linked image with the same section/loader contract.
- [x] **Step 1: Write failing tests.** A tiny archive fixture (2–3 members, one symbol each) linked by `tms-link`; a missing-symbol and a duplicate-definition negative; a `flib`-only program (e.g. `FD$ADD`) linked without GSPLNK; the current CLI does not read archives.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Parse `!<arch>\n`, 60-byte member headers, decimal sizes, even-byte padding, `/` and `//` special members, and `/N`/name forms; reject malformed archives loudly.
- Add archive members to the link as candidate objects; extract only members that define an undefined symbol, iterating (archive semantics), never re-extracting a member; duplicate/undefined symbols fail with names.
- CLI: accept `-l LIB` and archive paths; preserve object inputs, `--entry`, layout, map, debug strip/keep.
- `scripts/m4/run.sh`: allow `M4_LINKER=tms-link` with `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`; pass library paths; keep GSPLNK the default and the oracle.
- [x] **Step 4: Run green.** Unit/archive tests; the M5 native and M6 runtime/i64 links with `tms-link` + libs; GSPLNK byte/symbol parity; MAME markers; one full native run. Do not regress non-library links.
- [x] **Step 5: Commit** (project; compiler unchanged unless a target bug appears).
### Task 2: Multi-TU DWARF merging
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `scripts/tests/m8/dwarf-multi.sh`, fixtures (`scripts/m8/debug-a.c`, `debug-b.c`, entry)
- Test: `scripts/tests/m7/debug.sh` (single-TU compatibility), `llvm-dwarfdump`, MAME
**Interfaces:**
- Consumes: multiple `--keep-debug`-capable debug-bearing objects from Task 1's linker and the M7 debug sections.
- Produces: merged `.debug_info`/`.debug_abbrev`/`.debug_str`/`.debug_str_offsets`/`.debug_line`/`.debug_addr` (and related) sections with rehomed section-relative offsets/relocations across CUs; single-TU output unchanged; loud failure on unsupported shapes.
- [x] **Step 1: Write failing tests.** Two TUs with functions/lines, linked `--keep-debug`; the current linker refuses >1 debug object. Wrap the sections in the test ELF container and require `llvm-dwarfdump` to show both TUs' files/functions/lines/addresses.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Concatenate `.debug_info`/`.debug_line`/etc. while relocating each object's section-relative contributions: `.debug_abbrev` offsets in CU headers, `.debug_str_offsets` bases, `.debug_addr` bases, `.debug_line`/`.debug_line_str` offsets, and cross-section relocations to allocated sections.
- Resolve relocations against the linked section layout; keep debug sections section-relative (paddr 0), `nreloc=0`.
- Preserve the single-debug-TU output; refuse unsupported DWARF shapes loudly.
- [x] **Step 4: Run green.** Multi-TU dwarfdump, single-TU `m7/debug.sh`, the stripped image in MAME, the M7.2 gates.
- [x] **Step 5: Commit.**
### Task 3: Conformance depth and performance
**Files:**
- Modify: the relevant target lowering/tests for fixed classes; the full-suite skip file; the perf driver if extending it
- Test: `scripts/tests/m7/full-suite.sh` (accounting), `scripts/tests/m7/c-torture.sh`/`c-testsuite.sh`, `scripts/tests/m7/i64div.sh`
**Interfaces:**
- Consumes: the M7.4 full-suite baseline (1,576 pass / 336 skip / 0 fail / 0 crash).
- Produces: additional fixed classes with flipped counts, an updated honest skip list, and at least one new measured performance path (e.g. 64/32 i64 division when the divisor fits 32 bits).
- [x] **Step 1: Pick the highest-value classes** from the retained skip classes (rotates/`cttz`/`bswap`/`blockaddress`; inline-asm constraints; one ABI return shape; one timeout/image-size case) and write failing lit/runtime tests.
- [x] **Step 2: Implement** the fixes, update the skip curation only where the class remains a genuine M8/M9 boundary, and re-run the affected full-suite rows.
- [x] **Step 3: Performance:** implement and measure the 64/32 fast path (or an equally justified path) against the existing slow path; record frames/checksums.
- [x] **Step 4: Run green** and record the new exact counts/flips.
- [x] **Step 5: Commit.**
### Task 4: Hardware status, final M8 docs, full gates, final review, push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, the spec (M8 status)
- Test: the full M0–M8 list
- [x] **Step 1: Hardware.** If the VT1200 is available, run `VT1200_HOST=… scripts/tests/m7/hardware.sh` and record the real-unit evidence; otherwise keep `HARDWARE: DEFERRED` explicit. Do not fake a pass.
- [x] **Step 2: Docs.** Record M8.1/M8.2/M8.3 results, the final full-suite/perf counts, the remaining limitations, and the M8/M9 boundary.
- [x] **Step 3: Gates and review.** Run the full serial list, commit, final whole-branch review, then push `m8` (default stays `m7` unless asked).
---
## Execution Handoff
M8.1 makes the native path library-complete; M8.2 makes debug info multi-TU; M8.3 raises the conformance/performance surface; M8.4 closes the milestone with the hardware status and boundary. The compiler repo remains canonical for target code; the project holds the linker, harness, plans and gates.
@@ -458,6 +458,204 @@ plan/ledger ruling).
> `JR`/`MMTM`, and the curated conformance tier. **Debug info is M7** per
> the M6 plan and ledger ruling (`progress.md`), not M6.
### M7 — correctness residuals, object/debug, hardware, conformance
M7 closes the M6 boundary in four sequential sub-milestones. Each has its own
design/plan, subagent-driven execution, task reviews, final whole-branch
review, and a push of the `m7` branch (default unchanged unless the user
asks). M2–M6 remain binding.
- **M7.1 — correctness and ABI residuals.** (a) The `-O2` bit-pointer
semantic barrier: `tms-clang` scales GEPs to calls to an opaque
`@__tms_bitptr(i32 bitoff, ptr base)` before the optimizer, scales only the
optimizer-created byte GEPs afterwards, then lowers the bitptr calls to
`inttoptr(add(ptrtoint,...))` and runs a final instcombine. This removes the
`p += n` over-scale while preserving the M0 `int_diff = 8/32` contract; the
shim `memmove` workaround is removed. (b) The sub-byte array/nested-record
stride: emit a loud, default-on diagnostic for arrays and nested members of
records whose bit content is not a byte multiple (TI advances by the bit
content; Clang's byte-rounded `sizeof` would silently diverge), or implement
the bit-content stride if a sound lowering is found. (c) `.data`
initializers for i64, aggregates/unions and bitfield globals, including the
object path and relocations; i64 words are little-endian/least-significant
first. (d) Keep the nonzero byte-offset narrow-load/store guard.
- **M7.2 — object/debug.** (a) Debug info in the native TI-COFF object:
`llc -march=tms34010 -filetype=obj` on a module with `!dbg` metadata emits
DWARF line/source sections (`.debug_info`, `.debug_abbrev`, `.debug_line`,
`.debug_str`, and the auxiliary sections LLVM produces) as non-allocated
COFF sections; long section names use the COFF `/offset` string-table form.
The native linker resolves their relocations and, by default, strips them
from the load image; `--keep-debug` retains them for tools. M7.2 supports one
debug-bearing object per link (multi-TU DWARF merging is loud, M8); the
`tms-link --map` output includes the section allocation and global symbol
map; source-line information lives in the kept `.debug_line` sections and is
dumped/validated with `llvm-dwarfdump` (Task 3), not parsed by the linker. (b) `tools/tms-link`
is a native TI-COFF linker: it reads relocatable objects, resolves public
symbols including names longer than GSPA's 31-character limit, lays out
`.text`/`.data`/`.cinit` in the `prog` region and `.bss` in `ram`, applies
the R-RELLONG fixups, and emits a position-dependent linked COFF with
`nreloc = 0`, an optional header (entry, text/data/bss start and size) and a
map. `.cinit` is a first-class section (TI init-record table: u16 word count,
u32 destination, data words), placed after `.data`; the linker defines the
public `cinit` symbol. (c) Object-path gates compare `tms-link` output with
GSPLNK for the same objects (byte-identical allocated sections, identical
symbol addresses, same MAME markers) and cover `.cinit`, >31-character
public names, and a `llvm-dwarfdump`-validated debug image.
M7.2 acceptance: `llc -filetype=obj` emits a debug-bearing TI-COFF whose
`.debug_*` sections validate with `llvm-dwarfdump` after the linker keeps them;
the default linked image is debug-stripped and the loader/MAME acceptance is
unchanged; `tms-link` links the M5 native objects with allocated-section
bytes and symbol addresses equal to GSPLNK (the M6 gates continue to link
with GSPLNK; both use the same object writer); a C `.cinit` table is placed,
relocated and processed by an entry in MAME; two TUs with a 40-character public
function link and run; every M2–M7.1 gate stays green.
- **M7.3 — runtime and hardware.** (a) The wider Xlib surface: add the
remaining ROM-validated entries from the Ghidra/dis34 table
(`XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`,
`XInternAtom`, `XChangeProperty`, `XChangeGC`), extend `x11m4.h`, and add a
client (`xmore`) that exercises them together with text (`XLoadFont`,
`XDrawString`), drawing, and a heap image (`XCreateImage`/`XGetImage`/
`XPutImage`/`XDestroyImage`), with MAME markers and no X errors;
`scripts/m4/validate-syms.sh` validates every added address. (b) stderr
capture: the conformance shim exposes a distinct `stderr` stream
(`fprintf`/`fputs`/`fputc`/`fwrite`) into a second buffer/length cell, the
runner and MAME check compare it (`--expect-stderr`/`;stderr=`), and
selftests cover empty, non-empty and truncated stderr. (c) Real-hardware
validation for the VT1200: a harness builds the marker client at the proven
hardware origins (`018C0000`/`018D0000`/`018D8000`), runs the same COFF in
MAME (the permanent acceptance), and, with `VT1200_HOST` set, drives
`dwt/loader/hostload.py --marker` over rdebug against the real unit. The
unit is unavailable for the first two weeks, so the hardware run is
**DEFERRED** and does not block M7; the harness and its MAME-equivalent
acceptance are delivered now.
M7.3 acceptance: `xmore` runs in MAME with the expected markers and no X
errors, and every added Xlib address passes `validate-syms`; the stderr
selftests prove empty, formatted and truncated stderr; the hardware gate
passes its MAME marker check and reports `HARDWARE: DEFERRED` without a unit
(the same command runs `hostload.py --marker` when `VT1200_HOST` is set); every
M2–M7.2 gate stays green.
- **M7.4 — conformance and performance.** (a) Full external suites: run the
pinned GCC 16.2.0 `gcc.c-torture/execute` corpus (1,692 files) and the
c-testsuite `single-exec` corpus (220) beyond the curated lists, at `-O0`
with the conformance classifier; every test is pass, an honest
feature/curation skip with a reason, or a recorded failure category — never
an unclassified crash. The bounded `-O2` subsets stay as the optimization
smoke tier. (b) Performance: an i64 divide/remainder fast path that, after
the signed absolute-value normalization, uses one 32-bit `DIVU` when both
normalized high words are zero instead of the 64-step restoring loop (the
signed forms divide magnitudes, so they also select `DIVU`), with the same
quotient/remainder sign fixup, unit/asm coverage, the M6 i64 gate, and a
cycle/frame-based measurement gate. (c) Final M7
docs, exact counts, known limitations, and the M7/M8 boundary (M8 owns
multi-TU DWARF merging, `.lib` linking, the real VT1200 run if still
deferred, and any remaining performance work).
M7.4 acceptance (met, M7 complete): the full pinned corpora account for
**1,912** files — c-torture **1,692 = 1,366 pass / 326 skip / 0 fail / 0
crash** and c-testsuite **220 = 210 pass / 10 skip / 0 fail / 0 crash** —
with every skip carrying a classifier or curation reason and the 272 curated
rows re-run without skips (272/272 still failed). The i64 fast path uses one
32-bit `DIVU` when both normalized operands' high words are zero; the
implementation divides magnitudes for the signed forms as well, so `DIVU` is
emitted and `DIVS` is not (this matches the M6 loop's unsigned
compare/subtract). The MAME measurement is `fast_frames=90 slow_frames=2424
ratio=26.9` for the same 16,384 iterations, status `600D600D`, checksums
`000000011E6F9AB4`/`00000000007512AE`. Every M2–M7.3 gate stays green; lit is
**118/118** (114 CodeGen + 4 MC) and the shipped c-testsuite tier remains the
curated 48 pass / 172 skip. The real VT1200 run is still **DEFERRED**; M8
owns multi-TU DWARF merging, `.lib` linking under `tms-link`, the hardware
run, the remaining conformance classes and further performance work.
M7.1 acceptance: the `p += n` shape is correct at the default `-O2` with one
scale; M0 `int_diff` 8/32; the stride diagnostic fires for the oracle shapes
and not for byte-multiple records; `.data` i64/aggregate/bitfield globals
assemble/link/load with exact bytes; every M2–M6 gate stays green; MAME and
the dwt loader are the acceptance environment.
### M8 — object/link completeness, conformance depth, hardware
M8 closes the M7/M8 boundary in four workstreams, using the same plan,
subagent-driven execution, review and push discipline as M7. The `m7` branch
is the M8 baseline and the repository default; M8 work is on `m8` and does not
change the default unless the user asks.
- **M8.1 — native `.lib` linking.** `tools/tms-link` reads System V/`ar`
archives (the 1990 `flib.lib`/`rts.lib` are `!<arch>` with TI-COFF members),
performs iterative selective extraction of members that define needed
symbols, resolves duplicate/undefined symbols loudly, and exposes the
libraries through the CLI and the `M4_LINKER=tms-link` path. GSPLNK remains
the oracle; the M5/M6 native and runtime gates must produce the same
allocated bytes/symbol addresses (and MAME markers) with either linker.
Acceptance: M4/M5/M6 native links that need `flib`/`rts` link with
`tms-link`, produce a loader-accepted image with the expected markers, and
match GSPLNK on the allocated image; unmatched/duplicate archive symbols
fail loudly.
- **M8.2 — multi-TU DWARF merging.** The native linker merges debug
information from multiple debug-bearing objects: concatenate `.debug_info`
CUs while adjusting `.debug_abbrev`/`.debug_str_offsets`/`.debug_addr`/
`.debug_line` section-relative contributions and their relocations; keep
section-relative offsets correct, resolve line/file tables, and validate the
result with `llvm-dwarfdump`. The default load image remains debug-stripped;
`--keep-debug` is the tool image. Acceptance: a two- or three-TU program
built with debug info links with `--keep-debug`, `llvm-dwarfdump` reports
every TU's functions/lines/addresses, and the stripped image still runs in
MAME; a single-TU link remains byte-compatible with M7.
- **M8.3 — conformance depth and performance.** Raise the full-suite pass
rate by fixing or honestly re-curating the remaining classes (codegen
rotates/`cttz`/`bswap`/`blockaddress`/vectors, inline-asm constraints,
sret/aggregate/variadic/float returns, VLAs, nested functions, libm and the
frame-limited timeouts), and extend performance work beyond the 32-bit i64
fast path (e.g. a 64/32 path when the divisor fits 32 bits) with measured
evidence. Acceptance: the full pinned corpora still account for every file
with 0 unclassified crashes and an honest skip list; the newly fixed classes
flip to pass and are recorded; any new performance path is measured against
the existing slow path.
- **M8.4 — hardware and close-out.** Run the real VT1200 hardware harness when
the unit is available (the harness and MAME-equivalent acceptance already
exist), record the real-unit evidence, and produce the final M8 docs/counts/
limitations and the M8/M9 boundary. The hardware run remains deferred and
does not block M8.1–M8.3; if it is still unavailable, mark it deferred and
state that explicitly.
M8.3 also runs the corpora on a bare-metal MAME tier by default (sections
mapped, `.bss` zeroed, PC/SP set, no firmware/loader), using the 2ine-hosted
1990 OS/2 assembler and `tms-link`; the curated M5/M6 loader gates, X11/runtime
and an explicit full-loader exception list keep the loader tier. The accounting
and acceptance counts are unchanged.
M8.1 acceptance: a library-only link (no GSPLNK) resolves the needed members
and runs; M8.2 acceptance: multi-TU debug links and validates; M8.3
acceptance: the full corpora remain fully accounted with the recorded flips;
M8.4 acceptance: the final docs/boundary are accurate and the hardware status
is explicit.
M8 acceptance (met, M8 complete): `tms-link` reads the System V `ar`
`FLIB.LIB`/`RTS.LIB`, extracts needed members iteratively and links the M4/M5/
M6 library programs with allocated bytes, section metadata and public symbols
equal to GSPLNK 2.00 (`scripts/tests/m8/native-lib.sh`, 3 sections, 16 public
`C_EXT` addresses, MAME markers). Multi-TU `--keep-debug` concatenates and
rehomes the supported DWARF5 sections; `llvm-dwarfdump` shows both TUs'
functions, lines and linked PCs, the stripped image runs in MAME, and the
single-TU link is byte-identical to M7 (`scripts/tests/m8/dwarf-multi.sh`).
The bit-op class (rotate/`cttz`/`ctpop`/`ctlz`/`bswap`) lowers without invented
instructions, and the 64/32 i64 divide path measures **218** frames versus
**2,440** for the 64-step loop (11.2×), while the fits-32 path measures **87**
(28.0×), status `600D600D`, checksums `000000011E6F9AB4`/
`00000000007512AE`/`00025AF70AF974E0`. The fresh end-to-end full suite
accounts for **1,912 = 1,596 pass / 316 skip / 0 fail / 0 crash** (c-torture
**1,386 / 306**, c-testsuite **210 / 10**), with 64 classifier plus 252
curated skips, each with a reason; the 20 flipped rows are the six rotates,
six `cttz`, four `bswap` and four per-test `LOADER_END=2000` runtime rows.
Lit is **120/120** (116 CodeGen + 4 MC) and clang Sema/CodeGen **5/5**. The
real VT1200 run remains **DEFERRED** (`VT1200_HOST` unset; the hardware gate
prints `HARDWARE: DEFERRED` on the MAME-equivalent acceptance). M9 owns the
remaining conformance classes (`blockaddress`, vector `.data`, inline-asm
constraints, nested functions, VLAs, sret/aggregate/variadic/float returns,
libm, runtime aborts), the pre-existing `pr63843` hang, further performance
work and the real VT1200 run when the unit is available.
## 9. Risks and mitigations
| risk | mitigation |
+236
View File
@@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Validate (and repair) a linked TI-COFF image for the VT1200 loader.
GSPLNK 2.00 has two observed output shapes that the loader rejects:
* when the test object has no initialised .data, it writes a fully zeroed
20-byte file header + 28-byte optional header, while the section table at
byte 48 is valid (loader status 3, "bad COFF magic");
* an odd-length .bss makes the section's bit size not a whole word (loader
status 4, "section size not whole words").
This helper validates the magic, the section table and the section sizes. With
--repair it reconstructs the zeroed header/optional header from the intact
section table and the linker map entry point, and rounds only .bss up to a
16-bit word. It never touches .text/.data contents or the entry point.
Usage: coff-check.py [--repair] [--entry HEX] FILE
"""
import argparse
import struct
import sys
FILE_MAGIC = 0x0090
OPT_MAGIC = 0x0108
OPT_VERSION = 0x00C7
FILE_FLAGS = 0x0103
OPT_HDR_SIZE = 28
ZERO_HEADER_SIZE = 20 + OPT_HDR_SIZE
def u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def put_u16(data, off, value):
struct.pack_into("<H", data, off, value)
def put_u32(data, off, value):
struct.pack_into("<I", data, off, value)
def section_at(data, off):
raw = data[off:off + 8]
name = raw.split(b"\0", 1)[0].decode("ascii", "replace")
return {
"off": off,
"name": name,
"paddr": u32(data, off + 8),
"size": u32(data, off + 16),
"scnptr": u32(data, off + 20),
"flags": u32(data, off + 36),
}
def parse(data):
if len(data) < 20:
raise ValueError("file is shorter than the 20-byte COFF header")
magic = u16(data, 0)
nscns = u16(data, 2)
opt = u16(data, 16)
return {
"magic": magic,
"nscns": nscns,
"opthdr": opt,
"optmagic": u16(data, 20) if opt else 0,
"entry": u32(data, 20 + 16) if opt else 0,
"textstart": u32(data, 20 + 20) if opt else 0,
}
def scan_recoverable_sections(data):
"""Recover the section table of GSPLNK's zero-header shape.
GSPLNK always leaves the 20-byte file header and 28-byte optional header
(48 bytes) zero, then writes the section table at byte 48. Stop at the
first entry whose name does not start with '.', so a trailing symbol table
is not mistaken for a section.
"""
if len(data) < ZERO_HEADER_SIZE + 40:
raise ValueError("no room for a recovered section table")
sections = []
off = ZERO_HEADER_SIZE
while off + 40 <= len(data) and len(sections) < 96:
sec = section_at(data, off)
if not sec["name"].startswith("."):
break
sections.append(sec)
off += 40
if not sections:
raise ValueError("zero header and no section table at byte 48")
return sections
def validate(data, sections, label):
bad = []
for sec in sections:
name = sec["name"]
size = sec["size"]
if not name:
bad.append("empty section name")
if size % 16 != 0 and name != ".bss":
bad.append(f"{name}: bit size {size} is not a whole word")
if name == ".bss" and size % 16 != 0:
bad.append(".bss: bit size %d is not a whole word" % size)
# scnptr points at raw bytes for non-.bss sections; the file must
# contain size/8 bytes there. .bss has no file payload.
if name != ".bss" and sec["scnptr"]:
need = sec["scnptr"] + (size + 7) // 8
if need > len(data):
bad.append(f"{name}: payload ends past EOF ({need} > {len(data)})")
if bad:
raise ValueError(f"{label}: " + "; ".join(bad))
def repair(data, entry):
header_zero = data[:20] == b"\0" * 20
opt_zero = data[20:ZERO_HEADER_SIZE] == b"\0" * OPT_HDR_SIZE
changed = []
if header_zero and opt_zero:
sections = scan_recoverable_sections(data)
names = {sec["name"]: sec for sec in sections}
for required in (".text", ".data", ".bss"):
if required not in names:
raise ValueError(f"recoverable header lacks {required}")
text = names[".text"]
dat = names[".data"]
bss = names[".bss"]
bss_size = (bss["size"] + 15) & ~15
if bss_size != bss["size"]:
put_u32(data, bss["off"] + 16, bss_size)
changed.append(f".bss size {bss['size']} -> {bss_size} bits")
# File header: magic, section count, timestamp, symbol pointer/count,
# optional-header size, flags.
put_u16(data, 0, FILE_MAGIC)
put_u16(data, 2, len(sections))
put_u32(data, 4, 0)
put_u32(data, 8, 0)
put_u32(data, 12, 0)
put_u16(data, 16, OPT_HDR_SIZE)
put_u16(data, 18, FILE_FLAGS)
# Optional header: magic, version, text/data/bss bits, entry and the
# text/data origins.
put_u16(data, 20, OPT_MAGIC)
put_u16(data, 22, OPT_VERSION)
put_u32(data, 24, text["size"])
put_u32(data, 28, dat["size"])
put_u32(data, 32, bss_size)
put_u32(data, 36, entry)
put_u32(data, 40, text["paddr"])
put_u32(data, 44, dat["paddr"])
changed.append("reconstructed zeroed file/optional header")
return changed, sections
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}, want {FILE_MAGIC:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
for sec in sections:
if sec["name"] == ".bss" and sec["size"] % 16 != 0:
new_size = (sec["size"] + 15) & ~15
put_u32(data, sec["off"] + 16, new_size)
# Keep the optional header's bss-size field consistent.
put_u32(data, 32, new_size)
changed.append(f".bss size {sec['size']} -> {new_size} bits")
sec["size"] = new_size
return changed, sections
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--repair", action="store_true",
help="repair the observed GSPLNK header/.bss shapes")
ap.add_argument("--entry", default="018A0000",
help="entry bit address for a reconstructed header")
ap.add_argument("file")
args = ap.parse_args()
try:
entry = int(args.entry, 16) if not args.entry.startswith("0x") else int(args.entry, 0)
except ValueError:
print(f"coff-check: bad --entry {args.entry}", file=sys.stderr)
return 2
try:
data = bytearray(open(args.file, "rb").read())
except OSError as exc:
print(f"coff-check: {exc}", file=sys.stderr)
return 1
try:
info = parse(data)
zero_header = info["magic"] == 0 and info["nscns"] == 0
if zero_header and not args.repair:
raise ValueError("zeroed file/optional header (GSPLNK shape); rerun with --repair")
if args.repair:
changed, sections = repair(data, entry)
if changed:
with open(args.file, "wb") as out:
out.write(data)
for item in changed:
print(f"coff-check: repaired {item}")
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
validate(data, sections, "post-repair")
except ValueError as exc:
print(f"coff-check: FAIL: {exc}", file=sys.stderr)
return 1
names = ",".join(sec["name"] for sec in sections)
print(f"coff-check: OK sections={len(sections)} [{names}] entry={info['entry']:#010x}")
return 0
if __name__ == "__main__":
sys.exit(main())
+137 -15
View File
@@ -16,8 +16,14 @@
# M4_ROM_SYMBOLS=1 append the per-ROM import stubs from symbols
# M4_EXTRA_ASM="/a.asm /b.asm" extra assembly to concatenate
# M4_EXTRA_INCLUDES="-I dir" extra tms-clang include flags
# M4_EXTRA_CFLAGS="-std=..." extra tms-clang language flags (default empty;
# the conformance sweep uses this for c-torture's
# gnu89 dialect; shipped gates pass nothing)
# M4_NATIVE=1 compile with llc -filetype=obj and link the
# objects with GSPLNK (the default is GSPA text)
# M4_NATIVE_SKIP_ASM=1 in native mode, do not also emit .s for a TU
# whose raw GSPA form is intentionally rejected
# (for example an odd-offset pointer record)
# M4_NATIVE_RTS=1 add `-l rts.lib` to the native link
# M4_NATIVE_LIBS="a b" add `-l a -l b` to the native link (library
# files must already be in the SDK directory; the
@@ -25,10 +31,26 @@
# M4_NATIVE_PROG_LEN=8000h native program region length (bits)
# M4_NATIVE_RAM_LEN=80000h native RAM region length (bits)
# M4_LINK_CMD=/path/link.cmd asm-path GSPLNK command file (default link.cmd)
# M4_LINKER=tms-link native-mode opt-in: link the GSPA entry/extras
# objects and any M4_NATIVE_LIBS/M4_NATIVE_RTS
# archives with tools/tms-link instead of GSPLNK
# (default: gsplnk, which remains the oracle).
# Requires M4_NATIVE=1.
# M4_OS2=1 assemble/link with the 1990 r5.01 OS/2 tools
# under 2ine+qemu-i386 instead of DOSBox (run
# scripts/m8/setup-os2.sh first; the 1987
# GSPA/GSPLNK oracle is still the default)
# M4_OS2_LX=/path ../../2ine-tms34010/build-qemu/lx_loader
# M4_OS2_SDK=/path extracted r5.01 tree (bin/ and lib/)
# M4_SKIP_MAME=1 stop after a clean GSPA/GSPLNK link
# M4_COFF_REPAIR=1 validate the linked COFF magic/section sizes and
# repair GSPLNK's observed zero-header and
# odd-.bss shapes (default 1; set 0 to validate
# only and fail on the defect)
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT LOADER_END
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC TMS_LINK MAME DOSBOX
# DOSBOX_CONF SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT
# LOADER_END M4_COFF_REPAIR
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
@@ -39,6 +61,7 @@ TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
@@ -61,12 +84,17 @@ CHECK_LUA=${M4_CHECK_LUA:-$DIR/m4-check.lua}
CLANG_OPT=${M4_CLANG_OPT:--O0}
LLC_OPT=${M4_LLC_OPT:--O0}
EXTRA_INCLUDES=${M4_EXTRA_INCLUDES:-}
EXTRA_CFLAGS=${M4_EXTRA_CFLAGS:-}
NATIVE=${M4_NATIVE:-0}
OS2=${M4_OS2:-0}
NATIVE_SKIP_ASM=${M4_NATIVE_SKIP_ASM:-0}
NATIVE_RTS=${M4_NATIVE_RTS:-0}
NATIVE_LIBS=${M4_NATIVE_LIBS:-}
NATIVE_PROG_LEN=${M4_NATIVE_PROG_LEN:-8000h}
NATIVE_RAM_LEN=${M4_NATIVE_RAM_LEN:-80000h}
LINK_CMD=${M4_LINK_CMD:-$DIR/link.cmd}
LINKER=${M4_LINKER:-gsplnk}
COFF_REPAIR=${M4_COFF_REPAIR:-1}
fail() {
echo "m4: $*" >&2
@@ -76,6 +104,14 @@ fail() {
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
case $LINKER in
gsplnk|tms-link) ;;
*) fail "M4_LINKER must be 'gsplnk' or 'tms-link', got '$LINKER'" ;;
esac
if [ "$LINKER" = tms-link ]; then
[ "$NATIVE" = 1 ] || fail "M4_LINKER=tms-link requires M4_NATIVE=1"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
fi
[ -f "$ENTRY" ] || fail "missing entry: $ENTRY"
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
@@ -83,6 +119,7 @@ mkdir -p "$(dirname "$COFF")"
echo "== compile and select ($CLANG_OPT / llc $LLC_OPT)"
export TMS_CLANG TMS_OPT TMS_BITADDR
export TMS_CLANG_EXTRA_FLAGS="$EXTRA_CFLAGS"
for name in $SOURCES; do
case $name in
*/*) src=$name ;;
@@ -93,15 +130,20 @@ for name in $SOURCES; do
# shellcheck disable=SC2086
"$ROOT/scripts/tms-clang" "$CLANG_OPT" $EXTRA_INCLUDES \
-o "$ASM/$base.ll" "$src"
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
if [ "$NATIVE" = 1 ]; then
if [ "$NATIVE_SKIP_ASM" != 1 ]; then
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
fi
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=obj \
"$ASM/$base.ll" -o "$ASM/$base.o" \
|| fail "llc -filetype=obj failed for $name"
echo " $base.o: $(wc -c < "$ASM/$base.o") bytes"
else
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
echo " $base.s: $(grep -c . "$ASM/$base.s") lines"
fi
done
@@ -161,6 +203,12 @@ strip_end() {
sed '/^[[:space:]]*\.end[[:space:]]*$/d' "$1"
}
# Optional host-side 1990 OS/2 r5.01 assembler/linker path (2ine + qemu-i386).
if [ "$OS2" = 1 ]; then
. "$ROOT/scripts/m8/os2-toolchain.sh"
os2_init
fi
EXTRAS=
if [ -n "${M4_EXTRA_ASM:-}" ]; then
for extra in $M4_EXTRA_ASM; do
@@ -213,10 +261,18 @@ if [ "$NATIVE" = 1 ]; then
[ -f "$SDK/RTS.LIB" ] || fail "RTS.LIB not extracted into $SDK"
NATIVE_LIBS="$NATIVE_LIBS rts.lib"
fi
# Resolve the library names to SDK paths for tms-link. GSPLNK keeps
# consuming the -l lines in M4.CMD; the order is identical.
NATIVE_LIB_PATHS=
for lib in $NATIVE_LIBS; do
dos=$(printf '%s' "$lib" | tr '[:lower:]' '[:upper:]')
[ -f "$SDK/$dos" ] || [ -f "$SDK/$lib" ] \
|| fail "$lib not extracted into $SDK"
if [ -f "$SDK/$dos" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$dos"
elif [ -f "$SDK/$lib" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$lib"
else
fail "$lib not extracted into $SDK"
fi
done
{
printf '%s\n' '-a' '-o M4.OUT' '-m M4.MAP' '-e _start'
@@ -277,7 +333,33 @@ run_dosbox() {
-noprimaryconf -nolocalconf "$@" > "$WORK/dosbox.log" 2>&1
}
if [ "$NATIVE" = 1 ] && [ -n "$EXTRAS" ]; then
if [ "$OS2" = 1 ]; then
os2_gspa M4
if [ -f "$SDK/M4EXT.ASM" ]; then
os2_gspa M4EXT
fi
# tms-link is a host tool and runs below; the asm/GSPLNK path links here.
if [ "$NATIVE" != 1 ] || [ "$LINKER" != tms-link ]; then
os2_gsplnk
fi
elif [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
# tms-link is a host tool: GSPA still assembles the entry/extras objects,
# but GSPLNK is not run.
if [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gspa M4EXT M4EXT.obj M4EXT.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
else
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
elif [ "$NATIVE" = 1 ] && [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
@@ -294,6 +376,23 @@ else
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
if [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
TMSLINK_INPUTS=
for obj in $NATIVE_OBJS; do
TMSLINK_INPUTS="$TMSLINK_INPUTS $SDK/$obj"
done
echo "== link with tools/tms-link"
# shellcheck disable=SC2086
"$TMS_LINK" -o "$SDK/M4.OUT" --map "$SDK/M4.MAP" --entry _start \
--text 018A0000 --bss 01A00000 \
--prog-len "$NATIVE_PROG_LEN" --ram-len "$NATIVE_RAM_LEN" \
$TMSLINK_INPUTS $NATIVE_LIB_PATHS \
|| fail "tms-link failed"
# Keep the pre-coff-check image so parity gates can compare tms-link's
# raw output; the repaired $COFF below remains the loader image.
cp "$SDK/M4.OUT" "$WORK/M4.RAW.OUT"
fi
check_lst() {
lst=$1
[ -f "$SDK/$lst.LST" ] \
@@ -309,16 +408,35 @@ check_lst() {
check_lst M4
[ -z "$EXTRAS" ] || [ "$NATIVE" != 1 ] || check_lst M4EXT
[ -f "$SDK/M4.OUT" ] || fail "GSPLNK produced no M4.OUT"
[ -f "$SDK/M4.OUT" ] || fail "$LINKER produced no M4.OUT"
sed 's/\r$//' "$SDK/M4.MAP" > "$WORK/m4.map"
cp "$SDK/M4.OUT" "$COFF"
cp "$SDK/M4.ASM" "$WORK/m4.asm"
[ ! -f "$SDK/M4EXT.ASM" ] || cp "$SDK/M4EXT.ASM" "$WORK/m4ext.asm"
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m4.map")
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m4.map" | tr 'a-f' 'A-F')
[ "$ENTRY_ADDR" = "018A0000" ] || fail "linker entry _start is '$ENTRY_ADDR', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m4.map" \
|| fail "linker map has no _start entry point"
# GSPLNK 2.00 can zero the 48-byte file+optional header (observed on links
# whose test object contributed no initialized .data), and can emit an odd
# .bss size.
# Validate every linked COFF and repair only those two known shapes; any other
# malformed image is a hard link failure.
command -v python3 >/dev/null 2>&1 || fail "python3 is required for COFF validation"
if [ "$COFF_REPAIR" = 1 ]; then
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --repair \
--entry "$ENTRY_ADDR" "$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation/repair failed for $COFF"; }
else
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --entry "$ENTRY_ADDR" \
"$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation failed for $COFF"; }
fi
printf '%s\n' "$coff_out" | sed 's/^/ /'
echo " linked .text at 018A0000, M4.OUT -> $COFF"
if [ -n "${M4_SKIP_MAME:-}" ]; then
@@ -351,15 +469,19 @@ timeout "${MAME_TIMEOUT:-900}" "$MAME" vt1200 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M4: ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4 markers"; }
MARKERS=$(grep -E '^(M4|M7|M8 LIB): ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4/M7/M8 LIB markers"; }
echo " $MARKERS"
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^M4 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "M4 marker check failed"; }
grep -qE '^M[47] MAME: PASS|^M8 LIB MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
echo "M4 MAME: PASS"
case "$MARKERS" in
M7:*) echo "M7 MAME: PASS" ;;
M8\ LIB:*) echo "M8 LIB MAME: PASS" ;;
*) echo "M4 MAME: PASS" ;;
esac
+107 -1
View File
@@ -39,6 +39,16 @@ ROM_HI=$((0x3FFFFFFF))
MAPWINDOW=$((0x3FD64F60))
RAISEWINDOW=$((0x3FD645B0))
# M7.3 wider surface: the six GUI_APPS table entries, pinned as addresses as
# well as by opcode/helper. A table edit to a different builder with the same
# opcode still fails here.
WIDER_MAPSUBWINDOWS=$((0x3FD64BF0))
WIDER_CHANGEWATTRS=$((0x3FD38770))
WIDER_CONFIGUREWINDOW=$((0x3FD3A510))
WIDER_INTERNATOM=$((0x3FD5E420))
WIDER_CHANGEPROPERTY=$((0x3FD37330))
WIDER_CHANGEGC=$((0x3F999F80))
fail() {
echo "m4 validate-syms: FAIL: $*" >&2
exit 1
@@ -79,6 +89,10 @@ require_match() { # require_match DIS_TEXT ERE WHAT
}
}
require_addr() { # require_addr NAME ADDR WANT WHAT
[ "$(($2))" -eq "$3" ] || fail "$1 is $2, expected $(printf '0x%08X' "$3") ($4)"
}
check_prologue() { # check_prologue NAME ADDR
_name=$1
_addr=$2
@@ -229,6 +243,97 @@ check_xcreateimage() {
echo " ok XCreateImage allocates an 88-byte XImage"
}
# The M7.3 wider surface: six public entries from the GUI_APPS table. Each
# body is the ROM request builder named by that table, so pin the request
# opcode (and the helper each builder calls) rather than trusting the name.
# XMapSubwindows opcode 9
# XChangeWindowAttributes opcode 2, values walker 0x3FDA A550
# XConfigureWindow opcode 12, fixed CWX|CWY|CWWidth|CWHeight mask 15
# XInternAtom opcode 16, strlen on the name
# XChangeProperty opcode 18, blit_copy for the value bytes
# XChangeGC opcode 56 (0x38), GC cache serializer 0x3F997AD0
check_wider_xlib() {
_addr=$(sym_addr XMapSubwindows)
[ -n "$_addr" ] || fail "table has no XMapSubwindows entry"
require_addr XMapSubwindows "$_addr" "$WIDER_MAPSUBWINDOWS" "GUI_APPS"
dis_at "$((_addr))" 384 "$TMP/mapsubwindows"
require_match "$TMP/mapsubwindows" 'movk[[:space:]]+9,[[:space:]]+a[0-9]+' \
"XMapSubwindows does not build MapSubwindows request opcode 9"
require_match "$TMP/mapsubwindows" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XMapSubwindows does not write its request opcode to the buffer"
echo " ok XMapSubwindows builds MapSubwindows opcode 9"
_addr=$(sym_addr XChangeWindowAttributes)
[ -n "$_addr" ] || fail "table has no XChangeWindowAttributes entry"
require_addr XChangeWindowAttributes "$_addr" "$WIDER_CHANGEWATTRS" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/changewattrs"
require_match "$TMP/changewattrs" 'movk[[:space:]]+2,[[:space:]]+a[0-9]+' \
"XChangeWindowAttributes does not build ChangeWindowAttributes request opcode 2"
require_match "$TMP/changewattrs" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeWindowAttributes does not write its request opcode to the buffer"
require_match "$TMP/changewattrs" 'calla[[:space:]]+0x3fdaa550' \
"XChangeWindowAttributes does not call the XSetWindowAttributes value walker"
echo " ok XChangeWindowAttributes builds opcode 2 + value walker"
_addr=$(sym_addr XConfigureWindow)
[ -n "$_addr" ] || fail "table has no XConfigureWindow entry"
require_addr XConfigureWindow "$_addr" "$WIDER_CONFIGUREWINDOW" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/configurewindow"
require_match "$TMP/configurewindow" 'movk[[:space:]]+12,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not build ConfigureWindow request opcode 12"
require_match "$TMP/configurewindow" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XConfigureWindow does not write its request opcode to the buffer"
require_match "$TMP/configurewindow" 'movk[[:space:]]+15,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not arm the fixed CWX|CWY|CWWidth|CWHeight mask 15"
require_match "$TMP/configurewindow" '\*a13\(0xffa0\)' \
"XConfigureWindow does not read the x argument (a13-12)"
require_match "$TMP/configurewindow" '\*a13\(0xff80\)' \
"XConfigureWindow does not read the y argument (a13-16)"
require_match "$TMP/configurewindow" '\*a13\(0xff60\)' \
"XConfigureWindow does not read the width argument (a13-20)"
require_match "$TMP/configurewindow" '\*a13\(0xff40\)' \
"XConfigureWindow does not read the height argument (a13-24)"
echo " ok XConfigureWindow builds opcode 12, fixed mask 15, x/y/width/height"
_addr=$(sym_addr XInternAtom)
[ -n "$_addr" ] || fail "table has no XInternAtom entry"
require_addr XInternAtom "$_addr" "$WIDER_INTERNATOM" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/internatom"
require_match "$TMP/internatom" 'movk[[:space:]]+16,[[:space:]]+a[0-9]+' \
"XInternAtom does not build InternAtom request opcode 16"
require_match "$TMP/internatom" 'calla[[:space:]]+0x3fb458d0' \
"XInternAtom does not strlen the atom name"
require_match "$TMP/internatom" '\*a13\(0xffa0\)' \
"XInternAtom does not read the only_if_exists argument (a13-12)"
echo " ok XInternAtom builds opcode 16, strlens the name"
_addr=$(sym_addr XChangeProperty)
[ -n "$_addr" ] || fail "table has no XChangeProperty entry"
require_addr XChangeProperty "$_addr" "$WIDER_CHANGEPROPERTY" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changeproperty"
require_match "$TMP/changeproperty" 'movk[[:space:]]+18,[[:space:]]+a[0-9]+' \
"XChangeProperty does not build ChangeProperty request opcode 18"
require_match "$TMP/changeproperty" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeProperty does not write its request opcode to the buffer"
require_match "$TMP/changeproperty" 'calla[[:space:]]+0x3fb44400' \
"XChangeProperty does not copy its value bytes through blit_copy"
require_match "$TMP/changeproperty" '\*a13\(0xff00\)' \
"XChangeProperty does not read the nelements argument (a13-32)"
echo " ok XChangeProperty builds opcode 18, blit_copy value bytes"
_addr=$(sym_addr XChangeGC)
[ -n "$_addr" ] || fail "table has no XChangeGC entry"
require_addr XChangeGC "$_addr" "$WIDER_CHANGEGC" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changegc"
require_match "$TMP/changegc" 'movi[[:space:]]+0x38,[[:space:]]+a[0-9]+' \
"XChangeGC does not build ChangeGC request opcode 56 (0x38)"
require_match "$TMP/changegc" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeGC does not write its request opcode to the buffer"
require_match "$TMP/changegc" 'calla[[:space:]]+0x3f997ad0' \
"XChangeGC does not call the GC value-cache serializer"
echo " ok XChangeGC builds opcode 56, flushes the GC value cache"
}
# The error-handler setters write the per-process XG block: IO at +0x40,
# protocol error at +0x60. The defaults are the ROM's _XDefaultIOError and
# _XDefaultError.
@@ -273,6 +378,7 @@ check_image_requests
check_font_copy
check_pixmap_focus
check_xcreateimage
check_wider_xlib
check_error_handlers
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned)"
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned; M7.3 wider Xlib opcodes pinned)"
+141 -3
View File
@@ -230,6 +230,107 @@ typedef union _XEvent {
#define XYPixmap 1
#define ZPixmap 2
/*
* M7.3 wider Xlib surface. The VT1200 ROM is X11R4: these are the X11R4
* value-mask bits and struct layouts (32-bit fields, packed by the TMS34010
* C ABI). The ROM's own request builders use the same ordering: the
* ConfigureWindow entry arms CWX|CWY|CWWidth|CWHeight (mask 15), and the
* window-attributes walker reads background_pixel from byte 4.
*/
typedef struct {
int x, y;
int width, height;
int border_width;
Window sibling;
int stack_mode;
} XWindowChanges;
#define CWBackPixmap (1L << 0)
#define CWBackPixel (1L << 1)
#define CWBorderPixmap (1L << 2)
#define CWBorderPixel (1L << 3)
#define CWBitGravity (1L << 4)
#define CWWinGravity (1L << 5)
#define CWBackingStore (1L << 6)
#define CWBackingPlanes (1L << 7)
#define CWBackingPixel (1L << 8)
#define CWOverrideRedirect (1L << 9)
#define CWSaveUnder (1L << 10)
#define CWEventMask (1L << 11)
#define CWDontPropagate (1L << 12)
#define CWColormap (1L << 13)
#define CWCursor (1L << 14)
#define CWX (1L << 0)
#define CWY (1L << 1)
#define CWWidth (1L << 2)
#define CWHeight (1L << 3)
#define CWBorderWidth (1L << 4)
#define CWSibling (1L << 5)
#define CWStackMode (1L << 6)
/* X11R4 XSetWindowAttributes: background_pixel is byte 4 (CWBackPixel). */
typedef struct {
unsigned long background_pixmap;
unsigned long background_pixel;
unsigned long border_pixmap;
unsigned long border_pixel;
int bit_gravity;
int win_gravity;
int backing_store;
unsigned long backing_planes;
unsigned long backing_pixel;
Bool save_under;
long event_mask;
long do_not_propagate_mask;
Bool override_redirect;
Colormap colormap;
Cursor cursor;
} XSetWindowAttributes;
/* X11R4 XGCValues: the ROM value walker reads GCFont's field at byte 60. */
typedef struct {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
Pixmap tile;
Pixmap stipple;
int ts_x_origin;
int ts_y_origin;
Font font;
int subwindow_mode;
int graphics_exposures;
int clip_x_origin;
int clip_y_origin;
Pixmap clip_mask;
int dash_offset;
char dashes;
} XGCValues;
#define GCFunction (1L << 0)
#define GCPlaneMask (1L << 1)
#define GCForeground (1L << 2)
#define GCBackground (1L << 3)
#define GCLineWidth (1L << 4)
#define GCLineStyle (1L << 5)
#define GCCapStyle (1L << 6)
#define GCJoinStyle (1L << 7)
#define GCFillStyle (1L << 8)
#define GCFillRule (1L << 9)
#define GCTile (1L << 10)
#define GCStipple (1L << 11)
#define GCTileStipXOrigin (1L << 12)
#define GCTileStipYOrigin (1L << 13)
#define GCFont (1L << 14)
#define True 1
#define False 0
#define None 0L
@@ -241,9 +342,10 @@ typedef int (*XIOErrorHandler)(Display *);
* Real Xlib entry points. The VT1200 ROM exports these names; Task 5
* validates their bit addresses in symbols/vt1200-v22.syms.
*
* XCreateGC's XGCValues* and XLookupString's XComposeStatus* are modelled as
* void*: the layout is not needed by the M4 clients and the 32-bit pointer
* ABI is unchanged.
* XCreateGC's values argument stays void* (the 32-bit pointer ABI is
* unchanged); the X11R4 XGCValues layout is declared above for the M7.3
* wider-surface client and its offset checks. XLookupString's
* XComposeStatus* is modelled as void*.
*/
extern Display *XOpenDisplay(const char *name);
extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
@@ -252,6 +354,38 @@ extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
unsigned long border,
unsigned long background);
extern int XMapWindow(Display *display, Window window);
/*
* M7.3 wider surface, validated in symbols/vt1200-v22.syms.
*
* XMapSubwindows maps every child of `window` (MapSubwindows opcode 9).
*/
extern int XMapSubwindows(Display *display, Window window);
/*
* The ROM's ConfigureWindow entry (0x3FD3A510) is the fixed-mask builder:
* opcode 12, value-mask CWX|CWY|CWWidth|CWHeight, and four scalar arguments.
* That is Xlib's XMoveResizeWindow call shape, not the XWindowChanges-pointer
* shape; XWindowChanges above documents the same four values.
*/
extern int XConfigureWindow(Display *display, Window window, int x, int y,
unsigned int width, unsigned int height);
/* ChangeWindowAttributes opcode 2 (XSetWindowAttributes value walker). */
extern int XChangeWindowAttributes(Display *display, Window window,
unsigned long valuemask,
XSetWindowAttributes *attributes);
/* InternAtom opcode 16; only_if_exists False creates the atom. */
extern Atom XInternAtom(Display *display, const char *name,
Bool only_if_exists);
/* ChangeProperty opcode 18; format 8, mode PropModeReplace = 0. */
extern int XChangeProperty(Display *display, Window window, Atom property,
Atom type, int format, int mode,
const unsigned char *data, int nelements);
/*
* ChangeGC opcode 56. The ROM entry's public shape is (display, gc): it
* serializes the GC's pending value cache (the same serializer the drawing
* primitives call). Values are selected by the cache setters, e.g.
* XSetForeground, or by XCreateGC's XGCValues.
*/
extern int XChangeGC(Display *display, GC gc);
/* CreatePixmap opcode 0x35; depth 1 for the image client's 1-bit pixmap. */
extern Pixmap XCreatePixmap(Display *display, Drawable drawable,
unsigned int width, unsigned int height,
@@ -298,6 +432,10 @@ extern XImage *XCreateImage(Display *display, Visual *visual,
extern int XPutImage(Display *display, Drawable drawable, GC gc, XImage *image,
int src_x, int src_y, int dest_x, int dest_y,
unsigned int width, unsigned int height);
/* GetImage opcode 0x49: synchronous reply; format is XYPixmap or ZPixmap. */
extern XImage *XGetImage(Display *display, Drawable drawable, int x, int y,
unsigned int width, unsigned int height,
unsigned long plane_mask, int format);
extern int XDestroyImage(XImage *image);
extern XErrorHandler XSetErrorHandler(XErrorHandler handler);
extern XIOErrorHandler XSetIOErrorHandler(XIOErrorHandler handler);
+8 -1
View File
@@ -13,7 +13,11 @@
# M4_NATIVE=1, links them with GSPLNK and runs the M4 image/event MAME check.
# The asm/GSPA path remains the default of run.sh.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN
# M5_NATIVE_LINKER=tms-link runs the same native builds through tools/tms-link
# (the termtris run also exercises the rts.lib archive path); the default is
# GSPLNK, which remains the oracle.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN M5_NATIVE_LINKER
# M5_XSHOW_WORK TERMTRIS_WORK TERMTRIS_SDK VT1200_TERMTRIS
# M4_SDK DOSBOX DOSBOX_CONF SDK_IMG MAME LOADER_AT LOADER_END
set -eu
@@ -23,6 +27,7 @@ MODE=${1:-termtris}
DIR=$ROOT/scripts/m4
TERMTRIS_DIR=$DIR/termtris
VENDOR=${VT1200_TERMTRIS:-$ROOT/vendor/vt1200-termtris}
LINKER=${M5_NATIVE_LINKER:-gsplnk}
fail() {
echo "M5 native driver: $*" >&2
@@ -33,6 +38,7 @@ case $MODE in
xshow)
WORK=${M5_XSHOW_WORK:-$ROOT/build/m5-native-xshow}
M4_NATIVE=1 \
M4_LINKER="$LINKER" \
M4_SOURCES="xshow xgfix" \
M4_ENTRY="$DIR/xshow-entry.asm" \
M4_CHECK_LUA="$DIR/xshow-check.lua" \
@@ -61,6 +67,7 @@ termtris)
# section non-empty, so the empty cinit.asm is sufficient (the asm gate's
# CINITZ fallback is only needed when no library contributes .cinit).
M4_NATIVE=1 \
M4_LINKER="$LINKER" \
M4_SKIP_MAME=1 \
M4_SOURCES="$SRC/vt1200/main.c $SRC/game.c $SRC/vt1200/scoredb.c $SRC/vt1200/x11.c $SRC/vt1200/compat.c $SRC/vt1200/xgfix.c" \
M4_EXTRA_INCLUDES="-I $SRC -I $SRC/vt1200 -I $TERMTRIS_DIR/include" \
+10
View File
@@ -24,6 +24,16 @@
_start:
setf 16, 1, 0
setf 32, 0, 1
; Clear the shim's stream lengths. This entry does not otherwise touch
; the result block, and the shim's shadows cannot repair a cell it never
; writes (an empty stream), so clear both cells here.
movi 01B00020h, a1
sub a0, a0
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
calla _runtime_run
+51
View File
@@ -0,0 +1,51 @@
; cinit-entry.asm -- M7.2 `.cinit` gate entry, linked at bit 018A0000.
;
; The `.cinit` loop is byte-for-byte the termtris `_start` loop from
; vendor/vt1200-termtris/apps/termtris/src/vt1200/entry.asm:
;
; movi cinit,a9
; move *a9+,count ; u16 data-word count
; jrz done
; move *a9+,dest,1 ; u32 destination (a TMS34010 bit address)
; move *a9+,*dest+ ; copy `count` words
;
; The public `cinit` symbol is defined at offset 0 of this object's empty
; `.cinit` section (the termtris cinit.asm shape), so the linker places it at
; the `.cinit` origin and the C table (concatenated after this zero-size input
; section) is the record the loop reads. GSPA emits this object's sections in
; the order .text/.data/.bss/.cinit; tms-link accepts that GSPA order as well
; as the llc .text/.data/.cinit/.bss order.
;
; After the copy loop the entry calls cinit_probe(), which returns the sum of
; the three copied words; that value is the 018A8000 marker.
.ref _cinit_probe
.text
.globl _start
_start:
setf 32,0,1
movi _cstack,a14
move a14,a13
movi cinit,a9
ci_loop:
setf 16,0,0
move *a9+,a11
jrz ci_done
move *a9+,a10,1
ci_copy:
move *a9+,*a10+
dsjs a11,ci_copy
jruc ci_loop
ci_done:
setf 32,0,1
move a13,a14
calla _cinit_probe
move a8,@018A8000h,1
rets
.sect ".cinit"
.globl cinit
cinit:
.bss _cstack,32768,16
.end
+51
View File
@@ -0,0 +1,51 @@
/* M7.2 `.cinit` gate table: the TI init-record format in C.
*
* The TI format is a sequence of records:
*
* packed struct {
* unsigned short count; // data word count
* unsigned long destination; // TMS34010 *bit* address
* unsigned short data[count];
* };
*
* terminated by a zero count. `cinit-entry.asm` defines the public `cinit`
* symbol at the start of its own empty `.cinit` section (the termtris
* `cinit.asm` shape) and walks this table exactly like the termtris `_start`:
* `movi cinit,a9; move *a9+,count; move *a9+,dst,1; copy count words`.
*
* The destination is a pointer-typed union member rather than a plain
* `unsigned long` initialised with `(unsigned long)&cinit_target`. Both are
* the same packed 32-bit field at byte offset 2, but the object writer emits a
* relocation only for a pointer constant; casting the address to an integer
* produces an LLVM `ptrtoint` constant expression that the `.data`/.cinit
* emitter deliberately rejects as unsupported. The pointer value *is* the
* TMS34010 bit address in this ABI, so the linked field is the resolved bit
* address the entry loop needs. The record header is packed, so the 32-bit
* destination sits at bit offset 16 and the linker resolves it as an ordinary
* R-RELLONG field (the CPU copy loop is bit-addressed).
*/
unsigned short cinit_target[4];
struct __attribute__((packed)) cinit_record {
unsigned short count;
union {
unsigned long destination;
unsigned short *address;
} target;
unsigned short data[3];
unsigned short end;
};
/* The table lives in `.cinit`; the entry object contributes the `cinit`
* symbol at offset 0 of the concatenated section. */
__attribute__((section(".cinit")))
const struct cinit_record cinit_table = {
3, { .address = cinit_target }, { 0x1111, 0x2222, 0x3333 }, 0
};
/* Called by the entry after the copy loop; returns the sum of the copied
* words (0x1111 + 0x2222 + 0x3333 = 0x6666). */
int cinit_probe(void) {
return cinit_target[0] + cinit_target[1] + cinit_target[2];
}
+29
View File
@@ -0,0 +1,29 @@
; debug-entry.asm -- M7.2 debug-info gate entry, linked at bit 018A0000.
;
; debug.c is linked first so debug_mul is the text-origin function and its
; DWARF low PC is the expected 0x314000 (text origin 018A0000 / 8). This
; entry calls debug_mul(), debug_add() and debug_ptr() and stores their
; results, 43, 14 and 30, at 018A8000, 018A8020 and 018A8040.
;
; debug_ptr() takes no argument: it uses the .data debug_index (2) for the
; pointer update, so the entry needs no argument-pushing sequence.
.ref _debug_mul
.ref _debug_add
.ref _debug_ptr
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _debug_mul
move a8,@018A8000h,1
calla _debug_add
move a8,@018A8020h,1
calla _debug_ptr
move a8,@018A8040h,1
rets
.bss _cstack,32768,16
.end
+37
View File
@@ -0,0 +1,37 @@
int debug_mul(void) {
int product = 42;
return product + 1;
}
int debug_add(void) {
int sum = 7;
return sum + 7;
}
int debug_array[4] = {10, 20, 30, 40};
int debug_index = 2;
int debug_ptr(void) {
int *p = debug_array;
p += debug_index;
return *p;
}
/* M7.2 debug-info gate driver.
*
* Three functions, so the linked `.debug_info` has three subprograms and the
* second/third `.text` offsets are nonzero. debug_mul returns 43,
* debug_add returns 14 and debug_ptr returns debug_array[2] = 30; the entry
* stores them at 018A8000/018A8020/018A8040 after the stripped link is loaded
* in MAME.
*
* debug_ptr is the bit-pointer barrier coverage: `p += debug_index` is a
* runtime `getelementptr` that --bitptr rewrites, so the -O0 gate proves the
* line row survives that rewrite; debug.sh also builds this TU at -O2 -g to
* exercise opt/--scale/--lower-bitptr/instcombine.
*
* The declarations are on lines 1, 6 and 14; the first local-variable /
* pointer-update lines are 2, 7, 15 and 16; debug.sh asserts those
* `.debug_line` rows and the DW_AT_decl_line values. The comment is
* deliberately after the code so the line numbers stay stable.
*/
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Wrap linked TI-COFF `.debug_*` sections in a minimal ELF32 container.
The TMS34010 native path is TI-COFF end to end; `llvm-dwarfdump` reads ELF,
Mach-O and Wasm, not the 1987 TI COFF variant. This test-only helper extracts
the non-allocated `.debug_*` sections from a `tms-link --keep-debug` image and
writes an ELF32 little-endian relocatable container with section headers and a
`.shstrtab` but no program headers or symbol table.
No addresses or relocations are rewritten: `tms-link` has already resolved the
DWARF byte addresses (for example `.debug_addr` holds 0x314000 for text origin
0x018A0000), and DWARF section-internal offsets are section-relative.
Usage:
elf-debug-wrap.py -o OUT.elf LINKED.coff [SECTION ...]
With no SECTION arguments every `.debug_*` section is wrapped. The input is
parsed directly (the helper has no project dependencies) so the debug gate can
assert the linked TI-COFF and the ELF wrapper independently.
"""
from __future__ import annotations
import argparse
import struct
import sys
MAGIC = 0x0090
class WrapError(Exception):
pass
def _u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def _u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def _string_at(table, offset, what):
if offset < 4:
raise WrapError("%s string-table offset %d is inside the 4-byte size "
"field" % (what, offset))
end = table.find(b"\0", offset)
if end < 0:
raise WrapError("%s string-table entry at %d is not terminated"
% (what, offset))
return table[offset:end].decode("latin1")
def read_coff(path):
with open(path, "rb") as fh:
data = fh.read()
if len(data) < 20:
raise WrapError("%s: shorter than a COFF file header" % path)
machine, nscns, _timdat, symptr, nsyms, opthdr, _flags = \
struct.unpack_from("<HHIIIHH", data, 0)
if machine != MAGIC:
raise WrapError("%s: machine %#06x, expected %#06x"
% (path, machine, MAGIC))
if nscns == 0:
raise WrapError("%s: no sections" % path)
string_table = b""
if nsyms:
string_base = symptr + nsyms * 18
if string_base + 4 > len(data):
raise WrapError("%s: symbol/string table runs past EOF" % path)
size = _u32(data, string_base)
if size < 4 or string_base + size > len(data):
raise WrapError("%s: implausible string-table size %d"
% (path, size))
string_table = data[string_base:string_base + size]
sections = []
base = 20 + opthdr
for i in range(nscns):
off = base + i * 40
if off + 40 > len(data):
raise WrapError("%s: section header %d past EOF" % (path, i))
raw_name = data[off:off + 8]
if raw_name.startswith(b"/"):
digits = raw_name[1:].split(b"\0", 1)[0]
if not digits.isdigit():
raise WrapError("%s: bad long section name %r"
% (path, raw_name))
name = _string_at(string_table, int(digits),
"%s: section %d" % (path, i + 1))
else:
name = raw_name.split(b"\0", 1)[0].decode("latin1")
paddr, vaddr, size, scnptr, relptr, _lnnoptr, nreloc, _nlnno, flags = \
struct.unpack_from("<IIIIIIHHI", data, off + 8)
if size % 8:
raise WrapError("%s: section %r size %d bits is not whole bytes"
% (path, name, size))
blob = b""
if size and name != ".bss":
if scnptr + size // 8 > len(data):
raise WrapError("%s: section %r raw data runs past EOF"
% (path, name))
blob = data[scnptr:scnptr + size // 8]
sections.append(dict(name=name, paddr=paddr, vaddr=vaddr, size=size,
flags=flags, nreloc=nreloc, raw=blob))
by_name = {s["name"]: s for s in sections}
if len(by_name) != len(sections):
raise WrapError("%s: duplicate section names" % path)
return sections
def build_elf(sections):
# Only the section-header table and the section payloads exist; the DWARF
# data is already absolute, so no symbol table or relocations are needed.
shstr = bytearray(b"\0")
name_off = {}
for sec in sections:
name_off[sec["name"]] = len(shstr)
shstr.extend(sec["name"].encode("latin1"))
shstr.append(0)
shstr_name = len(shstr)
shstr.extend(b".shstrtab\0")
shnum = len(sections) + 2 # null section + payload sections + shstrtab
shoff = 52
cursor = (shoff + shnum * 40 + 3) & ~3
payload_off = []
for sec in sections:
payload_off.append(cursor)
cursor += len(sec["raw"])
cursor = (cursor + 3) & ~3
shstr_off = cursor
cursor += len(shstr)
total = (cursor + 3) & ~3
out = bytearray(total)
e_ident = b"\x7fELF" + bytes([1, 1, 1, 0]) + bytes(8) # 32-bit LE v1
struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, e_ident,
1, # e_type ET_REL
# EM_386 keeps llvm-dwarfdump from warning about an
# unknown machine (there is no standard TMS34010 EM_*).
3, # e_machine EM_386
1, # e_version
0, # e_entry
0, # e_phoff (no program headers)
shoff, # e_shoff
0, # e_flags
52, # e_ehsize
0, 0, # e_phentsize, e_phnum
40, # e_shentsize
shnum, # e_shnum
shnum - 1) # e_shstrndx
for i, sec in enumerate(sections, start=1):
off = shoff + i * 40
struct.pack_into("<IIIIIIIIII", out, off,
name_off[sec["name"]],
1, # SHT_PROGBITS
0, # no sh_flags
0, # sh_addr (DWARF is absolute)
payload_off[i - 1],
len(sec["raw"]),
0, 0, # sh_link, sh_info
1, # sh_addralign
0) # sh_entsize
out[payload_off[i - 1]:payload_off[i - 1] + len(sec["raw"])] = \
sec["raw"]
off = shoff + (shnum - 1) * 40
struct.pack_into("<IIIIIIIIII", out, off, shstr_name, 3, 0, 0,
shstr_off, len(shstr), 0, 0, 1, 0)
out[shstr_off:shstr_off + len(shstr)] = shstr
return bytes(out)
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("-o", "--output", required=True, metavar="OUT.elf",
help="ELF32 output container")
p.add_argument("coff", metavar="LINKED.coff",
help="linked TI-COFF with --keep-debug")
p.add_argument("sections", nargs="*", metavar="SECTION",
help="debug section names to include (default: all "
".debug_*)")
args = p.parse_args(argv)
try:
all_sections = read_coff(args.coff)
by_name = {s["name"]: s for s in all_sections}
if args.sections:
missing = [n for n in args.sections if n not in by_name]
if missing:
raise WrapError("%s: missing section(s): %s"
% (args.coff, ", ".join(missing)))
chosen = [by_name[n] for n in args.sections]
else:
chosen = [s for s in all_sections
if s["name"].startswith(".debug_")]
if not chosen:
raise WrapError("%s: no .debug_* sections to wrap" % args.coff)
for sec in chosen:
if not sec["name"].startswith(".debug_"):
raise WrapError("%s: %r is not a .debug_* section"
% (args.coff, sec["name"]))
if sec["paddr"] != 0 or sec["vaddr"] != 0:
raise WrapError("%s: debug section %r has paddr/vaddr "
"%#x/%#x, expected 0/0"
% (args.coff, sec["name"], sec["paddr"],
sec["vaddr"]))
elf = build_elf(chosen)
with open(args.output, "wb") as fh:
fh.write(elf)
print("elf-debug-wrap: %s <- %s (%s)"
% (args.output, args.coff,
" ".join("%s=%dB" % (s["name"], len(s["raw"]))
for s in chosen)))
return 0
except (WrapError, OSError) as exc:
print("elf-debug-wrap: error: %s" % exc, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+111
View File
@@ -0,0 +1,111 @@
-- hw-check.lua -- M7.3 real-hardware marker gate, MAME-equivalent acceptance.
--
-- Loads the same COFF that hostload.py sends to the real unit
-- (scripts/m7/hwmark.c, linked at .text 018C0000 / .data 018D0000 /
-- .bss 018D8000) through vendor/vt1200/dwt/loader/loader.lua, then requires
-- exactly what hostload.py's verify_markers() requires:
--
-- 018E0000 start == the loader result block's entry (018C0000)
-- 018E0020 data == 0xDEADBEEF (copied .data)
-- 018E0040 data2 == 0x12345678 (copied .data)
-- 018E0060 bss == 0 (zeroed .bss; loader pre-fills A5A5)
-- 018E0080 count advances (the child is scheduled, not jumped)
--
-- and that the loader result status is 0. LOADER_AT/LOADER_END come from the
-- M4-style environment; the counter is sampled after the child has run, then
-- again one frame before the loader exits.
dofile(os.getenv("M4_LOADER_LUA"))
local AT = tonumber(os.getenv("LOADER_AT") or "2500")
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local RESULT = 0x01882D00
local CELLS = {
{ 0x018E0000, "start" },
{ 0x018E0020, "data" },
{ 0x018E0040, "data2" },
{ 0x018E0060, "bss" },
{ 0x018E0080, "count" },
}
-- First sample: a few frames after injection, so the child has started.
-- Second sample: the last frame before loader.lua inspects and exits.
local SAMPLE0 = math.max(AT + 5, ENDF - 11)
local SAMPLE1 = ENDF - 1
local frames = 0
local first_count = nil
local checked = false
local function r32(prog, addr)
local ok, v = pcall(function() return prog:read_u32(addr) end)
if ok then return v end
return nil
end
emu.register_frame_done(function()
frames = frames + 1
if frames == SAMPLE0 and first_count == nil then
local prog = manager.machine.devices[':maincpu'].spaces['program']
first_count = r32(prog, 0x018E0080)
end
if frames == SAMPLE1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local v = {}
for _, cell in ipairs(CELLS) do
v[cell[2]] = r32(prog, cell[1])
end
local status = r32(prog, RESULT + 0x000)
local entry = r32(prog, RESULT + 0x020)
local count0 = first_count or 0
local count1 = v.count or 0
print(string.format(
"M7 HW: start=0x%08X data=0x%08X data2=0x%08X bss=0x%08X count=%d->%d status=%d entry=0x%08X",
v.start or 0, v.data or 0, v.data2 or 0, v.bss or 0,
count0, count1, status or -1, entry or 0))
local problems = {}
if status ~= 0 then
problems[#problems + 1] = string.format("loader status=%s, want 0",
tostring(status))
end
if entry ~= 0x018C0000 then
problems[#problems + 1] = string.format(
"loader entry=0x%08X, want 0x018C0000", entry or 0)
end
if v.start ~= entry then
problems[#problems + 1] = string.format(
"start=0x%08X, want the entry 0x%08X", v.start or 0, entry or 0)
end
if v.data ~= 0xDEADBEEF then
problems[#problems + 1] = string.format("data=0x%08X, want 0xDEADBEEF",
v.data or 0)
end
if v.data2 ~= 0x12345678 then
problems[#problems + 1] = string.format(
"data2=0x%08X, want 0x12345678", v.data2 or 0)
end
if v.bss ~= 0 then
problems[#problems + 1] = string.format("bss=0x%08X, want 0",
v.bss or 0)
end
if count0 <= 0 or count1 <= count0 then
problems[#problems + 1] = string.format(
"count did not advance (%d -> %d)", count0, count1)
end
if #problems == 0 then
print("M7 HW MAME: PASS")
else
for _, p in ipairs(problems) do
print("M7 HW: FAIL: " .. p)
end
print("M7 HW MAME: FAIL")
end
end
end, "m7-hw-check")
+76
View File
@@ -0,0 +1,76 @@
/*
* hwmark.c -- M7.3 real-hardware marker client, built at the proven VT1200
* hardware origins:
*
* .text 018C0000h
* .data 018D0000h
* .bss 018D8000h
*
* This is the COFF image that dwt/loader/hostload.py pokes and that
* dwt/loader/loader.asm places through create_process. The marker cells are
* the ones hostload.py's MARKER_CELLS names (all TMS34010 *bit* addresses):
*
* 018E0000 _start address at run time (must equal the loader entry)
* 018E0020 d_magic read from .data (must be DEADBEEF)
* 018E0040 d_two read from .data (must be 12345678)
* 018E0060 b_zero read from .bss (must be 0)
* 018E0080 b_counter, a live counter (must advance)
*
* The M7.3 brief prefers a C-only entry when the compiler can express it, so
* `start` is an ordinary C function and the COFF entry point is `_start`.
* create_process() supplies the process stack (the firmware allocates it; the
* xhello trace records a valid entry A14). The MAME run proves the generated
* prologue did not fault and the markers/counter are correct, not that A14/SP
* point at the create_process stack; the real-unit run (VT1200_HOST) is the
* hardware confirmation. The `.data` pointer
* initializer below is supported as an ordinary pointer relocation, so no
* `ptrtoint` constant initializer and no assembly entry are needed.
*
* The loader zeroes .bss after the harness has pre-filled it with A5A5, so a
* zero at 018E0060 is the loader's work, not fresh RAM. The delay loop is
* marker.asm's 2000h `dsjs` delay: the child stays scheduled but does not burn
* the cooperative scheduler with an unbroken hot loop.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018E0000u + (n) * 0x20u))
/* Initialised .data: the loader must copy these bytes from the COFF. */
unsigned int d_magic = 0xDEADBEEFu;
unsigned int d_two = 0x12345678u;
/* Uninitialised .bss: the loader must zero these. */
unsigned int b_zero;
unsigned int b_counter;
void start(void);
/*
* The entry address as a relocated pointer, not a ptrtoint constant. The
* loader's result block reports the same `_start` bit address as the COFF
* entry point, so the runtime start cell proves placement, not a guess.
*/
void (*const start_address)(void) = start;
/* A volatile .bss sink keeps the delay loop from being folded away. */
static volatile unsigned int delay_sink;
void start(void) {
unsigned int count = 0;
MARK(0) = (unsigned int)start_address;
MARK(1) = d_magic;
MARK(2) = d_two;
MARK(3) = b_zero;
for (;;) {
unsigned int spin;
count++;
b_counter = count;
MARK(4) = count;
for (spin = 0; spin < 0x2000u; spin++) {
delay_sink = spin;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
-a
-o M4.OUT
-m M4.MAP
-e _start
M4.obj
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Assert the M7.4 i64div perf marker cells are outside every linked section.
Usage:
i64div-map-check.py MAP MARKER_HEX [PROG_ORIGIN PROG_LEN RAM_ORIGIN RAM_LEN]
MAP is a GSPLNK 2.00 map (the SECTION ALLOCATION MAP has origin/length in
bits) or a tms-link map (the symbol addresses give .text/etext,
.data/edata, .bss/end). MARKER_HEX is the marker base bit address; the gate
uses 12 cells 0x20 bits apart. The optional region arguments are also in hex
(bits) and bound .text/.data to prog and .bss/the markers to ram.
Exit status: 0 = every check passed, 1 = overlap/out-of-region, 2 = the map
could not be parsed.
"""
import re
import sys
def parse_sections(lines):
"""Return {name: (start, end)} for .text/.data/.bss."""
sections = {}
# GSPLNK allocation lines: name page origin length [attributes]
for line in lines:
m = re.match(
r"^\s*(\.\w+)\s+\d+\s+([0-9A-Fa-f]+)\s+([0-9A-Fa-f]+)\b",
line)
if not m:
continue
origin = int(m.group(2), 16)
length = int(m.group(3), 16)
sections[m.group(1)] = (origin, origin + length)
if sections:
return sections
# tms-link map: "ADDR .text" / "ADDR etext" style symbol addresses.
starts, ends = {}, {}
for line in lines:
m = re.match(
r"^\s*([0-9A-Fa-f]+)\s+(\.\w+|etext|edata|end)\s*$", line)
if not m:
continue
addr = int(m.group(1), 16)
name = m.group(2)
if name in (".text", ".data", ".bss"):
starts[name] = addr
else:
ends[name] = addr
for name, endname in ((".text", "etext"), (".data", "edata"),
(".bss", "end")):
if name in starts and endname in ends:
sections[name] = (starts[name], ends[endname])
return sections
def main():
if len(sys.argv) not in (3, 7):
print(__doc__, file=sys.stderr)
return 2
map_path = sys.argv[1]
marker = int(sys.argv[2], 16)
marker_end = marker + 12 * 0x20
regions = None
if len(sys.argv) == 7:
prog_origin, prog_len, ram_origin, ram_len = (
int(v, 16) for v in sys.argv[3:7])
regions = (prog_origin, prog_origin + prog_len,
ram_origin, ram_origin + ram_len)
with open(map_path, encoding="ascii", errors="replace") as f:
sections = parse_sections(f.read().splitlines())
missing = [s for s in (".text", ".data", ".bss") if s not in sections]
if missing:
print(
"i64div perf map: cannot find %s in %s"
% (", ".join(missing), map_path),
file=sys.stderr)
return 2
ok = True
for name in (".text", ".data", ".bss"):
lo, hi = sections[name]
if marker < hi and marker_end > lo:
print(
"i64div perf map: markers 0x%08X..0x%08X overlap %s "
"0x%08X..0x%08X" % (marker, marker_end, name, lo, hi),
file=sys.stderr)
ok = False
if regions is not None:
prog_lo, prog_hi, ram_lo, ram_hi = regions
for name in (".text", ".data"):
lo, hi = sections[name]
if lo < prog_lo or hi > prog_hi:
print(
"i64div perf map: %s 0x%08X..0x%08X is outside prog "
"0x%08X..0x%08X" % (name, lo, hi, prog_lo, prog_hi),
file=sys.stderr)
ok = False
lo, hi = sections[".bss"]
if lo < ram_lo or hi > ram_hi:
print(
"i64div perf map: .bss 0x%08X..0x%08X is outside ram "
"0x%08X..0x%08X" % (lo, hi, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if marker < ram_lo or marker_end > ram_hi:
print(
"i64div perf map: markers 0x%08X..0x%08X are outside ram "
"0x%08X..0x%08X" % (marker, marker_end, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if not ok:
return 1
extents = ", ".join(
"%s 0x%08X..0x%08X" % (name, sections[name][0], sections[name][1])
for name in (".text", ".data", ".bss"))
print(
"i64div perf map: %s; markers 0x%08X..0x%08X outside every section"
% (extents, marker, marker_end))
if regions is not None:
print(
"i64div perf map: markers inside ram 0x%08X..0x%08X"
% (regions[2], regions[3]))
return 0
if __name__ == "__main__":
sys.exit(main())
+147
View File
@@ -0,0 +1,147 @@
-- i64div-perf-check.lua -- measure the M7.4 i64 divide/remainder fast path in
-- MAME.
--
-- Loads the gate COFF with vendor/vt1200/dwt/loader/loader.lua (through the
-- M4_LOADER_LUA variable scripts/m4/run.sh exports) and polls the marker
-- words once per frame. A MAME frame is a fixed number of emulated 50 MHz
-- cycles, so the number of frames between the start marker and each phase's
-- completion marker is a reproducible cycle proxy for the equal-iteration
-- workloads in scripts/m7/i64div-perf.c:
--
-- fast phase: 16384 iterations, every divide fits 32 bits -> one DIVU each;
-- slow phase: 16384 iterations, both high words nonzero -> the 64-step loop;
-- wide phase: 16384 iterations, nonzero dividend high word but a 32-bit
-- divisor -> two even-destination DIVUs (the M8.3 64/32 path).
--
-- The gate requires the fast phase to complete in materially fewer frames
-- (slow_frames >= 8 * max(fast_frames, 1)) and the slow phase to be long
-- enough to measure (>= 20 frames). A sub-frame fast phase is reported as
-- fast_frames=0 and compared as one frame, which can only make the check
-- harder. The wide phase must also be materially faster than the loop
-- (slow_frames >= 4 * max(wide_frames, 1)) and measurable (>= 2 frames).
--
-- All three phase checksums are required to equal the deterministic values
-- below. They were computed from the same LCG/arithmetic with an independent
-- host implementation of scripts/m7/i64div-perf.c (see the header comment
-- there):
-- fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE,
-- wide = 0x00025AF70AF974E0.
-- The in-image self-check (marker 7) also covers large 32-bit magnitudes
-- (0xFFFFFFFF/7, -123/7 and INT32_MIN/3) plus the 64/32 shapes with hi >= d,
-- hi == d, hi < d and INT64_MIN, so a wrong quotient or remainder fails before
-- the timing comparison.
--
-- Markers at 01A20000h, 0x20 bits apart (free RAM above the 4 KiB entry stack;
-- scripts/m7/i64div-map-check.py asserts they are outside .text/.data/.bss):
-- 0 start 0x51A47A11 | 1/2 fast checksum | 3 fast done 0xFA57D01E
-- 4/5 slow checksum | 6 slow done 0x5104D0E5 | 7 status 0x600D600D
-- 8 wide done 0x81DE0D0E | 9/10 wide checksum
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "4000")
local BASE = 0x01A20000
local START = 0x51A47A11
local FAST_DONE = 0xFA57D01E
local SLOW_DONE = 0x5104D0E5
local WIDE_DONE = 0x81DE0D0E
local STATUS_OK = 0x600D600D
local FAST_HI, FAST_LO = 0x00000001, 0x1E6F9AB4
local SLOW_HI, SLOW_LO = 0x00000000, 0x007512AE
local WIDE_HI, WIDE_LO = 0x00025AF7, 0x0AF974E0
local frames = 0
local start_f, fast_f, slow_f, wide_f
local reported = false
local function rd(n)
local prog = manager.machine.devices[':maincpu'].spaces['program']
return prog:read_u32(BASE + n * 0x20)
end
emu.register_frame_done(function()
frames = frames + 1
if start_f == nil and rd(0) == START then
start_f = frames
end
if start_f ~= nil and fast_f == nil and rd(3) == FAST_DONE then
fast_f = frames
end
if fast_f ~= nil and slow_f == nil and rd(6) == SLOW_DONE then
slow_f = frames
end
if slow_f ~= nil and wide_f == nil and rd(8) == WIDE_DONE then
wide_f = frames
end
if wide_f ~= nil and not reported then
reported = true
local fast_frames = fast_f - start_f
local slow_frames = slow_f - fast_f
local wide_frames = wide_f - slow_f
local basis = fast_frames
if basis < 1 then
basis = 1
end
local wide_basis = wide_frames
if wide_basis < 1 then
wide_basis = 1
end
local status = rd(7)
local cs_fast_hi, cs_fast_lo = rd(2), rd(1)
local cs_slow_hi, cs_slow_lo = rd(5), rd(4)
local cs_wide_hi, cs_wide_lo = rd(10), rd(9)
local ratio = slow_frames / basis
local wide_ratio = slow_frames / wide_basis
local cs_ok = cs_fast_hi == FAST_HI and cs_fast_lo == FAST_LO
and cs_slow_hi == SLOW_HI and cs_slow_lo == SLOW_LO
and cs_wide_hi == WIDE_HI and cs_wide_lo == WIDE_LO
local ok = status == STATUS_OK and cs_ok
and slow_frames >= 20
and slow_frames >= 8 * basis
and wide_frames >= 2
and slow_frames >= 4 * wide_basis
print(string.format(
"M7: i64div perf: start=%d fast_done=%d slow_done=%d "
.. "wide_done=%d fast_frames=%d slow_frames=%d "
.. "wide_frames=%d ratio=%.1f wide_ratio=%.1f "
.. "status=%08X cs_fast=%08X%08X cs_slow=%08X%08X "
.. "cs_wide=%08X%08X "
.. "cs_expected=%08X%08X/%08X%08X/%08X%08X cs=%s",
start_f, fast_f, slow_f, wide_f, fast_frames, slow_frames,
wide_frames, ratio, wide_ratio,
status, cs_fast_hi, cs_fast_lo, cs_slow_hi, cs_slow_lo,
cs_wide_hi, cs_wide_lo,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO, WIDE_HI, WIDE_LO,
cs_ok and "ok" or "BAD"))
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (status=%08X checksums=%s "
.. "fast_frames=%d slow_frames=%d wide_frames=%d; "
.. "want status %08X, fast %08X%08X, slow %08X%08X, "
.. "wide %08X%08X, slow_frames >= 20 and "
.. ">= 8*max(fast_frames,1), wide_frames >= 2 and "
.. "slow_frames >= 4*max(wide_frames,1))",
status, cs_ok and "ok" or "BAD",
fast_frames, slow_frames, wide_frames, STATUS_OK,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO,
WIDE_HI, WIDE_LO))
end
elseif frames == ENDF - 1 and not reported then
reported = true
local seen = string.format(
"start=%s fast_done=%s slow_done=%s wide_done=%s",
tostring(start_f), tostring(fast_f), tostring(slow_f),
tostring(wide_f))
print(string.format(
"M7: i64div perf: incomplete at frame %d at marker 0x%08X",
frames, BASE))
print("M7 MAME: FAIL (timed out: " .. seen .. ")")
end
end, "i64div-perf-check")
+19
View File
@@ -0,0 +1,19 @@
; i64div-perf-entry.asm -- M7.4 i64 divide/remainder performance gate entry,
; linked at bit 018A0000 by scripts/tests/m7/i64div.sh through
; scripts/m4/run.sh.
;
; Sets the TI C field sizes, points STK/FP at the gate stack and calls
; i64div_perf_run(), which writes the phase markers and returns. The loader
; harness inspects the markers at LOADER_END-1, so no post-return sentinel is
; needed; the program's last marker write is the slow-phase completion flag.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64div_perf_run
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+265
View File
@@ -0,0 +1,265 @@
/* M7.4/M8.3 i64 divide/remainder fast-path performance driver.
*
* Three equal-iteration workloads exercise the paths of
* TMS34010LowerI64::lowerDivRem:
*
* fast phase: both operands fit 32 bits after the signed magnitude
* normalization, so the compiler emits one 32-bit DIVU (plus
* the div/mul/sub remainder reconstruction) instead of the
* 64-step restoring loop;
* slow phase: both operands have nonzero high words, so the 64-step loop
* runs for each of the four i64 div/rem forms;
* wide phase: the dividend has a nonzero high word but the divisor fits
* 32 bits, so the M8.3 64/32 path emits two even-destination
* DIVUs (q1/r1 then q0/r0) instead of the 64-step loop.
*
* The loop bodies are driven by a volatile iteration count and volatile
* seeds, and every result feeds a volatile accumulator that is published in
* the marker words, so neither phase can be constant-folded or discarded.
*
* Markers (0x20 bits apart at 01A20000h, the free RAM area above the 4 KiB
* entry stack at 01A00000h; outside .text/.data/.bss, see
* scripts/m7/i64div-map-check.py):
* 0 start 0x51A47A11
* 1 fast checksum low (printed evidence)
* 2 fast checksum high
* 3 fast phase done 0xFA57D01E
* 4 slow checksum low (printed evidence)
* 5 slow checksum high
* 6 slow phase done 0x5104D0E5
* 7 self-check status 0x600D600D on success
* 8 wide phase done 0x81DE0D0E
* 9 wide checksum low (printed evidence)
* 10 wide checksum high
*
* The self-check runs known i64 divisions first (fast and slow, unsigned and
* signed, including full-width low words and the INT32_MIN magnitude), so the
* timing comparison is between two correct paths rather than between a
* fast-but-wrong path and the loop. scripts/m7/i64div-perf-check.lua polls
* the markers once per MAME frame, turns the frame numbers into the gate's
* cycle proxy, and requires the exact phase checksums. With the 16384
* iterations above the deterministic LCG workloads produce
* fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE
* (checked against an independent host implementation of this file; the
* target compiler must produce the same integer results).
*/
typedef unsigned int u32;
typedef int s32;
typedef unsigned long long u64;
typedef long long s64;
#define MARK(n) (*(volatile u32 *)(0x01A20000u + (u32)(n) * 0x20u))
#define PERF_START 0x51A47A11u
#define PERF_FAST_DONE 0xFA57D01Eu
#define PERF_SLOW_DONE 0x5104D0E5u
#define PERF_WIDE_DONE 0x81DE0D0Eu
#define PERF_STATUS_OK 0x600D600Du
#define PERF_STATUS_BAD 0xBAD0BAD0u
/* 16384 iterations put the fast phase at a few frames and the slow phase at a
* few hundred frames on the emulated 50 MHz part, with a wide margin under
* the 4000-frame loader budget. The count is volatile so the optimizer keeps
* a real loop and does not unroll it into a folded constant. */
static volatile u32 perf_iters = 16384u;
/* Seeds are volatile for the same reason: the divisions must really execute. */
static volatile u64 seed_a = 0x0000000012345678ull;
static volatile u64 seed_b = 0x000000009ABCDEF1ull;
/* Known-value inputs (values pinned by the M6 i64 gate). */
static volatile u64 sc_n1 = 0x123456789ABCDEF0ull;
static volatile u64 sc_d1 = 0x0000000000001234ull;
static volatile u64 sc_d2 = 0x0000000123456789ull;
static volatile s64 sc_n3 = -1000000000000ll;
static volatile s64 sc_d3 = 7ll;
static volatile s64 sc_n4 = 123ll;
static volatile s64 sc_d4 = -7ll;
/* Fast-path cases with large low words: the high word is zero (or the value
* is a negative 32-bit value whose magnitude still fits), so the quotient and
* remainder must come from the 32-bit DIVU, not the loop. */
static volatile u64 sc_max32 = 0xFFFFFFFFull;
static volatile u64 sc_seven = 7ull;
static volatile s64 sc_neg123 = -123ll;
static volatile s64 sc_int32min = -2147483648ll;
static volatile s64 sc_three = 3ll;
/* M8.3 64/32-path cases: nonzero dividend high word, 32-bit divisor. The
* first, second and INT64_MIN cases exercise the two-step form where the
* quotient needs 33+ bits (hi >= d); the third has hi < d, so q1 is zero and
* the second even-destination divide produces the whole quotient. The helper
* still executes both divides in every case. */
static volatile u64 sc_wide1 = 0xFEDCBA9876543210ull;
static volatile u64 sc_wide_d1 = 0x12345678ull;
static volatile u64 sc_wide2 = 0xFFFFFFFFFFFFFFFFull;
static volatile u64 sc_wide_d2 = 0xFFFFFFFFull;
static volatile u64 sc_wide3 = 0x00000001FFFFFFFFull;
static volatile u64 sc_wide4 = 0x8000000000000000ull;
static volatile s64 sc_int64min = -9223372036854775807ll - 1ll;
static u32 lcg(u32 x)
{
return x * 1103515245u + 12345u;
}
/* Known-value checks for both paths, unsigned and signed, including the
* full-width low words and INT32_MIN. */
static u32 selfcheck(void)
{
u64 q, r;
s64 sq, sr;
u32 ok = 1;
q = sc_n1 / sc_d1;
r = sc_n1 % sc_d1;
ok &= (q == 0x00010004C016906Bull) && (r == 0x334ull);
/* Divisor above 32 bits: the restoring loop. */
q = sc_n1 / sc_d2;
r = sc_n1 % sc_d2;
ok &= (q == 0x0000000010000000ull) && (r == 0x0ABCDEF0ull);
/* Both signed values fit after normalization: the signed fast path. */
sq = sc_n4 / sc_d4;
sr = sc_n4 % sc_d4;
ok &= (sq == -17ll) && (sr == 4ll);
/* Fast paths with large low words. A wrong 32-bit quotient/remainder
* for a full-width magnitude (or for INT32_MIN's magnitude 2^31) must
* fail here before the timing comparison. */
q = sc_max32 / sc_seven;
r = sc_max32 % sc_seven;
ok &= (q == 0x0000000024924924ull) && (r == 3ull);
/* sc_d3 is the signed 7: sc_seven is u64, so mixing it with a negative
* s64 would make the comparison unsigned (the same C conversion the
* target performs). */
sq = sc_neg123 / sc_d3;
sr = sc_neg123 % sc_d3;
ok &= (sq == -17ll) && (sr == -4ll);
sq = sc_int32min / sc_three;
sr = sc_int32min % sc_three;
ok &= (sq == -715827882ll) && (sr == -2ll);
/* A large signed dividend: the signed wide path (32-bit divisor 7). */
sq = sc_n3 / sc_d3;
sr = sc_n3 % sc_d3;
ok &= (sq == -142857142857ll) && (sr == -1ll);
/* M8.3 64/32 path with hi >= d: the quotient needs 36 bits. */
q = sc_wide1 / sc_wide_d1;
r = sc_wide1 % sc_wide_d1;
ok &= (q == 0x0000000E00000077ull) && (r == 0x48ull);
/* M8.3 64/32 path with hi == d: the quotient needs 33 bits. */
q = sc_wide2 / sc_wide_d2;
r = sc_wide2 % sc_wide_d2;
ok &= (q == 0x0000000100000001ull) && (r == 0ull);
/* M8.3 64/32 path with hi < d: the quotient fits in one divide. */
q = sc_wide3 / sc_wide_d2;
r = sc_wide3 % sc_wide_d2;
ok &= (q == 2ull) && (r == 1ull);
/* M8.3 unsigned INT64_MIN magnitude and signed INT64_MIN / 3. */
q = sc_wide4 / sc_three;
r = sc_wide4 % sc_three;
ok &= (q == 0x2AAAAAAAAAAAAAAAull) && (r == 2ull);
sq = sc_int64min / sc_three;
sr = sc_int64min % sc_three;
ok &= (sq == -3074457345618258602ll) && (sr == -2ll);
return ok ? PERF_STATUS_OK : PERF_STATUS_BAD;
}
/* Small operands: the high words are zero, so the four divisions take the
* 32-bit fast path. The signed forms cast a 32-bit value to i64; a negative
* value still has a 32-bit magnitude, so it also takes the fast path. */
static void run_fast(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = (u64)(lcg((u32)a) & 0x7FFFFFFFu) + 1u;
b = (u64)(lcg((u32)b) & 0x0000FFFFu) + 1u;
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)(s32)a / (s64)(s32)b);
acc ^= (u64)((s64)(s32)a % (s64)(s32)b);
}
MARK(1) = (u32)acc;
MARK(2) = (u32)(acc >> 32);
MARK(3) = PERF_FAST_DONE;
}
/* Nonzero high words in both operands: all four forms take the 64-step
* restoring loop. The same iteration count as the fast phase makes the frame
* counts directly comparable. */
static void run_slow(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(1u + (lcg((u32)(a >> 32)) & 0xFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = ((u64)(1u + (lcg((u32)(b >> 32)) & 0x00FFu)) << 32)
| (u64)(lcg((u32)b) | 1u);
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(4) = (u32)acc;
MARK(5) = (u32)(acc >> 32);
MARK(6) = PERF_SLOW_DONE;
}
/* Nonzero dividend high word, 32-bit divisor: all four forms take the M8.3
* two-step 64/32 path (two even-destination DIVUs) instead of the 64-step
* loop. The high word is capped at 16 bits and the divisor at 16 bits so the
* values stay in the tested range while still covering hi >= d and hi < d. */
static void run_wide(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(1u + (lcg((u32)(a >> 32)) & 0xFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = (u64)(1u + (lcg((u32)b) & 0x0000FFFFu));
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(9) = (u32)acc;
MARK(10) = (u32)(acc >> 32);
MARK(8) = PERF_WIDE_DONE;
}
void i64div_perf_run(void)
{
MARK(7) = selfcheck();
MARK(0) = PERF_START;
run_fast();
run_slow();
run_wide();
}
+11
View File
@@ -0,0 +1,11 @@
/* M7.2 long-public-name gate, TU A.
*
* The public function name is 44 characters (45 with the C `_` prefix),
* longer than GSPA 2.00's 31-character symbol limit. The object path keeps it
* intact; tms-link resolves the cross-TU reference from longname-b.c and writes
* the full name into its map.
*/
int tms34010_public_function_name_longer_than_31(void) {
return 42;
}
+12
View File
@@ -0,0 +1,12 @@
/* M7.2 long-public-name gate, TU B.
*
* Declares and calls the 44-character public function from longname-a.c. The
* call is a normal undefined-external R-RELLONG in this object; tms-link
* resolves it to TU A's definition without truncating either name.
*/
int tms34010_public_function_name_longer_than_31(void);
int longname_call(void) {
return tms34010_public_function_name_longer_than_31() + 1;
}
+21
View File
@@ -0,0 +1,21 @@
; longname-entry.asm -- M7.2 long-public-name gate entry, linked at 018A0000.
;
; Calls the short-named TU B wrapper (which calls the 44-character public
; function in TU A) and stores its result, 43, at 018A8000. GSPA never sees
; the long name: it only assembles the short `_longname_call` reference, so
; the gate exercises tms-link's long-name symbol resolution rather than GSPA's
; 31-character truncation.
.ref _longname_call
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _longname_call
move a8,@018A8000h,1
rets
.bss _cstack,32768,16
.end
+149
View File
@@ -0,0 +1,149 @@
-- xmore-check.lua -- load the M7.3 wider-Xlib COFF with dwt/loader/loader.lua,
-- then prove the markers and the window pixels.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame (default 3400)
--
-- Markers (0x20 bits apart, read at LOADER_END-1):
-- 018A8000 parent Window id, nonzero
-- 018A8020 child Window id, nonzero
-- 018A8040 gc GC pointer, nonzero
-- 018A8060 atom XInternAtom("WM_NAME"): nonzero atom, or
-- 0xFFFFFFFF documented skip (the ROM _XSend path
-- that carries the name does not complete here)
-- 018A8080 property 1 after the XChangeProperty call site ran (no
-- server read-back; zero X errors is the only
-- runtime check)
-- 018A80A0 configure client-computed (child width << 16) | height
-- (0x00C80096); the move is pixel-proven, the size
-- is not read back
-- 018A80C0 font XLoadFont("fixed"), nonzero
-- 018A80E0 image (pixel << 8) | flags (0x13F when the full
-- XCreateImage/XGetImage/XPutImage/XDestroyImage
-- round trip worked: pixel=1 and flags=0x3F)
-- 018A8100 errors X protocol error count (0)
-- 018A8120 stage 14 = InternAtom attempted (skip), 15 = returned
-- 018A8140 attrs 1 after the XChangeWindowAttributes call site ran;
-- the real proof is the black CWBackPixel margin
-- (the ROM builder does not set A8)
-- 018A8160 gcchange XChangeGC source call count (2); runtime entry is
-- not proven, and the ROM entry is a cache flush
-- 018A8180 text set pixels in the XDrawString band (0,126) 64x16
-- 018A81A0 display Display pointer stored just before XInternAtom
-- 018A81C0 fill (FILL_W << 16) | FILL_H (0xA00078), pins the
-- margin sample's fill geometry
--
-- Geometry: parent at screen (100,100) 400x300 (the WM leaves a top-level
-- client window at its requested origin, as the M4 xshow gate proves), child
-- configured to (20,20) 200x150. The child is created with background 1
-- (white), then CWBackPixel=0 (black). The 160x120 black fill leaves a
-- right/bottom margin; screen (300,240) is in that margin, so it is black only
-- because of the window attribute (without it the child background is white).
-- The white rectangle is at child (0,0) 32x32 (screen 120,120), the heap image
-- at child (40,32) (screen 160,152; 32-bit aligned) and the XGetImage result
-- put back at child (104,32) (screen 224,152). The text is drawn at baseline
-- child (4,140) on the black margin, and the XGetImage band (child 0,126 64x16)
-- counts its white glyph pixels.
--
-- The printed "parent(...)" coordinate is screen minus the parent origin
-- (100,100), i.e. parent-relative, not child-relative (the child is at 20,20
-- inside the parent).
--
-- Pixel sampling reads the exact VRAM bit address (VR319: 2048-bit rows,
-- LSB-first), not a whole unaligned word. If XConfigureWindow did not move the
-- child from its created (40,40), the p_rect sample (screen 128,128) is outside
-- the child and p_back (screen 240,160) maps outside the put-back image; p_img
-- alone would still be white (it would land inside the 32x32 rectangle).
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local VRAM_BASE = 0x04000000
local VRAM_PITCH = 2048
local WIN_X, WIN_Y = 100, 100
local frames = 0
local checked = false
local function read_bit(prog, sx, sy)
local bit = VRAM_BASE + sy * VRAM_PITCH + sx
return prog:read_u16(bit) % 2, bit
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 14 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M7: window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14]))
local function sample(sx, sy, want)
local b, bit = read_bit(prog, sx, sy)
print(string.format(
"M7: pixel screen(%d,%d) parent(%d,%d) bit=0x%08X value=%d %s",
sx, sy, sx - WIN_X, sy - WIN_Y, bit, b,
b == 1 and "white" or "black"))
return b == want
end
-- (screen x, screen y, expected); parent-relative coordinates.
local p_rect = sample(128, 128, 1) -- parent (28,28): XFillRectangle
local p_img = sample(170, 162, 1) -- parent (70,62): heap XPutImage
local p_back = sample(240, 160, 1) -- parent (140,60): put back
local p_bg = sample(300, 240, 0) -- parent (200,140): CWBackPixel margin
local configure_want = 200 * 65536 + 150
local image_want = 0x13F
local atom_skip = (m[3] == 0xFFFFFFFF)
local atom_ok = (m[3] ~= 0 and m[3] ~= 0xFFFFFFFF
and m[3] ~= 0xFFFFFFFE)
local stage_ok = (atom_skip and m[9] == 14)
or (atom_ok and m[9] == 15)
local text_want_max = 64 * 16
local ok = m[0] ~= 0 and m[1] ~= 0 and m[2] ~= 0
and (atom_skip or atom_ok)
and m[4] == 1 and m[5] == configure_want and m[6] ~= 0
and m[7] == image_want and m[8] == 0 and stage_ok
and m[10] == 1 and m[11] == 2
and m[12] > 0 and m[12] < text_want_max
and m[13] ~= 0 and m[14] == 0xA00078
and p_rect and p_img and p_back and p_bg
print(string.format(
"M7: text band child(0,126) 64x16 set_pixels=%d (%s); "
.. "gcchange=%d (source call sites; runtime entry not proven); "
.. "attrs_called=%d; property_called=%d (call site ran, no "
.. "server read-back)",
m[12], (m[12] > 0 and m[12] < text_want_max) and "ok" or "BAD",
m[11], m[10], m[4]))
if atom_skip then
print("M7: internatom=SKIP (ROM _XSend scatter path blocks; "
.. "WM_NAME written with predefined atom 39; the display "
.. "marker only proves the connection was live before the "
.. "call; the isolated probe is narrative entry evidence)")
elseif atom_ok then
print(string.format("M7: internatom=0x%X", m[3]))
end
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X; pixels rect=%s image=%s putback=%s margin=%s)",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14],
tostring(p_rect), tostring(p_img), tostring(p_back),
tostring(p_bg)))
end
end
end, "xmore-check")
+25
View File
@@ -0,0 +1,25 @@
; xmore-entry.asm -- M7.3 wider-Xlib client entry, linked at bit 018A0000.
;
; Installs the TI all-stack ABI fields and the 4 KiB stack, then calls the
; compiled xmore() client. Markers (0x20 bits apart):
; 018A8000 parent nonzero
; 018A8020 child nonzero
; 018A8040 gc nonzero
; 018A8060 atom WM_NAME atom, or 0xFFFFFFFF documented skip
; 018A8080 property post-call flag, 1 (no server read-back)
; 018A80A0 configure (width << 16) | height (client-computed; move pixel-proven)
; 018A80C0 font XLoadFont("fixed") handle
; 018A80E0 image (pixel << 8) | round-trip flags
; 018A8100 errors 0
; 018A8120 stage last completed step (14 skip, 15 atom returned)
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _xmore
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+456
View File
@@ -0,0 +1,456 @@
/*
* xmore.c -- the M7.3 wider VT1200 Xlib surface client.
*
* The client opens the ROM X display, builds one parent window and one child
* window, maps the children with XMapSubwindows, moves/resizes the child with
* the ROM's fixed-mask XConfigureWindow builder, writes the parent's WM_NAME
* property (XChangeProperty), changes the child's background with
* XChangeWindowAttributes, changes the GC foreground with XChangeGC, loads a
* font and draws text (XLoadFont + XDrawString) and a rectangle, and performs
* a heap image round trip: XCreateImage with malloc'd bytes, XPutImage,
* XGetImage of the same region, a second XPutImage of the returned image, then
* XDestroyImage on both. XInternAtom("WM_NAME") is the last surface call.
*
* The child is created with background 1 (white) and then given
* CWBackPixel=0 (black); the 160x120 black fill leaves a right/bottom margin
* that only the window attribute can make black. The text is drawn on that
* margin and its pixels are counted from an XGetImage band.
*
* Markers live at 0x018A8000 + n*0x20 (bit addresses):
* 0 parent Window id (nonzero)
* 1 child Window id (nonzero; the XMapSubwindows child)
* 2 gc GC pointer (nonzero)
* 3 atom XInternAtom("WM_NAME") result:
* nonzero the call returned the atom
* 0xFFFFFFFF the call was attempted but blocked; the
* surface is kept and the skip is explicit
* 0xFFFFFFFE the call returned None
* 4 property 1 after the XChangeProperty call site ran (no server
* read-back; the zero X-error count is the only runtime
* check)
* 5 configure client-computed (child width << 16) | child height; the
* move is pixel-proven, the size is not read back
* 6 font XLoadFont("fixed") handle (nonzero; the GC uses the
* server default font, see the CreateGC note below)
* 7 image (get_pixel << 8) | flags:
* 0x01 XCreateImage, 0x02 XGetImage returned an image,
* 0x04 the XGetImage pixel word was all white,
* 0x08 XPutImage of the returned image,
* 0x10 XDestroyImage both images,
* 0x20 XGetImage was usable (not skipped)
* all six flags plus a white pixel is 0x13F
* 8 errors X protocol error count (0)
* 9 stage last completed step (14 = XInternAtom attempted after
* everything else; 15 = it returned and the property was
* rewritten with that atom)
* 10 attrs 1 after the XChangeWindowAttributes call site ran; the
* real proof is the black CWBackPixel margin sampled by the
* gate (the ROM builder does not set A8)
* 11 gcchange count of XChangeGC source call sites (2). The ROM entry is
* the 2-arg GC-cache flush; this counts the calls in source,
* not their runtime entry.
* 12 text set pixels counted in the XDrawString band (64x16 at
* child 0,126) after XGetImage; must be > 0 and below the
* band size
* 13 display Display pointer stored just before XInternAtom; proves the
* connection was live at the pre-call marker, not that the
* call was entered
* 14 fill (FILL_W << 16) | FILL_H, so the hard-coded margin sample
* cannot silently become vacuous if the fill changes
*
* The image marker distinguishes a usable XGetImage (0x13F) from a failed or
* skipped one; a failed call clears IMG_USABLE and the gate names it.
*
* XInternAtom is deliberately last. The ROM's _XSend (0x3F9B44C0) is the
* scatter/service-write path used for InternAtom's name bytes (and for
* XPutImage's direct-send path); the M4 xshow client already records that
* this path does not make progress in the loader harness. The call is kept in
* the surface, and marker 3 records the documented skip instead of dropping
* it. The WM_NAME property is therefore written first with the predefined
* X11R4 atom XA_WM_NAME (39), which the server knows without an InternAtom.
* If XInternAtom does return (the real unit), the client rewrites the property
* with the returned atom and advances to stage 15.
*
* Two ROM/Xlib details matter:
* - XChangeProperty copies the value bytes with the ROM blitter entry
* blit_copy (0x3FB44400), just as _XPutImage does. A loader child starts
* with a zeroed blitter context, so prime it once before the property.
* - The ROM XChangeGC entry is (display, gc): it serializes the GC value
* cache that XSetForeground/XSetFont marked dirty. The drawing
* primitives call the same serializer, but the explicit call is what the
* gate exercises.
*/
#include "x11m4.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
#define PARENT_X 100
#define PARENT_Y 100
#define PARENT_W 400
#define PARENT_H 300
/* Created at (40,40) 240x160, then configured to (20,20) 200x150. */
#define CHILD_X 20
#define CHILD_Y 20
#define CHILD_W 200
#define CHILD_H 150
#define IMG_W 64
#define IMG_H 64
#define IMG_BPL (IMG_W / 8)
/* The black fill leaves a margin so the CWBackPixel background is visible. */
#define FILL_W 160
#define FILL_H 120
/* XDrawString("xmore") at baseline (4,140), on the black bottom margin. */
#define TEXT_X 4
#define TEXT_Y 140
#define TEXT_LEN 5
#define TEXT_BAND_X 0
#define TEXT_BAND_Y 126
#define TEXT_BAND_W 64
#define TEXT_BAND_H 16
#define XA_STRING 31
#define XA_WM_NAME 39
#define PropModeReplace 0
#define INTERNATOM_SKIPPED 0xFFFFFFFFu
#define INTERNATOM_NONE 0xFFFFFFFEu
/*
* The wider-surface ABI, pinned here so a header edit cannot silently change
* the offsets the ROM request builders read (X11R4 32-bit structs: 4-byte
* fields). XWindowChanges.width=8; XSetWindowAttributes.background_pixel=4
* (CWBackPixel); XGCValues.font=60 (GCFont; the ROM walker reads byte 60).
*/
_Static_assert(__builtin_offsetof(XWindowChanges, width) == 8,
"XWindowChanges.width must be at byte 8");
_Static_assert(__builtin_offsetof(XSetWindowAttributes, background_pixel) == 4,
"XSetWindowAttributes.background_pixel must be at byte 4");
_Static_assert(__builtin_offsetof(XGCValues, font) == 60,
"XGCValues.font must be at byte 60");
#define IMG_CREATED 0x01
#define IMG_GOT 0x02
#define IMG_PIXEL 0x04
#define IMG_PUT 0x08
#define IMG_DESTROYED 0x10
#define IMG_USABLE 0x20
/* The ROM allocator (symbols/vt1200-v22.syms: malloc/free). */
extern void *malloc(unsigned int size);
extern void free(void *p);
static int xerrors;
/* The two explicit XChangeGC call sites (marker 11). */
static unsigned int gc_changes;
static int on_error(Display *d, XErrorEvent *e) {
(void)d;
(void)e;
xerrors++;
return 0;
}
/* The ROM sleep through a function pointer, as the M4 client does. */
static int (*volatile vt_sleep)(int) = sleep;
/* XImage.data is heap memory here, so the ROM destructor may free it. */
static XImage *heap_image;
/*
* The blitter is process-global and starts zeroed in a loader child. Prime
* it with a four-byte self-copy before XChangeProperty's value copy.
*/
static void prime_blitter(void) {
static unsigned int word;
blit_copy(&word, &word, 4);
}
static void clear_black(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 0);
XChangeGC(d, gc);
gc_changes++;
/* Leave the child's right/bottom margin to the CWBackPixel background. */
XFillRectangle(d, w, gc, 0, 0, FILL_W, FILL_H);
}
static void draw_white(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 1);
XChangeGC(d, gc);
gc_changes++;
/* The drawing call and the text call, both after the GC change. The
* text sits on the black CWBackPixel margin so its pixels are countable. */
XFillRectangle(d, w, gc, 0, 0, 32, 32);
XDrawString(d, w, gc, TEXT_X, TEXT_Y, "xmore", TEXT_LEN);
}
/*
* Prove XDrawString with pixels: XGetImage the text band and count set bits.
* The band is black CWBackPixel background; white glyphs make the count
* nonzero. A solid white count (>= the band size) would mean the band was not
* contrasting, so the gate also requires it below the band size.
*/
static void text_pixels(Display *d, Window w) {
XImage *im = XGetImage(d, w, TEXT_BAND_X, TEXT_BAND_Y, TEXT_BAND_W,
TEXT_BAND_H, ~0L, XYPixmap);
unsigned int count = 0;
int y, x;
if (!im) {
MARK(12) = 0;
return;
}
if (im->data) {
for (y = 0; y < TEXT_BAND_H; y++) {
unsigned int *row = (unsigned int *)(void *)(im->data +
y * im->bytes_per_line);
for (x = 0; x < (TEXT_BAND_W / 8) / 4; x++) {
unsigned int v = row[x];
while (v) {
count += v & 1u;
v >>= 1;
}
}
}
}
MARK(12) = count;
XDestroyImage(im);
}
static void image_roundtrip(Display *d, Window w, GC gc) {
char *bytes;
XImage *got;
unsigned int flags = 0;
unsigned int pixel = 0;
int i;
int destroyed = 0;
bytes = (char *)malloc(IMG_BPL * IMG_H);
if (bytes) {
unsigned int *words = (unsigned int *)bytes;
for (i = 0; i < (IMG_BPL * IMG_H) / 4; i++)
words[i] = 0xFFFFFFFFu;
}
heap_image = XCreateImage(d, 0, 1, XYBitmap, 0, bytes, IMG_W, IMG_H, 32,
IMG_BPL);
if (!heap_image) {
if (bytes)
free(bytes);
MARK(7) = 0;
return;
}
flags |= IMG_CREATED;
heap_image->byte_order = LSBFirst;
heap_image->bitmap_bit_order = LSBFirst;
/* A 32-bit-aligned destination x (screen 100+20+40 = 160) is required by
* the server's 1-bit bitmap copy path, as the M4 xshow client found. */
if (XPutImage(d, w, gc, heap_image, 0, 0, 40, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
XSync(d, 0);
got = XGetImage(d, w, 40, 32, IMG_W, IMG_H, ~0L, XYPixmap);
if (!got) {
/* The call ran and failed. Destroy our half of the surface and leave
* the caller's stage at 12 (the text-pixel step), so the check names
* XGetImage. */
if (XDestroyImage(heap_image))
flags |= IMG_DESTROYED;
heap_image = 0;
MARK(7) = flags;
return;
}
flags |= IMG_GOT | IMG_USABLE;
/* The region is all white: the first 32 bits of row 0 are all ones. */
if (got->data && *(unsigned int *)(void *)got->data == 0xFFFFFFFFu) {
flags |= IMG_PIXEL;
pixel = 1;
}
/* Put the returned heap image back at child x=104 (screen 224). */
if (XPutImage(d, w, gc, got, 0, 0, 104, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
if (XDestroyImage(got))
destroyed++;
if (XDestroyImage(heap_image))
destroyed++;
heap_image = 0;
if (destroyed == 2)
flags |= IMG_DESTROYED;
MARK(7) = (pixel << 8) | flags;
}
int xmore(void) {
Display *d;
Window root;
Window parent;
Window child;
GC gc;
Font font;
XSetWindowAttributes attrs = {0};
XWindowChanges wc;
int tries;
int i;
for (i = 0; i <= 14; i++)
MARK(i) = 0;
if (!vt_install_xg())
return -1;
d = 0;
for (tries = 0; tries < 40; tries++) {
d = XOpenDisplay("0::0");
if (d)
break;
vt_sleep(50);
}
if (!d)
return -1;
MARK(9) = 1;
XSetErrorHandler(on_error);
prime_blitter();
root = vt_root(d);
parent = XCreateSimpleWindow(d, root, PARENT_X, PARENT_Y, PARENT_W,
PARENT_H, 0, 0, 0);
MARK(0) = (unsigned)parent;
/* Background 1 (white) at creation: CWBackPixel must make it black. */
child = XCreateSimpleWindow(d, parent, 40, 40, 240, 160, 0, 0, 1);
MARK(1) = (unsigned)child;
MARK(9) = 2;
/* opcode 9: map both the parent's children (the child above). */
XMapSubwindows(d, parent);
MARK(9) = 3;
/*
* opcode 12 with the ROM's fixed CWX|CWY|CWWidth|CWHeight mask. The
* XWindowChanges record holds the same four values; the X11R4 client
* API's mask is implied by the entry.
*/
wc.x = CHILD_X;
wc.y = CHILD_Y;
wc.width = CHILD_W;
wc.height = CHILD_H;
wc.border_width = 0;
wc.sibling = 0;
wc.stack_mode = 0;
XConfigureWindow(d, child, wc.x, wc.y, (unsigned int)wc.width,
(unsigned int)wc.height);
/*
* The configure marker is client-computed: it records the four values
* passed to the ROM builder. The move is pixel-proven below; the size is
* not read back from the server.
*/
MARK(5) = ((unsigned int)wc.width << 16) | (unsigned int)wc.height;
MARK(9) = 4;
/*
* The property value first goes through the predefined XA_WM_NAME atom,
* so the XChangeProperty surface is exercised even if XInternAtom cannot
* complete below. Marker 4 is a plain post-call flag: the ROM builder
* never sets A8, so there is no return value or server read-back; zero X
* errors is the only runtime check.
*/
XChangeProperty(d, parent, XA_WM_NAME, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 5;
/* The struct was zero-initialized at its declaration; only
* CWBackPixel's byte 4 is selected here. */
attrs.background_pixel = 0;
XChangeWindowAttributes(d, child, CWBackPixel, &attrs);
/* Post-call flag only; the black margin is the real attribute proof. */
MARK(10) = 1;
MARK(9) = 6;
/*
* Map the top-level parent after the child is mapped, then let the WM
* frame it before drawing: an X11 map fills the background and would
* erase anything drawn while the window is still unmapped.
*/
XMapWindow(d, parent);
XSync(d, 0);
vt_sleep(300);
MARK(9) = 7;
font = XLoadFont(d, "fixed");
MARK(6) = (unsigned)font;
MARK(9) = 8;
/*
* The GC uses the server's default font. XLoadFont is still exercised
* above (marker 6); its returned value is a ROM font handle, not the
* server font XID, so passing it as GCFont makes CreateGC fail BadFont.
* The default GC font is the 6x13 cell the termtris client documents.
*/
gc = XCreateGC(d, child, 0, 0);
MARK(2) = (unsigned)gc;
MARK(9) = 9;
clear_black(d, child, gc);
MARK(9) = 10;
draw_white(d, child, gc);
MARK(9) = 11;
/* XGetImage the text band and count its white pixels (marker 12). */
text_pixels(d, child);
MARK(9) = 12;
image_roundtrip(d, child, gc);
/* Only a usable XGetImage advances the image stage. */
if ((MARK(7) & IMG_USABLE) != 0) {
XSync(d, 0);
MARK(8) = (unsigned)xerrors;
MARK(9) = 13;
} else {
MARK(8) = (unsigned)xerrors;
}
/*
* Last: the InternAtom surface. The skip marker and the live Display
* pointer are written before the call so a blocked _XSend still leaves
* the documented state behind. The marker proves only that the
* connection was live before the call; entry into the ROM function is
* not proven by it (the report's isolated probe is narrative evidence).
*/
MARK(13) = (unsigned)d;
MARK(11) = gc_changes;
MARK(14) = ((unsigned)FILL_W << 16) | (unsigned)FILL_H;
MARK(3) = INTERNATOM_SKIPPED;
MARK(9) = 14;
{
Atom a = XInternAtom(d, "WM_NAME", False);
if (a) {
MARK(3) = (unsigned)a;
XChangeProperty(d, parent, a, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 15;
} else {
MARK(3) = INTERNATOM_NONE;
}
}
/*
* Do not return: returning tears the process (and its windows) down before
* the harness reads the markers and VRAM. Keep the connection drained and
* hold the last completed stage so a failed call stays visible.
*/
for (;;) {
MARK(8) = (unsigned)xerrors;
MARK(11) = gc_changes;
XFlush(d);
vt_sleep(5);
}
}
+20
View File
@@ -0,0 +1,20 @@
int debug_a_base = 3;
int debug_a_mul(void) {
int product = debug_a_base * 7;
return product + 1;
}
int debug_a_add(void) {
int sum = debug_a_base + 4;
return sum * 2;
}
/* M8.2 multi-TU debug gate, first translation unit.
*
* Two functions with distinct source lines; debug_a_mul returns 22 and
* debug_a_add returns 14. debug-b.c is the second debug-bearing TU, and
* debug-entry.asm calls all four functions so the linked image exercises both
* units at runtime. The comment is after the code so the line numbers used by
* dwarf-multi.sh stay stable.
*/
+19
View File
@@ -0,0 +1,19 @@
int debug_b_base = 5;
int debug_b_sub(void) {
int diff = debug_b_base - 2;
return diff * 3;
}
int debug_b_mul(void) {
int factor = debug_b_base + 1;
return factor * factor;
}
/* M8.2 multi-TU debug gate, second translation unit.
*
* debug_b_sub returns 9 and debug_b_mul returns 36. The TU's `.text` is
* concatenated after debug-a.c's, so its functions and DWARF addresses are at
* nonzero text offsets; dwarf-multi.sh asserts the rehomed CU/section bases
* and the linked low PCs.
*/
+31
View File
@@ -0,0 +1,31 @@
; debug-entry.asm -- M8.2 multi-TU debug gate entry, linked at bit 018A0000.
;
; debug-a.o is linked first and debug-b.o second, so debug_a_mul is the text
; origin function (DWARF low PC 0x314000), debug-b's functions are at nonzero
; text offsets, and _start follows both TUs. The entry calls all four
; functions and stores their results (22, 14, 9, 36) at 018A8000, 018A8020,
; 018A8040 and 018A8060; debug-multi-check.lua reads them after the stripped
; image loads.
.ref _debug_a_mul
.ref _debug_a_add
.ref _debug_b_sub
.ref _debug_b_mul
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _debug_a_mul
move a8,@018A8000h,1
calla _debug_a_add
move a8,@018A8020h,1
calla _debug_b_sub
move a8,@018A8040h,1
calla _debug_b_mul
move a8,@018A8060h,1
rets
.bss _cstack,32768,16
.end
+19
View File
@@ -0,0 +1,19 @@
dofile(os.getenv("M4_LOADER_LUA"))
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local a_mul = prog:read_u32(0x018A8000)
local a_add = prog:read_u32(0x018A8020)
local b_sub = prog:read_u32(0x018A8040)
local b_mul = prog:read_u32(0x018A8060)
print(string.format("DEBUG MULTI: a_mul=%d a_add=%d b_sub=%d b_mul=%d",
a_mul, a_add, b_sub, b_mul))
if a_mul == 22 and a_add == 14 and b_sub == 9 and b_mul == 36 then
print("DEBUG MULTI MAME: PASS")
else
print("DEBUG MULTI MAME: FAIL (want 22/14/9/36)")
end
end
end, "debug-multi-check")
+34
View File
@@ -0,0 +1,34 @@
-- lib-check.lua -- read the M8 native-library gate marker words.
--
-- The driver writes five words at 018A8000 + n*0x20:
-- 0: (int)(1.5 + 2.5) == 4 (flib FD$ADD + FD$DTOI)
-- 1: (int)(1.5 * 2.5) == 3 (flib FD$MUL + FD$DTOI)
-- 2: isascii('A') != 0 (rts.lib _isascii)
-- 3: isascii(0xC8) == 0 (rts.lib _isascii)
-- 4: 0x4C494231 ("LIB1" sentinel)
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local frames = 0
local checked = false
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
for i = 0, 4 do
got[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format("M8 LIB: sum=%d product=%d asciiA=%d asciiC8=%d sentinel=%08X",
got[0], got[1], got[2], got[3], got[4]))
if got[0] == 4 and got[1] == 3 and got[2] ~= 0 and
got[3] == 0 and got[4] == 0x4C494231 then
print("M8 LIB MAME: PASS")
else
print("M8 LIB MAME: FAIL (want 4 3 nonzero 0 4C494231)")
end
end
end, "m8-lib-check")
+16
View File
@@ -0,0 +1,16 @@
; lib-entry.asm -- M8 native-library gate entry, linked at bit 018A0000.
;
; Calls the compiled driver libcheck_test(), which uses flib.lib doubles and
; rts.lib _isascii. Marker words live at 018A8000 + n*0x20 and are checked by
; lib-check.lua.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _libcheck_test
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+26
View File
@@ -0,0 +1,26 @@
/* M8 native-library gate driver.
*
* The double operations lower to flib.lib's FD$ADD/FD$MUL and the fptosi
* conversions to FD$DTOI; isascii is the rts.lib member. The markers are
* fixed bit addresses in the prog region because the linker map's symbol
* values are not needed by this tiny check.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
extern int isascii(int);
static volatile double fa = 1.5;
static volatile double fb = 2.5;
int libcheck_test(void)
{
double sum = fa + fb;
double product = fa * fb;
MARK(0) = (unsigned)(int)sum; /* 4: FD$ADD + FD$DTOI */
MARK(1) = (unsigned)(int)product; /* 3: FD$MUL + FD$DTOI */
MARK(2) = (unsigned)isascii('A'); /* 1: rts.lib _isascii */
MARK(3) = (unsigned)isascii(0xC8); /* 0: rts.lib _isascii */
MARK(4) = 0x4C494231u; /* "LIB1" sentinel */
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# os2-toolchain.sh -- run the 1990 TI r5.01 OS/2 tools under 2ine/qemu-i386.
#
# Sourced by scripts/m4/run.sh when M4_OS2=1. The 1990 tools are 16-bit OS/2
# 1.x NE programs; the patched 2ine loader runs them on a 64-bit Linux host
# via qemu-i386 (the plain lx_loader needs a kernel with 16-bit LDT support).
#
# Environment:
# M4_OS2=1 enable this path
# M4_OS2_2INE=PATH 2ine checkout (default /home/arti/os2-work/2ine-tms34010)
# M4_OS2_LX=PATH lx_loader (default $2ine/build/lx_loader; the
# build-qemu wrapper is the fallback)
# M4_OS2_SDK=PATH extracted r5.01 tree with bin/ and lib/
# M4_OS2_ROOT=PATH parent of the default 2ine/os2-501 (default /home/arti/os2-work)
#
# The functions expect run.sh globals: WORK, SDK, fail, NATIVE_OBJS,
# NATIVE_LIBS. Outputs are copied back with the uppercase names run.sh uses.
os2_init() {
OS2_2INE=${M4_OS2_2INE:-${M4_OS2_ROOT:-/home/arti/os2-work}/2ine-tms34010}
OS2_LX=${M4_OS2_LX:-$OS2_2INE/build/lx_loader}
if [ ! -x "$OS2_LX" ] && [ -x "$OS2_2INE/build-qemu/lx_loader" ]; then
OS2_LX=$OS2_2INE/build-qemu/lx_loader
fi
OS2_SDK=${M4_OS2_SDK:-${M4_OS2_ROOT:-/home/arti/os2-work}/os2-501}
[ -x "$OS2_LX" ] || fail "M4_OS2=1: missing 2ine lx_loader: $OS2_LX (run scripts/m8/setup-os2.sh)"
[ -f "$OS2_SDK/bin/gspa.exe" ] \
|| fail "M4_OS2=1: missing OS/2 gspa.exe under $OS2_SDK/bin (run scripts/m8/setup-os2.sh)"
case $OS2_LX in
*/build-qemu/*)
command -v qemu-i386 >/dev/null 2>&1 \
|| fail "M4_OS2=1: qemu-i386 is required for the build-qemu wrapper" ;;
esac
OS2_QEMU=$OS2_2INE/build-qemu/lx_loader
OS2_DIR=$WORK/os2
rm -rf "$OS2_DIR"
mkdir -p "$OS2_DIR"
# 2ine loads its OS/2 import modules from the working directory.
for so in "$OS2_2INE"/build/lib*.so; do
[ -e "$so" ] && ln -sf "$so" "$OS2_DIR/"
done
cp "$OS2_SDK/bin/gspa.exe" "$OS2_DIR/"
cp "$OS2_SDK/bin/gsplnk.exe" "$OS2_DIR/"
cp "$OS2_SDK/lib/rts.lib" "$OS2_SDK/lib/flib.lib" "$OS2_DIR/" 2>/dev/null || true
}
os2_gspa() { # os2_gspa NAME (M4 or M4EXT)
_name=$1
[ -f "$SDK/$_name.ASM" ] || fail "M4_OS2: missing $SDK/$_name.ASM"
cp "$SDK/$_name.ASM" "$OS2_DIR/$_name.ASM"
_gspa() { # _gspa LX
( cd "$OS2_DIR" && \
"$1" ./gspa.exe "$_name.ASM" "$_name.obj" "$_name.lst" -l \
) > "$OS2_DIR/$_name.gspa.log" 2>&1 || true
}
rm -f "$OS2_DIR/$_name.lst" "$OS2_DIR/$_name.obj"
_gspa "$OS2_LX"
if ! grep -q 'No Errors' "$OS2_DIR/$_name.lst" 2>/dev/null; then
# The direct 2ine loader can hit its segment assertion on some large
# inputs; qemu-i386 is the reliable fallback.
if [ -x "$OS2_QEMU" ] && [ "$OS2_LX" != "$OS2_QEMU" ]; then
echo " note: direct 2ine gspa failed; retrying under qemu" >&2
_gspa "$OS2_QEMU"
fi
fi
grep -q 'No Errors' "$OS2_DIR/$_name.lst" 2>/dev/null || {
cat "$OS2_DIR/$_name.gspa.log" >&2
fail "OS/2 gspa failed for $_name"
}
cp "$OS2_DIR/$_name.obj" "$SDK/$_name.OBJ"
cp "$OS2_DIR/$_name.lst" "$SDK/$_name.LST"
}
os2_gsplnk() {
# Copy every object the linker command may reference, plus the lowercase
# library names the 5.01 command file uses.
for obj in "$SDK"/*.OBJ "$SDK"/*.obj; do
[ -e "$obj" ] && cp "$obj" "$OS2_DIR/"
done
# Copy every library the command file may reference; the 1987/1990 files
# are uppercase on disk while the linker command uses lowercase names.
for lib in "$SDK"/*.LIB "$SDK"/*.lib; do
[ -e "$lib" ] || continue
_low=$(basename "$lib" | tr '[:upper:]' '[:lower:]')
cp "$lib" "$OS2_DIR/$_low"
done
cp "$SDK/M4.CMD" "$OS2_DIR/M4.CMD"
rm -f "$OS2_DIR/M4.OUT" "$OS2_DIR/M4.MAP"
_gsplnk() {
( cd "$OS2_DIR" && "$1" ./gsplnk.exe M4.CMD ) \
> "$OS2_DIR/M4.gsplnk.log" 2>&1 || true
}
_gsplnk "$OS2_LX"
if [ ! -f "$OS2_DIR/M4.OUT" ] && [ -x "$OS2_QEMU" ] \
&& [ "$OS2_LX" != "$OS2_QEMU" ]; then
echo " note: direct 2ine gsplnk failed; retrying under qemu" >&2
_gsplnk "$OS2_QEMU"
fi
[ -f "$OS2_DIR/M4.OUT" ] || {
cat "$OS2_DIR/M4.gsplnk.log" >&2
fail "OS/2 gsplnk failed"
}
cp "$OS2_DIR/M4.OUT" "$SDK/M4.OUT"
cp "$OS2_DIR/M4.MAP" "$SDK/M4.MAP"
}
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# setup-os2.sh -- provision the 1990 TI r5.01 OS/2 toolchain for the harness.
#
# The r5.01 tools are 16-bit OS/2 1.x NE console programs. They run on a
# 64-bit Linux host through the patched 2ine loader under qemu-i386 (the plain
# lx_loader needs a kernel with 16-bit LDT support; qemu-i386 provides it).
#
# scripts/m8/setup-os2.sh
#
# Environment:
# M4_OS2_ROOT install root (default $HOME/os2-work)
# M4_OS2_2INE 2ine checkout (default $M4_OS2_ROOT/2ine-tms34010)
# M4_OS2_SDK extracted r5.01 tree (default $M4_OS2_ROOT/os2-501)
#
# Then run gates with M4_OS2=1 (and optionally M4_LINKER=tms-link). The
# default harness remains the 1987 DOSBox GSPA/GSPLNK oracle.
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OS2_ROOT=${M4_OS2_ROOT:-$HOME/os2-work}
TWOINE=${M4_OS2_2INE:-$OS2_ROOT/2ine-tms34010}
SDK=${M4_OS2_SDK:-$OS2_ROOT/os2-501}
SDK_SRC="$ROOT/vendor/vt1200/tools/tms34010-sdk/1990-11 TMS340 Family SDK"
fail() { echo "setup-os2: FAIL: $*" >&2; exit 1; }
command -v git >/dev/null 2>&1 || fail "git is required"
command -v cmake >/dev/null 2>&1 || fail "cmake is required"
command -v unzip >/dev/null 2>&1 || fail "unzip is required"
# The direct loader is preferred; qemu-i386 is only needed as a fallback on
# kernels without 16-bit LDT support.
if [ ! -x "$TWOINE/build/lx_loader" ]; then
echo "== clone and build 2ine-tms34010 into $TWOINE"
mkdir -p "$(dirname "$TWOINE")"
[ -d "$TWOINE/.git" ] || \
git clone https://git.wut.ee/opencode.energia.arti.ee/2ine-tms34010.git "$TWOINE"
cmake -S "$TWOINE" -B "$TWOINE/build" -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_POLICY_VERSION_MINIMUM=3.5
cmake --build "$TWOINE/build" -j"${JOBS:-$(nproc)}"
fi
LX=${M4_OS2_LX:-$TWOINE/build/lx_loader}
if [ ! -x "$LX" ]; then
# Kernel fallback: wrap the loader in qemu-i386 (which provides 16-bit LDT
# support even when CONFIG_X86_16BIT is off).
command -v qemu-i386 >/dev/null 2>&1 \
|| fail "lx_loader is missing and qemu-i386 is unavailable"
mkdir -p "$TWOINE/build-qemu"
cat > "$TWOINE/build-qemu/lx_loader" <<EOF
#!/bin/sh
exec qemu-i386 "$TWOINE/build/lx_loader" "\$@"
EOF
chmod +x "$TWOINE/build-qemu/lx_loader"
LX=$TWOINE/build-qemu/lx_loader
fi
if [ ! -f "$SDK/bin/gspa.exe" ]; then
echo "== extract the r5.01 tools into $SDK"
[ -f "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip" ] \
|| fail "missing the r5.01 tools zip under $SDK_SRC"
mkdir -p "$SDK/bin" "$SDK/lib" "$SDK/work"
unzip -oq "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip" -d "$SDK/bin"
unzip -oq "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (2 of 2) r5.01 rev2564062-1641.zip" -d "$SDK/lib"
fi
[ -f "$SDK/bin/gspa.exe" ] || fail "gspa.exe missing after extraction"
[ -x "$LX" ] || fail "lx_loader missing: $LX"
# Smoke test: assemble an empty source in a throw-away work dir.
TMP=$(mktemp -d "$OS2_ROOT/os2-smoke.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
for so in "$TWOINE"/build/lib*.so; do [ -e "$so" ] && ln -sf "$so" "$TMP/"; done
cp "$SDK/bin/gspa.exe" "$TMP/"
: > "$TMP/t.asm"
( cd "$TMP" && "$LX" ./gspa.exe t.asm > gspa.log 2>&1 ) || true
if ! grep -q 'No Errors' "$TMP/gspa.log"; then
# Retry through qemu if the direct loader cannot allocate 16-bit LDTs.
if [ "$LX" = "$TWOINE/build/lx_loader" ] && command -v qemu-i386 >/dev/null 2>&1; then
mkdir -p "$TWOINE/build-qemu"
cat > "$TWOINE/build-qemu/lx_loader" <<EOF
#!/bin/sh
exec qemu-i386 "$TWOINE/build/lx_loader" "\$@"
EOF
chmod +x "$TWOINE/build-qemu/lx_loader"
LX=$TWOINE/build-qemu/lx_loader
( cd "$TMP" && "$LX" ./gspa.exe t.asm > gspa.log 2>&1 ) || true
fi
grep -q 'No Errors' "$TMP/gspa.log" \
|| { cat "$TMP/gspa.log" >&2; fail "gspa smoke test failed"; }
fi
cat <<EOF
OS/2 r5.01 toolchain ready:
M4_OS2_ROOT=$OS2_ROOT
M4_OS2_2INE=$TWOINE
M4_OS2_LX=$LX
M4_OS2_SDK=$SDK
Use it with:
M4_OS2=1 scripts/tests/m7/full-suite.sh --corpus all --work build/m8-os2-full
M4_OS2=1 M4_LINKER=tms-link scripts/tests/m5/c-torture.sh
M4_OS2=1 scripts/m4/run.sh # asm path: OS/2 gspa + OS/2 gsplnk
The default harness still uses the 1987 DOSBox GSPA/GSPLNK oracle.
EOF
+6
View File
@@ -3,3 +3,9 @@ int int_diff4(int *p) { return (int)(p + 1) - (int)p; }
long pd_char(char *a, char *b) { return a - b; }
long pd_int(int *a, int *b) { return a - b; }
int late(char *p, char *q) { return (char *)((unsigned)p + 24) == q; }
int late64(char *p, char *q) {
return (char *)((unsigned long long)(unsigned)p + 24) == q;
}
int late64s(char *p, char *q) {
return (char *)((long long)(int)p + 24) == q;
}
+35 -3
View File
@@ -13,14 +13,46 @@ grep -A2 'define.*@int_diff(' "$OUT/pdiff.ll" | grep -q 'ret i32 8'
grep -A2 'define.*@int_diff4' "$OUT/pdiff.ll" | grep -q 'ret i32 32'
grep -A6 'define.*@pd_char' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -A6 'define.*@pd_int' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -Eq 'add i32 %bit.base[0-9]*, 24' "$OUT/pdiff.ll"
# The final instcombine canonicalizes the lowered `inttoptr(add(ptrtoint, 24))`
# into `getelementptr i8, %p, 24`; llc treats a GEP index as a bit offset, so
# either shape carries the M0 24-bit addend. Scope the positive to `late`
# itself (the identical `late64` line must not satisfy it); keep the 192
# rejection file-wide.
grep -A6 'define.*@late(' "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192' \
"$OUT/pdiff.ll"; then
echo "M0 pipeline: FAIL: late GEP was scaled twice (192)" >&2
exit 1
fi
# The 64-bit pointer-int shapes (`(unsigned long long)(unsigned)p + 24` and
# `(long long)(int)p + 24`) must take the same 24-bit low word, not 192.
for fn in late64 late64s; do
grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192'; then
echo "M0 pipeline: FAIL: $fn over-scaled to 192" >&2
exit 1
fi
done
"$TMS_OPT" -passes=verify -disable-output "$OUT/pdiff.ll"
"$ROOT/scripts/tms-clang" -O2 -I "$ROOT/spike" -o "$OUT/xclient.ll" "$ROOT/spike/xclient.c"
test "$(grep -c getelementptr "$OUT/xclient.ll")" -eq 0
# The M7.1 barrier is gone after lowering, and any GEP the final instcombine
# creates from a lowered inttoptr is the `i8` bit-index form. A typed GEP here
# would mean a byte offset escaped the post-opt --scale.
if grep -q '__tms_bitptr' "$OUT/xclient.ll"; then
echo "M0 pipeline: FAIL: __tms_bitptr was not lowered" >&2
exit 1
fi
if grep 'getelementptr' "$OUT/xclient.ll" | grep -qv 'getelementptr i8'; then
echo "M0 pipeline: FAIL: a typed (byte) GEP escaped the post-opt scale" >&2
exit 1
fi
grep -Eq 'add i32 %bit.base[0-9]*, 1056' "$OUT/xclient.ll"
grep -Eq 'mul i32 [^,]+, 640' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit.addr[0-9]*, 320' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit\.(base|addr)[0-9]*, 320' "$OUT/xclient.ll"
"$TMS_OPT" -passes=verify -disable-output "$OUT/xclient.ll"
"$ROOT/scripts/tms-clang" -O0 -o "$OUT/pdiff.o0.ll" "$ROOT/scripts/tests/m0/ptrdiff.c"
+5
View File
@@ -29,6 +29,11 @@
# M5_C_TESTSUITE_WORK M5_CONFORMANCE_DIR M5_CONFORMANCE_MODE
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
+2 -2
View File
@@ -171,12 +171,12 @@
00201 unselected: classifier-supported; outside the curated output subset
00202 unselected: classifier-supported; outside the curated output subset
00204 format-unsupported: printf %n, positional $, %e/%g/%a/%F, %j, long-double %L/%F and wide %ls/%lc are not implemented by the shim
00205 runtime: M2 .data supports only integer, pointer and byte-array initializers (host compile fails)
00205 unselected: curated list not re-evaluated after the M7.1 .data extension
00206 unselected: classifier-supported; outside the curated output subset
00207 unselected: classifier-supported; outside the curated output subset
00208 wide-char: wide characters are unsupported
00209 unselected: classifier-supported; outside the curated output subset
00210 unselected: classifier-supported; outside the curated output subset
00211 unselected: classifier-supported; outside the curated output subset
00216 runtime: M2 .data supports only integer, pointer and byte-array initializers (host compile fails)
00216 unselected: curated list not re-evaluated after the M7.1 .data extension
00220 wide-char: wide characters are unsupported
+5
View File
@@ -31,6 +31,11 @@
# M5_CONFORMANCE_CLANG_OPT M5_CONFORMANCE_LLC_OPT (per pass)
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
+174
View File
@@ -0,0 +1,174 @@
-- bare-check.lua -- run a freestanding conformance COFF on the VT1200 CPU
-- without booting the firmware or using the COFF loader.
--
-- The test harness maps the image itself: each section is copied to its COFF
-- paddr, .bss is zeroed, the result block is cleared, and PC/SP are set. This
-- is the fast tier for codegen/semantics tests; the full loader/X11/runtime
-- tiers still use loader.lua.
--
-- Required env: BARE_COFF, BARE_ENTRY, BARE_SP (bit addresses), CONF_RESULT.
-- Optional: BARE_END (frame budget, default 1000).
local machine = manager.machine
local cpu = machine.devices[':maincpu']
local prog = cpu.spaces['program']
local COFF = os.getenv("BARE_COFF") or ""
local ENTRY = tonumber(os.getenv("BARE_ENTRY") or "0", 16)
local SP = tonumber(os.getenv("BARE_SP") or "0", 16)
local ENDF = tonumber(os.getenv("BARE_END") or "1000")
local RESULT = os.getenv("CONF_RESULT") or "conformance-result.txt"
local STATUS = 0x01B00000
local LEN = 0x01B00020
local MAGIC = 0x01B00040
local ERRLEN = 0x01B00060
local OUT = 0x01B10000
local ERR = 0x01B30000
local CAP = 16384
local MAGIC_VAL = 0x434F4E46
local ST_IE = 0x200000
local function slurp(path)
local f = io.open(path, "rb")
if not f then error("cannot open " .. path) end
local d = f:read("*a")
f:close()
return d
end
local function u16(d, o) return string.unpack("<I2", d, o + 1) end
local function u32(d, o) return string.unpack("<I4", d, o + 1) end
local function parse_coff(d)
local c = {}
c.magic = u16(d, 0)
c.nscns = u16(d, 2)
c.opthdr = u16(d, 16)
c.entry = c.opthdr ~= 0 and u32(d, 20 + 16) or 0
c.sections = {}
local base = 20 + c.opthdr
for i = 0, c.nscns - 1 do
local o = base + i * 40
local name = d:sub(o + 1, o + 8):gsub("%z", "")
c.sections[#c.sections + 1] = {
name = name,
paddr = u32(d, o + 8),
size = u32(d, o + 16),
scnptr = u32(d, o + 20),
flags = u32(d, o + 36),
}
end
return c
end
local function poke_bytes(bitaddr, data)
local n = math.floor((#data + 1) / 2)
for i = 0, n - 1 do
local lo = data:byte(i * 2 + 1) or 0
local hi = data:byte(i * 2 + 2) or 0
prog:write_u16(bitaddr + i * 16, lo + hi * 256)
end
return n
end
local function zero_bytes(bitaddr, nbytes)
for i = 0, math.floor((nbytes + 1) / 2) - 1 do
prog:write_u16(bitaddr + i * 16, 0)
end
end
local function rd32(a)
local ok, v = pcall(function() return prog:read_u32(a) end)
if ok then return v end
return 0xDEADBEEF
end
local function rd8(a)
local ok, v = pcall(function() return prog:read_u8(a) end)
if ok then return v end
return 0
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local magic = rd32(MAGIC)
local raw_errlen = rd32(ERRLEN)
local bytes, n = {}, 0
local nread = (raw_len >= 0 and raw_len <= CAP) and raw_len or 0
for i = 0, nread - 1 do
bytes[#bytes + 1] = string.format("%02X", rd8(OUT + i * 8))
n = n + 1
end
local errbytes = {}
local erread = (raw_errlen >= 0 and raw_errlen <= CAP) and raw_errlen or 0
for i = 0, erread - 1 do
errbytes[#errbytes + 1] = string.format("%02X", rd8(ERR + i * 8))
end
print(string.format(
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s errlen=%d err=%s",
tag, status, raw_len, magic, 0, table.concat(bytes),
raw_errlen, table.concat(errbytes)))
local f = io.open(RESULT, "w")
if f then
f:write(string.format("status=%08X\n", status))
f:write(string.format("len=%d\n", raw_len))
f:write(string.format("magic=%08X\n", magic))
f:write("loader=00000000\n")
f:write("out=" .. table.concat(bytes) .. "\n")
f:write(string.format("errlen=%d\n", raw_errlen))
f:write("err=" .. table.concat(errbytes) .. "\n")
f:close()
end
if magic == MAGIC_VAL then
print("BARE MAME: PASS")
else
print("BARE MAME: FAIL")
end
end
local frames = 0
local started = false
local done = false
local function setup()
local d = slurp(COFF)
local c = parse_coff(d)
if c.magic ~= 0x0090 then
print(string.format("BARE: bad COFF magic %04X", c.magic))
machine:exit()
return
end
for _, s in ipairs(c.sections) do
if s.name == ".bss" then
zero_bytes(s.paddr, math.floor((s.size + 7) / 8))
elseif s.size > 0 then
local nb = math.floor((s.size + 7) / 8)
poke_bytes(s.paddr, d:sub(s.scnptr + 1, s.scnptr + nb))
end
end
-- Clear the result block; the entry also does it, but this is idempotent.
prog:write_u32(STATUS, 0); prog:write_u32(LEN, 0)
prog:write_u32(MAGIC, 0); prog:write_u32(ERRLEN, 0)
cpu.state['SP'].value = SP
local st = cpu.state['ST'].value
cpu.state['ST'].value = st & ~ST_IE
cpu.state['PC'].value = (ENTRY ~= 0) and ENTRY or c.entry
print(string.format("BARE: entry=%08X sp=%08X sections=%d", cpu.state['PC'].value, SP, c.nscns))
end
emu.register_frame_done(function()
frames = frames + 1
if not started then
started = true
setup()
return
end
if done then return end
if rd32(MAGIC) == MAGIC_VAL or frames >= ENDF then
done = true
dump(frames >= ENDF and "timeout" or "result")
machine:exit()
end
end, "m5-bare-check")
+9 -3
View File
@@ -40,6 +40,8 @@ pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-testsuite.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
@@ -53,15 +55,19 @@ while IFS= read -r name; do
[ -f "$src" ] || fail "missing c-testsuite source: $src"
[ -f "$expected" ] || fail "missing c-testsuite expected output: $expected"
if "$RUN" --id "c-testsuite/$base" --classify --mode native \
--expect-status 0 --expect-output-file "$expected" "$src"; then
--expect-status 0 --expect-output-file "$expected" "$src" \
> "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
if [ "$rc" -eq 2 ]; then
cat "$ONE_LOG"
# Exit 2 is a skip only with a real SKIP row (see c-torture.sh).
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-testsuite: FAIL $base" >&2
echo "c-testsuite: FAIL $base (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
+10 -3
View File
@@ -38,6 +38,8 @@ pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-torture.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
@@ -47,15 +49,20 @@ while IFS= read -r name; do
src=$SUITE_DIR/$name.c
[ -f "$src" ] || fail "missing c-torture source: $src"
if "$RUN" --id "c-torture/$name" --classify \
--expect-status 0 --ignore-output "$src"; then
--expect-status 0 --ignore-output "$src" > "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
if [ "$rc" -eq 2 ]; then
cat "$ONE_LOG"
# Exit 2 is a skip only when the runner printed a real SKIP row.
# run.sh also uses 2 for a native-COFF loader rejection; treating a
# bare 2 as a skip would turn a genuine failure into a pass-like row.
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-torture: FAIL $name" >&2
echo "c-torture: FAIL $name (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
@@ -6,11 +6,14 @@
-- 01B00000 status
-- 01B00020 out_len
-- 01B00040 magic 0x434F4E46
-- 01B10000 output bytes (bit addresses, 8 bits apart)
-- 01B00060 err_len
-- 01B10000 output bytes (bit addresses, 8 bits apart; 16 KiB ends at
-- 01B2FFFF, so it cannot reach stderr)
-- 01B30000 stderr bytes (bit addresses, 8 bits apart; 16 KiB)
--
-- The block is above the linker-managed .bss region (01A00000..01A80000), so
-- test globals cannot overwrite it. The runner rejects len >= the 16 KiB cap
-- because the shim truncates there.
-- (or errlen >= the cap) because the shim truncates there.
--
-- The result is written to CONF_RESULT in a stable, shell-readable form:
-- status=<8 hex>
@@ -18,6 +21,8 @@
-- magic=<8 hex>
-- loader=<8 hex> (loader result block status at 01882D00)
-- out=<uppercase hex bytes>
-- errlen=<decimal>
-- err=<uppercase hex bytes>
--
-- The runner compares this file against the manifest/expected result. A
-- missing magic is a failure, never a pass.
@@ -35,7 +40,9 @@ local RESULT = os.getenv("CONF_RESULT") or "conformance-result.txt"
local STATUS = 0x01B00000
local LEN = 0x01B00020
local MAGIC = 0x01B00040
local ERRLEN = 0x01B00060
local OUT = 0x01B10000
local ERR = 0x01B30000
local CAP = 16384
local MAGIC_VAL = 0x434F4E46
local LOADER_STATUS = 0x01882D00
@@ -55,38 +62,46 @@ local function rd8(a)
return 0
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
-- Read raw_len bytes at bit address `base` (8 bits apart). Keep the raw
-- length for the runner (it rejects len >= CAP), but never loop over an
-- implausible value. Returns the full hex dump and its 128-byte preview.
local function dump_bytes(base, raw_len)
local bytes = {}
local shown = {}
local n = 0
local nread = raw_len
-- Keep the raw length for the runner (it rejects len >= CAP), but never
-- loop over an implausible value.
if nread < 0 or nread > CAP then
nread = 0
end
for i = 0, nread - 1 do
local b = rd8(OUT + i * 8)
local b = rd8(base + i * 8)
bytes[#bytes + 1] = string.format("%02X", b)
if i < 128 then
shown[#shown + 1] = string.format("%02X", b)
end
n = n + 1
end
local outhex = table.concat(bytes)
local shownhex = table.concat(shown)
if n > 128 then
shownhex = shownhex .. "..."
end
return table.concat(bytes), shownhex
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local raw_errlen = rd32(ERRLEN)
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
local outhex, shownhex = dump_bytes(OUT, raw_len)
local errhex, errshownhex = dump_bytes(ERR, raw_errlen)
print(string.format(
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s",
tag, status, raw_len, magic, loader, shownhex))
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s errlen=%d err=%s",
tag, status, raw_len, magic, loader, shownhex,
raw_errlen, errshownhex))
local f, err = io.open(RESULT, "w")
if not f then
@@ -100,6 +115,8 @@ local function dump(tag)
f:write(string.format("magic=%08X\n", magic))
f:write(string.format("loader=%08X\n", loader))
f:write("out=" .. outhex .. "\n")
f:write(string.format("errlen=%d\n", raw_errlen))
f:write("err=" .. errhex .. "\n")
f:close()
if magic == MAGIC_VAL and loader == 0 then
+5 -1
View File
@@ -6,7 +6,9 @@
; 01B00000 status main's return value
; 01B00020 out_len maintained by shim.c
; 01B00040 magic 0x434F4E46 after main returns
; 01B10000 output shim.c's 16 KiB output buffer
; 01B00060 err_len maintained by shim.c
; 01B10000 output shim.c's 16 KiB output buffer (ends at 01B2FFFF)
; 01B30000 error shim.c's 16 KiB stderr buffer
;
; The result block is above the linker-managed RAM region
; (01A00000..01A80000), so a test's .bss cannot overwrite it. That region is
@@ -30,6 +32,8 @@ _start:
move a0, *a1, 1
movi 01B00040h, a1
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
+57
View File
@@ -0,0 +1,57 @@
/*
* heap.c -- optional bounded allocator for the conformance shim.
*
* This object is linked only for tests whose source references
* malloc/calloc/free, so adding the allocator does not shift the hot shim
* code that the shipped 300/600-frame gates time. The arena is the 64 KiB gap
* between the linker RAM region (01A00000..01A80000) and the result block
* (01B00000); it lies outside every loaded section. free() is a no-op because
* each conformance test is a single short-lived process.
*/
#include <stddef.h>
#define CONF_HEAP_START 0x01A80000UL
#define CONF_HEAP_END 0x01B00000UL
static unsigned int heap_next;
/* Sizes are bytes; the target's pointers are bit addresses, so advance the
* cursor by 8 bits per byte. Align to a 16-bit word. */
void *malloc(size_t n)
{
unsigned int p;
n = (n + 1) & ~(size_t)1;
if (n == 0)
n = 2;
if (heap_next == 0)
heap_next = CONF_HEAP_START;
if (n > (CONF_HEAP_END - heap_next) / 8)
return 0;
p = heap_next;
heap_next += n * 8;
return (void *)p;
}
void *calloc(size_t nmemb, size_t size)
{
size_t total;
char *p;
size_t i;
if (nmemb != 0 && size > (size_t)~0 / nmemb)
return 0;
total = nmemb * size;
p = (char *)malloc(total);
if (!p)
return 0;
for (i = 0; i < total; i++)
p[i] = 0;
return p;
}
void free(void *ptr)
{
(void)ptr;
}
@@ -0,0 +1,14 @@
#ifndef CONFORMANCE_ASSERT_H
#define CONFORMANCE_ASSERT_H
/* The freestanding conformance runtime has no libc assert; abort() publishes
* the terminal status, so a failed assertion is an honest nonzero result. */
void abort(void);
#ifdef NDEBUG
#define assert(expr) ((void)0)
#else
#define assert(expr) ((expr) ? (void)0 : abort())
#endif
#endif
@@ -0,0 +1,40 @@
#ifndef CONFORMANCE_MATH_H
#define CONFORMANCE_MATH_H
/* Minimal <math.h> for the freestanding corpus. There is no libm in the bare
* loader, so transcendental functions are only declared (a test that calls
* sin/pow/floor and expects a value is curated as a libm skip); the useful
* classification macros and fabs* are compiler builtins and do not link. */
#define HUGE_VAL (__builtin_huge_val())
#define HUGE_VALF (__builtin_huge_valf())
#define INFINITY (__builtin_inff())
#define NAN (__builtin_nanf(""))
#define M_PI 3.14159265358979323846
#define isfinite(x) __builtin_isfinite(x)
#define isinf(x) __builtin_isinf(x)
#define isnan(x) __builtin_isnan(x)
#define signbit(x) __builtin_signbit(x)
#define fabs(x) __builtin_fabs(x)
#define fabsf(x) __builtin_fabsf(x)
double acos(double);
double asin(double);
double atan(double);
double atan2(double, double);
double ceil(double);
double cos(double);
double cosh(double);
double exp(double);
double floor(double);
double fmod(double, double);
double log(double);
double log10(double);
double pow(double, double);
double sin(double);
double sinh(double);
double sqrt(double);
double tan(double);
double tanh(double);
#endif
@@ -0,0 +1,12 @@
#ifndef CONFORMANCE_STDBOOL_H
#define CONFORMANCE_STDBOOL_H
/* C99 <stdbool.h> for the freestanding C99-and-older corpus. clang accepts
* _Bool in its gnu89 mode as a GNU extension; the c-torture sweep uses gnu89
* for the K&R-era files but still compiles the few files that include this. */
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
@@ -2,12 +2,31 @@
#define CONFORMANCE_STDIO_H
#include <stddef.h>
#include <stdarg.h>
#define EOF (-1)
/* stdout and stderr are distinct sink descriptors: stdout writes the fixed
* CONF_OUT stream (01B10000/01B00020), stderr the CONF_ERR stream
* (01B30000/01B00060). 16 KiB of bytes is 0x20000 bit address units, so
* stdout ends at 01B2FFFF and does not alias stderr. Both cap at 16 KiB; the
* runner rejects a full buffer
* as truncated. fprintf/vfprintf return the untruncated formatted length;
* fputs/fwrite return the untruncated byte/item count; fputc returns the
* character written. */
typedef struct conf_file FILE;
extern FILE *stdout;
extern FILE *stderr;
int printf(const char *fmt, ...);
int sprintf(char *buf, const char *fmt, ...);
int fprintf(FILE *stream, const char *fmt, ...);
int vfprintf(FILE *stream, const char *fmt, va_list ap);
int putchar(int c);
int puts(const char *s);
int fputc(int c, FILE *stream);
int fputs(const char *s, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
#endif
@@ -13,4 +13,10 @@ void abort(void);
int atoi(const char *s);
int abs(int v);
/* Bounded allocator in the 64 KiB gap between the linker RAM region and the
* result block (see shim.c); free is a no-op. */
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
#endif
+2 -1
View File
@@ -2,8 +2,9 @@
#
# test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason
#
# expected: status=<decimal> or status=<decimal>;stdout=<escaped text>
# expected: status=<decimal>[;stdout=<escaped text>][;stderr=<escaped text>]
# escapes: \n \t \r \\ (interpreted with printf %b)
# stderr defaults to empty when the field is absent
# features: space-separated classifier tags (int-control, print, ...)
# skip_reason: empty for a runnable row; a non-empty reason is reported as a
# SKIP and is never counted as a pass.
1 # M5 conformance manifest
2 #
3 # test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason
4 #
5 # expected: status=<decimal> or status=<decimal>;stdout=<escaped text> # expected: status=<decimal>[;stdout=<escaped text>][;stderr=<escaped text>]
6 # escapes: \n \t \r \\ (interpreted with printf %b)
7 # stderr defaults to empty when the field is absent
8 # features: space-separated classifier tags (int-control, print, ...)
9 # skip_reason: empty for a runnable row; a non-empty reason is reported as a
10 # SKIP and is never counted as a pass.
+218 -25
View File
@@ -1,7 +1,7 @@
#!/bin/sh
# M5 conformance runner: compile one C test with the shim and entry, link it
# through the M4 pipeline (native TI-COFF when it works, asm/GSPA fallback),
# load the COFF in MAME, and compare the observed status/stdout with the
# load the COFF in MAME, and compare the observed status/stdout/stderr with the
# expected result.
#
# run.sh [options] SOURCE.c
@@ -9,12 +9,17 @@
# --id ID label (default: source basename)
# --expect SPEC expected result:
# status=<decimal>[;stdout=<escaped text>]
# [;stderr=<escaped text>]
# escapes understood by printf %b: \n \t \r \\
# default: status=0;stdout= (silent success)
# default: status=0;stdout=;stderr= (silent success)
# --expect-status N override the expected status
# --expect-stderr TEXT expect stderr to be exactly TEXT (printf %b escapes);
# overrides any ;stderr= in --expect/--manifest-row
# --expect-output-file F expect stdout to be exactly the bytes in F
# --ignore-output compare only the status (c-torture success is silent
# or diagnostic output; c-testsuite keeps the compare)
# --ignore-output compare only the status (stdout and stderr are
# ignored: c-torture success may print diagnostics;
# c-testsuite keeps the exact compare). It cannot be
# combined with --expect-stderr.
# --manifest-row ROW parse test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason
# --classify skip (exit 2) when classify.sh rejects SOURCE
# --mode auto|native|asm link mode (default auto: native, asm fallback)
@@ -27,10 +32,12 @@
#
# The linker-managed .bss region is 01A00000..01A80000 (64 KiB, including the
# 4 KiB _cstack in entry.asm). The result block is above it at 01B00000, so a
# test's globals cannot overwrite the status/output.
# test's globals cannot overwrite the status/stdout/stderr streams. Bit
# addresses make 16 KiB = 0x20000 units: stdout is 01B10000..01B2FFFF and
# stderr is 01B30000..01B4FFFF; the runner asserts they do not overlap.
#
# The runner prints one machine-readable result line:
# CONFORMANCE: PASS id=... status=... stdout_len=... link=...
# CONFORMANCE: PASS id=... status=... stdout_len=... stderr_len=... link=...
# CONFORMANCE: FAIL id=...
# CONFORMANCE: SKIP id=... reason=...
#
@@ -38,7 +45,7 @@
# DOSBOX_CONF SDK_IMG M4_SDK M6_LIB_SDK LOADER_AT LOADER_END
# MAME_TIMEOUT M5_CONFORMANCE_WORK M5_CONFORMANCE_CLANG_OPT
# M5_CONFORMANCE_LLC_OPT M5_CONFORMANCE_MODE
# M5_CONFORMANCE_CLASSIFY
# M5_CONFORMANCE_CLASSIFY M5_CONFORMANCE_EXTRA_CFLAGS
set -eu
ROOT=$(cd "$(dirname "$0")/../../../.." && pwd)
@@ -66,20 +73,51 @@ WORK_BASE=${M5_CONFORMANCE_WORK:-$ROOT/build/m5-conformance}
CLANG_OPT=${M5_CONFORMANCE_CLANG_OPT:--O0}
LLC_OPT=${M5_CONFORMANCE_LLC_OPT:--O0}
MODE=${M5_CONFORMANCE_MODE:-auto}
BARE=${M5_CONFORMANCE_BARE:-1}
# The OS/2 r5.01 tools (2ine) are preferred for assembly/linking when present;
# the 1987 DOSBox GSPA/GSPLNK remains the fallback and the byte oracle.
case ${M4_OS2:-auto} in
auto)
# The fast bare tier prefers the 2ine OS/2 assembler; the full-loader tier
# stays on the 1987 GSPA/GSPLNK oracle.
if [ "$BARE" = 1 ] \
&& [ -x "${M4_OS2_LX:-$HOME/os2-work/2ine-tms34010/build/lx_loader}" ]; then
M4_OS2=1
else
M4_OS2=0
fi
export M4_OS2
;;
0|1) export M4_OS2 ;;
*) fail "M4_OS2 must be 0, 1 or auto" ;;
esac
# Shim contract constants (keep in sync with shim.c and conformance-check.lua).
OUT_CAP=16384
OUT_BASE=$((0x01B10000))
ERR_BASE=$((0x01B30000))
PROG_ORIGIN=$((0x018A0000))
PROG_END=$((0x018F8000))
RAM_ORIGIN=$((0x01A00000))
RAM_END=$((0x01A80000))
RESULT_BASE=$((0x01B00000))
# Each byte occupies eight bit addresses. Never let the 16 KiB stdout range
# reach the stderr base: that would silently alias the two streams (the M7.3
# Task 2 review caught exactly this at the old stderr address 01B20000).
if [ $((OUT_BASE + OUT_CAP * 8)) -gt "$ERR_BASE" ]; then
echo "conformance: FAIL: stdout range $(printf '%08X' "$OUT_BASE")+$OUT_CAP bytes overlaps stderr base $(printf '%08X' "$ERR_BASE")" >&2
exit 1
fi
ID=
SRC=
EXPECT_SPEC=
EXPECT_SPEC_SET=0
EXPECT_STATUS=
EXPECT_STDERR=
EXPECT_STDERR_SET=0
EXPECT_OUTPUT_FILE=
MANIFEST_ROW=
DO_CLASSIFY=0
@@ -114,6 +152,12 @@ while [ $# -gt 0 ]; do
EXPECT_STATUS=$2
shift 2
;;
--expect-stderr)
[ $# -ge 2 ] || usage
EXPECT_STDERR=$2
EXPECT_STDERR_SET=1
shift 2
;;
--expect-output-file)
[ $# -ge 2 ] || usage
EXPECT_OUTPUT_FILE=$2
@@ -216,17 +260,46 @@ if [ "$DO_CLASSIFY" -eq 1 ]; then
esac
fi
# Parse the expected result after any manifest/option overrides.
# Parse the expected result after any manifest/option overrides. The spec
# keeps the historical status-first form and adds an optional stderr field;
# stdout/stderr may appear in either order, either may be absent, and an
# explicit --expect-stderr wins over the spec (like --expect-status). TEXT is
# printf-%b escaped, so a literal ';stdout='/'stderr=' inside the text is not
# representable, same as before.
STATUS_EXPECT=0
OUT_ESCAPED=
ERR_ESCAPED=
if [ "$EXPECT_SPEC_SET" -eq 1 ]; then
case $EXPECT_SPEC in
status=*)
REST=${EXPECT_SPEC#status=}
case $REST in
*';stdout='*)
STATUS_EXPECT=${REST%%;stdout=*}
OUT_ESCAPED=${REST#*;stdout=}
PRE_OUT=${REST%%;stdout=*}
case $REST in
*';stderr='*)
PRE_ERR=${REST%%;stderr=*}
if [ "${#PRE_OUT}" -lt "${#PRE_ERR}" ]; then
STATUS_EXPECT=$PRE_OUT
TMP=${REST#*;stdout=}
OUT_ESCAPED=${TMP%%;stderr=*}
ERR_ESCAPED=${TMP#*;stderr=}
else
STATUS_EXPECT=$PRE_ERR
TMP=${REST#*;stderr=}
ERR_ESCAPED=${TMP%%;stdout=*}
OUT_ESCAPED=${TMP#*;stdout=}
fi
;;
*)
STATUS_EXPECT=$PRE_OUT
OUT_ESCAPED=${REST#*;stdout=}
;;
esac
;;
*';stderr='*)
STATUS_EXPECT=${REST%%;stderr=*}
ERR_ESCAPED=${REST#*;stderr=}
;;
*)
STATUS_EXPECT=$REST
@@ -234,10 +307,14 @@ if [ "$EXPECT_SPEC_SET" -eq 1 ]; then
esac
;;
*)
fail "bad expected result '$EXPECT_SPEC' (want status=N[;stdout=TEXT])"
fail "bad expected result '$EXPECT_SPEC' (want status=N[;stdout=TEXT][;stderr=TEXT])"
;;
esac
fi
[ "$EXPECT_STDERR_SET" -eq 0 ] || ERR_ESCAPED=$EXPECT_STDERR
if [ "$IGNORE_OUTPUT" -eq 1 ] && [ "$EXPECT_STDERR_SET" -eq 1 ]; then
fail "--ignore-output cannot be combined with --expect-stderr"
fi
[ -z "$EXPECT_STATUS" ] || STATUS_EXPECT=$EXPECT_STATUS
case $STATUS_EXPECT in
''|*[!0-9]*) fail "expected status is not decimal: '$STATUS_EXPECT'" ;;
@@ -248,19 +325,23 @@ if [ -n "$EXPECT_OUTPUT_FILE" ]; then
[ -f "$EXPECT_OUTPUT_FILE" ] \
|| fail "missing expected output file: $EXPECT_OUTPUT_FILE"
EXPECT_HEX=$(od -An -v -tx1 "$EXPECT_OUTPUT_FILE" | tr -d ' \n')
EXPECT_SOURCE=$EXPECT_OUTPUT_FILE
EXPECT_SOURCE="$EXPECT_OUTPUT_FILE;stderr=$ERR_ESCAPED"
else
EXPECT_HEX=$(printf '%b' "$OUT_ESCAPED" | od -An -v -tx1 | tr -d ' \n')
EXPECT_SOURCE="status=$STATUS_EXPECT;stdout=$OUT_ESCAPED"
EXPECT_SOURCE="status=$STATUS_EXPECT;stdout=$OUT_ESCAPED;stderr=$ERR_ESCAPED"
fi
EXPECT_HEX=$(printf '%s' "$EXPECT_HEX" | tr '[:lower:]' '[:upper:]')
EXPECT_ERR_HEX=$(printf '%b' "$ERR_ESCAPED" | od -An -v -tx1 | tr -d ' \n')
EXPECT_ERR_HEX=$(printf '%s' "$EXPECT_ERR_HEX" | tr '[:lower:]' '[:upper:]')
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
[ -x "$MAME" ] || fail "missing MAME: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing COFF loader payload: $LOADER_BIN"
if [ "$BARE" != 1 ]; then
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing COFF loader payload: $LOADER_BIN"
fi
[ -f "$HERE/shim.c" ] || fail "missing shim: $HERE/shim.c"
[ -f "$HERE/entry.asm" ] || fail "missing entry: $HERE/entry.asm"
@@ -293,13 +374,22 @@ SRC_DIR=$(cd "$(dirname "$SRC")" && pwd)
COMPILE_SRC=$WORK/test.c
cp "$SRC" "$COMPILE_SRC"
# Link the optional heap object only when the test actually references the
# allocator surface. Keeping it out of the common shim preserves the code
# layout (and the shipped 300/600-frame gate timing) for non-heap tests.
TEST_SOURCES="$COMPILE_SRC $HERE/shim.c"
if grep -Eq '(malloc|calloc|free)[[:space:]]*\(' "$COMPILE_SRC"; then
TEST_SOURCES="$TEST_SOURCES $HERE/heap.c"
fi
link_once() {
native=$1
log=$2
M4_SOURCES="$COMPILE_SRC $HERE/shim.c" \
M4_SOURCES="$TEST_SOURCES" \
M4_ENTRY="$HERE/entry.asm" \
M4_CLANG_OPT="$CLANG_OPT" \
M4_LLC_OPT="$LLC_OPT" \
M4_EXTRA_CFLAGS="${M5_CONFORMANCE_EXTRA_CFLAGS:-}" \
M4_EXTRA_INCLUDES="-I $HERE/include -I $SRC_DIR" \
M4_WORK="$WORK/m4" \
M4_COFF="$WORK/m4/m4.coff" \
@@ -307,6 +397,7 @@ link_once() {
M4_NATIVE_PROG_LEN=58000h \
M4_NATIVE_RAM_LEN=80000h \
M4_NATIVE_LIBS="m6flib.lib m6rts.lib" \
M4_LINKER="${M4_LINKER:-$([ "$BARE" = 1 ] && echo tms-link || echo gsplnk)}" \
M4_LINK_CMD="$HERE/link.cmd" \
M4_EXTRA_ASM="$HERE/data-pad.asm" \
M4_SKIP_MAME=1 \
@@ -315,6 +406,10 @@ link_once() {
}
check_map() {
# The bare tier maps the COFF itself and validates placement by execution;
# the tms-link map has a different shape, so the GSPLNK map check is only
# for the full-loader tier.
[ "$BARE" = 1 ] && return 0
map=$WORK/m4/m4.map
[ -f "$map" ] || fail "linker produced no map: $map"
for sec in .text .data .bss; do
@@ -359,9 +454,82 @@ check_link() {
echo " linked $COFF ($LINK_MODE)"
}
bare_sp() {
if [ -n "${M5_BARE_SP:-}" ]; then
printf '%s' "$M5_BARE_SP"
return 0
fi
_map=$WORK/m4/m4.map
_origin=$(awk '$1 == ".bss" { print $3; exit }' "$_map")
_length=$(awk '$1 == ".bss" { print $4; exit }' "$_map")
if [ -z "$_origin" ]; then
# tms-link map: "01A00000 .bss" (no length). Use the top of the
# loader's 64 KiB RAM region for the stack; the bare tier has no
# create_process stack.
printf '01A80000'
return 0
fi
[ -n "$_origin" ] && [ -n "$_length" ] \
|| fail "bare mode: linker map has no .bss origin/length"
_origin=$((0x$_origin))
_length=$((0x$_length))
# Place the stack above .bss (the loader gives create_process a separate
# 0x6000-bit stack); cap at the end of the 0x80000-bit RAM region.
_sp=$((_origin + _length + 0x6000))
[ "$_sp" -le 0x01A80000 ] || _sp=0x01A80000
printf '%08X' "$_sp"
}
run_mame() {
echo "== run the COFF in MAME ($LINK_MODE)"
echo "== run the COFF in MAME ($LINK_MODE${BARE:+ bare})"
rm -f "$WORK/result.txt"
if [ "$BARE" = 1 ]; then
BARE_SP=$(bare_sp) || exit 1
set +e
BARE_COFF="$COFF" BARE_ENTRY=018A0000 BARE_SP="$BARE_SP" \
BARE_END="${BARE_END:-1000}" CONF_RESULT="$WORK/result.txt" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$HERE/bare-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1
MAME_RC=$?
set +e
if [ "$MAME_RC" -ne 0 ]; then
tail -40 "$WORK/mame.log" >&2 || true
fail "MAME exited $MAME_RC"
fi
grep -q 'CONF: .* status=' "$WORK/mame.log" \
|| { tail -40 "$WORK/mame.log" >&2; fail "bare MAME produced no CONF result"; }
RESULT=$WORK/result.txt
[ -f "$RESULT" ] || fail "bare MAME wrote no result file: $RESULT"
STATUS_HEX=$(sed -n 's/^status=//p' "$RESULT" | tr -d '\r')
LEN=$(sed -n 's/^len=//p' "$RESULT" | tr -d '\r')
MAGIC_HEX=$(sed -n 's/^magic=//p' "$RESULT" | tr -d '\r')
LOADER_HEX=$(sed -n 's/^loader=//p' "$RESULT" | tr -d '\r')
ACTUAL_HEX=$(sed -n 's/^out=//p' "$RESULT" | tr -d '\r')
ERRLEN=$(sed -n 's/^errlen=//p' "$RESULT" | tr -d '\r')
ACTUAL_ERR_HEX=$(sed -n 's/^err=//p' "$RESULT" | tr -d '\r')
[ -n "$STATUS_HEX" ] || fail "result file has no status"
[ -n "$MAGIC_HEX" ] || fail "result file has no magic"
[ -n "$LOADER_HEX" ] || fail "result file has no loader status"
ACTUAL_HEX=$(printf '%s' "$ACTUAL_HEX" | tr '[:lower:]' '[:upper:]')
ACTUAL_ERR_HEX=$(printf '%s' "$ACTUAL_ERR_HEX" | tr '[:lower:]' '[:upper:]')
if [ "$MAGIC_HEX" != "434F4E46" ]; then
tail -40 "$WORK/mame.log" >&2 || true
fail "no completion magic (got $MAGIC_HEX): test did not finish"
fi
[ -n "$LEN" ] || fail "result file has no output length"
case $LEN in *[!0-9]*) fail "result output length is not decimal: '$LEN'" ;; esac
[ "$LEN" -lt "$OUT_CAP" ] || fail "output truncated: length $LEN reached the $OUT_CAP-byte shim cap"
[ -n "$ERRLEN" ] || fail "result file has no stderr length"
case $ERRLEN in *[!0-9]*) fail "result stderr length is not decimal: '$ERRLEN'" ;; esac
[ "$ERRLEN" -lt "$OUT_CAP" ] || fail "stderr truncated: length $ERRLEN reached the $OUT_CAP-byte shim cap"
return 0
fi
set +e
M4_LOADER_LUA="$LOADER_LUA" \
VT1200_MONITOR=VR319 \
@@ -379,7 +547,10 @@ run_mame() {
-autoboot_script "$HERE/conformance-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1
MAME_RC=$?
set -e
# Keep errexit off through the loader-status return below. With set -e
# active, `return 2` aborts the whole script and the caller never sees the
# status (a loader rejection would look like a bare exit 2, i.e. a skip).
set +e
if [ "$MAME_RC" -ne 0 ]; then
tail -40 "$WORK/mame.log" >&2 || true
fail "MAME exited $MAME_RC"
@@ -397,15 +568,25 @@ run_mame() {
MAGIC_HEX=$(sed -n 's/^magic=//p' "$RESULT" | tr -d '\r')
LOADER_HEX=$(sed -n 's/^loader=//p' "$RESULT" | tr -d '\r')
ACTUAL_HEX=$(sed -n 's/^out=//p' "$RESULT" | tr -d '\r')
ERRLEN=$(sed -n 's/^errlen=//p' "$RESULT" | tr -d '\r')
ACTUAL_ERR_HEX=$(sed -n 's/^err=//p' "$RESULT" | tr -d '\r')
[ -n "$STATUS_HEX" ] || fail "result file has no status"
[ -n "$MAGIC_HEX" ] || fail "result file has no magic"
[ -n "$LOADER_HEX" ] || fail "result file has no loader status"
ACTUAL_HEX=$(printf '%s' "$ACTUAL_HEX" | tr '[:lower:]' '[:upper:]')
ACTUAL_ERR_HEX=$(printf '%s' "$ACTUAL_ERR_HEX" | tr '[:lower:]' '[:upper:]')
if [ "$LOADER_HEX" != "00000000" ]; then
return 2
fi
# Completion first: a test that never started leaves prefilled length
# cells, and "truncated" would be the wrong diagnosis.
if [ "$MAGIC_HEX" != "434F4E46" ]; then
tail -40 "$WORK/mame.log" >&2 || true
fail "no completion magic (got $MAGIC_HEX): test did not finish"
fi
[ -n "$LEN" ] || fail "result file has no output length"
case $LEN in
*[!0-9]*) fail "result output length is not decimal: '$LEN'" ;;
@@ -413,10 +594,12 @@ run_mame() {
if [ "$LEN" -ge "$OUT_CAP" ]; then
fail "output truncated: length $LEN reached the $OUT_CAP-byte shim cap"
fi
if [ "$MAGIC_HEX" != "434F4E46" ]; then
tail -40 "$WORK/mame.log" >&2 || true
fail "no completion magic (got $MAGIC_HEX): test did not finish"
[ -n "$ERRLEN" ] || fail "result file has no stderr length"
case $ERRLEN in
*[!0-9]*) fail "result stderr length is not decimal: '$ERRLEN'" ;;
esac
if [ "$ERRLEN" -ge "$OUT_CAP" ]; then
fail "stderr truncated: length $ERRLEN reached the $OUT_CAP-byte shim cap"
fi
return 0
}
@@ -479,18 +662,28 @@ OUTPUT_MISMATCH=0
if [ "$IGNORE_OUTPUT" -eq 0 ] && [ "$ACTUAL_HEX" != "$EXPECT_HEX" ]; then
OUTPUT_MISMATCH=1
fi
STDERR_MISMATCH=0
if [ "$IGNORE_OUTPUT" -eq 0 ] && [ "$ACTUAL_ERR_HEX" != "$EXPECT_ERR_HEX" ]; then
STDERR_MISMATCH=1
fi
if [ "$STATUS_HEX" != "$EXPECT_STATUS_HEX" ] || [ "$OUTPUT_MISMATCH" -eq 1 ]; then
echo "CONFORMANCE: FAIL id=$ID status=$STATUS_HEX expected_status=$EXPECT_STATUS_HEX stdout_len=$LEN"
if [ "$STATUS_HEX" != "$EXPECT_STATUS_HEX" ] || [ "$OUTPUT_MISMATCH" -eq 1 ] \
|| [ "$STDERR_MISMATCH" -eq 1 ]; then
echo "CONFORMANCE: FAIL id=$ID status=$STATUS_HEX expected_status=$EXPECT_STATUS_HEX stdout_len=$LEN stderr_len=$ERRLEN"
if [ "$STATUS_HEX" != "$EXPECT_STATUS_HEX" ]; then
echo " status mismatch: expected $EXPECT_STATUS_HEX, got $STATUS_HEX"
fi
if [ "$OUTPUT_MISMATCH" -eq 1 ]; then
echo " output mismatch: expected '$EXPECT_HEX', got '$ACTUAL_HEX'"
fi
if [ "$STDERR_MISMATCH" -eq 1 ]; then
echo " stderr mismatch: expected '$EXPECT_ERR_HEX', got '$ACTUAL_ERR_HEX'"
fi
if [ "$OUTPUT_MISMATCH" -eq 1 ] || [ "$STDERR_MISMATCH" -eq 1 ]; then
printf ' expected source: %s\n' "$EXPECT_SOURCE"
fi
echo " work dir: $WORK"
exit 1
fi
echo "CONFORMANCE: PASS id=$ID status=$STATUS_HEX stdout_len=$LEN link=$LINK_MODE"
echo "CONFORMANCE: PASS id=$ID status=$STATUS_HEX stdout_len=$LEN stderr_len=$ERRLEN link=$LINK_MODE"
+215 -4
View File
@@ -13,7 +13,13 @@
# Additional cases prove the shim's real va_list walk (format), the M6
# %lld/%f/sprintf formats through the same shim (format-m6), entry's
# main(1, argv) contract (argv), and that a large .bss cannot overwrite the
# result block (bigbss). Classifier checks prove the M6 %lld/%f/varargs source
# result block (bigbss). The stderr cases prove an empty expectation, the
# fprintf/fputs/fputc/fwrite surface and both expectation forms
# (--expect-stderr and ;stderr=), an exact mismatch, default-empty rejection,
# a 12 KiB stdout + stderr non-aliasing case, and truncation rejection at the
# 16 KiB cap. The truncate-return cases prove a single >16 KiB fwrite still
# returns the full count while len/errlen == CAP rejects the run.
# Classifier checks prove the M6 %lld/%f/varargs source
# is accepted, a genuinely unsupported source (__int128) is a skip (not a
# pass), an all-skip suite is a failure, a classifier error is a failure, and
# an unsafe id is rejected before any rm -rf.
@@ -28,6 +34,7 @@ set -eu
ROOT=$(cd "$(dirname "$0")/../../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=${M5_CONFORMANCE_SELFTEST_WORK:-$ROOT/build/m5-conformance-selftest}
RUN_WORK=${M5_CONFORMANCE_WORK:-$ROOT/build/m5-conformance}
MODE=${M5_CONFORMANCE_MODE:-auto}
RUN=$HERE/run.sh
@@ -125,12 +132,97 @@ __int128 unsupported_feature;
int main(void) { return 0; }
EOF
cat > "$WORK/stderr.c" <<'EOF'
#include <stdio.h>
int main(void)
{
int n = fprintf(stderr, "err=%d/%s\n", 42, "hi");
if (n != 10)
return 1;
if (fputs("tail", stderr) != 4)
return 2;
if (fputc('!', stderr) != '!')
return 3;
if (fwrite("ab", 1, 2, stderr) != 2)
return 4;
printf("out\n");
return 0;
}
EOF
cat > "$WORK/stderr-truncate.c" <<'EOF'
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 16384; i++)
fputc('e', stderr);
return 0;
}
EOF
cat > "$WORK/dual-stream.c" <<'EOF'
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 12288; i++)
putchar('o');
printf("END\n");
fprintf(stderr, "e\n");
return 0;
}
EOF
cat > "$WORK/truncate-return.c" <<'EOF'
#include <stdio.h>
int main(void)
{
static char buf[20000];
int i;
for (i = 0; i < 20000; i++)
buf[i] = 'x';
if (fwrite(buf, 1, 20000, stdout) != 20000)
return 9;
if (fprintf(stdout, "%s", "y") != 1)
return 8;
return 0;
}
EOF
cat > "$WORK/stderr-truncate-return.c" <<'EOF'
#include <stdio.h>
int main(void)
{
static char buf[20000];
int i;
for (i = 0; i < 20000; i++)
buf[i] = 'x';
if (fwrite(buf, 1, 20000, stderr) != 20000)
return 9;
if (fprintf(stderr, "%s", "y") != 1)
return 8;
return 0;
}
EOF
run_case() {
id=$1
expect=$2
src=$3
log=$4
if ! "$RUN" --id "$id" --mode "$MODE" --expect "$expect" "$src" \
shift 4
if ! "$RUN" --id "$id" --mode "$MODE" --expect "$expect" "$@" "$src" \
> "$log" 2>&1; then
cat "$log" >&2
fail "$id did not pass"
@@ -200,6 +292,123 @@ grep -q 'output truncated' "$WORK/truncate.log" \
|| { cat "$WORK/truncate.log" >&2; \
fail "truncation was not diagnosed"; }
echo "== stderr: an explicit empty expectation passes"
run_case selftest-stderr-empty 'status=0;stdout=' "$WORK/pass.c" \
"$WORK/stderr-empty.log" --expect-stderr ''
echo "== stderr: the write surface and --expect-stderr compare exactly"
run_case selftest-stderr 'status=0;stdout=out\n' "$WORK/stderr.c" \
"$WORK/stderr.log" --expect-stderr 'err=42/hi\ntail!ab'
grep -q '^CONFORMANCE: PASS id=selftest-stderr .*stderr_len=17' \
"$WORK/stderr.log" \
|| { cat "$WORK/stderr.log" >&2; \
fail "stderr case did not report stderr_len=17"; }
echo "== stderr: the ;stderr= spec form compares exactly"
run_case selftest-stderr-spec \
'status=0;stdout=out\n;stderr=err=42/hi\ntail!ab' \
"$WORK/stderr.c" "$WORK/stderr-spec.log"
grep -q '^CONFORMANCE: PASS id=selftest-stderr-spec' "$WORK/stderr-spec.log" \
|| { cat "$WORK/stderr-spec.log" >&2; \
fail "stderr spec case has no PASS line"; }
echo "== streams: 12 KiB stdout and a short stderr must not alias"
awk 'BEGIN { for (i = 0; i < 12288; i++) printf "o"; printf "END\n" }' \
> "$WORK/dual-stream.out"
run_case selftest-dual-stream 'status=0' "$WORK/dual-stream.c" \
"$WORK/dual-stream.log" --expect-output-file "$WORK/dual-stream.out" \
--expect-stderr 'e\n'
grep -q '^CONFORMANCE: PASS id=selftest-dual-stream .*stdout_len=12292 stderr_len=2' \
"$WORK/dual-stream.log" \
|| { cat "$WORK/dual-stream.log" >&2; \
fail "dual-stream case did not preserve both lengths"; }
echo "== stderr: a wrong expectation must fail"
if "$RUN" --id selftest-stderr-mismatch --mode "$MODE" \
--expect 'status=0;stdout=out\n' --expect-stderr 'wrong\n' \
"$WORK/stderr.c" > "$WORK/stderr-mismatch.log" 2>&1; then
cat "$WORK/stderr-mismatch.log" >&2
fail "wrong expected stderr unexpectedly passed"
fi
grep -q '^CONFORMANCE: FAIL id=selftest-stderr-mismatch' \
"$WORK/stderr-mismatch.log" \
|| { cat "$WORK/stderr-mismatch.log" >&2; \
fail "stderr mismatch has no FAIL line"; }
grep -q 'stderr mismatch' "$WORK/stderr-mismatch.log" \
|| { cat "$WORK/stderr-mismatch.log" >&2; \
fail "mismatch was not diagnosed as stderr"; }
grep -q '6572723D34322F68690A7461696C216162' "$WORK/stderr-mismatch.log" \
|| { cat "$WORK/stderr-mismatch.log" >&2; \
fail "stderr mismatch did not report actual 'err=42/hi\\ntail!ab'"; }
echo "== stderr: an omitted expectation means empty and must fail"
if "$RUN" --id selftest-stderr-default --mode "$MODE" \
--expect 'status=0;stdout=out\n' "$WORK/stderr.c" \
> "$WORK/stderr-default.log" 2>&1; then
cat "$WORK/stderr-default.log" >&2
fail "a test writing stderr passed with the default empty expectation"
fi
grep -q '^CONFORMANCE: FAIL id=selftest-stderr-default' \
"$WORK/stderr-default.log" \
|| { cat "$WORK/stderr-default.log" >&2; \
fail "default-empty stderr case has no FAIL line"; }
grep -q 'stderr mismatch' "$WORK/stderr-default.log" \
|| { cat "$WORK/stderr-default.log" >&2; \
fail "default-empty stderr case was not diagnosed as stderr"; }
echo "== stderr truncation: errlen at the 16 KiB cap must fail"
set +e
"$RUN" --id selftest-stderr-truncate --mode "$MODE" --expect-status 0 \
--ignore-output "$WORK/stderr-truncate.c" \
> "$WORK/stderr-truncate.log" 2>&1
RC=$?
set -e
[ "$RC" -eq 1 ] || { cat "$WORK/stderr-truncate.log" >&2; \
fail "stderr truncation case exited $RC, want 1"; }
grep -q 'stderr truncated' "$WORK/stderr-truncate.log" \
|| { cat "$WORK/stderr-truncate.log" >&2; \
fail "stderr truncation was not diagnosed"; }
echo "== stdout truncation: one >16 KiB fwrite returns the full count"
set +e
"$RUN" --id selftest-truncate-return --mode "$MODE" --expect-status 0 \
--ignore-output "$WORK/truncate-return.c" \
> "$WORK/truncate-return.log" 2>&1
RC=$?
set -e
[ "$RC" -eq 1 ] || { cat "$WORK/truncate-return.log" >&2; \
fail "stdout truncate-return case exited $RC, want 1"; }
grep -q 'output truncated' "$WORK/truncate-return.log" \
|| { cat "$WORK/truncate-return.log" >&2; \
fail "stdout truncate-return was not diagnosed as truncation"; }
TRUNC_RESULT=$RUN_WORK/selftest-truncate-return/result.txt
[ -f "$TRUNC_RESULT" ] || fail "missing result file: $TRUNC_RESULT"
sed -n 's/^status=//p' "$TRUNC_RESULT" | tr -d '\r' | grep -qx '00000000' \
|| { cat "$TRUNC_RESULT" >&2; \
fail "stdout fwrite/fprintf did not return the untruncated count"; }
sed -n 's/^len=//p' "$TRUNC_RESULT" | tr -d '\r' | grep -qx '16384' \
|| { cat "$TRUNC_RESULT" >&2; fail "stdout length is not the cap"; }
echo "== stderr truncation: one >16 KiB fwrite returns the full count"
set +e
"$RUN" --id selftest-stderr-truncate-return --mode "$MODE" \
--expect-status 0 --ignore-output "$WORK/stderr-truncate-return.c" \
> "$WORK/stderr-truncate-return.log" 2>&1
RC=$?
set -e
[ "$RC" -eq 1 ] || { cat "$WORK/stderr-truncate-return.log" >&2; \
fail "stderr truncate-return case exited $RC, want 1"; }
grep -q 'stderr truncated' "$WORK/stderr-truncate-return.log" \
|| { cat "$WORK/stderr-truncate-return.log" >&2; \
fail "stderr truncate-return was not diagnosed as truncation"; }
TRUNC_RESULT=$RUN_WORK/selftest-stderr-truncate-return/result.txt
[ -f "$TRUNC_RESULT" ] || fail "missing result file: $TRUNC_RESULT"
sed -n 's/^status=//p' "$TRUNC_RESULT" | tr -d '\r' | grep -qx '00000000' \
|| { cat "$TRUNC_RESULT" >&2; \
fail "stderr fwrite/fprintf did not return the untruncated count"; }
sed -n 's/^errlen=//p' "$TRUNC_RESULT" | tr -d '\r' | grep -qx '16384' \
|| { cat "$TRUNC_RESULT" >&2; fail "stderr length is not the cap"; }
echo "== print: a wrong expected output must fail"
if "$RUN" --id selftest-mismatch --mode "$MODE" \
--expect 'status=0;stdout=no\n' "$WORK/print.c" \
@@ -316,5 +525,7 @@ grep -q 'unsafe id' "$WORK/unsafe-id.log" \
echo "conformance selftest: PASS"
echo " pass, expected-fail status 7, print, format, format-m6, argv, bigbss,"
echo " truncation, output mismatch, classifier accepts M6, classifier int128"
echo " skip, classifier error, all-skip suite, unsafe id"
echo " truncation, stderr empty/write/mismatch/default-empty/truncation,"
echo " dual-stream non-aliasing, untruncated return at the cap, output"
echo " mismatch, classifier accepts M6, classifier int128 skip, classifier"
echo " error, all-skip suite, unsafe id"
+142 -42
View File
@@ -23,15 +23,24 @@
* 01B00000 status 0 = success, otherwise the main/exit/abort status
* 01B00020 out_len number of bytes written to the output buffer
* 01B00040 magic 0x434F4E46 once the result is complete ("CONF")
* 01B00060 err_len number of bytes written to the error buffer
* 01B10000 output text written by printf/putchar/puts (16 KiB)
* 01B30000 error text written to stderr (16 KiB)
*
* The result block is above the linker-managed RAM region
* (01A00000..01A80000, 64 KiB of .bss including the 4 KiB _cstack), so a
* test's globals cannot overwrite the status/output. entry.asm writes
* status/magic when main returns. exit/abort write them directly and then
* spin, so the result is observable even if the test does not return normally.
* out_char() stops at CONF_CAP; the runner rejects out_len == CONF_CAP as a
* truncation rather than accepting a partial output.
* stream_put() stops at CONF_CAP; the runner rejects out_len == CONF_CAP or
* err_len == CONF_CAP as a truncation rather than accepting partial output.
*
* stdout and stderr are distinct sink descriptors (FILE *): stdout continues
* the fixed CONF_OUT stream that printf/putchar/puts use, stderr uses CONF_ERR.
* fprintf/vfprintf reuse conf_format; fputs/fputc/fwrite write raw bytes. The
* return value is the untruncated length (fprintf/vfprintf/fputs/fwrite count
* bytes, fputc keeps the C character result); only the stored bytes are
* capped.
*
* sprintf has no size argument in C, so this freestanding shim gives it a
* fixed destination cap (SPRINTF_CAP bytes, including the NUL). Callers must
@@ -42,7 +51,11 @@
#define CONF_STATUS ((volatile int *)0x01B00000UL)
#define CONF_LEN ((volatile int *)0x01B00020UL)
#define CONF_MAGIC ((volatile int *)0x01B00040UL)
#define CONF_ERRLEN ((volatile int *)0x01B00060UL)
/* 16 KiB of bytes spans 0x20000 bit-address units, so stdout occupies
* 01B10000..01B2FFFF and stderr starts at the next free bit address. */
#define CONF_OUT ((char *)0x01B10000UL)
#define CONF_ERR ((char *)0x01B30000UL)
#define CONF_CAP 16384
#define CONF_MAGIC_VAL 0x434F4E46
#define SPRINTF_CAP 256
@@ -55,26 +68,76 @@
#define FLOAT_PREC_MAX 6
#define FLOAT_MAX_I32 2147483520.0 /* 2^31 - 128, safely inside i32 */
static int out_len;
/* Spelled like the header's stddef size_t (unsigned int on this target) so
* fwrite's declaration and definition cannot drift. */
typedef unsigned int size_t;
/* Destination for the shared formatter. printf starts `used` at out_len so it
* continues the fixed CONF_OUT stream; sprintf starts at 0 in the caller's
* buffer. The formatter's own return value counts every formatted character,
* including bytes dropped at the cap. */
/* A console stream descriptor. The target's .data writer cannot represent a
* pointer-to-absolute-address initializer, so the descriptor is just a kind
* tag and the buffer/length cells are selected in stream_put. stdout and
* stderr are distinct objects; a test may pass either to the f* surface. */
struct conf_file {
int kind; /* 0 = stdout, 1 = stderr */
};
typedef struct conf_file FILE;
static struct conf_file conf_stdout = { 0 };
static struct conf_file conf_stderr = { 1 };
FILE *stdout = &conf_stdout;
FILE *stderr = &conf_stderr;
/* Shadow lengths start at zero even if the harness did not clear the result
* cells (the M6 runtime entry does not); each byte publishes the shadow to the
* cell, so printf/fprintf/fputs/fputc/fwrite can interleave on one stream. */
static int out_len;
static int err_len;
/* Store one byte unless the stream is full; always report one byte written so
* callers can return the untruncated length. */
static int stream_put(FILE *f, int c)
{
char *buf;
volatile int *lenp;
int *shadow;
int len;
if (f && f->kind == 1) {
buf = CONF_ERR;
lenp = CONF_ERRLEN;
shadow = &err_len;
} else {
buf = CONF_OUT;
lenp = CONF_LEN;
shadow = &out_len;
}
len = *shadow;
if (len < CONF_CAP) {
buf[len] = (char)c;
*shadow = len + 1;
*lenp = *shadow;
}
return 1;
}
/* Destination for the shared formatter. A non-null `stream` continues that
* console stream (used by printf and fprintf); otherwise bytes go to the
* caller's buffer (sprintf). The formatter's own return value counts every
* formatted character, including bytes dropped at the cap. */
struct sink {
char *buf;
int cap;
int used;
int conf;
FILE *stream;
};
static void sink_char(struct sink *s, int c)
{
if (s->used < s->cap)
if (s->stream) {
stream_put(s->stream, c);
} else if (s->used < s->cap) {
s->buf[s->used++] = (char)c;
if (s->conf) {
out_len = s->used;
*CONF_LEN = out_len;
}
}
@@ -92,12 +155,7 @@ static void sink_str(struct sink *s, const char *p)
static int out_char(int c)
{
if (out_len < CONF_CAP) {
CONF_OUT[out_len] = (char)c;
out_len++;
*CONF_LEN = out_len;
}
return 1;
return stream_put(stdout, c);
}
static int out_str(const char *s)
@@ -370,7 +428,6 @@ static int emit_float(struct sink *s, double v, int width, int zero, int left,
int putchar(int c)
{
out_char(c);
*CONF_LEN = out_len;
return c;
}
@@ -379,10 +436,40 @@ int puts(const char *s)
int n = out_str(s);
out_char('\n');
*CONF_LEN = out_len;
return n + 1;
}
int fputc(int c, FILE *stream)
{
/* C: the EOF argument writes nothing and returns EOF. */
if (c < 0)
return -1;
stream_put(stream, c);
return (unsigned char)c;
}
int fputs(const char *s, FILE *stream)
{
int n = 0;
while (s[n]) {
stream_put(stream, s[n]);
n++;
}
return n;
}
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
const char *p = (const char *)ptr;
size_t n = size * nmemb;
size_t i;
for (i = 0; i < n; i++)
stream_put(stream, p[i]);
return nmemb;
}
unsigned int strlen(const char *s)
{
const char *p = s;
@@ -478,22 +565,10 @@ void *memmove(void *dst, const void *src, unsigned int n)
while (n--)
*d++ = *s++;
} else if (d > s) {
char *de = d;
const char *se = s;
unsigned int k = n;
/* Advance end pointers with constant 8-bit steps instead of
* `d += n`. At -O2 the optimizer canonicalises an
* `inttoptr(add(ptrtoint p, n*8))` back into a byte-indexed
* pointer GEP; tms-clang's post-opt `--scale` then scales that
* GEP a second time (the late-GEP over-scaling risk recorded in
* the Task 6 report). Constant steps are not rewritten. */
while (k--) {
de++;
se++;
}
d += n;
s += n;
while (n--)
*--de = *--se;
*--d = *--s;
}
return dst;
}
@@ -799,14 +874,36 @@ int printf(const char *fmt, ...)
int r;
__builtin_va_start(ap, fmt);
s.buf = CONF_OUT;
s.cap = CONF_CAP;
s.used = out_len;
s.conf = 1;
s.buf = 0;
s.cap = 0;
s.used = 0;
s.stream = stdout;
r = conf_format(fmt, ap, &s);
__builtin_va_end(ap);
out_len = s.used;
*CONF_LEN = out_len;
return r;
}
int vfprintf(FILE *stream, const char *fmt, __builtin_va_list ap)
{
struct sink s;
if (!stream)
stream = stdout;
s.buf = 0;
s.cap = 0;
s.used = 0;
s.stream = stream;
return conf_format(fmt, ap, &s);
}
int fprintf(FILE *stream, const char *fmt, ...)
{
__builtin_va_list ap;
int r;
__builtin_va_start(ap, fmt);
r = vfprintf(stream, fmt, ap);
__builtin_va_end(ap);
return r;
}
@@ -820,7 +917,7 @@ int sprintf(char *buf, const char *fmt, ...)
s.buf = buf;
s.cap = SPRINTF_CAP - 1;
s.used = 0;
s.conf = 0;
s.stream = 0;
r = conf_format(fmt, ap, &s);
__builtin_va_end(ap);
buf[s.used] = 0;
@@ -829,7 +926,10 @@ int sprintf(char *buf, const char *fmt, ...)
void exit(int status)
{
/* Publish both shadows, including empty streams, so a harness entry that
* does not clear the result cells cannot leave prefill there. */
*CONF_LEN = out_len;
*CONF_ERRLEN = err_len;
*CONF_STATUS = status;
*CONF_MAGIC = CONF_MAGIC_VAL;
for (;;)
+10 -11
View File
@@ -11,15 +11,17 @@
# diagnostic categories from the sweep; "M6" marks a feature deferred from
# the M5 subset (float/double, i128 and wider integers, general varargs,
# aggregates, GC). i64 is implemented by M6 Task 2; its former entries were
# removed from this manifest when they started compiling.
2004-05-09-LiveVarPartialRegister target rejection: M2 .data supports only integer, pointer and byte-array initializers
# removed from this manifest when they started compiling. M7.1 removed
# 2004-05-09-LiveVarPartialRegister, gc-lowering and shadow-stack-gc-lowering
# when the recursive .data initializer extension made them compile. M8.3
# removed 2008-02-04-Ctlz and llvm-ct-intrinsics when the ctlz/ctpop/cttz
# lowering landed.
2007-04-08-MultipleFrameIndices inline asm register constraint cannot be allocated
2007-04-27-InlineAsm-X-Dest inline asm register constraint cannot be allocated
2007-04-27-LargeMemObject inline asm memory constraint is not supported
2007-12-17-InvokeAsm inline asm memory constraint is not supported
2008-02-04-Ctlz target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
2008-02-20-MatchingMem inline asm memory constraint is not supported
2008-08-07-PtrToInt-SmallerInt target rejection: M2 .data supports only integer, pointer and byte-array initializers
2008-08-07-PtrToInt-SmallerInt target rejection: unsupported .data initializer
2010-ZeroSizedArg target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
APIntParam target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
APIntSextParam target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
@@ -27,10 +29,10 @@ APIntZextParam target rejection: TMS34010 supports only integer (<=64 bit) and p
GlobalISel/irtranslator-byte-type target rejection: M2 supports only void/integer(<=64)/pointer returns
add-with-overflow-128 target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
addr-label blockaddress values are not supported
annotate target rejection: M2 .data supports only integer, pointer and byte-array initializers
annotate target rejection: unsupported .data initializer
bfloat target rejection: M2 supports only void/integer(<=64)/pointer returns
bfloat-op missing libcall lowering (floats/vectors are deferred to M6)
cast-fp target rejection: M2 .data supports only integer, pointer and byte-array initializers
cast-fp target rejection: unsupported .data initializer
dag-combine-ossfuzz-crash target rejection: TMS34010: integer multiply wider than 64 bits is not supported (M6 implements exactly 64-bit arithmetic)
expand-experimental-reductions target rejection: M2 supports only void/integer(<=64)/pointer returns
extractelement-shuffle target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
@@ -46,14 +48,13 @@ icmp-illegal target rejection: TMS34010 supports only integer (<=64 bit) and poi
inline-asm-mem-clobber inline asm register constraint cannot be allocated
inline-asm-special-strings inline asm syntax is not supported by the TMS34010 parser
intrinsics target rejection: M2 supports only void/integer(<=64)/pointer returns
llvm-ct-intrinsics target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
nested-select target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
overloaded-intrinsic-name gc.statepoint calls are not supported
pr12507 target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
pr24662 target rejection: M2 supports only void/integer(<=64)/pointer returns
pr49872 target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
print-arith-fp target rejection: M2 .data supports only integer, pointer and byte-array initializers
ptr-annotate target rejection: M2 .data supports only integer, pointer and byte-array initializers
print-arith-fp target rejection: unsupported .data initializer
ptr-annotate target rejection: unsupported .data initializer
replace-intrinsics-with-veclib target rejection: M2 supports only void/integer(<=64)/pointer returns
replace-intrinsics-with-veclib-darwin-libsystem-m target rejection: M2 supports only void/integer(<=64)/pointer returns
select target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
@@ -61,5 +62,3 @@ select-cc target rejection: M2 supports only void/integer(<=64)/pointer returns
trap target rejection: M2 supports only direct calls to global functions and indirect calls through a function pointer
vector missing libcall lowering (floats/vectors are deferred to M6)
zero-sized-array target rejection: TMS34010 supports only integer (<=64 bit) and pointer arguments
gc-lowering target rejection: M2 .data supports only integer, pointer and byte-array initializers
shadow-stack-gc-lowering target rejection: M2 .data supports only integer, pointer and byte-array initializers
+9 -5
View File
@@ -222,11 +222,15 @@ echo " $MARKER"
echo "== linked .text size"
# Recorded baseline for the unchanged M3 sources (branch.c, layout.c, xhello.c).
# Update these constants together if those sources, the relaxation, or the
# frame save/restore change. MMTM/MMFM shortened xhello's 4-register save and
# restore by 8 bytes (882 -> 874); functions saving one or two registers keep
# the same or grow by up to 4 bytes, so re-measure after changing the ABI.
EXPECTED_TEXT_BYTES=874
# Update these constants together if those sources, the relaxation, the frame
# save/restore, or the generated ROM-import stub set changes. MMTM/MMFM
# shortened xhello's 4-register save and restore by 8 bytes (882 -> 874 at
# M5); functions saving one or two registers keep the same or grow by up to 4
# bytes, so re-measure after changing the ABI. M7.3 grew the v2.2 table from
# 30 to 36 entries; scripts/m3/run.sh generates a 6-byte JAUC stub for every
# entry, so the linked image gained 6*6 = 36 bytes (874 -> 910). The stub set
# is part of this fixture, not target code.
EXPECTED_TEXT_BYTES=910
EXPECTED_JR=14
TEXT_BITS=$(awk '$1 == ".text" && $2 == "0" { print $4; exit }' "$M3_WORK/m3.map")
[ -n "$TEXT_BITS" ] || fail "the linker map has no .text section"
+5 -1
View File
@@ -17,7 +17,11 @@
# the decoded instruction streams. Layouts are allowed to differ; a raw
# byte compare is not used.
#
# Overridable: M5_NATIVE_WORK MAME_TIMEOUT DOSBOX_TIMEOUT
# M5_NATIVE_LINKER=tms-link runs both native builds through tools/tms-link
# instead of GSPLNK (termtris then exercises the rts.lib archive path); the
# GSPLNK default remains the oracle.
#
# Overridable: M5_NATIVE_WORK MAME_TIMEOUT DOSBOX_TIMEOUT M5_NATIVE_LINKER
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
+5
View File
@@ -26,6 +26,11 @@
# M5_CONFORMANCE_DIR
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$ROOT/scripts/tests/m5/conformance}
+10 -3
View File
@@ -10,9 +10,11 @@
# -O0. Every listed test must pass: a classifier skip or a compile/link/MAME
# failure fails the gate, so the list can never be silently weakened. A
# bounded -O2 subset (scripts/tests/m6/c-torture-O2.list: the 20 M6 feature
# tests) then runs at -O2; those tests avoid the known M6 `-O2 p += n`
# over-scale shape (pointer-increment / memmove / string loops), which is an
# M7 item. The full-list -O2 pass lives in scripts/tests/m5/c-torture.sh.
# tests) then runs at -O2. The M6 subset originally avoided the `-O2 p += n`
# over-scale shape (pointer-increment / memmove / string loops); M7.1's
# bit-pointer barrier fixed that shape, and scripts/tests/m7/pointer-o2.sh now
# exercises it directly. The full-list -O2 pass lives in
# scripts/tests/m5/c-torture.sh.
#
# The 40-60 curated-target ruling is a soft bound for this one-time expansion;
# restoring the 19 legacy tests keeps every previously gated shape covered.
@@ -30,6 +32,11 @@
# M5_CONFORMANCE_DIR
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$ROOT/scripts/tests/m5/conformance}
+50 -9
View File
@@ -18,9 +18,13 @@
# - no 64-bit runtime helper: rts.lib has none and the compiler must not
# invent one (the map/asm are checked for the common libgcc names).
#
# M6_LINKER=tms-link optionally links the GSPA-assembled M6.OBJ with the 1990
# flib.lib/rts.lib through tools/tms-link instead of GSPLNK; the GSPLNK default
# remains the oracle.
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG TMS_OPT TMS_BITADDR MAME DOSBOX
# DOSBOX_CONF SDK_IMG I64_WORK I64_COFF I64_SDK LOADER_AT
# LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT
# LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT M6_LINKER TMS_LINK
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
@@ -32,6 +36,8 @@ TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
@@ -48,6 +54,7 @@ LOADER_END=${LOADER_END:-3400}
# -O0 by default (like the M2 gate). I64_OPT=-O2 runs the same program with
# the codegen optimizer on; the driver also runs its IR optimizer then.
I64_OPT=${I64_OPT:--O0}
LINKER=${M6_LINKER:-gsplnk}
fail() {
echo "m6 i64: FAIL: $*" >&2
@@ -57,6 +64,14 @@ fail() {
for tool in "$TMS_LLC" "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
case $LINKER in
gsplnk|tms-link) ;;
*) fail "M6_LINKER must be 'gsplnk' or 'tms-link', got '$LINKER'" ;;
esac
if [ "$LINKER" = tms-link ]; then
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] || fail "missing independent COFF reader: $M7COFF"
fi
mkdir -p "$WORK" "$SDK" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
@@ -103,14 +118,40 @@ cat "$DIR/i64-entry.asm" "$WORK/i64-funcs.s" "$WORK/i64-main.s" > "$SDK/M6.ASM"
sed 's/\r$//' "$DIR/i64-link.cmd" | sed 's/$/\r/' > "$SDK/M6.CMD"
rm -f "$SDK/M6.OBJ" "$SDK/M6.OUT" "$SDK/M6.MAP" "$SDK/M6.LST" "$SDK/M6.LNK"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
if [ "$LINKER" = tms-link ]; then
# GSPLNK oracle and tms-link from the same M6.OBJ and libraries.
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$SDK/M6.OUT" ] \
|| { if [ -f "$SDK/M6.LNK" ]; then cat "$SDK/M6.LNK" >&2; fi; \
fail "GSPLNK oracle produced no M6.OUT"; }
mv "$SDK/M6.OUT" "$SDK/M6.GSP.OUT"
mv "$SDK/M6.MAP" "$SDK/M6.GSP.MAP"
echo "== link M6.OBJ + flib.lib/rts.lib with tools/tms-link"
"$TMS_LINK" -o "$SDK/M6.OUT" --map "$SDK/M6.MAP" --entry _start \
--text 018A0000 --bss 01A00000 \
--prog-len 40000h --ram-len 80000h \
"$SDK/M6.OBJ" "$SDK/flib.lib" "$SDK/rts.lib" \
|| fail "tms-link failed"
python3 "$ROOT/scripts/tests/m8/coff-parity.py" \
"$M7COFF" "$SDK/M6.GSP.OUT" "$SDK/M6.OUT" \
|| fail "tms-link image differs from the GSPLNK oracle"
else
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
[ -f "$SDK/M6.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M6.LST" > "$WORK/m6.lst"
+51 -8
View File
@@ -30,9 +30,14 @@
# at 01B10000h) and the checker compares those bytes exactly with the expected
# text.
#
# M6_LINKER=tms-link optionally links the GSPA-assembled M6.OBJ with the 1990
# flib.lib/rts.lib through tools/tms-link instead of GSPLNK; the GSPLNK default
# remains the oracle.
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG TMS_OPT TMS_BITADDR MAME DOSBOX
# DOSBOX_CONF SDK_IMG RUNTIME_WORK RUNTIME_COFF RUNTIME_SDK
# LOADER_AT LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT RUNTIME_OPT
# M6_LINKER TMS_LINK
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
@@ -44,6 +49,8 @@ TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
@@ -57,6 +64,7 @@ LOADER_BIN=${LOADER_BIN:-$ROOT/vendor/vt1200/dwt/loader/build/loader.bin}
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-3400}
RUNTIME_OPTS=${RUNTIME_OPT:--O0 -O2}
LINKER=${M6_LINKER:-gsplnk}
fail() {
echo "m6 runtime: FAIL: $*" >&2
@@ -66,6 +74,14 @@ fail() {
for tool in "$TMS_LLC" "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
case $LINKER in
gsplnk|tms-link) ;;
*) fail "M6_LINKER must be 'gsplnk' or 'tms-link', got '$LINKER'" ;;
esac
if [ "$LINKER" = tms-link ]; then
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] || fail "missing independent COFF reader: $M7COFF"
fi
[ -f "$SHIM" ] || fail "missing shared shim: $SHIM"
[ -x "$MAME" ] || fail "MAME binary not built: $MAME"
[ -f "$LOADER_LUA" ] || fail "COFF loader missing: $LOADER_LUA"
@@ -144,14 +160,41 @@ run_one() {
sed 's/\r$//' "$DIR/runtime-link.cmd" | sed 's/$/\r/' > "$SDK/M6.CMD"
rm -f "$SDK/M6.OBJ" "$SDK/M6.OUT" "$SDK/M6.MAP" "$SDK/M6.LST" "$SDK/M6.LNK"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "$opt: DOSBox failed"; }
if [ "$LINKER" = tms-link ]; then
# Produce the GSPLNK oracle from the same M6.OBJ and libraries, then
# link the same inputs with tms-link and compare the allocated image.
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "$opt: DOSBox failed"; }
[ -f "$SDK/M6.OUT" ] \
|| { if [ -f "$SDK/M6.LNK" ]; then cat "$SDK/M6.LNK" >&2; fi; \
fail "$opt: GSPLNK oracle produced no M6.OUT"; }
mv "$SDK/M6.OUT" "$SDK/M6.GSP.OUT"
mv "$SDK/M6.MAP" "$SDK/M6.GSP.MAP"
echo "== [$opt] link M6.OBJ + flib.lib/rts.lib with tools/tms-link"
"$TMS_LINK" -o "$SDK/M6.OUT" --map "$SDK/M6.MAP" --entry _start \
--text 018A0000 --bss 01A00000 \
--prog-len 40000h --ram-len 80000h \
"$SDK/M6.OBJ" "$SDK/flib.lib" "$SDK/rts.lib" \
|| fail "$opt: tms-link failed"
python3 "$ROOT/scripts/tests/m8/coff-parity.py" \
"$M7COFF" "$SDK/M6.GSP.OUT" "$SDK/M6.OUT" \
|| fail "$opt: tms-link image differs from the GSPLNK oracle"
else
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M6 M6.obj M6.lst -l" \
-c "gsplnk M6.cmd > M6.LNK" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "$opt: DOSBox failed"; }
fi
[ -f "$SDK/M6.LST" ] || fail "$opt: GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M6.LST" > "$WORK/m6.lst"
+424
View File
@@ -0,0 +1,424 @@
#!/bin/sh
# M7.2 `.cinit` gate: a C TI init-record table linked and processed at run time.
#
# scripts/tests/m7/cinit.sh
#
# 1. scripts/m7/cinit.c emits a packed TI `.cinit` record
# (`u16 count; u32 destination; u16 data[count];`, terminated by a zero
# count) with a pointer-typed union member holding the destination *bit*
# address. scripts/m7/cinit-entry.asm defines the public `cinit` symbol at
# offset 0 of its empty `.cinit` section and walks the table exactly like
# the termtris `_start`.
# 2. GSPA assembles the entry; GSPLNK 2.00 links ENTRY.O + CINIT.O (the
# oracle) and tms-link links the same objects.
# 3. The gate requires identical allocated `.text`/`.data`/`.cinit`/`.bss`
# bytes and placement, an identical public C_EXT set, `cinit` at the
# `.cinit` origin, and the record's destination field equal to the
# `_cinit_target` bit address.
# 4. MAME loads the tms-link image; the entry's copy loop writes
# 0x1111/0x2222/0x3333 to cinit_target and cinit_probe() returns 0x6666.
#
# Overridable: LLVM_BIN TMS_CLANG TMS_LLC TMS_LINK M7COFF M7_CINIT_WORK M7_SDK
# SDK_IMG DOSBOX DOSBOX_CONF MAME MAME_TIMEOUT LOADER_AT
# LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M7_CINIT_WORK:-$ROOT/build/m7-cinit}
SDK=${M7_SDK:-$WORK/sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "M7 cinit: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF (set M7COFF=...)"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing loader payload: $LOADER_BIN"
rm -rf "$WORK"
mkdir -p "$WORK/dos" "$WORK/run/nvram" "$WORK/run/cfg" "$WORK/evidence"
WORK=$(cd "$WORK" && pwd)
echo "== compile scripts/m7/cinit.c and llc -filetype=obj"
( cd "$DIR" && "$TMS_CLANG" -O0 -o "$WORK/cinit.ll" cinit.c ) \
|| fail "tms-clang failed"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/cinit.ll" -o "$WORK/cinit.o" \
|| fail "llc -filetype=obj failed"
python3 - "$M7COFF" "$WORK/cinit.o" <<'PY' || fail "C .cinit object is not the TI record shape"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
c = m7coff.parse(sys.argv[2])
sections = [s["name"] for s in c["sections"]]
if ".cinit" not in sections:
sys.exit("C object has no .cinit section: %r" % sections)
sec = m7coff.section(c, ".cinit")
if sec["flags"] != 0x40:
sys.exit(".cinit flags %#x, want 0x40" % sec["flags"])
if sec["size"] != 112:
sys.exit(".cinit size %d bits, want 112 (14 bytes)" % sec["size"])
if sec["raw"][0:2] != b"\x03\x00":
sys.exit(".cinit count bytes %r, want 0300" % sec["raw"][0:2])
if sec["raw"][6:12] != b"\x11\x11\x22\x22\x33\x33":
sys.exit(".cinit data bytes %r" % sec["raw"][6:12])
if sec["raw"][12:14] != b"\x00\x00":
sys.exit(".cinit terminator %r, want 0000" % sec["raw"][12:14])
if len(sec["relocs"]) != 1:
sys.exit(".cinit has %d relocations, want exactly 1 (destination)"
% len(sec["relocs"]))
raddr, symidx, rtype = sec["relocs"][0]
if raddr != 0x10 or rtype != 0x11:
sys.exit(".cinit relocation %s, want (0x10, sym, 0x11)"
% ((hex(raddr), symidx, hex(rtype)),))
field = int.from_bytes(sec["raw"][raddr // 8:raddr // 8 + 4], "little")
if field != 0:
sys.exit(".cinit relocation addend %#x, want 0" % field)
by_index = {s["index"]: s for s in c["symbols"]}
target = by_index.get(symidx)
if target is None:
sys.exit(".cinit relocation names missing symbol record %d" % symidx)
# The writer canonicalizes a reference to the .bss section base to the .bss
# section symbol; _cinit_target is that section's offset-0 symbol (value 0).
bss_index = m7coff.section(c, ".bss")["index"]
if not ((target["name"] == ".bss" and target["secno"] == bss_index and
target["sclass"] == 3) or
(target["name"] == "_cinit_target" and
target["secno"] == bss_index and target["value"] == 0)):
sys.exit(".cinit relocation target %r (sec %d) is not the .bss/"
"_cinit_target section base"
% (target["name"], target["secno"]))
print(" C object .cinit: %d bits, reloc (%#x, %s, addend 0), data %s"
% (sec["size"], raddr, target["name"], sec["raw"][6:12].hex()))
PY
echo "== extract the GSPA/GSPLNK toolchain"
if [ ! -f "$SDK/GSPA.EXE" ] || [ ! -f "$SDK/GSPLNK.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
[ -f "$SDK/GSPLNK.EXE" ] || fail "GSPLNK.EXE is not extracted in $SDK"
DOS=$WORK/dos
cp "$SDK/GSPA.EXE" "$SDK/GSPLNK.EXE" "$DOS/"
cp "$WORK/cinit.o" "$DOS/CINIT.O"
sed 's/\r$//' "$DIR/cinit-entry.asm" | sed 's/$/\r/' > "$DOS/ENTRY.ASM"
cat > "$DOS/CINIT.CMD" <<'CMD'
-a
-o CINIT.OUT
-m CINIT.MAP
-e _start
ENTRY.O CINIT.O
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.cinit: {} > prog
.bss: {} > ram
}
CMD
sed 's/$/\r/' "$DOS/CINIT.CMD" > "$DOS/CINIT.CMD.crlf"
mv "$DOS/CINIT.CMD.crlf" "$DOS/CINIT.CMD"
echo "== assemble ENTRY.ASM and link with GSPLNK 2.00 (oracle)"
rm -f "$DOS/ENTRY.O" "$DOS/ENTRY.LST" "$DOS/CINIT.OUT" "$DOS/CINIT.MAP"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa ENTRY ENTRY.O ENTRY.LST -l" \
-c "gsplnk CINIT.CMD" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/ENTRY.LST" ] || fail "GSPA produced no ENTRY.LST"
sed 's/\r$//' "$DOS/ENTRY.LST" > "$WORK/entry.lst"
grep -q 'No Errors' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
[ -f "$DOS/CINIT.OUT" ] \
|| { tail -30 "$WORK/dosbox.log" >&2; fail "GSPLNK produced no CINIT.OUT"; }
cp "$DOS/CINIT.OUT" "$WORK/oracle.coff"
sed 's/\r$//' "$DOS/CINIT.MAP" > "$WORK/oracle.map"
echo "== link the same objects with tms-link"
"$TMS_LINK" -o "$WORK/tms-link.coff" --map "$WORK/tms-link.map" \
--entry _start --text 018A0000 --bss 01A00000 \
"$DOS/ENTRY.O" "$DOS/CINIT.O" \
|| fail "tms-link failed"
python3 - "$M7COFF" "$WORK/oracle.coff" "$WORK/tms-link.coff" \
"$WORK/cinit-env" <<'PY' || fail "tms-link .cinit output differs from GSPLNK"
import os
import struct
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
oracle_path, ours_path, env_path = sys.argv[2], sys.argv[3], sys.argv[4]
a = m7coff.parse(oracle_path)
b = m7coff.parse(ours_path)
if [s["name"] for s in a["sections"]] != [s["name"] for s in b["sections"]]:
sys.exit("section lists differ: %r != %r"
% ([s["name"] for s in a["sections"]],
[s["name"] for s in b["sections"]]))
if [s["name"] for s in a["sections"]] != [".text", ".data", ".cinit", ".bss"]:
sys.exit("sections %r, want .text/.data/.cinit/.bss"
% [s["name"] for s in a["sections"]])
for sa, sb in zip(a["sections"], b["sections"]):
if sa["paddr"] != sb["paddr"] or sa["size"] != sb["size"]:
sys.exit("%s paddr/size %#x/%d != %#x/%d"
% (sa["name"], sa["paddr"], sa["size"], sb["paddr"],
sb["size"]))
if sa["flags"] != sb["flags"]:
sys.exit("%s flags %#x != %#x"
% (sa["name"], sa["flags"], sb["flags"]))
if sa["name"] == ".bss":
continue
if sa["raw"] != sb["raw"]:
sys.exit("%s bytes differ: %s != %s"
% (sa["name"], sa["raw"].hex(), sb["raw"].hex()))
if sb["nreloc"]:
sys.exit("%s still has %d relocations" % (sb["name"], sb["nreloc"]))
if a["flags"] != b["flags"]:
sys.exit("file flags %#x != %#x" % (a["flags"], b["flags"]))
if a["opthdr"] != 28 or b["opthdr"] != 28:
sys.exit("optional header sizes %d != %d" % (a["opthdr"], b["opthdr"]))
opt_a = struct.unpack_from("<HHIIIIII", a["data"], 20)
opt_b = struct.unpack_from("<HHIIIIII", b["data"], 20)
if opt_a != opt_b:
sys.exit("optional header %r != %r" % (opt_a, opt_b))
def ext(obj):
return {s["name"]: s["value"] for s in obj["symbols"]
if s["sclass"] == 2 and s["secno"] > 0}
ea, eb = ext(a), ext(b)
if ea != eb:
missing = sorted(set(ea) - set(eb))
extra = sorted(set(eb) - set(ea))
wrong = sorted(n for n in set(ea) & set(eb) if ea[n] != eb[n])
sys.exit("public C_EXT mismatch: missing=%r extra=%r wrong=%r"
% (missing, extra,
[(n, hex(ea[n]), hex(eb[n])) for n in wrong]))
def sym(obj, name):
for s in obj["symbols"]:
if s["name"] == name:
return s
sys.exit("missing symbol %s" % name)
cinit_sec = m7coff.section(b, ".cinit")
cinit_sym = sym(b, "cinit")
table_sym = sym(b, "_cinit_table")
target_sym = sym(b, "_cinit_target")
if cinit_sym["secno"] != cinit_sec["index"] or cinit_sym["value"] != cinit_sec["paddr"]:
sys.exit("cinit symbol %#x sec %d is not the .cinit origin %#x"
% (cinit_sym["value"], cinit_sym["secno"], cinit_sec["paddr"]))
if table_sym["value"] != cinit_sec["paddr"]:
sys.exit("_cinit_table %#x is not the .cinit origin %#x"
% (table_sym["value"], cinit_sec["paddr"]))
if target_sym["secno"] == 0:
sys.exit("_cinit_target is not defined in .bss")
raw = cinit_sec["raw"]
count = int.from_bytes(raw[0:2], "little")
dest = int.from_bytes(raw[2:6], "little")
words = [int.from_bytes(raw[6 + i * 2:8 + i * 2], "little")
for i in range(3)]
term = int.from_bytes(raw[12:14], "little")
if count != 3 or words != [0x1111, 0x2222, 0x3333] or term != 0:
sys.exit("record count=%d words=%r term=%d, want 3/[0x1111,0x2222,"
"0x3333]/0" % (count, words, term))
if dest != target_sym["value"]:
sys.exit("record destination %#x is not the _cinit_target bit address %#x"
% (dest, target_sym["value"]))
if dest % 8:
sys.exit("record destination %#x is not byte aligned" % dest)
with open(env_path, "w", encoding="ascii") as fh:
fh.write("CINIT_TABLE=%08X\n" % cinit_sec["paddr"])
fh.write("CINIT_DEST=%08X\n" % target_sym["value"])
print(" oracle == tms-link: .text=%d .data=%d .cinit=%d .bss=%d bits"
% (a["sections"][0]["size"], a["sections"][1]["size"],
a["sections"][2]["size"], a["sections"][3]["size"]))
print(" .cinit at %08X: count=%d destination=%08X (_cinit_target) "
"words=%04X/%04X/%04X end=%d cinit=%08X"
% (cinit_sec["paddr"], count, dest, words[0], words[1], words[2],
term, cinit_sym["value"]))
print(" public C_EXT set equal (%d names)" % len(ea))
PY
echo "== exercise the linker-synthesized cinit symbol"
# CINIT.O alone has the table but no input defines `cinit`; tms-link must
# synthesize the public symbol at the .cinit origin. (The entry-defined path
# above is the real startup shape; this link-only case proves the other branch
# of the spec's "the linker defines the public cinit symbol".)
"$TMS_LINK" -o "$WORK/tms-link-synth.coff" \
--map "$WORK/tms-link-synth.map" --entry _cinit_probe \
--text 018A0000 --bss 01A00000 \
"$DOS/CINIT.O" \
|| fail "tms-link synthetic-cinit link failed"
python3 - "$M7COFF" "$DOS/CINIT.O" "$WORK/tms-link-synth.coff" \
"$WORK/tms-link.coff" <<'PY' \
|| fail "the linker did not synthesize cinit at the .cinit origin"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
inp_path, synth_path, main_path = sys.argv[2], sys.argv[3], sys.argv[4]
inp = m7coff.parse(inp_path)
if any(s["name"] == "cinit" and s["sclass"] == 2 and s["secno"] > 0
for s in inp["symbols"]):
sys.exit("CINIT.O already defines cinit; the synthesis case is invalid")
out = m7coff.parse(synth_path)
sec = m7coff.section(out, ".cinit")
csym = next((s for s in out["symbols"]
if s["name"] == "cinit" and s["sclass"] == 2), None)
if csym is None:
sys.exit("synthetic-cinit link has no public cinit symbol")
if csym["value"] != sec["paddr"] or csym["secno"] != sec["index"]:
sys.exit("synthetic cinit %#x sec %d is not the .cinit origin %#x"
% (csym["value"], csym["secno"], sec["paddr"]))
tsym = next((s for s in out["symbols"]
if s["name"] == "_cinit_table" and s["sclass"] == 2), None)
if tsym is None or tsym["value"] != sec["paddr"]:
sys.exit("synthetic link _cinit_table is not the .cinit origin")
target = next((s for s in out["symbols"]
if s["name"] == "_cinit_target" and s["sclass"] == 2), None)
if target is None:
sys.exit("synthetic link has no _cinit_target")
dest = int.from_bytes(sec["raw"][2:6], "little")
if dest != target["value"]:
sys.exit("synthetic link destination %#x is not _cinit_target %#x"
% (dest, target["value"]))
main = m7coff.parse(main_path)
main_sec = m7coff.section(main, ".cinit")
# The destination differs because this link has no entry-object .bss stack, so
# _cinit_target is at the ram origin. The count, data words and terminator
# must be byte-identical to the entry-defined link.
if (sec["raw"][:2] + sec["raw"][6:]) != (main_sec["raw"][:2] +
main_sec["raw"][6:]):
sys.exit("synthetic-cinit count/data/terminator differ from the "
"entry-defined link")
print(" synthesized cinit=%08X at the .cinit origin (no input defines it), "
"destination=%08X" % (csym["value"], dest))
PY
. "$WORK/cinit-env"
echo "== run the tms-link .cinit image in MAME"
cat > "$WORK/cinit-check.lua" <<'LUA'
dofile(os.getenv("M4_LOADER_LUA"))
local TABLE = tonumber(os.getenv("CINIT_TABLE"), 16)
local DEST = tonumber(os.getenv("CINIT_DEST"), 16)
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local count = prog:read_u16(TABLE)
local dest = prog:read_u32(TABLE + 16)
local w0 = prog:read_u16(TABLE + 48)
local w1 = prog:read_u16(TABLE + 64)
local w2 = prog:read_u16(TABLE + 80)
local term = prog:read_u16(TABLE + 96)
local d0 = prog:read_u16(DEST)
local d1 = prog:read_u16(DEST + 16)
local d2 = prog:read_u16(DEST + 32)
local marker = prog:read_u32(0x018A8000)
print(string.format(
"CINIT: table=%08X count=%d dest=%08X words=%04X/%04X/%04X " ..
"end=%d data=%04X/%04X/%04X marker=%d",
TABLE, count, dest, w0, w1, w2, term, d0, d1, d2, marker))
if count == 3 and dest == DEST and w0 == 0x1111 and
w1 == 0x2222 and w2 == 0x3333 and term == 0 and
d0 == 0x1111 and d1 == 0x2222 and d2 == 0x3333 and
marker == 0x6666 then
print("CINIT MAME: PASS")
else
print("CINIT MAME: FAIL (want count=3 dest=target " ..
"words=1111/2222/3333 end=0 marker=26214)")
end
end
end, "cinit-check")
LUA
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$WORK/tms-link.coff" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
CINIT_TABLE="$CINIT_TABLE" CINIT_DEST="$CINIT_DEST" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$WORK/cinit-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; \
fail "COFF loader did not report status 0"; }
grep -q 'placed \.cinit .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .cinit bytes"
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -Eq '^CINIT: table=.* count=3 dest=.* words=1111/2222/3333 end=0 data=1111/2222/3333 marker=26214$' \
"$WORK/mame.log" \
|| { grep '^CINIT:' "$WORK/mame.log" >&2 || true; \
fail ".cinit record or copied words are wrong in MAME"; }
grep -q '^CINIT MAME: PASS$' "$WORK/mame.log" \
|| fail "MAME .cinit marker check failed"
echo "M7 cinit: PASS (C TI record table, cinit at .cinit origin, destination"
echo " resolved to the _cinit_target bit address, copy loop in MAME,"
echo " bytes/placement equal to GSPLNK)"
+177
View File
@@ -0,0 +1,177 @@
-- data-check.lua -- read the M7.1 `.data` initializer gate markers and the raw
-- object bytes, and compare them with the exact expected values.
--
-- M4_LOADER_LUA is the dwt loader script. Marker n is at 018A8000 + n*0x20
-- bits; marker 60 is the post-return sentinel. The raw image is at
-- 018A9000: x@0, s@8, p@13, arr@26, u@44, pt@64, y@80 (the pt pointer bytes
-- are compared with the linked address of x from marker 25). In the native
-- run only, markers 26..29 and the 5-byte packed odd-offset pointer record at
-- byte 96 are checked too; the raw GSPA path rejects that shape.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local BASE = 0x018A8000
local OUT = 0x018A9000
local N = 34
local SENT_IDX = 60
local SENT = 0x5A5A5A5A
local NATIVE = os.getenv("M7_DATA_NATIVE") == "1"
local frames = 0
local checked = false
local expect = {
0x55667788, -- 0: low word of x
0x11223344, -- 1: high word of x
5, -- 2: s.a
17, -- 3: s.b
0xFFFFFFFD, -- 4: s.c (signed -3)
0x000ABCDE, -- 5: s.d
9, -- 6: s.e
0x11, -- 7: p.a
0x22334455, -- 8: p.b
0xAABBCCDD, -- 9: low word of p.c
0x66778899, -- 10: high word of p.c
0x11223344, -- 11: arr[0].a
0x778899AA, -- 12: arr[1].a
0xDDEEFF00, -- 13: arr[2].a
0x5566, -- 14: arr[0].b
0x12345678, -- 15: union active struct i
0x9ABC, -- 16: union active struct h
1, -- 17: pp == &x and *pp == x
3, -- 18: cp - &x in bytes
0x1234, -- 19: pt.tag
1, -- 20: pt.p == &x and pt.c == 0x5A
0x12345678, -- 21: union low word
0x00009ABC, -- 22: union high word
0x1122, -- 23: arr[2].b
0xBBCC, -- 24: arr[1].b
nil, -- 25: linked address of x (runtime)
nil, -- 26: odd.c (native only)
nil, -- 27: odd.p == &x (native only)
nil, -- 28: low word of *odd.p (native only)
nil, -- 29: high word of *odd.p (native only)
0x55667788, -- 30: low word of y[0]
0x11223344, -- 31: high word of y[0]
0xDDEEFF00, -- 32: low word of y[1]
0x99AABBCC, -- 33: high word of y[1]
}
local raw = {
{ 0, "8877665544332211", "x" },
{ 8, "8DEDCDAB09", "s" },
{ 13, "1155443322DDCCBBAA99887766", "p" },
{ 26, "443322116655AA998877CCBB00FFEEDD2211", "arr" },
{ 44, "78563412BC9A0000", "u" },
{ 80, "887766554433221100FFEEDDCCBBAA99", "y" },
}
local function read_bytes(prog, off, len)
local out = {}
for i = 0, len - 1 do
out[#out + 1] = string.char(prog:read_u8(OUT + (off + i) * 8))
end
return table.concat(out)
end
local function hex(s)
return (s:gsub(".", function(c) return string.format("%02X", string.byte(c)) end))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if expect[i + 1] ~= nil and got[i] ~= expect[i + 1] then
bad = bad + 1
end
end
local sent = prog:read_u32(BASE + SENT_IDX * 0x20)
if sent ~= SENT then
bad = bad + 1
end
for _, r in ipairs(raw) do
local got_bytes = read_bytes(prog, r[1], #r[2] / 2)
if hex(got_bytes) ~= r[2] then
bad = bad + 1
print(string.format(
"M7 data: %s bytes got %s want %s",
r[3], hex(got_bytes), r[2]))
end
end
-- pt: tag, linked pointer, char. The pointer bytes are the
-- little-endian linked address of x from marker 25.
local pt = read_bytes(prog, 64, 9)
local pt_tag = string.unpack("<I4", pt, 1)
local pt_ptr = string.unpack("<I4", pt, 5)
local pt_c = string.byte(pt, 9)
if pt_tag ~= 0x1234 or pt_c ~= 0x5A or pt_ptr ~= got[25] then
bad = bad + 1
print(string.format(
"M7 data: pt bytes got %s (ptr %08X want %08X)",
hex(pt), pt_ptr, got[25]))
end
if hex(read_bytes(prog, 64, 4)) ~= "34120000" then
bad = bad + 1
print("M7 data: pt.tag bytes do not match the field read")
end
-- Native-only packed { char, long long * }: the pointer field is
-- at byte offset 1. Marker 25 is the linked address of x.
if NATIVE then
local odd = read_bytes(prog, 96, 5)
local odd_c = string.byte(odd, 1)
local odd_ptr = string.unpack("<I4", odd, 2)
if got[26] ~= 0x5A or got[27] ~= 1 or
got[28] ~= 0x55667788 or got[29] ~= 0x11223344 then
bad = bad + 1
print(string.format(
"M7 data: odd markers %08X %08X %08X %08X",
got[26], got[27], got[28], got[29]))
end
if odd_c ~= 0x5A or odd_ptr ~= got[25] then
bad = bad + 1
print(string.format(
"M7 data: odd bytes %s (ptr %08X want %08X)",
hex(odd), odd_ptr, got[25]))
end
end
io.write("M7 data:")
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write(string.format(" %08X\n", sent))
if bad == 0 then
print("M4: data gate markers and raw bytes match")
print("M4 MAME: PASS")
print("M7 DATA MAME: PASS")
else
for i = 0, N - 1 do
if expect[i + 1] ~= nil and got[i] ~= expect[i + 1] then
print(string.format(
"M7 data: marker %d got %08X want %08X",
i, got[i], expect[i + 1]))
end
end
if sent ~= SENT then
print(string.format(
"M7 data: sentinel got %08X want %08X",
sent, SENT))
end
print("M4: data gate marker/byte mismatch")
print("M4 MAME: FAIL")
print("M7 DATA MAME: FAIL")
end
end
end, "m7-data-check")
+22
View File
@@ -0,0 +1,22 @@
; data-entry.asm -- M7.1 `.data` gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; drivers (data_run and the i64-array driver), and writes a post-return
; sentinel at marker slot 60. This is the GSPA text-path entry: the
; odd-offset-pointer driver is native-only and is called by
; data-native-entry.asm instead.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _data_run
calla _data64_run
movi 5A5A5A5Ah, a0
movi 018A8780h, a2 ; marker 60, the post-return sentinel
move a0, *a2, 1
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+21
View File
@@ -0,0 +1,21 @@
; data-native-entry.asm -- M7.1 `.data` gate entry for the native TI-COFF path.
;
; Same as data-entry.asm plus the odd-offset-pointer driver. The raw GSPA
; path cannot represent that record's pointer (data.sh asserts the loud
; diagnostic), so only the M4_NATIVE=1 run compiles and calls it.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _data_run
calla _data64_run
calla _data_odd_run
movi 5A5A5A5Ah, a0
movi 018A8780h, a2 ; marker 60, the post-return sentinel
move a0, *a2, 1
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+256
View File
@@ -0,0 +1,256 @@
#!/bin/sh
# M7.1 `.data` initializer gate: C globals through both the GSPA text path and
# the native TI-COFF object path, with MAME reading the field values and the
# exact raw object bytes.
#
# scripts/tests/m7/data.sh
#
# The C driver m7data.c defines:
# - a 64-bit scalar (0x1122334455667788, LSW first in memory);
# - the 1987 bitfield struct s (5 bytes: 8D ED CD AB 09);
# - a packed record <{ i8, i32, i64 }> (13 bytes);
# - an array of packed records (3 x 6 bytes);
# - a union whose active member is the 6-byte struct (8-byte allocation);
# - a pointer global, a +3-byte pointer addend, and a pointer field inside a
# packed record.
# i64arr.c adds an i64 array (Clang's ConstantArray<i64> form).
# oddptr.c adds the native-only packed { char, long long * } whose pointer is
# at byte offset 1; the raw GSPA path cannot represent it, so this script also
# asserts that the raw compile fails with the specific diagnostic.
#
# The script runs the driver set through scripts/m4/run.sh:
# 1. the default GSPA assembly text path (m7data.c + i64arr.c);
# 2. M4_NATIVE=1, i.e. llc -filetype=obj + GSPLNK (plus oddptr.c).
# Both link/load with the 1987 GSPA/GSPLNK tools, the dwt loader and MAME.
# data-check.lua checks the marker words and raw byte image (including the
# native-only odd-offset pointer). The unlinked objects are also parsed
# directly to pin the `.data` sizes, literal relocation addresses/type and the
# pointer addend before the linker sees them.
#
# Overridable: LLVM_BIN TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX
# DOSBOX_CONF SDK_IMG M7_DATA_WORK DATA_OPT LOADER_AT LOADER_END
# MAME_TIMEOUT DOSBOX_TIMEOUT
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/tests/m7
WORK=${M7_DATA_WORK:-$ROOT/build/m7-data}
OPT=${DATA_OPT:--O0}
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
fail() {
echo "m7 data: FAIL: $*" >&2
exit 1
}
rm -rf "$WORK"
mkdir -p "$WORK"
run_one() { # run_one TAG NATIVE ENTRY SOURCES ODD_NATIVE
tag=$1
native=$2
entry=$3
sources=$4
odd_native=$5
echo "== [$tag] compile/link/run the C drivers ($OPT)"
M7_DATA_NATIVE="$odd_native" \
M4_WORK="$WORK/$tag" \
M4_SDK="$WORK/sdk-$tag" \
M4_COFF="$WORK/data-$tag.coff" \
M4_SOURCES="$sources" \
M4_ENTRY="$entry" \
M4_CHECK_LUA="$DIR/data-check.lua" \
M4_CLANG_OPT="$OPT" \
M4_LLC_OPT=-O0 \
M4_NATIVE="$native" \
M4_NATIVE_SKIP_ASM="$native" \
"$ROOT/scripts/m4/run.sh" > "$WORK/$tag.log" 2>&1 \
|| { tail -80 "$WORK/$tag.log" >&2; \
fail "$tag: compile/link/MAME harness failed"; }
grep -q '^M4 MAME: PASS' "$WORK/$tag/mame.log" \
|| { tail -50 "$WORK/$tag/mame.log" >&2; \
fail "$tag: M4 harness marker check failed"; }
grep -q '^M7 DATA MAME: PASS' "$WORK/$tag/mame.log" \
|| { grep -E '^M7 data' "$WORK/$tag/mame.log" >&2 || true; \
tail -50 "$WORK/$tag/mame.log" >&2; \
fail "$tag: field values or raw bytes did not match in MAME"; }
grep -E '^M7 data' "$WORK/$tag/mame.log" | sed 's/^/ /'
}
run_one asm 0 "$DIR/data-entry.asm" \
"$DIR/m7data.c $DIR/i64arr.c" 0
run_one native 1 "$DIR/data-native-entry.asm" \
"$DIR/m7data.c $DIR/i64arr.c $DIR/oddptr.c" 1
echo "== the raw GSPA path must reject the odd-offset pointer"
export TMS_CLANG TMS_OPT TMS_BITADDR
"$ROOT/scripts/tms-clang" "$OPT" -o "$WORK/oddptr.ll" "$DIR/oddptr.c" \
|| fail "tms-clang failed for oddptr.c"
if "$TMS_LLC" -march=tms34010 "$OPT" -filetype=asm "$WORK/oddptr.ll" \
-o "$WORK/oddptr.s" > "$WORK/oddptr-raw.log" 2>&1; then
fail "the raw GSPA path accepted the odd-offset pointer"
fi
grep -Fq "a pointer field at an odd .data byte offset cannot be represented in GSPA assembly" \
"$WORK/oddptr-raw.log" \
|| { cat "$WORK/oddptr-raw.log" >&2; \
fail "the raw path did not emit the specific odd-pointer diagnostic"; }
echo " $(grep -m1 'pointer field at an odd' "$WORK/oddptr-raw.log")"
echo "== object-mode wide integers from the CodeGen fixture"
# The asm arm of the i24/i40/i48/i56 and [2 x i24] tests lives in the LLVM lit
# test. Compile the same module to TI-COFF here so the object emit arm is
# byte-checked too (the object writer needs a .text anchor, which the fixture
# provides).
WIDE_LL=${WIDE_LL:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7-data-initializers.ll}
[ -f "$WIDE_LL" ] || fail "missing wide-integer fixture $WIDE_LL"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj "$WIDE_LL" \
-o "$WORK/wide.o" > "$WORK/wide.log" 2>&1 \
|| { cat "$WORK/wide.log" >&2; fail "object-mode wide-integer compile failed"; }
echo "== parse the native objects' .data before linking"
python3 - "$WORK/native/asm/m7data.o" \
"$WORK/native/asm/i64arr.o" \
"$WORK/native/asm/oddptr.o" \
"$WORK/wide.o" <<'PY' \
|| fail "native .data bytes/symbols/relocations do not match"
import struct
import sys
def parse(path):
data = open(path, "rb").read()
machine, nscns, _time, symptr, nsyms, opthdr, _flags = \
struct.unpack_from("<HHIIIHH", data, 0)
if machine != 0x0090:
sys.exit(f"{path}: machine {machine:#06x}, want 0x0090")
base = 20 + opthdr
sections = {}
for i in range(nscns):
off = base + i * 40
name = data[off:off + 8].split(b"\0", 1)[0].decode("latin1")
size, ptr, relptr, _lnptr = struct.unpack_from(
"<IIII", data, off + 16)
nrel, _nln = struct.unpack_from("<HH", data, off + 32)
sections[name] = (size, ptr, relptr, nrel)
symbols = {}
i = 0
while i < nsyms:
off = symptr + i * 18
name = data[off:off + 8]
if name[:4] == b"\0\0\0\0":
soff = struct.unpack_from("<I", data, off + 4)[0]
end = data.find(b"\0", symptr + nsyms * 18 + soff)
nm = data[symptr + nsyms * 18 + soff:end].decode("latin1")
else:
nm = name.rstrip(b"\0").decode("latin1")
value = struct.unpack_from("<I", data, off + 8)[0]
cls = data[off + 16]
naux = data[off + 17]
if cls != 3:
symbols[nm] = value
i += 1 + naux
if ".data" not in sections:
sys.exit(f"{path}: no .data section")
data_size, data_ptr, rel_ptr, nrel = sections[".data"]
raw = data[data_ptr:data_ptr + data_size // 8]
relocs = []
for i in range(nrel):
off = rel_ptr + i * 10
addr, _sym, typ = struct.unpack_from("<IIH", data, off)
if typ != 0x11:
sys.exit(f"{path}: relocation type {typ:#06x}, want 0x11")
relocs.append(addr)
return raw, data_size, symbols, relocs
def at(symbols, name, raw, hexbytes, field_off=0, path=""):
if name not in symbols:
sys.exit(f"{path}: missing symbol {name}")
off = symbols[name] // 8 + field_off
got = raw[off:off + len(hexbytes) // 2]
if got.hex() != hexbytes:
sys.exit(f"{path}: {name} bytes {got.hex()}, want {hexbytes}")
base_path, i64_path, odd_path, wide_path = sys.argv[1:5]
# The original .data set: exactly 72 bytes and the three literal relocation
# addresses for _pp, _cp and _pt.p.
raw, size, symbols, relocs = parse(base_path)
if size != 72 * 8:
sys.exit(f"{base_path}: .data size {size} bits, want 72 bytes (576)")
if sorted(relocs) != [0x1B0, 0x1D0, 0x210]:
sys.exit(f"{base_path}: relocations {[hex(r) for r in relocs]}, "
f"want 0x1b0/0x1d0/0x210")
want = {
"_x": "8877665544332211",
"_s": "8dedcdab09",
"_p": "1155443322ddccbbaa99887766",
"_arr": "443322116655aa998877ccbb00ffeedd2211",
"_u": "78563412bc9a0000",
}
for name, hexbytes in want.items():
at(symbols, name, raw, hexbytes, path=base_path)
# Pointer fields: zero in the object plus an R-RELLONG at those addresses.
for name, field_off in (("_pp", 0), ("_cp", 0), ("_pt", 4)):
off = symbols[name] // 8 + field_off
got = raw[off:off + 4]
if name == "_cp":
if got != bytes([24, 0, 0, 0]):
sys.exit(f"{base_path}: _cp addend {got.hex()}, want 18000000")
elif got != b"\0\0\0\0":
sys.exit(f"{base_path}: {name} field {got.hex()}, want zero + reloc")
# i64 array: 2 * 8 bytes, no relocations.
raw, size, symbols, relocs = parse(i64_path)
if size != 16 * 8:
sys.exit(f"{i64_path}: .data size {size} bits, want 16 bytes (128)")
if relocs:
sys.exit(f"{i64_path}: unexpected relocations {[hex(r) for r in relocs]}")
at(symbols, "_y", raw, "887766554433221100ffeeddccbbaa99", path=i64_path)
# Odd-offset pointer: one 6-byte object with the pointer at byte 1 and a
# relocation at bit 8.
raw, size, symbols, relocs = parse(odd_path)
if size != 6 * 8:
sys.exit(f"{odd_path}: .data size {size} bits, want 6 bytes (48)")
if relocs != [8]:
sys.exit(f"{odd_path}: relocations {[hex(r) for r in relocs]}, "
f"want exactly [0x8] (the pointer at byte 1)")
at(symbols, "_odd", raw, "5a0000000000", path=odd_path)
if symbols["_odd"] != 0:
sys.exit(f"{odd_path}: _odd is at bit {symbols['_odd']}, want 0")
# Object-mode wide integers from m7-data-initializers.ll: exact value bytes
# and allocation padding, in TI-COFF rather than asm text.
raw, _size, symbols, _relocs = parse(wide_path)
wide_want = {
"_wide3": "56341200", # i24 + alloc pad
"_wide5": "9a7856341200", # i40 + alloc pad
"_wide6": "bc9a78563412", # i48, no pad
"_wide7": "debc9a7856341200", # i56 + alloc pad
"_wide3arr": "5634120021436500", # [2 x i24], stride 4
"_i64arr": "887766554433221100ffeeddccbbaa99",
}
for name, hexbytes in wide_want.items():
at(symbols, name, raw, hexbytes, path=wide_path)
print("m7-data-object: own .data=72 bytes relocs=0x1b0/0x1d0/0x210; "
"i64arr .data=16 bytes; oddptr .data=6 bytes reloc=0x8; "
"wide i24/i40/i48/i56 + [2 x i24] bytes exact")
PY
echo "m7 data: PASS (i64 LSW-first in asm and object mode, i64 array, i24/i40/"
echo " i48/i56 and [2 x i24] bytes in asm and object mode, packed "
echo " records, bitfields, union, pointer relocations, and the "
echo " native-only odd-offset pointer in TI-COFF/MAME)"
+589
View File
@@ -0,0 +1,589 @@
#!/bin/sh
# M7.2 debug-info gate: `llc -filetype=obj` DWARF through tms-link.
#
# scripts/tests/m7/debug.sh
#
# 1. Compile scripts/m7/debug.c with `tms-clang -g -O0` (clang -g through the
# bit-pointer barrier) and `llc -filetype=obj`; require the object's
# long-named `.debug_*` sections and assert, in the final IR, that the
# `@debug_ptr` body's barrier-synthesized instructions (`mul`, `shl i32`,
# `ptrtoint ptr`, `add i32`, `inttoptr i32`) plus its loads/stores carry
# `!dbg`. The TU has three functions: debug_mul (int arithmetic),
# debug_add (int arithmetic), and debug_ptr (`p += debug_index; return *p`,
# a runtime GEP the barrier rewrites).
# 2. Also build the same TU with `tms-clang -g -O2` (the full
# --bitptr -> opt -> --scale -> --lower-bitptr -> instcombine path), require
# the six core `.debug_*` sections, link it with `--keep-debug`, wrap it and
# smoke-check `debug.c`, a subprogram name and the linked base address with
# llvm-dwarfdump. The optimized layout is not stable, so the exact
# low/high/line assertions stay on the -O0 fixture.
# 3. GSPA assembles scripts/m7/debug-entry.asm; tms-link links DEBUG.O first
# (so debug_mul is the text-origin function) and DENTRY.O second, twice:
# --keep-debug and the default strip.
# 4. The kept -O0 `.debug_*` sections are wrapped in a minimal ELF32 container
# by scripts/m7/elf-debug-wrap.py and read by llvm-dwarfdump. The gate
# asserts:
# - filename debug.c and .debug_line rows for all three functions;
# - low PC = text origin / 8 + function offset (debug_mul 0x314000,
# debug_add 0x31402c, debug_ptr 0x314058) and the CU low/high;
# - DW_AT_high_pc is the function byte size (DW_FORM_data4), not divided;
# - .debug_addr entries read by index after the DWARF v5 header;
# - .debug_str_offsets/.debug_str resolve the function/local/global names.
# 5. The default strip link has exactly .text/.data/.bss and its image loads
# and runs in MAME (debug_mul -> 43 at 018A8000, debug_add -> 14 at
# 018A8020, debug_ptr -> 30 at 018A8040).
#
# Overridable: LLVM_BIN TMS_CLANG TMS_LLC TMS_LINK M7COFF M7_DEBUG_WORK M7_SDK
# SDK_IMG DOSBOX DOSBOX_CONF MAME MAME_TIMEOUT LOADER_AT
# LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
DWARFDUMP=${DWARFDUMP:-$LLVM_BIN/llvm-dwarfdump}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M7_DEBUG_WORK:-$ROOT/build/m7-debug}
SDK=${M7_SDK:-$WORK/sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "M7 debug: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -x "$DWARFDUMP" ] || fail "missing llvm-dwarfdump: $DWARFDUMP"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF (set M7COFF=...)"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing loader payload: $LOADER_BIN"
rm -rf "$WORK"
mkdir -p "$WORK/dos" "$WORK/run/nvram" "$WORK/run/cfg" "$WORK/evidence"
WORK=$(cd "$WORK" && pwd)
echo "== compile scripts/m7/debug.c with tms-clang -g and llc -filetype=obj"
# Compile from scripts/m7 with the relative name so DW_AT_name and the
# .debug_line file table name are exactly "debug.c", not an absolute path.
( cd "$DIR" && "$TMS_CLANG" -g -O0 -o "$WORK/debug.ll" debug.c ) \
|| fail "tms-clang -g failed"
grep -q '!dbg' "$WORK/debug.ll" || fail "debug.ll has no !dbg metadata"
# The barrier-synthesized instructions must carry !dbg, not just the ordinary
# loads/stores. Extract @debug_ptr and check the --bitptr / --lower-bitptr
# chain plus the load/store through the computed pointer. This is the
# attribution the line-table rows alone cannot prove.
awk '
/^define .*@debug_ptr\(/ { in_fn = 1 }
in_fn { print }
in_fn && /^}/ { exit }
' "$WORK/debug.ll" > "$WORK/debug_ptr.ll"
[ -s "$WORK/debug_ptr.ll" ] \
|| fail "no @debug_ptr definition in $WORK/debug.ll"
check_dbg_line() { # check_dbg_line LABEL ERE
label=$1
pattern=$2
grep -E "$pattern" "$WORK/debug_ptr.ll" \
> "$WORK/debug_ptr.check" || true
if [ ! -s "$WORK/debug_ptr.check" ]; then
cat "$WORK/debug_ptr.ll" >&2
fail "@debug_ptr has no $label (pattern: $pattern)"
fi
if grep -vq '!dbg' "$WORK/debug_ptr.check"; then
cat "$WORK/debug_ptr.ll" >&2
fail "@debug_ptr has a $label without !dbg: $(grep -v '!dbg' \
"$WORK/debug_ptr.check" | head -n 1)"
fi
}
check_dbg_line "GEP index multiply" 'mul i32 .*'
check_dbg_line "bit-offset shl" 'shl i32 .* 3'
check_dbg_line "ptrtoint base" 'ptrtoint ptr .* to i32'
check_dbg_line "bit-address add" 'add i32 .*'
check_dbg_line "lowered inttoptr" 'inttoptr i32 .* to ptr'
for op in store load; do
grep -E "^[[:space:]]*${op} |^[[:space:]]*%[^ ]+ = ${op} " \
"$WORK/debug_ptr.ll" > "$WORK/debug_ptr.$op.ll" || true
[ -s "$WORK/debug_ptr.$op.ll" ] \
|| { cat "$WORK/debug_ptr.ll" >&2; \
fail "@debug_ptr has no $op through the computed pointer"; }
if grep -vq '!dbg' "$WORK/debug_ptr.$op.ll"; then
cat "$WORK/debug_ptr.ll" >&2
fail "@debug_ptr has a $op without !dbg"
fi
done
echo " @debug_ptr barrier IR: mul/shl/ptrtoint/add/inttoptr + loads/stores"
echo " all carry !dbg"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/debug.ll" -o "$WORK/debug.o" \
|| fail "llc -filetype=obj failed"
python3 - "$M7COFF" "$WORK/debug.o" <<'PY' || fail "debug object has no .debug_* sections"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
c = m7coff.parse(sys.argv[2])
debug = [s["name"] for s in c["sections"] if s["name"].startswith(".debug_")]
if not debug:
sys.exit("no .debug_* sections in the object")
for name in (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr"):
if name not in debug:
sys.exit("missing %s; got %r" % (name, debug))
print(" object debug sections: " + " ".join(debug))
PY
echo "== build the same TU at -O2 -g (full barrier/optimizer pipeline)"
# -O2 runs clang -> --bitptr -> opt -> --scale -> --lower-bitptr ->
# instcombine. Requiring the object's .debug_* sections from this build (and
# the dwarfdump check below) proves !dbg survives the barrier and the
# optimizer, not just the -O0 path.
( cd "$DIR" && "$TMS_CLANG" -g -O2 -o "$WORK/debug-o2.ll" debug.c ) \
|| fail "tms-clang -g -O2 failed"
grep -q '!dbg' "$WORK/debug-o2.ll" \
|| fail "the -O2 -g IR has no !dbg metadata"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/debug-o2.ll" -o "$WORK/debug-o2.o" \
|| fail "llc -filetype=obj failed for the -O2 -g IR"
python3 - "$M7COFF" "$WORK/debug-o2.o" <<'PY' \
|| fail "the -O2 -g object has no .debug_* sections"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
c = m7coff.parse(sys.argv[2])
debug = [s["name"] for s in c["sections"] if s["name"].startswith(".debug_")]
for name in (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr"):
if name not in debug:
sys.exit("-O2 -g object missing %s; got %r" % (name, debug))
print(" -O2 -g object debug sections: " + " ".join(debug))
PY
echo "== extract the GSPA/GSPLNK toolchain"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
DOS=$WORK/dos
cp "$SDK/GSPA.EXE" "$DOS/"
cp "$WORK/debug.o" "$DOS/DEBUG.O"
sed 's/\r$//' "$DIR/debug-entry.asm" | sed 's/$/\r/' > "$DOS/DENTRY.ASM"
echo "== assemble debug-entry.asm with GSPA 2.00"
rm -f "$DOS/DENTRY.O" "$DOS/DENTRY.LST"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa DENTRY DENTRY.O DENTRY.LST -l" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/DENTRY.LST" ] || fail "GSPA produced no DENTRY.LST"
sed 's/\r$//' "$DOS/DENTRY.LST" > "$WORK/dentry.lst"
grep -q 'No Errors' "$WORK/dentry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/dentry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/dentry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/dentry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
echo "== link with tms-link: --keep-debug and the default strip"
"$TMS_LINK" -o "$WORK/debug-keep.coff" --keep-debug \
--map "$WORK/debug-keep.map" --entry _start \
--text 018A0000 --bss 01A00000 \
"$DOS/DEBUG.O" "$DOS/DENTRY.O" \
|| fail "tms-link --keep-debug failed"
"$TMS_LINK" -o "$WORK/debug-strip.coff" \
--map "$WORK/debug-strip.map" --entry _start \
--text 018A0000 --bss 01A00000 \
"$DOS/DEBUG.O" "$DOS/DENTRY.O" \
|| fail "tms-link (strip) failed"
echo "== link the -O2 -g object with --keep-debug and dump it"
"$TMS_LINK" -o "$WORK/debug-o2-keep.coff" --keep-debug \
--map "$WORK/debug-o2-keep.map" --entry _start \
--text 018A0000 --bss 01A00000 \
"$WORK/debug-o2.o" "$DOS/DENTRY.O" \
|| fail "tms-link --keep-debug failed for the -O2 -g object"
"$DIR/elf-debug-wrap.py" -o "$WORK/debug-o2.elf" \
"$WORK/debug-o2-keep.coff" \
|| fail "elf-debug-wrap failed for the -O2 -g object"
"$DWARFDUMP" --debug-info --verbose --debug-line "$WORK/debug-o2.elf" \
> "$WORK/dwarf-o2.txt" 2> "$WORK/dwarf-o2.err" \
|| { cat "$WORK/dwarf-o2.err" >&2; \
fail "llvm-dwarfdump failed on the -O2 -g image"; }
grep -q 'DW_AT_name.*"debug.c"' "$WORK/dwarf-o2.txt" \
|| { head -30 "$WORK/dwarf-o2.txt" >&2; \
fail "the -O2 -g image has no debug.c compile unit"; }
grep -Eq 'string = "debug_(mul|add|ptr)"' "$WORK/dwarf-o2.txt" \
|| { head -40 "$WORK/dwarf-o2.txt" >&2; \
fail "the -O2 -g image has no debug subprogram name"; }
grep -q '0x0000000000314000' "$WORK/dwarf-o2.txt" \
|| { head -40 "$WORK/dwarf-o2.txt" >&2; \
fail "the -O2 -g image has no linked low PC 0x314000"; }
echo " -O2 -g linked image: debug.c, subprogram names and 0x314000 present"
echo "== inspect the linked keep/strip images"
python3 - "$M7COFF" "$WORK/debug-keep.coff" "$WORK/debug-strip.coff" \
"$WORK/debug-env" <<'PY' || fail "linked debug image layout is wrong"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
keep_path, strip_path, env_path = sys.argv[2], sys.argv[3], sys.argv[4]
keep = m7coff.parse(keep_path)
strip = m7coff.parse(strip_path)
keep_sections = [s["name"] for s in keep["sections"]]
strip_sections = [s["name"] for s in strip["sections"]]
if strip_sections != [".text", ".data", ".bss"]:
sys.exit("default strip has sections %r, want .text/.data/.bss"
% strip_sections)
if keep_sections[:3] != [".text", ".data", ".bss"]:
sys.exit("kept image leading sections %r" % keep_sections[:3])
debug = [n for n in keep_sections[3:] if n.startswith(".debug_")]
if debug != keep_sections[3:] or not debug:
sys.exit("kept image sections after .bss are %r"
% keep_sections[3:])
for name in (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr"):
if name not in debug:
sys.exit("kept image missing %s; got %r" % (name, debug))
for sa, sb in zip(keep["sections"][:3], strip["sections"]):
if sa["paddr"] != sb["paddr"] or sa["size"] != sb["size"]:
sys.exit("%s keep/strip paddr/size %#x/%d != %#x/%d"
% (sa["name"], sa["paddr"], sa["size"], sb["paddr"],
sb["size"]))
if sa["flags"] != sb["flags"]:
sys.exit("%s keep/strip flags differ" % sa["name"])
if sa["name"] == ".bss":
continue
if sa["raw"] != sb["raw"]:
sys.exit("%s keep/strip bytes differ" % sa["name"])
for sec in keep["sections"]:
if sec["name"].startswith(".debug_"):
if sec["paddr"] != 0 or sec["vaddr"] != 0:
sys.exit("%s paddr/vaddr %#x/%#x, want 0/0"
% (sec["name"], sec["paddr"], sec["vaddr"]))
if sec["flags"] != 0:
sys.exit("%s flags %#x, want 0" % (sec["name"], sec["flags"]))
if sec["nreloc"]:
sys.exit("%s still has %d relocations"
% (sec["name"], sec["nreloc"]))
elif sec["nreloc"]:
sys.exit("%s still has %d relocations" % (sec["name"], sec["nreloc"]))
syms = {s["name"]: s for s in keep["symbols"]}
for name in ("_debug_mul", "_debug_add", "_debug_ptr", "_start",
"_debug_array", "_debug_index"):
if name not in syms:
sys.exit("kept image missing symbol %s" % name)
mul = syms["_debug_mul"]["value"]
add = syms["_debug_add"]["value"]
ptr = syms["_debug_ptr"]["value"]
start = syms["_start"]["value"]
array = syms["_debug_array"]["value"]
index = syms["_debug_index"]["value"]
text = m7coff.section(keep, ".text")
text_end = text["paddr"] + text["size"]
if not (text["paddr"] <= mul < add < ptr < start < text_end):
sys.exit("debug functions are not at increasing text offsets: "
"%#x %#x %#x %#x %#x %#x" % (text["paddr"], mul, add, ptr,
start, text_end))
# `.debug_addr` is DWARF v5: unit_length (4), version (2), address_size (1),
# segment_selector_size (1), then 4-byte entries. Read the entries by index.
addr = m7coff.section(keep, ".debug_addr")["raw"]
if len(addr) < 8:
sys.exit(".debug_addr is too short: %s" % addr.hex())
unit_length = int.from_bytes(addr[0:4], "little")
version = int.from_bytes(addr[4:6], "little")
addr_size = addr[6]
seg_size = addr[7]
if version != 5 or addr_size != 4 or seg_size != 0:
sys.exit(".debug_addr header version/size/seg %d/%d/%d, want 5/4/0"
% (version, addr_size, seg_size))
if unit_length != len(addr) - 4:
sys.exit(".debug_addr unit_length %d does not cover %d bytes"
% (unit_length, len(addr) - 4))
entries = [int.from_bytes(addr[8 + i * 4:12 + i * 4], "little")
for i in range((len(addr) - 8) // 4)]
# The first three entries are the CU/subprogram low PCs; the last two are the
# .data globals referenced by DW_OP_addrx in their DW_TAG_variable locations.
# This exact list/order is deterministic at compiler b9ef51a587b5; a DWARF
# emission change may legitimately add or reorder entries, in which case relax
# this assertion to a prefix/subset while keeping the indexed read.
want_addr = [mul // 8, add // 8, ptr // 8, array // 8, index // 8]
if entries != want_addr:
sys.exit(".debug_addr entries %r, want %r"
% ([hex(v) for v in entries], [hex(v) for v in want_addr]))
# The names live in .debug_str and are selected through .debug_str_offsets.
debug_str = m7coff.section(keep, ".debug_str")["raw"]
for name in (b"debug_mul", b"debug_add", b"debug_ptr", b"product", b"sum",
b"debug_array", b"debug_index", b"debug.c"):
if name + b"\0" not in debug_str:
sys.exit(".debug_str does not contain %r" % name)
with open(env_path, "w", encoding="ascii") as fh:
fh.write("DEBUG_TEXT_ORIGIN=%d\n" % text["paddr"])
fh.write("DEBUG_MUL_BITS=%d\n" % mul)
fh.write("DEBUG_ADD_BITS=%d\n" % add)
fh.write("DEBUG_PTR_BITS=%d\n" % ptr)
fh.write("DEBUG_START_BITS=%d\n" % start)
fh.write("DEBUG_TEXT_END=%d\n" % text_end)
print(" keep sections: %s" % " ".join(keep_sections))
print(" strip sections: %s" % " ".join(strip_sections))
print(" _debug_mul=%#x _debug_add=%#x _debug_ptr=%#x _start=%#x (bits), "
"text end=%#x" % (mul, add, ptr, start, text_end))
PY
. "$WORK/debug-env"
MUL_SIZE=$(((DEBUG_ADD_BITS - DEBUG_MUL_BITS) / 8))
ADD_SIZE=$(((DEBUG_PTR_BITS - DEBUG_ADD_BITS) / 8))
PTR_SIZE=$(((DEBUG_START_BITS - DEBUG_PTR_BITS) / 8))
[ "$((DEBUG_TEXT_ORIGIN / 8))" -eq $((0x314000)) ] \
|| fail "text origin byte address is $((DEBUG_TEXT_ORIGIN / 8)), want 0x314000"
echo "== wrap the kept .debug_* sections in a minimal ELF32 container"
"$DIR/elf-debug-wrap.py" -o "$WORK/debug.elf" "$WORK/debug-keep.coff" \
|| fail "elf-debug-wrap failed"
echo "== llvm-dwarfdump"
"$DWARFDUMP" --debug-info --verbose "$WORK/debug.elf" \
> "$WORK/dwarf-info.txt" 2> "$WORK/dwarf-info.err" \
|| { cat "$WORK/dwarf-info.err" >&2; fail "llvm-dwarfdump --debug-info failed"; }
"$DWARFDUMP" --debug-line "$WORK/debug.elf" \
> "$WORK/dwarf-line.txt" 2> "$WORK/dwarf-line.err" \
|| { cat "$WORK/dwarf-line.err" >&2; fail "llvm-dwarfdump --debug-line failed"; }
grep -q 'DW_AT_name.*"debug.c"' "$WORK/dwarf-info.txt" \
|| { head -40 "$WORK/dwarf-info.txt" >&2; \
fail "DWARF has no debug.c compilation-unit name"; }
grep -q 'name: "debug.c"' "$WORK/dwarf-line.txt" \
|| { head -40 "$WORK/dwarf-line.txt" >&2; \
fail ".debug_line has no debug.c filename"; }
python3 - "$WORK/dwarf-info.txt" "$WORK/dwarf-line.txt" \
"$DEBUG_TEXT_ORIGIN" "$DEBUG_MUL_BITS" "$DEBUG_ADD_BITS" \
"$DEBUG_PTR_BITS" "$DEBUG_START_BITS" "$MUL_SIZE" "$ADD_SIZE" \
"$PTR_SIZE" <<'PY' \
|| fail "DWARF subprograms/line rows are wrong"
import re
import sys
info_path, line_path = sys.argv[1], sys.argv[2]
text_origin_bits = int(sys.argv[3])
mul_bits = int(sys.argv[4])
add_bits = int(sys.argv[5])
ptr_bits = int(sys.argv[6])
start_bits = int(sys.argv[7])
mul_size = int(sys.argv[8])
add_size = int(sys.argv[9])
ptr_size = int(sys.argv[10])
# DWARF addresses are bytes; COFF symbol values are bits. The linked low PC is
# the text origin in bytes plus the function's bit offset / 8 (exactly once).
text_origin = text_origin_bits // 8
mul_low = text_origin + (mul_bits - text_origin_bits) // 8
add_low = text_origin + (add_bits - text_origin_bits) // 8
ptr_low = text_origin + (ptr_bits - text_origin_bits) // 8
start_low = text_origin + (start_bits - text_origin_bits) // 8
if text_origin != 0x314000:
sys.exit("text origin byte address %#x, want 0x314000" % text_origin)
subs = []
cu = {"name": None, "low": None, "high": None, "high_form": None,
"line": None}
cur = None
mode = None
for raw in open(info_path, encoding="latin1"):
line = raw.rstrip("\n")
if "DW_TAG_compile_unit" in line:
mode = "cu"
cur = cu
continue
if "DW_TAG_subprogram" in line:
cur = {"name": None, "low": None, "high": None, "high_form": None,
"line": None}
subs.append(cur)
mode = "sub"
continue
if "DW_TAG_" in line:
mode = None
continue
if mode is None or cur is None:
continue
m = re.search(r"DW_AT_low_pc.*address = 0x([0-9a-fA-F]+)", line)
if m:
cur["low"] = int(m.group(1), 16)
continue
m = re.search(r"DW_AT_high_pc \[([A-Za-z0-9_]+)\]\s+\(0x([0-9a-fA-F]+)\)", line)
if m:
cur["high_form"] = m.group(1)
cur["high"] = int(m.group(2), 16)
continue
m = re.search(r'DW_AT_name.*string = "([^"]+)"', line)
if m:
cur["name"] = m.group(1)
continue
m = re.search(r"DW_AT_decl_line \[[A-Za-z0-9_]+\]\s+\((\d+)\)", line)
if m:
cur["line"] = int(m.group(1))
continue
if cu["name"] != "debug.c":
sys.exit("compile unit name %r, want debug.c" % cu["name"])
if cu["low"] != text_origin:
sys.exit("compile unit low_pc %#x, want text origin %#x"
% (cu["low"], text_origin))
cu_size = (start_bits - text_origin_bits) // 8
if cu["high_form"] != "DW_FORM_data4" or cu["high"] != cu_size:
sys.exit("compile unit high_pc %r/%#x, want DW_FORM_data4/%#x"
% (cu["high_form"], cu["high"], cu_size))
by_name = {s["name"]: s for s in subs if s["name"]}
for name, low, size, decl in (
("debug_mul", mul_low, mul_size, 1),
("debug_add", add_low, add_size, 6),
("debug_ptr", ptr_low, ptr_size, 14)):
if name not in by_name:
sys.exit("no DW_TAG_subprogram named %s (saw %r)"
% (name, sorted(by_name)))
s = by_name[name]
if s["low"] != low:
sys.exit("%s low_pc %#x, want %#x (text %#x + offset %#x)"
% (name, s["low"], low, text_origin, low - text_origin))
if s["high_form"] != "DW_FORM_data4":
sys.exit("%s high_pc form %r, want DW_FORM_data4"
% (name, s["high_form"]))
if s["high"] != size:
sys.exit("%s high_pc field %#x, want byte size %#x (not divided)"
% (name, s["high"], size))
if s["line"] != decl:
sys.exit("%s DW_AT_decl_line %r, want %d" % (name, s["line"], decl))
# Line rows: a row at each function low PC with the declaration line, plus a
# body row for the first local-variable/pointer-update line.
rows = {}
files = {}
for raw in open(line_path, encoding="latin1"):
m = re.match(r"^(0x[0-9a-fA-F]+)\s+(\d+)\s+(\d+)\s+(\d+)\s",
raw.strip() + " ")
if m:
rows[int(m.group(1), 16)] = int(m.group(2))
files[int(m.group(1), 16)] = int(m.group(4))
if rows.get(mul_low) != 1:
sys.exit("no .debug_line row at debug_mul %#x with line 1 (rows %r)"
% (mul_low, rows))
if rows.get(add_low) != 6:
sys.exit("no .debug_line row at debug_add %#x with line 6 (rows %r)"
% (add_low, rows))
if rows.get(ptr_low) != 15:
sys.exit("no .debug_line row at debug_ptr %#x with line 15 (rows %r)"
% (ptr_low, rows))
for label, low in (("debug_mul", mul_low), ("debug_add", add_low),
("debug_ptr", ptr_low)):
if files.get(low) != 0:
sys.exit("%s .debug_line file index %r, want 0"
% (label, files.get(low)))
def has_line(lo, hi, want):
return any(lo <= a < hi and line == want for a, line in rows.items())
if not has_line(mul_low, add_low, 2):
sys.exit("no line-2 row inside debug_mul")
if not has_line(add_low, ptr_low, 7):
sys.exit("no line-7 row inside debug_add")
if not has_line(ptr_low, start_low, 16):
sys.exit("no line-16 pointer-update row inside debug_ptr")
print(" compile unit: %s low=%#x high=%#x (%d B)"
% (cu["name"], cu["low"], cu["high"], cu["high"]))
print(" subprograms: " + ", ".join(
"%s low=%#x high=%#x (%d B) line=%d"
% (s["name"], s["low"], s["high"], s["high"], s["line"])
for s in subs if s["name"] in ("debug_mul", "debug_add", "debug_ptr")))
print(" line rows: debug_mul@%#x=1 (body 2), debug_add@%#x=6 (body 7), "
"debug_ptr@%#x=15 (pointer update 16)"
% (mul_low, add_low, ptr_low))
PY
echo "== run the stripped image in MAME"
cat > "$WORK/debug-check.lua" <<'LUA'
dofile(os.getenv("M4_LOADER_LUA"))
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local mul = prog:read_u32(0x018A8000)
local add = prog:read_u32(0x018A8020)
local ptr = prog:read_u32(0x018A8040)
print(string.format("DEBUG: mul=%d add=%d ptr=%d", mul, add, ptr))
if mul == 43 and add == 14 and ptr == 30 then
print("DEBUG MAME: PASS")
else
print("DEBUG MAME: FAIL (want mul=43 add=14 ptr=30)")
end
end
end, "debug-check")
LUA
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$WORK/debug-strip.coff" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$WORK/debug-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; \
fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^DEBUG: mul=43 add=14 ptr=30$' "$WORK/mame.log" \
|| { grep '^DEBUG:' "$WORK/mame.log" >&2 || true; \
fail "debug markers are wrong"; }
grep -q '^DEBUG MAME: PASS$' "$WORK/mame.log" \
|| fail "MAME marker check failed"
echo "M7 debug: PASS (barrier-rewritten pointer TU at -O0 and -O2, DWARF"
echo " filename/line/low/high/strings, indexed .debug_addr,"
echo " stripped load image runs in MAME)"
+390
View File
@@ -0,0 +1,390 @@
# M8.4 full-suite report
# generated: 2026-11-16T17:41:34Z
# work: build/m8-bare-full
# settings: -O0, bare conformance (2ine+tms-link) with a full-loader list; LOADER_AT=200, LOADER_END=1000 (default), per-test MAME timeout=120s, outer wall=210s
# full-loader list: /home/arti/code/tms-c-compiler/scripts/tests/m7/full-suite.full-loader
# loader-end overrides: /home/arti/code/tms-c-compiler/scripts/tests/m7/full-suite.loader-end (4 rows)
# c-torture: /home/arti/code/tms-c-compiler/vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute (1692 files)
# c-testsuite: /home/arti/code/tms-c-compiler/vendor/conformance/c-testsuite/tests/single-exec (220 files)
# compiler: rev=774df1e6941f583822e09291c8becf73bada4005 bin=13cfe98909313a71 loader=200/1000
# dialect: explicit dg -std= wins; otherwise -std=gnu89 only for full-suite.gnu89 names; c-testsuite default
# results: build/m8-bare-full/full-suite-results.tsv
# accounting: every row has 5 fields, a legal result and a pinned name; no duplicate ids
#
# corpus total pass skip fail crash corpus_files remaining
c-torture 1692 1386 306 0 0 1692 0
c-testsuite 220 210 10 0 0 220 0
all 1912 1596 316 0 0 1912 0
# fail categories (per selected corpus)
# c-torture
# c-testsuite
# skip categories (per selected corpus)
# c-torture
abi-byval 1
abi-float-args 4
abi-indirect-call 2
abi-return 10
abi-sret 9
abi-varargs-return 3
builtin 11
codegen 2
codegen-float 2
compile 8
compiler-crash 6
corpus 5
data-init 14
data-odd-pointer 1
data-vector 5
extension 1
file-io 18
float-constant 1
inline-asm 33
int128 15
libc 1
memory 15
nested-function 30
output 1
runtime-abort 14
runtime-abort-alignment 2
runtime-abort-bitfield 9
runtime-abort-float 5
runtime-abort-i64 10
runtime-abort-varargs 6
runtime-abort-vector 3
runtime-bitfield 2
setjmp 6
signal 4
timeout 20
vector 2
vla 9
wide-char 16
# c-testsuite
file-io 3
format-unsupported 1
libm 1
timeout 1
wide-char 4
# non-pass rows (all selected corpora)
# corpus test result seconds
c-testsuite 00040 skip:timeout: did not finish within LOADER_END=1000 0
c-testsuite 00098 skip:wide-char: wide characters are unsupported 0
c-testsuite 00174 skip:libm: sin/float formatting differs from the expected libm output 0
c-testsuite 00179 skip:wide-char: wide characters are unsupported 0
c-testsuite 00182 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-testsuite 00187 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-testsuite 00189 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-testsuite 00204 skip:format-unsupported: printf %n, positional $, %e/%g/%a/%F, %j, long-double %L/%F and wide %ls/%lc are not implemented by the shim 0
c-testsuite 00208 skip:wide-char: wide characters are unsupported 0
c-testsuite 00220 skip:wide-char: wide characters are unsupported 0
c-torture 20000822-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20001009-2 skip:inline-asm: could not allocate input reg for constraint 'r' at line 105 0
c-torture 20001111-1 skip:builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration] 0
c-torture 20001124-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture 20010122-1 skip:compiler-crash: unexpected TMS34010 custom lowering operation (return address) 0
c-torture 20010209-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20010325-1 skip:wide-char: wide characters are unsupported 0
c-torture 20010605-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20010605-2 skip:libc: call to undeclared function 'exit'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration] 0
c-torture 20010904-1 skip:runtime-abort-alignment: test abort (status 0x86) 0
c-torture 20010904-2 skip:runtime-abort-alignment: test abort (status 0x86) 0
c-torture 20010924-1 skip:data-odd-pointer: pointer field at an odd .data byte offset 0
c-torture 20011008-3 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture 20020107-1 skip:inline-asm: could not allocate output register for constraint 'r' at line 336 0
c-torture 20020108-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture 20020314-1 skip:compile: incompatible integer to pointer conversion assigning to 'void *' from 'int' [-Wint-conversion] 0
c-torture 20020411-1 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture 20020412-1 skip:vla: variable-length array in a struct is unsupported 0
c-torture 20020418-1 skip:abi-indirect-call: indirect call through a non-function value 0
c-torture 20021010-2 skip:data-init: unsupported .data initializer 0
c-torture 20021127-1 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture 20030120-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture 20030209-1 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture 20030222-1 skip:inline-asm: could not allocate output register for constraint 'r' at line 495 0
c-torture 20030323-1 skip:compiler-crash: unexpected TMS34010 custom lowering operation 0
c-torture 20030501-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20030811-1 skip:compiler-crash: unexpected TMS34010 custom lowering operation 0
c-torture 20031003-1 skip:runtime-abort-float: test abort (status 0x86) 0
c-torture 20040223-1 skip:compile: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Wint-conversion] 0
c-torture 20040302-1 skip:data-init: unsupported .data initializer 0
c-torture 20040308-1 skip:vla: variable-length array in a struct is unsupported 0
c-torture 20040423-1 skip:vla: variable-length array in a struct is unsupported 0
c-torture 20040520-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20040709-1 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture 20040709-2 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture 20040709-3 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture 20041214-1 skip:data-init: unsupported .data initializer 0
c-torture 20041218-2 skip:vla: variable-length array in a struct is unsupported 0
c-torture 20050121-1 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture 20050316-1 skip:abi-float-args: float/double arguments are unsupported 0
c-torture 20050316-2 skip:abi-float-args: float/double arguments are unsupported 0
c-torture 20050316-3 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture 20050604-1 skip:runtime-abort-float: test abort (status 0x86) 0
c-torture 20050607-1 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture 20051012-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture 20060420-1 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture 20061220-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20070614-1 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture 20070824-1 skip:compiler-crash: dynamic alloca size scaling assertion 0
c-torture 20070919-1 skip:vla: variable-length array in a struct is unsupported 0
c-torture 20071210-1 skip:data-init: unsupported .data initializer 0
c-torture 20071220-1 skip:data-init: unsupported .data initializer 0
c-torture 20071220-2 skip:data-init: unsupported .data initializer 0
c-torture 20080502-1 skip:runtime-abort-float: test abort (status 0x86) 0
c-torture 20090219-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 20101011-1 skip:signal: signals are unavailable under the bare loader 0
c-torture 20111208-1 skip:wide-char: wide characters are unsupported 0
c-torture 20180921-1 skip:compile: chained comparison 'X < Y <= Z' does not behave the same as a mathematical expression [-Wparentheses] 0
c-torture 20210505-1 skip:setjmp: setjmp/longjmp need non-local jumps, which are unsupported 0
c-torture 20230630-1 skip:runtime-abort: test abort (status 0x86) 0
c-torture 20230630-3 skip:runtime-abort: test abort (status 0x86) 0
c-torture 20241029-1 skip:builtin: use of unknown builtin '__builtin_puts' [-Wimplicit-function-declaration] 0
c-torture 920302-1 skip:compile: incompatible pointer types passing 'short (*)[5]' to parameter of type 'short *' [-Wincompatible-pointer-types] 0
c-torture 920415-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 920428-1 skip:runtime-abort: test abort (status 0x86) 0
c-torture 920428-2 skip:nested-function: nested function definitions are unsupported 0
c-torture 920501-3 skip:codegen: t24: i32 = BlockAddress<@execute, %base> 0 0
c-torture 920501-4 skip:data-init: unsupported .data initializer 0
c-torture 920501-5 skip:data-init: unsupported .data initializer 0
c-torture 920501-7 skip:nested-function: nested function definitions are unsupported 0
c-torture 920612-2 skip:nested-function: nested function definitions are unsupported 0
c-torture 920625-1 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture 920721-4 skip:nested-function: nested function definitions are unsupported 0
c-torture 920726-1 skip:abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported 0
c-torture 920728-1 skip:compile: non-void function 'f' should return a value [-Wreturn-mismatch] 0
c-torture 920908-1 skip:signal: signals are unavailable under the bare loader 0
c-torture 920929-1 skip:signal: signals are unavailable under the bare loader 0
c-torture 921006-1 skip:signal: signals are unavailable under the bare loader 0
c-torture 921017-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 921208-2 skip:timeout: did not finish within LOADER_END=1000 0
c-torture 921215-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 930622-2 skip:codegen-float: only 32-bit integer sources are supported for float/double conversions 0
c-torture 931002-1 skip:nested-function: nested function definitions are unsupported 0
c-torture 931004-10 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-12 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-14 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-2 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-4 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-6 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 931004-8 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture 941202-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture 960312-1 skip:inline-asm: could not allocate input reg for constraint 'r' at line 218 0
c-torture 960512-1 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture 960521-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture 970214-1 skip:wide-char: wide characters are unsupported 0
c-torture 970214-2 skip:wide-char: wide characters are unsupported 0
c-torture 980709-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture 990130-1 skip:inline-asm: could not allocate output register for constraint 'r' at line 152 0
c-torture 990208-1 skip:codegen: t5: i32 = BlockAddress<@doit, %here> 0 0
c-torture 990413-2 skip:inline-asm: invalid output constraint '=t' 0
c-torture 991112-1 skip:runtime-abort: test abort (status 0x86) 0
c-torture align-nest skip:vla: variable-length array in a struct is unsupported 0
c-torture arith-rand-ll skip:timeout: did not finish within LOADER_END=1000 0
c-torture bitfld-3 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture bitfld-5 skip:runtime-abort-bitfield: test abort (status 0x86) 0
c-torture bitfld-6 skip:runtime-bitfield: wrong bitfield result (status 0x33333) 0
c-torture bitfld-7 skip:runtime-bitfield: wrong bitfield result (status 0x222222) 0
c-torture bswap-2 skip:timeout: did not finish within LOADER_END=1000 0
c-torture built-in-setjmp skip:setjmp: __builtin_longjmp is unsupported 0
c-torture builtin-prefetch-2 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture cmpsf-1 skip:float-constant: out-of-range constant in the GSP floating-point format 0
c-torture comp-goto-1 skip:data-init: unsupported .data initializer 0
c-torture comp-goto-2 skip:nested-function: nested function definitions are unsupported 0
c-torture complex-1 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture complex-2 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture complex-5 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture complex-6 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture conversion skip:codegen-float: only 32-bit integer sources are supported for float/double conversions 0
c-torture eeprof-1 skip:runtime-abort: test abort (status 0x86) 0
c-torture floatunsisf-1 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture fprintf-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture fprintf-2 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture fprintf-chk-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture frame-address skip:compiler-crash: unexpected TMS34010 custom lowering operation (frame address) 0
c-torture gofast skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture loop-2f skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 1
c-torture loop-2g skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture memchr-1 skip:wide-char: wide characters are unsupported 0
c-torture memclr skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture memcpy-1 skip:output: test writes more than the 16 KiB shim cap 0
c-torture memcpy-a1 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture memcpy-a2 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture memcpy-a4 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture memcpy-a8 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture nest-align-1 skip:nested-function: nested function definitions are unsupported 0
c-torture nest-stdar-1 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-1 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-2 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-3 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-5 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-6 skip:nested-function: nested function definitions are unsupported 0
c-torture nestfunc-7 skip:nested-function: nested function definitions are unsupported 0
c-torture pr103052 skip:builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration] 0
c-torture pr103255 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr103376 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr103405 skip:nested-function: nested function definitions are unsupported 0
c-torture pr105613 skip:int128: 128-bit integers are unsupported 0
c-torture pr105777 skip:corpus: references a gcc.dg source absent from the pinned execute tree 0
c-torture pr105984 skip:builtin: use of unknown builtin '__builtin_mul_overflow_p' [-Wimplicit-function-declaration] 0
c-torture pr107881-1 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture pr108292 skip:vector: address of vector element requested 0
c-torture pr108498-1 skip:inline-asm: could not allocate input reg for constraint 'r' at line 1233 0
c-torture pr109040 skip:abi-float-args: float/double arguments are unsupported 0
c-torture pr109938 skip:corpus: references a gcc.dg source absent from the pinned execute tree 0
c-torture pr109986 skip:corpus: references a gcc.dg source absent from the pinned execute tree 0
c-torture pr110252-2 skip:inline-asm: could not allocate output register for constraint 'r' at line 155 0
c-torture pr111469-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture pr114396 skip:wide-char: wide characters are unsupported 0
c-torture pr115033 skip:builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration] 0
c-torture pr117095 skip:int128: 128-bit integers are unsupported 0
c-torture pr117432 skip:compile: ISO C requires a named parameter before '...' 0
c-torture pr122943 skip:int128: 128-bit integers are unsupported 0
c-torture pr123625 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr123625-2 skip:data-vector: vector constants in .data are unsupported 0
c-torture pr123753 skip:vector: cannot decrement a vector value 0
c-torture pr123864 skip:builtin: use of unknown builtin '__builtin_mul_overflow_p' [-Wimplicit-function-declaration] 0
c-torture pr125291 skip:abi-indirect-call: indirect call through a non-function value 0
c-torture pr126405-3 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr17252 skip:timeout: did not finish within LOADER_END=1000 0
c-torture pr17377 skip:compiler-crash: unexpected TMS34010 custom lowering operation 0
c-torture pr20527-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture pr20621-1 skip:timeout: compilation did not finish within the 210s outer wall 0
c-torture pr22061-1 skip:compile: incompatible integer to pointer conversion assigning to 'void *' from 'int' [-Wint-conversion] 0
c-torture pr22061-3 skip:nested-function: nested function definitions are unsupported 0
c-torture pr22061-4 skip:nested-function: nested function definitions are unsupported 0
c-torture pr23135 skip:data-vector: vector constants in .data are unsupported 0
c-torture pr23324 skip:data-init: unsupported .data initializer 0
c-torture pr24135 skip:nested-function: nested function definitions are unsupported 0
c-torture pr28865 skip:vla: variable-length array in a struct is unsupported 0
c-torture pr28982b skip:timeout: compilation did not finish within the 210s outer wall 0
c-torture pr30314 skip:corpus: references a gcc.dg source absent from the pinned execute tree 0
c-torture pr32244-1 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr34456 skip:timeout: did not finish within LOADER_END=1000 0
c-torture pr34971 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr35456 skip:runtime-abort-float: test abort (status 0x86) 0
c-torture pr35800 skip:wide-char: wide characters are unsupported 0
c-torture pr38051 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr38151 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture pr38533 skip:inline-asm: could not allocate output register for constraint 'r' at line 2147513642 0
c-torture pr38969 skip:abi-sret: aggregate return via an sret pointer is unsupported 0
c-torture pr39228 skip:builtin: use of unknown builtin '__builtin_isinff' [-Wimplicit-function-declaration] 0
c-torture pr40022 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr40657 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr41239 skip:setjmp: setjmp/longjmp need non-local jumps, which are unsupported 0
c-torture pr41935 skip:vla: variable-length array in a struct is unsupported 0
c-torture pr43385 skip:inline-asm: could not allocate output register for constraint 'r' at line 328 0
c-torture pr43560 skip:inline-asm: could not allocate output register for constraint 'r' at line 298 0
c-torture pr43987 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture pr44575 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture pr44683 skip:runtime-abort-float: test abort (status 0x86) 0
c-torture pr45695 skip:inline-asm: could not allocate output register for constraint 'r' at line 121 0
c-torture pr47237 skip:builtin: use of unknown builtin '__builtin_apply' [-Wimplicit-function-declaration] 0
c-torture pr49218 skip:int128: 128-bit integers are unsupported 0
c-torture pr49279 skip:inline-asm: could not allocate output register for constraint 'r' at line 199 0
c-torture pr49390 skip:inline-asm: could not allocate output register for constraint 'r' at line 1508 0
c-torture pr51447 skip:nested-function: nested function definitions are unsupported 0
c-torture pr51581-1 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture pr51581-2 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture pr52286 skip:inline-asm: could not allocate output register for constraint 'r' at line 119 0
c-torture pr53645 skip:data-init: unsupported .data initializer 0
c-torture pr53645-2 skip:data-init: unsupported .data initializer 0
c-torture pr54471 skip:int128: 128-bit integers are unsupported 0
c-torture pr56866 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr56982 skip:setjmp: setjmp/longjmp need non-local jumps, which are unsupported 0
c-torture pr57344-3 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr57344-4 skip:runtime-abort-i64: test abort (status 0x86) 0
c-torture pr58209 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr58574 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture pr60003 skip:compile: incompatible pointer types passing 'unsigned long long (*)[5]' to parameter of type 'void **' [-Wincompatible-pointer-types] 0
c-torture pr60822 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture pr60960 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr61375 skip:int128: 128-bit integers are unsupported 0
c-torture pr63302 skip:int128: 128-bit integers are unsupported 0
c-torture pr63843 skip:timeout: codegen fixed at the M7.4 pin; already compiled at the M8 base and hangs identically (status 1, no completion magic) 0
c-torture pr64242 skip:setjmp: __builtin_longjmp is unsupported 0
c-torture pr65053-1 skip:inline-asm: could not allocate output register for constraint 'r' at line 281 0
c-torture pr65053-2 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr65170 skip:int128: 128-bit integers are unsupported 0
c-torture pr65401 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr65427 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr65648 skip:inline-asm: could not allocate input reg for constraint 'r' at line 225 0
c-torture pr65956 skip:inline-asm: could not allocate output register for constraint 'r' at line 285 0
c-torture pr67037 skip:timeout: did not finish within LOADER_END=1000 0
c-torture pr68328 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr68390 skip:abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported 0
c-torture pr68532 skip:wide-char: wide characters are unsupported 0
c-torture pr70460 skip:data-init: unsupported .data initializer 0
c-torture pr70566 skip:timeout: did not finish within LOADER_END=1000 0
c-torture pr70903 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr71494 skip:nested-function: nested function definitions are unsupported 0
c-torture pr71626-1 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr71626-2 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr78622 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture pr78791 skip:data-init: unsupported .data initializer 0
c-torture pr79327 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr79737-2 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr80421 skip:inline-asm: could not allocate input reg for constraint 'r' at line 113 0
c-torture pr80692 skip:extension: GNU decimal float type is unsupported 0
c-torture pr81588 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr82210 skip:vla: variable-length array in a struct is unsupported 0
c-torture pr82954 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr84169 skip:int128: 128-bit integers are unsupported 0
c-torture pr84521 skip:setjmp: __builtin_longjmp is unsupported 0
c-torture pr84524 skip:inline-asm: could not allocate output register for constraint 'r' at line 468 0
c-torture pr84748 skip:int128: 128-bit integers are unsupported 0
c-torture pr85156 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr85169 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr85331 skip:builtin: use of unknown builtin '__builtin_shuffle' [-Wimplicit-function-declaration] 0
c-torture pr85582-2 skip:int128: 128-bit integers are unsupported 0
c-torture pr85582-3 skip:int128: 128-bit integers are unsupported 0
c-torture pr85756 skip:inline-asm: could not allocate input reg for constraint 'r' at line 204 0
c-torture pr88693 skip:wide-char: wide characters are unsupported 0
c-torture pr88904 skip:inline-asm: could not allocate output register for constraint 'r' at line 174 0
c-torture pr92618 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr92904 skip:int128: 128-bit integers are unsupported 0
c-torture pr93213 skip:int128: 128-bit integers are unsupported 0
c-torture pr94130 skip:inline-asm: Could not match memory address. Inline asm failure! 0
c-torture pr94412 skip:runtime-abort: test abort (status 0x86) 0
c-torture pr94524-1 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr94524-2 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture pr94591 skip:builtin: use of unknown builtin '__builtin_shuffle' [-Wimplicit-function-declaration] 0
c-torture pr98304-2 skip:corpus: references a gcc.dg source absent from the pinned execute tree 0
c-torture pr98474 skip:int128: 128-bit integers are unsupported 0
c-torture printf-2 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture printf-chk-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture ptr-arith-1 skip:wide-char: wide characters are unsupported 0
c-torture scal-to-vec1 skip:runtime-abort-vector: test abort (status 0x86) 0
c-torture scal-to-vec2 skip:runtime-abort-vector: test abort (status 0x86) 0
c-torture scal-to-vec3 skip:runtime-abort-vector: test abort (status 0x86) 0
c-torture simd-1 skip:data-vector: vector constants in .data are unsupported 0
c-torture simd-2 skip:data-vector: vector constants in .data are unsupported 0
c-torture simd-4 skip:abi-float-args: float/double arguments are unsupported 0
c-torture simd-5 skip:data-vector: vector constants in .data are unsupported 0
c-torture simd-6 skip:abi-return: unsupported aggregate/variadic return shape 0
c-torture stdarg-3 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture stkalign skip:inline-asm: could not allocate output register for constraint 'r' at line 344 0
c-torture strct-stdarg-1 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture strct-varg-1 skip:runtime-abort-varargs: test abort (status 0x86) 0
c-torture string-opt-18 skip:timeout: did not finish within LOADER_END=1000 0
c-torture string-opt-5 skip:wide-char: wide characters are unsupported 0
c-torture strlen-5 skip:memory: linked image exceeds the 45 KiB program / 64 KiB RAM region 0
c-torture strncmp-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture struct-ret-1 skip:wide-char: wide characters are unsupported 0
c-torture user-printf skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture va-arg-21 skip:timeout: did not finish within LOADER_END=1000 0
c-torture va-arg-22 skip:abi-byval: byval argument has zero size 0
c-torture va-arg-26 skip:abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported 0
c-torture va-arg-pack-1 skip:builtin: use of unknown builtin '__builtin_va_arg_pack' [-Wimplicit-function-declaration] 0
c-torture vfprintf-chk-1 skip:file-io: stdio/POSIX file I/O is unavailable under the bare loader 0
c-torture vprintf-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture vprintf-chk-1 skip:timeout: did not finish within LOADER_END=1000 0
c-torture wchar_t-1 skip:wide-char: wide characters are unsupported 0
c-torture widechar-1 skip:wide-char: wide characters are unsupported 0
c-torture widechar-2 skip:wide-char: wide characters are unsupported 0
c-torture widechar-3 skip:wide-char: wide characters are unsupported 0
c-torture zerolen-2 skip:runtime-abort: test abort (status 0x86) 0
# resume
scripts/tests/m7/full-suite.sh --corpus all --work build/m8-bare-full
+20
View File
@@ -0,0 +1,20 @@
# Tests that need the full VT1200 loader tier.
#
# The conformance driver runs the corpus bare-metal (map sections, zero .bss,
# set PC/SP, no firmware boot). A few tests are unstable in that tier or rely
# on the GSPLNK/loader behavior, but pass through the real loader. They are
# listed here explicitly, with a reason and the linker tier, so only these
# boot the full ROM.
#
# name<TAB>reason<TAB>linker (os2|1987; default os2)
20141125-1 bare-mame: MAME host segfault in the bare tier; full loader passes os2
20230630-2 bare-mame: MAME host segfault in the bare tier; full loader passes os2
float-floor bare-mame: MAME host segfault in the bare tier; full loader passes os2
medce-1 linker: 5.01 gsplnk leaves _link_error undefined; 1987 GSPLNK passes 1987
multi-ix bare-mame: MAME did not exit after the result; full loader passes os2
pr44828 bare-mame: MAME host segfault in the bare tier; full loader passes os2
pr70005 bare-mame: MAME host segfault in the bare tier; full loader passes os2
pr79286 linker: tms-link rejects a negative relocation; 2ine GSPLNK passes os2
pr93945 bare-mame: MAME host segfault in the bare tier; full loader passes os2
strlen-3 bare-mame: MAME host segfault in the bare tier; full loader passes os2
+73
View File
@@ -0,0 +1,73 @@
# c-torture files with no explicit -std= directive that reject the
# compiler default (gnu17) with implicit-int/implicit-declaration diagnostics.
# The full-suite driver applies -std=gnu89 only to these names; every other
# c-torture file keeps the compiler default (or its explicit dg -std=).
#
20000412-3
20001111-1
20010209-1
20010605-1
20020314-1
20020819-1
20030501-1
20031211-2
20040223-1
20040520-1
20041019-1
20061220-1
20090219-1
20120427-1
20120427-2
20241029-1
920612-2
920721-4
920908-2
921110-1
930111-1
930208-1
930702-1
930818-1
931002-1
931017-1
931018-1
931208-1
941101-1
941110-1
950322-1
950426-1
950512-1
950621-1
960218-1
960402-1
cmpsf-1
cmpsi-1
cmpsi-2
divmod-1
fprintf-2
nest-align-1
nest-stdar-1
nestfunc-7
pr103052
pr103405
pr105984
pr115033
pr123864
pr22061-1
pr22061-3
pr22061-4
pr24135
pr34456
pr39228
pr47237
pr51447
pr55875
pr71494
pr85331
pr94591
printf-2
printf-chk-1
user-printf
va-arg-21
va-arg-pack-1
vprintf-1
vprintf-chk-1
+16
View File
@@ -0,0 +1,16 @@
# M8.3 per-test full-suite loader budgets.
#
# Rows are <corpus>/<test><TAB><LOADER_END>. The shipped default remains
# LOADER_END=1000; a row here only sets the budget for a test whose
# corrected/fixed workload is frame-limited at the default, not wrong or
# hung. A row may be below an explicit larger global LOADER_END. The M8.3
# rerun with LOADER_END=2000 flipped exactly these four rows to pass; every
# other runtime timeout in full-suite.skip still timed out at 2000 (and the
# two compile-time timeouts are unrelated to the loader).
#
# Keep this list tied to the same pinned tree as full-suite.skip.
#
c-torture/20040811-1 2000
c-torture/pr43220 2000
c-torture/strcmp-1 2000
c-torture/vla-dealloc-1 2000
+890
View File
@@ -0,0 +1,890 @@
#!/bin/sh
# M7.4 full-suite conformance driver (standalone, serial).
#
# scripts/tests/m7/full-suite.sh [options]
#
# Runs every *.c in the pinned corpora through the M5 conformance runner with
# the fast native loader settings:
#
# c-torture vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute
# (1,692 files, --classify --mode native --expect-status 0
# --ignore-output)
# c-testsuite vendor/conformance/c-testsuite/tests/single-exec
# (220 files, --classify --mode native --expect-status 0
# --expect-output-file <name>.c.expected)
#
# Both corpora run at -O0 with LOADER_AT=200 LOADER_END=1000. The shipped
# conformance gates keep their own defaults; this driver only sets the
# environment for its own child runs.
#
# Every file produces exactly one result row:
#
# pass
# skip:<reason> classifier or full-suite.skip curation
# fail:<category> compile | diagnostic | loader | status | output |
# timeout | crash | harness | unclassified
#
# A failure is never counted as a pass and a crash is never hidden. The
# driver writes:
#
# <work>/full-suite-results.tsv corpus<TAB>name<TAB>result<TAB>seconds<TAB>detail
# <work>/full-suite-report.txt retained summary and non-pass rows
# <work>/logs/<corpus>/<name>.log per-test runner log
# <work>/logs/<corpus>/<name>.rc per-test runner exit status
# <work>/run/<corpus>_<name>/ per-test compile/link/MAME work
#
# Rows already present in full-suite-results.tsv are skipped, so an interrupted
# run resumes per id. Use --redo to re-run recorded ids. The work directory
# records the clang/llc binary hash and source revision; a resume with a
# different compiler is refused (use a new --work or --record-compiler after an
# intentional pin).
#
# Exit status: 0 when every attempted file got a classified result and no
# crash/unclassified/harness failure occurred; 1 on a crash, an unclassified
# failure, a harness failure, an invalid results row/accounting, or bad usage.
# Ordinary fail:<compile|loader|status|output|timeout> rows are data for Task 3
# triage and do not fail the driver.
#
# --corpus c-torture|c-testsuite|all corpus selection (default: all)
# --jobs 1 only 1 is supported (MAME is serial)
# --prefix N consider only the first N sorted
# names of each selected corpus
# --limit N attempt at most N unrecorded tests
# --list FILE only names/paths in FILE (sample use)
# --redo re-run ids already in the results
# --record-compiler record the current compiler pin when
# the work directory has no sidecar
# --work DIR work/results directory
# --report FILE report path (default <work>/...)
# --results FILE results path (default <work>/...)
# --timeout SEC per-test MAME timeout (default 120;
# the outer wall bound is +90 s)
# -h, --help this help (exit 0)
#
# A per-test loader budget can be listed in full-suite.loader-end
# (<corpus>/<test><TAB><LOADER_END>). The shipped default stays 1000; the file
# only widens tests whose fixed workload is frame-limited rather than wrong.
#
# Overridable: M7_FULL_SUITE_WORK M7_FULL_SUITE_TIMEOUT M7_FULL_SUITE_LOADER_END
# C_TORTURE_DIR C_TESTSUITE_DIR M5_CONFORMANCE_DIR
# LLVM_BIN TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME
# MAME_TIMEOUT (per test) LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$ROOT/scripts/tests/m5/conformance}
RUN=$CONFORMANCE_DIR/run.sh
CLASSIFY=$CONFORMANCE_DIR/classify.sh
C_TORTURE_DIR=${C_TORTURE_DIR:-$ROOT/vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute}
C_TESTSUITE_DIR=${C_TESTSUITE_DIR:-$ROOT/vendor/conformance/c-testsuite/tests/single-exec}
SKIP_FILE=${M7_FULL_SUITE_SKIP:-$HERE/full-suite.skip}
DIALECT_FILE=${M7_FULL_SUITE_DIALECT:-$HERE/full-suite.gnu89}
FULL_LOADER_FILE=${M7_FULL_SUITE_FULL_LOADER:-$HERE/full-suite.full-loader}
LOADER_FILE=${M7_FULL_SUITE_LOADER_END:-$HERE/full-suite.loader-end}
C_TORTURE_EXPECTED=1692
C_TESTSUITE_EXPECTED=220
LOADER_AT=${LOADER_AT:-200}
LOADER_END=${LOADER_END:-1000}
TIME_LIMIT=${M7_FULL_SUITE_TIMEOUT:-120}
WORK=${M7_FULL_SUITE_WORK:-$ROOT/build/m7-full-suite}
JOBS=1
CORPUS_SELECT=all
PREFIX=0
LIMIT=0
LIST_FILE=
REDO=0
RECORD_COMPILER=0
REPORT=
RESULTS=
fail() {
echo "full-suite: FAIL: $*" >&2
exit 1
}
usage() {
sed -n '2,/^set -eu/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//' >&2
exit "${1:-1}"
}
case $TIME_LIMIT in
''|*[!0-9]*) fail "timeout must be a positive integer: '$TIME_LIMIT'" ;;
esac
[ "$TIME_LIMIT" -gt 0 ] || fail "timeout must be a positive integer: '$TIME_LIMIT'"
while [ $# -gt 0 ]; do
case $1 in
--corpus)
[ $# -ge 2 ] || usage
CORPUS_SELECT=$2
shift 2
;;
--jobs)
[ $# -ge 2 ] || usage
JOBS=$2
shift 2
;;
--prefix)
[ $# -ge 2 ] || usage
PREFIX=$2
shift 2
;;
--limit)
[ $# -ge 2 ] || usage
LIMIT=$2
shift 2
;;
--list)
[ $# -ge 2 ] || usage
LIST_FILE=$2
shift 2
;;
--redo)
REDO=1
shift
;;
--record-compiler)
RECORD_COMPILER=1
shift
;;
--work)
[ $# -ge 2 ] || usage
WORK=$2
shift 2
;;
--report)
[ $# -ge 2 ] || usage
REPORT=$2
shift 2
;;
--results)
[ $# -ge 2 ] || usage
RESULTS=$2
shift 2
;;
--timeout)
[ $# -ge 2 ] || usage
TIME_LIMIT=$2
shift 2
;;
-h|--help)
usage 0
;;
*)
echo "full-suite: unknown option: $1" >&2
usage
;;
esac
done
case $JOBS in
1) ;;
*) fail "--jobs $JOBS is unsupported: the corpora run serially (MAME and the shared SDK are not parallel-safe)" ;;
esac
case $CORPUS_SELECT in
c-torture|c-testsuite|all) ;;
*) fail "bad --corpus '$CORPUS_SELECT' (want c-torture, c-testsuite or all)" ;;
esac
case $PREFIX in
''|*[!0-9]*) fail "--prefix must be a non-negative integer: '$PREFIX'" ;;
esac
case $LIMIT in
''|*[!0-9]*) fail "--limit must be a non-negative integer: '$LIMIT'" ;;
esac
case $TIME_LIMIT in
''|*[!0-9]*) fail "--timeout must be a positive integer: '$TIME_LIMIT'" ;;
esac
[ "$TIME_LIMIT" -gt 0 ] || fail "--timeout must be a positive integer: '$TIME_LIMIT'"
[ -f "$RUN" ] || fail "missing conformance runner: $RUN"
[ -f "$CLASSIFY" ] || fail "missing classifier: $CLASSIFY"
[ -d "$C_TORTURE_DIR" ] || fail "missing pinned c-torture tree: $C_TORTURE_DIR"
[ -d "$C_TESTSUITE_DIR" ] || fail "missing pinned c-testsuite tree: $C_TESTSUITE_DIR"
[ -f "$SKIP_FILE" ] || fail "missing skip file: $SKIP_FILE"
[ -f "$DIALECT_FILE" ] || fail "missing dialect file: $DIALECT_FILE"
[ -z "$LIST_FILE" ] || [ -f "$LIST_FILE" ] || fail "missing --list file: $LIST_FILE"
REPORT=${REPORT:-$WORK/full-suite-report.txt}
RESULTS=${RESULTS:-$WORK/full-suite-results.tsv}
mkdir -p "$WORK/lists" "$WORK/logs" "$WORK/run"
mkdir -p "$(dirname "$RESULTS")" "$(dirname "$REPORT")"
: >> "$RESULTS"
# Compiler provenance: a resumable run must not mix two toolchains. The pin
# combines the compiler source revision, a hash of the actual clang/llc
# binaries (so a snapshot or a rebuilt tree is distinguishable), and the loader
# settings that affect the measured result.
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
CLANG_BIN=${TMS_CLANG:-$LLVM_BIN/clang}
LLC_BIN=${TMS_LLC:-$LLVM_BIN/llc}
compiler_rev=unknown
if command -v git >/dev/null 2>&1 && [ -d "$ROOT/build/llvm-clean/.git" ]; then
compiler_rev=$(git -C "$ROOT/build/llvm-clean" rev-parse HEAD 2>/dev/null) \
|| compiler_rev=unknown
fi
compiler_hash=unknown
if command -v sha256sum >/dev/null 2>&1 \
&& [ -f "$CLANG_BIN" ] && [ -f "$LLC_BIN" ]; then
compiler_hash=$(
{ sha256sum "$CLANG_BIN" "$LLC_BIN" 2>/dev/null || true; } \
| sha256sum | cut -c1-16
)
fi
compiler_id="rev=$compiler_rev bin=$compiler_hash loader=$LOADER_AT/$LOADER_END"
COMPILER_FILE=$WORK/full-suite-compiler.txt
if [ -s "$RESULTS" ]; then
if [ -f "$COMPILER_FILE" ]; then
previous_compiler=$(cat "$COMPILER_FILE")
[ "$previous_compiler" = "$compiler_id" ] \
|| fail "refusing to resume across a compiler/settings change: previous '$previous_compiler', current '$compiler_id' (use a new --work, or --record-compiler only after an intentional re-pin of an empty run)"
elif [ "$RECORD_COMPILER" -eq 1 ]; then
printf '%s\n' "$compiler_id" > "$COMPILER_FILE"
else
fail "results exist without a compiler pin; rerun with --record-compiler to assert the current pin ('$compiler_id') or use a new --work"
fi
else
printf '%s\n' "$compiler_id" > "$COMPILER_FILE"
fi
case $CORPUS_SELECT in
c-torture) CORPORA="c-torture" ;;
c-testsuite) CORPORA="c-testsuite" ;;
all) CORPORA="c-torture c-testsuite" ;;
esac
# Build a sorted name list for a corpus and pin its size. The pinned counts
# make a silently truncated tree or a wrong directory a hard error.
build_list() {
corpus=$1
dir=$2
expected=$3
out=$WORK/lists/$corpus.txt
find "$dir" -maxdepth 1 -type f -name '*.c' -printf '%f\n' \
| sed 's/\.c$//' | LC_ALL=C sort > "$out"
count=$(wc -l < "$out" | tr -d ' ')
[ "$count" -eq "$expected" ] \
|| fail "corpus $corpus has $count files, pinned count is $expected ($dir)"
}
build_list c-torture "$C_TORTURE_DIR" "$C_TORTURE_EXPECTED"
build_list c-testsuite "$C_TESTSUITE_DIR" "$C_TESTSUITE_EXPECTED"
# Validate and flatten the curated skip table. A skip row names a test that
# exists and carries a non-empty reason; stale rows are a hard error so a
# renamed test cannot silently disappear from the accounting.
CURATED=$WORK/lists/curated-skips.tsv
: > "$CURATED"
while IFS= read -r line; do
case $line in
''|\#*) continue ;;
esac
id=${line%% *}
reason=${line#* }
[ "$id" != "$line" ] || fail "malformed skip row (no tab): $line"
[ -n "$reason" ] || fail "skip row has no reason: $id"
case $reason in
*" "*) fail "skip reason contains a tab (TSV would shift): $id" ;;
esac
corpus=${id%%/*}
name=${id#*/}
[ "$corpus" != "$id" ] || fail "malformed skip id (no corpus/name): $id"
case $corpus in
c-torture|c-testsuite) ;;
*) fail "skip row has an unknown corpus: $id" ;;
esac
grep -Fxq "$name" "$WORK/lists/$corpus.txt" \
|| fail "skip row names a missing $corpus test: $id"
if grep -Fq "$id " "$CURATED" 2>/dev/null; then
if grep -Fqx "$id $reason" "$CURATED" 2>/dev/null; then
continue
fi
fail "conflicting skip rows for $id"
fi
printf '%s\t%s\n' "$id" "$reason" >> "$CURATED"
done < "$SKIP_FILE"
# Validate the per-test gnu89 list once; copy it to the work directory so a
# resumed run is auditable even if the source list changes later.
GNU89=$WORK/lists/gnu89.txt
: > "$GNU89"
while IFS= read -r line; do
case $line in
''|\#*) continue ;;
esac
grep -Fxq "$line" "$WORK/lists/c-torture.txt" \
|| fail "gnu89 list names a missing c-torture test: $line"
grep -Fxq "$line" "$GNU89" || printf '%s\n' "$line" >> "$GNU89"
done < "$DIALECT_FILE"
curated_reason() {
# First field is corpus/name; print the rest without the tab.
awk -F '\t' -v id="$1" '$1 == id {
pos = index($0, "\t")
if (pos > 0) print substr($0, pos + 1)
exit
}' "$CURATED"
}
# Validate and flatten the per-test loader-end table. A row names an existing
# test and the budget it was validated at; that budget may be below an explicit
# larger global LOADER_END (the row is applied verbatim). The shipped default
# stays 1000, with a 1000 floor and a 20000 sanity cap for table rows.
LOADER_OVERRIDES=$WORK/lists/loader-end.tsv
: > "$LOADER_OVERRIDES"
if [ -f "$LOADER_FILE" ]; then
while IFS= read -r line; do
case $line in
''|\#*) continue ;;
esac
id=${line%% *}
budget=${line#* }
[ "$id" != "$line" ] || fail "malformed loader-end row (no tab): $line"
case $budget in
''|*[!0-9]*) fail "loader-end budget is not an integer: $line" ;;
esac
# A row may be below an explicit larger global LOADER_END: it is the
# budget the row was validated at. Keep the shipped 1000 floor and a
# sanity cap so a typo cannot turn into a multi-hour run.
[ "$budget" -ge 1000 ] \
|| fail "loader-end budget $budget is below the shipped default 1000: $id"
[ "$budget" -le 20000 ] \
|| fail "loader-end budget $budget is above the sanity cap 20000: $id"
corpus=${id%%/*}
name=${id#*/}
[ "$corpus" != "$id" ] || fail "malformed loader-end id (no corpus/name): $id"
case $corpus in
c-torture|c-testsuite) ;;
*) fail "loader-end row has an unknown corpus: $id" ;;
esac
grep -Fxq "$name" "$WORK/lists/$corpus.txt" \
|| fail "loader-end row names a missing $corpus test: $id"
grep -Fq "$id " "$LOADER_OVERRIDES" 2>/dev/null \
&& fail "duplicate loader-end row for $id"
printf '%s\t%s\n' "$id" "$budget" >> "$LOADER_OVERRIDES"
done < "$LOADER_FILE"
fi
loader_end_for() {
awk -F '\t' -v id="$1" '$1 == id { print $2; exit }' "$LOADER_OVERRIDES"
}
already_recorded() {
awk -F '\t' -v c="$1" -v n="$2" \
'$1 == c && $2 == n { found = 1 } END { exit !found }' "$RESULTS"
}
drop_recorded() {
tmp=$RESULTS.tmp.$$
awk -F '\t' -v c="$1" -v n="$2" '!($1 == c && $2 == n)' "$RESULTS" > "$tmp"
mv "$tmp" "$RESULTS"
}
recorded_result() {
awk -F '\t' -v c="$1" -v n="$2" \
'$1 == c && $2 == n { print $3; exit }' "$RESULTS"
}
# Classify a failed runner log into a stable category. The runner's
# diagnostics are the contract; ordering matters (a status mismatch can also
# mention the work dir, and a loader rejection exits before the compare).
classify_failure() {
log=$1
rc=$2
runwork=$3
# run.sh exits 2 from run_mame when the COFF loader rejects the image, but
# its own set -e can turn that return into a silent process exit without a
# CONFORMANCE: SKIP row. Trust the result block, not the bare status.
if [ -n "$runwork" ] && [ -f "$runwork/result.txt" ] \
&& grep -q '== run the COFF in MAME' "$log" 2>/dev/null; then
loader_hex=$(sed -n 's/^loader=//p' "$runwork/result.txt" \
| tr -d '\r' | head -n 1)
case $loader_hex in
''|00000000) ;;
*)
echo loader
return 0
;;
esac
fi
case $rc in
124|137)
echo timeout
return 0
;;
esac
if grep -q 'MAME exited 124' "$log" 2>/dev/null \
|| grep -q 'timed out' "$log" 2>/dev/null; then
echo timeout
elif grep -q 'no completion magic' "$log" 2>/dev/null; then
echo timeout
elif grep -q 'LLVM ERROR:' "$log" 2>/dev/null \
|| grep -q 'PLEASE submit a bug report' "$log" 2>/dev/null \
|| grep -q 'Stack dump' "$log" 2>/dev/null \
|| grep -q 'Aborted' "$log" 2>/dev/null \
|| grep -q 'Segmentation fault' "$log" 2>/dev/null \
|| grep -q 'Bus error' "$log" 2>/dev/null \
|| grep -q 'Illegal instruction' "$log" 2>/dev/null; then
# A compiler abort or a crashing MAME is not an ordinary compile/
# status failure: it must be counted separately and fail the driver.
echo crash
elif grep -q 'missing tool:' "$log" 2>/dev/null \
|| grep -q 'classifier error' "$log" 2>/dev/null \
|| grep -q 'missing source' "$log" 2>/dev/null \
|| grep -q 'missing expected output' "$log" 2>/dev/null; then
echo harness
elif grep -q 'COFF loader rejected' "$log" 2>/dev/null; then
echo loader
elif grep -q 'output mismatch' "$log" 2>/dev/null \
|| grep -q 'stderr mismatch' "$log" 2>/dev/null \
|| grep -q 'output truncated' "$log" 2>/dev/null \
|| grep -q 'stderr truncated' "$log" 2>/dev/null; then
echo output
elif grep -q 'status mismatch' "$log" 2>/dev/null; then
echo status
elif grep -q 'compile/link failed' "$log" 2>/dev/null \
|| grep -q 'linker produced no map' "$log" 2>/dev/null \
|| grep -q 'has no M4 LINK: PASS' "$log" 2>/dev/null \
|| grep -q 'linker produced no COFF' "$log" 2>/dev/null; then
echo compile
elif grep -q 'MAME produced no CONF result' "$log" 2>/dev/null \
|| grep -q 'loader did not verify' "$log" 2>/dev/null \
|| grep -q 'result file has no' "$log" 2>/dev/null \
|| grep -q 'MAME exited' "$log" 2>/dev/null; then
echo crash
elif grep -q '^CONFORMANCE: FAIL ' "$log" 2>/dev/null; then
echo status
else
echo unclassified
fi
}
BAD=0
ATTEMPTED=0
record_row() {
corpus=$1
name=$2
result=$3
seconds=$4
detail=$5
printf '%s\t%s\t%s\t%s\t%s\n' "$corpus" "$name" "$result" "$seconds" "$detail" >> "$RESULTS"
}
# GCC's c-torture corpus is mostly K&R-era C: 73 files carry an explicit
# -std=gnu89 directive and many more rely on it implicitly. Clang 23 rejects
# implicit int/function declarations in its gnu17 default, so a plain sweep
# turns a language-mode gap into hundreds of fake compile failures. Honour an
# explicit -std= from dg-options/dg-additional-options, otherwise use gnu89.
# c-testsuite is modern C and keeps the compiler default.
dialect_flags() {
corpus=$1
name=$2
src=$3
[ "$corpus" = c-torture ] || return 0
directives=$(grep -E 'dg-(additional-)?options' "$src" 2>/dev/null || true)
std=$(printf '%s\n' "$directives" \
| grep -o -- '-std=[A-Za-z0-9+_-]*' | head -n 1)
if [ -n "$std" ]; then
flags=$std
elif grep -Fxq "$name" "$GNU89"; then
flags=-std=gnu89
else
flags=
fi
# A few torture tests spell out GNU inline/overflow semantics. Clang
# accepts both; -fpermissive and other GCC-only options are omitted.
if printf '%s\n' "$directives" | grep -q -- '-fgnu89-inline'; then
flags="${flags:+$flags }-fgnu89-inline"
fi
if printf '%s\n' "$directives" | grep -q -- '-fwrapv'; then
flags="${flags:+$flags }-fwrapv"
fi
printf '%s' "$flags"
}
full_loader_reason() {
[ -f "$FULL_LOADER_FILE" ] || return 0
awk -F '\t' -v n="$1" '$1 == n && $1 !~ /^#/ { print $2; exit }' "$FULL_LOADER_FILE"
}
full_loader_linker() {
[ -f "$FULL_LOADER_FILE" ] || { echo os2; return 0; }
_l=$(awk -F '\t' -v n="$1" '$1 == n && $1 !~ /^#/ { print $3; exit }' "$FULL_LOADER_FILE")
[ -n "$_l" ] || _l=os2
printf '%s' "$_l"
}
run_one() {
corpus=$1
name=$2
id=$corpus/$name
src=
expected=
case $corpus in
c-torture) src=$C_TORTURE_DIR/$name.c ;;
c-testsuite)
src=$C_TESTSUITE_DIR/$name.c
expected=$C_TESTSUITE_DIR/$name.c.expected
[ -f "$expected" ] || expected=$C_TESTSUITE_DIR/$name.expected
;;
esac
logdir=$WORK/logs/$corpus
log=$logdir/$name.log
mkdir -p "$logdir"
reason=$(curated_reason "$id")
if [ -n "$reason" ]; then
record_row "$corpus" "$name" "skip:$reason" 0 "curated"
printf 'SKIP %-44s curated: %s\n' "$id" "$reason"
return 0
fi
if [ ! -f "$src" ]; then
record_row "$corpus" "$name" "fail:diagnostic" 0 "missing source $src"
printf 'FAIL %-44s diagnostic (missing source)\n' "$id"
return 0
fi
if [ "$corpus" = c-testsuite ] && [ ! -f "$expected" ]; then
record_row "$corpus" "$name" "fail:diagnostic" 0 "missing expected output"
printf 'FAIL %-44s diagnostic (missing expected output)\n' "$id"
return 0
fi
safe_id=$(printf '%s' "$id" | tr -c 'A-Za-z0-9._-' '_')
runwork=$WORK/run/$safe_id
extra_cflags=$(dialect_flags "$corpus" "$name" "$src")
test_loader_end=$(loader_end_for "$id")
[ -n "$test_loader_end" ] || test_loader_end=$LOADER_END
bare=1
full_reason=$(full_loader_reason "$name")
full_linker=os2
if [ -n "$full_reason" ]; then
bare=0
full_linker=$(full_loader_linker "$name")
fi
start=$(date +%s)
set +e
if [ "$corpus" = c-torture ]; then
LOADER_AT=$LOADER_AT LOADER_END=$test_loader_end \
MAME_TIMEOUT=$TIME_LIMIT \
M5_CONFORMANCE_WORK=$WORK/run \
M5_CONFORMANCE_CLANG_OPT=-O0 M5_CONFORMANCE_LLC_OPT=-O0 \
M5_CONFORMANCE_MODE=native \
M5_CONFORMANCE_BARE="$bare" \
M4_OS2="$([ "$bare" = 1 ] && echo auto || { [ "$full_linker" = 1987 ] && echo 0 || echo 1; })" \
M5_CONFORMANCE_EXTRA_CFLAGS="$extra_cflags" \
timeout --kill-after=10 "$((TIME_LIMIT + 90))" \
"$RUN" --id "$id" --classify --mode native \
--expect-status 0 --ignore-output --timeout "$TIME_LIMIT" \
"$src" > "$log" 2>&1
else
LOADER_AT=$LOADER_AT LOADER_END=$test_loader_end \
MAME_TIMEOUT=$TIME_LIMIT \
M5_CONFORMANCE_WORK=$WORK/run \
M5_CONFORMANCE_CLANG_OPT=-O0 M5_CONFORMANCE_LLC_OPT=-O0 \
M5_CONFORMANCE_MODE=native \
M5_CONFORMANCE_BARE="$bare" \
M4_OS2="$([ "$bare" = 1 ] && echo auto || { [ "$full_linker" = 1987 ] && echo 0 || echo 1; })" \
M5_CONFORMANCE_EXTRA_CFLAGS= \
timeout --kill-after=10 "$((TIME_LIMIT + 90))" \
"$RUN" --id "$id" --classify --mode native \
--expect-status 0 --expect-output-file "$expected" \
--timeout "$TIME_LIMIT" "$src" > "$log" 2>&1
fi
rc=$?
set -e
end=$(date +%s)
elapsed=$((end - start))
printf '%s\n' "$rc" > "$log.rc"
case $rc in
0)
result=pass
if [ "$bare" = 1 ]; then
detail=link=native
else
detail="link=full-loader: $full_reason"
fi
printf 'PASS %-44s %3ss\n' "$id" "$elapsed"
;;
2)
if grep -q '^CONFORMANCE: SKIP ' "$log" 2>/dev/null; then
reason=$(sed -n 's/^CONFORMANCE: SKIP id=[^ ]* reason=//p' "$log" | head -n 1)
[ -n "$reason" ] || reason=classifier
result="skip:$reason"
detail=classifier
printf 'SKIP %-44s %3ss %s\n' "$id" "$elapsed" "$reason"
else
# Exit 2 without a SKIP row is not a skip (run.sh's loader path).
category=$(classify_failure "$log" "$rc" "$runwork")
result="fail:$category"
detail=log=$log
printf 'FAIL %-44s %3ss %s (no skip row)\n' \
"$id" "$elapsed" "$category"
case $category in
crash|unclassified|harness) BAD=1 ;;
esac
fi
;;
1)
category=$(classify_failure "$log" "$rc" "$runwork")
result="fail:$category"
detail=log=$log
printf 'FAIL %-44s %3ss %s\n' "$id" "$elapsed" "$category"
case $category in
crash|unclassified|harness) BAD=1 ;;
esac
;;
124|137)
# Outer wall timeout (124) or --kill-after SIGKILL (137): a hang, not a
# crash. The inner MAME timeout is handled inside run.sh as 124.
result=fail:timeout
detail="runner wall timeout (exit $rc)"
printf 'FAIL %-44s %3ss timeout (wall, exit %s)\n' "$id" "$elapsed" "$rc"
;;
*)
result=fail:crash
detail="runner exit $rc"
printf 'FAIL %-44s %3ss crash (runner exit %s)\n' "$id" "$elapsed" "$rc"
BAD=1
;;
esac
record_row "$corpus" "$name" "$result" "$elapsed" "$detail"
return 0
}
# Build the id stream for one corpus: sorted list, optional --list filter,
# optional --prefix, then skip ids already recorded (unless --redo).
build_ids() {
corpus=$1
list=$WORK/lists/$corpus.txt
out=$WORK/lists/selected-$corpus.txt
: > "$out"
prefix=$PREFIX
if [ -n "$LIST_FILE" ]; then
: > "$WORK/lists/user-$corpus.txt"
while IFS= read -r entry; do
case $entry in
''|\#*) continue ;;
esac
base=$(basename "$entry")
base=${base%.c}
if grep -Fxq "$base" "$list"; then
printf '%s\n' "$base" >> "$WORK/lists/user-$corpus.txt"
else
echo "full-suite: warning: --list entry is not in $corpus: $entry" >&2
fi
done < "$LIST_FILE"
LC_ALL=C sort -u "$WORK/lists/user-$corpus.txt" > "$out"
[ -s "$out" ] || fail "--list $LIST_FILE names no $corpus test"
# A user list already bounds the run; --prefix still applies if given.
if [ "$prefix" -gt 0 ]; then
sed -n "1,${prefix}p" "$out" > "$out.tmp"
mv "$out.tmp" "$out"
fi
else
if [ "$prefix" -gt 0 ]; then
sed -n "1,${prefix}p" "$list" > "$out"
else
cp "$list" "$out"
fi
fi
}
process_corpus() {
corpus=$1
build_ids "$corpus"
while IFS= read -r name; do
[ -n "$name" ] || continue
# Check the budget before dropping a row: --redo --limit N must not
# delete the (N+1)th row and then refuse to rerun it.
if [ "$LIMIT" -gt 0 ] && [ "$ATTEMPTED" -ge "$LIMIT" ]; then
return 0
fi
id=$corpus/$name
creason=$(curated_reason "$id")
if [ -n "$creason" ]; then
# Curation wins over an older failure row without needing --redo.
if [ "$REDO" -eq 0 ] \
&& [ "$(recorded_result "$corpus" "$name")" = "skip:$creason" ]; then
continue
fi
drop_recorded "$corpus" "$name"
run_one "$corpus" "$name"
ATTEMPTED=$((ATTEMPTED + 1))
continue
fi
if [ "$REDO" -eq 0 ] && already_recorded "$corpus" "$name"; then
continue
fi
if [ "$REDO" -eq 1 ]; then
drop_recorded "$corpus" "$name"
fi
run_one "$corpus" "$name"
ATTEMPTED=$((ATTEMPTED + 1))
done < "$WORK/lists/selected-$corpus.txt"
}
for corpus in $CORPORA; do
process_corpus "$corpus"
done
corpus_files() {
wc -l < "$WORK/lists/$1.txt" | tr -d ' '
}
# Mechanical accounting check: every row has five fields, a legal result, a
# name in the pinned list, and no duplicate id; the per-corpus totals cannot
# exceed the corpus size. A malformed artifact is a hard error, not a report.
validate_results() {
[ -s "$RESULTS" ] || return 0
awk -F '\t' '
NF != 5 {
printf "row %d has %d fields: %s\n", NR, NF, $0 > "/dev/stderr"
bad = 1
}
$3 != "pass" && $3 !~ /^skip:.+/ \
&& $3 !~ /^fail:(compile|diagnostic|loader|status|output|timeout|crash|harness|unclassified)$/ {
printf "row %d has an illegal result: %s\n", NR, $3 > "/dev/stderr"
bad = 1
}
END { exit bad }
' "$RESULTS" || fail "results file $RESULTS has a malformed row"
dup=$(cut -f1,2 "$RESULTS" | LC_ALL=C sort | uniq -d)
[ -z "$dup" ] || fail "duplicate result rows: $dup"
while IFS= read -r line; do
corpus=${line%% *}
rest=${line#* }
name=${rest%% *}
case $corpus in
c-torture|c-testsuite) ;;
*) fail "result row has an unknown corpus: $line" ;;
esac
grep -Fxq "$name" "$WORK/lists/$corpus.txt" \
|| fail "result names a missing $corpus test: $corpus/$name"
done < "$RESULTS"
for corpus in $CORPORA; do
total=$(awk -F '\t' -v c="$corpus" '$1 == c { n++ } END { print n + 0 }' "$RESULTS")
files=$(corpus_files "$corpus")
[ "$total" -le "$files" ] \
|| fail "$corpus has $total result rows for $files pinned files"
done
}
validate_results
# Exact summary from the retained rows. A corpus row is counted only when it
# is present in the results; corpus_files/remaining show the pinned total.
summary_row() {
corpus=$1
awk -F '\t' -v c="$corpus" '
$1 == c {
total++
if ($3 == "pass") pass++
else if ($3 ~ /^skip:/) skip++
else if ($3 ~ /^fail:/) {
fail++
if (substr($3, 6) == "crash") crash++
}
}
END {
printf "%s\t%d\t%d\t%d\t%d\t%d\n", c, total, pass, skip, fail, crash
}' "$RESULTS"
}
{
echo "# M8.4 full-suite report"
echo "# generated: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
echo "# work: $WORK"
echo "# settings: -O0, bare conformance (2ine+tms-link) with a full-loader list; LOADER_AT=$LOADER_AT, LOADER_END=$LOADER_END (default), per-test MAME timeout=${TIME_LIMIT}s, outer wall=$((TIME_LIMIT + 90))s"
echo "# full-loader list: $FULL_LOADER_FILE"
echo "# loader-end overrides: $LOADER_FILE ($(wc -l < "$LOADER_OVERRIDES" | tr -d ' ') rows)"
echo "# c-torture: $C_TORTURE_DIR ($(corpus_files c-torture) files)"
echo "# c-testsuite: $C_TESTSUITE_DIR ($(corpus_files c-testsuite) files)"
echo "# compiler: $compiler_id"
echo "# dialect: explicit dg -std= wins; otherwise -std=gnu89 only for full-suite.gnu89 names; c-testsuite default"
echo "# results: $RESULTS"
echo "# accounting: every row has 5 fields, a legal result and a pinned name; no duplicate ids"
echo "#"
echo "# corpus total pass skip fail crash corpus_files remaining"
for corpus in $CORPORA; do
row=$(summary_row "$corpus")
old_ifs=$IFS
IFS=' '
set -- $row
IFS=$old_ifs
c=$1 t=$2 p=$3 s=$4 f=$5 cr=$6
files=$(corpus_files "$corpus")
printf '%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n' \
"$corpus" "$t" "$p" "$s" "$f" "$cr" "$files" "$((files - t))"
done
if [ "$CORPUS_SELECT" = all ]; then
all=$(awk -F '\t' '
{ total++
if ($3 == "pass") pass++
else if ($3 ~ /^skip:/) skip++
else if ($3 ~ /^fail:/) { fail++; if (substr($3, 6) == "crash") crash++ } }
END { printf "%d\t%d\t%d\t%d\t%d\n", total, pass, skip, fail, crash }' "$RESULTS")
old_ifs=$IFS
IFS=' '
set -- $all
IFS=$old_ifs
printf 'all\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n' \
"$1" "$2" "$3" "$4" "$5" \
"$(( $(corpus_files c-torture) + $(corpus_files c-testsuite) ))" \
"$(( $(corpus_files c-torture) + $(corpus_files c-testsuite) - $1 ))"
fi
echo
echo "# fail categories (per selected corpus)"
for category_corpus in $CORPORA; do
echo "# $category_corpus"
awk -F '\t' -v c="$category_corpus" \
'$1 == c && $3 ~ /^fail:/ {
cat = substr($3, 6); n[cat]++
}
END { for (cat in n) printf "%s\t%d\n", cat, n[cat] }' "$RESULTS" \
| LC_ALL=C sort
done
echo
echo "# skip categories (per selected corpus)"
for category_corpus in $CORPORA; do
echo "# $category_corpus"
awk -F '\t' -v c="$category_corpus" \
'$1 == c && $3 ~ /^skip:/ {
r = substr($3, 6)
i = index(r, ":")
if (i > 0) r = substr(r, 1, i - 1)
n[r]++
}
END { for (r in n) printf "%s\t%d\n", r, n[r] }' "$RESULTS" \
| LC_ALL=C sort
done
echo
echo "# non-pass rows (all selected corpora)"
echo "# corpus test result seconds"
awk -F '\t' '$3 != "pass" { printf "%s\t%s\t%s\t%s\n", $1, $2, $3, $4 }' "$RESULTS" \
| LC_ALL=C sort
echo
echo "# resume"
if [ "$CORPUS_SELECT" = all ]; then
echo "$0 --corpus all --work $WORK"
else
echo "$0 --corpus $CORPUS_SELECT --work $WORK"
fi
} > "$REPORT.tmp"
mv "$REPORT.tmp" "$REPORT"
echo
echo "full-suite: summary"
awk -F '\t' 'NF == 8 && ($1 == "c-torture" || $1 == "c-testsuite" || $1 == "all") {
printf " %-12s total=%-5s pass=%-5s skip=%-5s fail=%-5s crash=%-3s remaining=%s\n",
$1, $2, $3, $4, $5, $6, $8
}' "$REPORT"
echo "full-suite: results $RESULTS"
echo "full-suite: report $REPORT"
echo "full-suite: logs $WORK/logs"
[ "$BAD" -eq 0 ] || exit 1
exit 0
+271
View File
@@ -0,0 +1,271 @@
# M7.4/M8.4 full-suite curated skips.
#
# Rows are <corpus>/<test><TAB><reason>. A row here is recorded as
# skip:<reason> without running the test, so it is never counted as a pass.
# The corpus/name must exist in the pinned tree; a stale row is a driver error.
# Classifier skips are reported by classify.sh and are not duplicated here;
# every row below was classifier-supported and re-run after the task that
# added it. M8.4 re-ran the whole corpus end-to-end with the final compiler
# (`--redo`, build/m8-full-suite); the retained M7.4/M8.3 evidence is history.
# M8.3 removed the rotates/cttz/bswap codegen class and the four frame-limited
# rows in full-suite.loader-end (per-test LOADER_END=2000); pr63843 now
# compiles and hits a pre-existing runtime hang. Reasons are tab-free; the
# retained per-test log is under build/m8-task3-full-suite-final and the
# timeout sweep under build/m8-task3-timeouts.
#
# Categories: compiler-crash, codegen, inline-asm, nested-function, vla,
# data-init, data-vector, data-odd-pointer, abi-*, builtin, libm, memory,
# corpus, compile, timeout, runtime-*, output, setjmp, vector, extension.
#
c-testsuite/00040 timeout: did not finish within LOADER_END=1000
c-testsuite/00174 libm: sin/float formatting differs from the expected libm output
c-torture/20000822-1 nested-function: nested function definitions are unsupported
c-torture/20001009-2 inline-asm: could not allocate input reg for constraint 'r' at line 105
c-torture/20001111-1 builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration]
c-torture/20010122-1 compiler-crash: unexpected TMS34010 custom lowering operation (return address)
c-torture/20010209-1 nested-function: nested function definitions are unsupported
c-torture/20010605-1 nested-function: nested function definitions are unsupported
c-torture/20010605-2 libc: call to undeclared function 'exit'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
c-torture/20010904-1 runtime-abort-alignment: test abort (status 0x86)
c-torture/20010904-2 runtime-abort-alignment: test abort (status 0x86)
c-torture/20010924-1 data-odd-pointer: pointer field at an odd .data byte offset
c-torture/20020107-1 inline-asm: could not allocate output register for constraint 'r' at line 336
c-torture/20020314-1 compile: incompatible integer to pointer conversion assigning to 'void *' from 'int' [-Wint-conversion]
c-torture/20020411-1 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/20020412-1 vla: variable-length array in a struct is unsupported
c-torture/20020418-1 abi-indirect-call: indirect call through a non-function value
c-torture/20021010-2 data-init: unsupported .data initializer
c-torture/20021127-1 runtime-abort-i64: test abort (status 0x86)
c-torture/20030209-1 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/20030222-1 inline-asm: could not allocate output register for constraint 'r' at line 495
c-torture/20030323-1 compiler-crash: unexpected TMS34010 custom lowering operation
c-torture/20030501-1 nested-function: nested function definitions are unsupported
c-torture/20030811-1 compiler-crash: unexpected TMS34010 custom lowering operation
c-torture/20031003-1 runtime-abort-float: test abort (status 0x86)
c-torture/20040223-1 compile: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Wint-conversion]
c-torture/20040302-1 data-init: unsupported .data initializer
c-torture/20040308-1 vla: variable-length array in a struct is unsupported
c-torture/20040423-1 vla: variable-length array in a struct is unsupported
c-torture/20040520-1 nested-function: nested function definitions are unsupported
c-torture/20040709-1 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/20040709-2 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/20040709-3 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/20041214-1 data-init: unsupported .data initializer
c-torture/20041218-2 vla: variable-length array in a struct is unsupported
c-torture/20050121-1 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/20050316-1 abi-float-args: float/double arguments are unsupported
c-torture/20050316-2 abi-float-args: float/double arguments are unsupported
c-torture/20050316-3 abi-return: unsupported aggregate/variadic return shape
c-torture/20050604-1 runtime-abort-float: test abort (status 0x86)
c-torture/20050607-1 runtime-abort-i64: test abort (status 0x86)
c-torture/20051012-1 timeout: did not finish within LOADER_END=1000
c-torture/20060420-1 runtime-abort-i64: test abort (status 0x86)
c-torture/20061220-1 nested-function: nested function definitions are unsupported
c-torture/20070614-1 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/20070824-1 compiler-crash: dynamic alloca size scaling assertion
c-torture/20070919-1 vla: variable-length array in a struct is unsupported
c-torture/20071210-1 data-init: unsupported .data initializer
c-torture/20071220-1 data-init: unsupported .data initializer
c-torture/20071220-2 data-init: unsupported .data initializer
c-torture/20080502-1 runtime-abort-float: test abort (status 0x86)
c-torture/20090219-1 nested-function: nested function definitions are unsupported
c-torture/20180921-1 compile: chained comparison 'X < Y <= Z' does not behave the same as a mathematical expression [-Wparentheses]
c-torture/20230630-1 runtime-abort: test abort (status 0x86)
c-torture/20230630-3 runtime-abort: test abort (status 0x86)
c-torture/20241029-1 builtin: use of unknown builtin '__builtin_puts' [-Wimplicit-function-declaration]
c-torture/920302-1 compile: incompatible pointer types passing 'short (*)[5]' to parameter of type 'short *' [-Wincompatible-pointer-types]
c-torture/920415-1 nested-function: nested function definitions are unsupported
c-torture/920428-1 runtime-abort: test abort (status 0x86)
c-torture/920428-2 nested-function: nested function definitions are unsupported
c-torture/920501-3 codegen: t24: i32 = BlockAddress<@execute, %base> 0
c-torture/920501-4 data-init: unsupported .data initializer
c-torture/920501-5 data-init: unsupported .data initializer
c-torture/920501-7 nested-function: nested function definitions are unsupported
c-torture/920612-2 nested-function: nested function definitions are unsupported
c-torture/920625-1 runtime-abort-varargs: test abort (status 0x86)
c-torture/920721-4 nested-function: nested function definitions are unsupported
c-torture/920726-1 abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported
c-torture/920728-1 compile: non-void function 'f' should return a value [-Wreturn-mismatch]
c-torture/921017-1 nested-function: nested function definitions are unsupported
c-torture/921208-2 timeout: did not finish within LOADER_END=1000
c-torture/921215-1 nested-function: nested function definitions are unsupported
c-torture/930622-2 codegen-float: only 32-bit integer sources are supported for float/double conversions
c-torture/931002-1 nested-function: nested function definitions are unsupported
c-torture/931004-10 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-12 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-14 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-2 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-4 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-6 runtime-abort-bitfield: test abort (status 0x86)
c-torture/931004-8 runtime-abort-bitfield: test abort (status 0x86)
c-torture/941202-1 timeout: did not finish within LOADER_END=1000
c-torture/960312-1 inline-asm: could not allocate input reg for constraint 'r' at line 218
c-torture/960512-1 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/960521-1 timeout: did not finish within LOADER_END=1000
c-torture/980709-1 timeout: did not finish within LOADER_END=1000
c-torture/990130-1 inline-asm: could not allocate output register for constraint 'r' at line 152
c-torture/990208-1 codegen: t5: i32 = BlockAddress<@doit, %here> 0
c-torture/990413-2 inline-asm: invalid output constraint '=t'
c-torture/991112-1 runtime-abort: test abort (status 0x86)
c-torture/align-nest vla: variable-length array in a struct is unsupported
c-torture/arith-rand-ll timeout: did not finish within LOADER_END=1000
c-torture/bitfld-3 runtime-abort-bitfield: test abort (status 0x86)
c-torture/bitfld-5 runtime-abort-bitfield: test abort (status 0x86)
c-torture/bitfld-6 runtime-bitfield: wrong bitfield result (status 0x33333)
c-torture/bitfld-7 runtime-bitfield: wrong bitfield result (status 0x222222)
c-torture/bswap-2 timeout: did not finish within LOADER_END=1000
c-torture/built-in-setjmp setjmp: __builtin_longjmp is unsupported
c-torture/cmpsf-1 float-constant: out-of-range constant in the GSP floating-point format
c-torture/comp-goto-1 data-init: unsupported .data initializer
c-torture/comp-goto-2 nested-function: nested function definitions are unsupported
c-torture/complex-1 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/complex-2 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/complex-5 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/complex-6 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/conversion codegen-float: only 32-bit integer sources are supported for float/double conversions
c-torture/eeprof-1 runtime-abort: test abort (status 0x86)
c-torture/floatunsisf-1 runtime-abort-i64: test abort (status 0x86)
c-torture/frame-address compiler-crash: unexpected TMS34010 custom lowering operation (frame address)
c-torture/memclr memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/memcpy-1 output: test writes more than the 16 KiB shim cap
c-torture/memcpy-a1 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/memcpy-a2 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/memcpy-a4 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/memcpy-a8 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/nest-align-1 nested-function: nested function definitions are unsupported
c-torture/nest-stdar-1 nested-function: nested function definitions are unsupported
c-torture/nestfunc-1 nested-function: nested function definitions are unsupported
c-torture/nestfunc-2 nested-function: nested function definitions are unsupported
c-torture/nestfunc-3 nested-function: nested function definitions are unsupported
c-torture/nestfunc-5 nested-function: nested function definitions are unsupported
c-torture/nestfunc-6 nested-function: nested function definitions are unsupported
c-torture/nestfunc-7 nested-function: nested function definitions are unsupported
c-torture/pr103052 builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration]
c-torture/pr103255 runtime-abort-i64: test abort (status 0x86)
c-torture/pr103376 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr103405 nested-function: nested function definitions are unsupported
c-torture/pr105777 corpus: references a gcc.dg source absent from the pinned execute tree
c-torture/pr105984 builtin: use of unknown builtin '__builtin_mul_overflow_p' [-Wimplicit-function-declaration]
c-torture/pr107881-1 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/pr108292 vector: address of vector element requested
c-torture/pr108498-1 inline-asm: could not allocate input reg for constraint 'r' at line 1233
c-torture/pr109040 abi-float-args: float/double arguments are unsupported
c-torture/pr109938 corpus: references a gcc.dg source absent from the pinned execute tree
c-torture/pr109986 corpus: references a gcc.dg source absent from the pinned execute tree
c-torture/pr110252-2 inline-asm: could not allocate output register for constraint 'r' at line 155
c-torture/pr115033 builtin: use of unknown builtin '__builtin_exit' [-Wimplicit-function-declaration]
c-torture/pr117432 compile: ISO C requires a named parameter before '...'
c-torture/pr123625 runtime-abort: test abort (status 0x86)
c-torture/pr123625-2 data-vector: vector constants in .data are unsupported
c-torture/pr123753 vector: cannot decrement a vector value
c-torture/pr123864 builtin: use of unknown builtin '__builtin_mul_overflow_p' [-Wimplicit-function-declaration]
c-torture/pr125291 abi-indirect-call: indirect call through a non-function value
c-torture/pr126405-3 abi-return: unsupported aggregate/variadic return shape
c-torture/pr17252 timeout: did not finish within LOADER_END=1000
c-torture/pr17377 compiler-crash: unexpected TMS34010 custom lowering operation
c-torture/pr20621-1 timeout: compilation did not finish within the 210s outer wall
c-torture/pr22061-1 compile: incompatible integer to pointer conversion assigning to 'void *' from 'int' [-Wint-conversion]
c-torture/pr22061-3 nested-function: nested function definitions are unsupported
c-torture/pr22061-4 nested-function: nested function definitions are unsupported
c-torture/pr23135 data-vector: vector constants in .data are unsupported
c-torture/pr23324 data-init: unsupported .data initializer
c-torture/pr24135 nested-function: nested function definitions are unsupported
c-torture/pr28865 vla: variable-length array in a struct is unsupported
c-torture/pr28982b timeout: compilation did not finish within the 210s outer wall
c-torture/pr30314 corpus: references a gcc.dg source absent from the pinned execute tree
c-torture/pr32244-1 runtime-abort-i64: test abort (status 0x86)
c-torture/pr34456 timeout: did not finish within LOADER_END=1000
c-torture/pr34971 runtime-abort-i64: test abort (status 0x86)
c-torture/pr35456 runtime-abort-float: test abort (status 0x86)
c-torture/pr38051 runtime-abort-i64: test abort (status 0x86)
c-torture/pr38151 runtime-abort-varargs: test abort (status 0x86)
c-torture/pr38533 inline-asm: could not allocate output register for constraint 'r' at line 2147513642
c-torture/pr38969 abi-sret: aggregate return via an sret pointer is unsupported
c-torture/pr39228 builtin: use of unknown builtin '__builtin_isinff' [-Wimplicit-function-declaration]
c-torture/pr40022 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr40657 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr41935 vla: variable-length array in a struct is unsupported
c-torture/pr43385 inline-asm: could not allocate output register for constraint 'r' at line 328
c-torture/pr43560 inline-asm: could not allocate output register for constraint 'r' at line 298
c-torture/pr44575 runtime-abort-varargs: test abort (status 0x86)
c-torture/pr44683 runtime-abort-float: test abort (status 0x86)
c-torture/pr45695 inline-asm: could not allocate output register for constraint 'r' at line 121
c-torture/pr47237 builtin: use of unknown builtin '__builtin_apply' [-Wimplicit-function-declaration]
c-torture/pr49279 inline-asm: could not allocate output register for constraint 'r' at line 199
c-torture/pr49390 inline-asm: could not allocate output register for constraint 'r' at line 1508
c-torture/pr51447 nested-function: nested function definitions are unsupported
c-torture/pr51581-1 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/pr51581-2 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/pr52286 inline-asm: could not allocate output register for constraint 'r' at line 119
c-torture/pr53645 data-init: unsupported .data initializer
c-torture/pr53645-2 data-init: unsupported .data initializer
c-torture/pr56866 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr57344-3 runtime-abort-i64: test abort (status 0x86)
c-torture/pr57344-4 runtime-abort-i64: test abort (status 0x86)
c-torture/pr58209 runtime-abort: test abort (status 0x86)
c-torture/pr58574 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/pr60003 compile: incompatible pointer types passing 'unsigned long long (*)[5]' to parameter of type 'void **' [-Wincompatible-pointer-types]
c-torture/pr60822 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/pr60960 abi-return: unsupported aggregate/variadic return shape
c-torture/pr63843 timeout: codegen fixed at the M7.4 pin; already compiled at the M8 base and hangs identically (status 1, no completion magic)
c-torture/pr64242 setjmp: __builtin_longjmp is unsupported
c-torture/pr65053-1 inline-asm: could not allocate output register for constraint 'r' at line 281
c-torture/pr65053-2 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr65401 runtime-abort: test abort (status 0x86)
c-torture/pr65427 runtime-abort: test abort (status 0x86)
c-torture/pr65648 inline-asm: could not allocate input reg for constraint 'r' at line 225
c-torture/pr65956 inline-asm: could not allocate output register for constraint 'r' at line 285
c-torture/pr67037 timeout: did not finish within LOADER_END=1000
c-torture/pr68328 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr68390 abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported
c-torture/pr70460 data-init: unsupported .data initializer
c-torture/pr70566 timeout: did not finish within LOADER_END=1000
c-torture/pr70903 abi-return: unsupported aggregate/variadic return shape
c-torture/pr71494 nested-function: nested function definitions are unsupported
c-torture/pr71626-1 abi-return: unsupported aggregate/variadic return shape
c-torture/pr71626-2 abi-return: unsupported aggregate/variadic return shape
c-torture/pr78791 data-init: unsupported .data initializer
c-torture/pr79327 runtime-abort: test abort (status 0x86)
c-torture/pr79737-2 runtime-abort: test abort (status 0x86)
c-torture/pr80421 inline-asm: could not allocate input reg for constraint 'r' at line 113
c-torture/pr80692 extension: GNU decimal float type is unsupported
c-torture/pr81588 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr82210 vla: variable-length array in a struct is unsupported
c-torture/pr82954 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr84521 setjmp: __builtin_longjmp is unsupported
c-torture/pr84524 inline-asm: could not allocate output register for constraint 'r' at line 468
c-torture/pr85156 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr85169 runtime-abort: test abort (status 0x86)
c-torture/pr85331 builtin: use of unknown builtin '__builtin_shuffle' [-Wimplicit-function-declaration]
c-torture/pr85756 inline-asm: could not allocate input reg for constraint 'r' at line 204
c-torture/pr88904 inline-asm: could not allocate output register for constraint 'r' at line 174
c-torture/pr92618 abi-return: unsupported aggregate/variadic return shape
c-torture/pr94130 inline-asm: Could not match memory address. Inline asm failure!
c-torture/pr94412 runtime-abort: test abort (status 0x86)
c-torture/pr94524-1 abi-return: unsupported aggregate/variadic return shape
c-torture/pr94524-2 abi-return: unsupported aggregate/variadic return shape
c-torture/pr94591 builtin: use of unknown builtin '__builtin_shuffle' [-Wimplicit-function-declaration]
c-torture/pr98304-2 corpus: references a gcc.dg source absent from the pinned execute tree
c-torture/printf-chk-1 timeout: did not finish within LOADER_END=1000
c-torture/scal-to-vec1 runtime-abort-vector: test abort (status 0x86)
c-torture/scal-to-vec2 runtime-abort-vector: test abort (status 0x86)
c-torture/scal-to-vec3 runtime-abort-vector: test abort (status 0x86)
c-torture/simd-1 data-vector: vector constants in .data are unsupported
c-torture/simd-2 data-vector: vector constants in .data are unsupported
c-torture/simd-4 abi-float-args: float/double arguments are unsupported
c-torture/simd-5 data-vector: vector constants in .data are unsupported
c-torture/simd-6 abi-return: unsupported aggregate/variadic return shape
c-torture/stdarg-3 runtime-abort-varargs: test abort (status 0x86)
c-torture/stkalign inline-asm: could not allocate output register for constraint 'r' at line 344
c-torture/strct-stdarg-1 runtime-abort-varargs: test abort (status 0x86)
c-torture/strct-varg-1 runtime-abort-varargs: test abort (status 0x86)
c-torture/string-opt-18 timeout: did not finish within LOADER_END=1000
c-torture/strlen-5 memory: linked image exceeds the 45 KiB program / 64 KiB RAM region
c-torture/strncmp-1 timeout: did not finish within LOADER_END=1000
c-torture/va-arg-21 timeout: did not finish within LOADER_END=1000
c-torture/va-arg-22 abi-byval: byval argument has zero size
c-torture/va-arg-26 abi-varargs-return: float/double/i64/aggregate return from a variadic definition is unsupported
c-torture/va-arg-pack-1 builtin: use of unknown builtin '__builtin_va_arg_pack' [-Wimplicit-function-declaration]
c-torture/vprintf-1 timeout: did not finish within LOADER_END=1000
c-torture/vprintf-chk-1 timeout: did not finish within LOADER_END=1000
c-torture/zerolen-2 runtime-abort: test abort (status 0x86)
+390
View File
@@ -0,0 +1,390 @@
#!/bin/sh
# M7.3 real-hardware marker gate with MAME-equivalent acceptance.
#
# Builds scripts/m7/hwmark.c (a C-only `_start`) as a TI-COFF object, links it
# with tools/tms-link at the proven VT1200 hardware origins, and proves the
# image in MAME through the same dwt loader that hostload.py drives:
#
# .text 018C0000h .data 018D0000h .bss 018D8000h
# 018E0000 start = entry (018C0000)
# 018E0020 data = DEADBEEF (loader copied .data)
# 018E0040 data2 = 12345678 (loader copied .data)
# 018E0060 bss = 0 (loader zeroed the A5-prefilled .bss)
# 018E0080 count advances (create_process scheduled a live child)
#
# GSPLNK 2.00 links the same object with explicit section origins as the
# layout oracle; the gate requires identical allocated bytes and placement.
#
# Real unit:
#
# VT1200_HOST=192.168.99.2 scripts/tests/m7/hardware.sh
#
# runs dwt/loader/hostload.py --host "$VT1200_HOST" --coff <same COFF>
# --marker --out <evidence> --tag hwmark and propagates its failure. Without
# VT1200_HOST the gate prints `HARDWARE: DEFERRED` and passes on the MAME
# evidence; it never reports a hardware pass without a unit.
#
# The unit is a stock v2.2 VT1200: MAC 08-00-2B-16-4B-5A, static IP
# 100.103.100.103 (the lab host is 100.103.255.254); the emulator lab uses
# 192.168.99.2. rdebug listens on TCP 771, which hostload.py uses.
#
# Run this gate alone and serially (it owns MAME/DOSBox and uses fixed
# hardware origins).
#
# Overridable: LLVM_BIN TMS_CLANG TMS_LLC TMS_LINK MAME MAME_TIMEOUT DOSBOX
# DOSBOX_TIMEOUT DOSBOX_CONF SDK_IMG M7_HW_WORK M7_HW_COFF
# M7_HW_EVIDENCE M7_SDK LOADER_AT LOADER_END VT1200_HOST
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${M7_HW_WORK:-$ROOT/build/m7-hardware}
COFF=${M7_HW_COFF:-$WORK/hw-marker.coff}
SDK=${M7_SDK:-$ROOT/build/m4-sdk}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
HOSTLOAD=$ROOT/vendor/vt1200/dwt/loader/hostload.py
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
HOST=${VT1200_HOST:-}
fail() {
echo "M7 hardware: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing COFF loader payload: $LOADER_BIN"
[ -f "$HOSTLOAD" ] || fail "missing hostload.py: $HOSTLOAD"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
EVIDENCE=${M7_HW_EVIDENCE:-$ROOT/build/m7-hardware-evidence}
rm -rf "$WORK"
mkdir -p "$WORK/run/nvram" "$WORK/run/cfg" "$EVIDENCE/hostload" "$WORK/dos"
echo "== compile the C-only marker client at the hardware origins"
"$TMS_CLANG" -O0 -o "$WORK/hwmark.ll" "$DIR/hwmark.c" \
|| fail "tms-clang failed"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/hwmark.ll" -o "$WORK/hwmark.o" \
|| fail "llc -filetype=obj failed"
echo "== link with tools/tms-link (.text 018C0000 .data 018D0000 .bss 018D8000)"
"$TMS_LINK" -o "$COFF" --map "$WORK/hwmark.map" --entry _start \
--text 018C0000 --data 018D0000 --bss 018D8000 \
--prog-len 18000 --ram-len 8000 \
"$WORK/hwmark.o" \
|| fail "tms-link failed"
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/hwmark.map")
[ "$ENTRY_ADDR" = "018C0000" ] \
|| fail "tms-link entry _start is '$ENTRY_ADDR', want 018C0000"
grep -q 'ENTRY POINT SYMBOL: "_start" address: 018C0000' "$WORK/hwmark.map" \
|| fail "tms-link map has no _start entry point at 018C0000"
echo "== inspect the linked COFF (origins, .data sentinels, no relocations)"
python3 - "$COFF" <<'PY' || fail "linked COFF does not match the hardware marker contract"
import struct
import sys
path = sys.argv[1]
d = open(path, "rb").read()
if len(d) < 20:
sys.exit(f"{path}: shorter than a COFF file header")
machine, nscns, _time, symptr, nsyms, opthdr, flags = struct.unpack_from(
"<HHIIIHH", d, 0)
if machine != 0x0090:
sys.exit(f"{path}: machine {machine:#06x}, want 0x0090")
if opthdr != 28:
sys.exit(f"{path}: optional header size {opthdr}, want 28")
if not (flags & 0x0001):
sys.exit(f"{path}: linked image is not executable (flags {flags:#06x})")
optmagic, = struct.unpack_from("<H", d, 20)
entry, textstart = struct.unpack_from("<II", d, 20 + 16)
if optmagic != 0x0108:
sys.exit(f"{path}: optional header magic {optmagic:#06x}, want 0x0108")
if entry != 0x018C0000 or textstart != 0x018C0000:
sys.exit(f"{path}: entry/textstart {entry:#x}/{textstart:#x}, "
f"want 018C0000")
SECTIONS = {}
base = 20 + opthdr
for i in range(nscns):
off = base + i * 40
name = d[off:off + 8].split(b"\0", 1)[0].decode("latin1")
paddr, _vaddr, size, scnptr = struct.unpack_from("<IIII", d, off + 8)
nreloc, = struct.unpack_from("<H", d, off + 32)
sflags, = struct.unpack_from("<I", d, off + 36)
if nreloc:
sys.exit(f"{path}: linked {name} still has {nreloc} relocations")
SECTIONS[name] = dict(index=i + 1, paddr=paddr, size=size,
scnptr=scnptr, flags=sflags)
want = {
".text": (0x018C0000, 0x20),
".data": (0x018D0000, 0x40),
".bss": (0x018D8000, 0x80),
}
if sorted(SECTIONS) != sorted(want):
sys.exit(f"{path}: sections {sorted(SECTIONS)}, want .text/.data/.bss")
for name, (paddr, sflags) in want.items():
sec = SECTIONS[name]
if sec["paddr"] != paddr:
sys.exit(f"{path}: {name} origin {sec['paddr']:#x}, want {paddr:#x}")
if sec["flags"] != sflags:
sys.exit(f"{path}: {name} flags {sec['flags']:#06x}, want {sflags:#06x}")
if sec["size"] == 0:
sys.exit(f"{path}: {name} is empty")
if SECTIONS[".data"]["size"] < 64:
sys.exit(f"{path}: .data is smaller than the two sentinels (64 bits)")
if SECTIONS[".bss"]["size"] < 64:
sys.exit(f"{path}: .bss is smaller than b_zero/b_counter (64 bits)")
if SECTIONS[".text"]["paddr"] + SECTIONS[".text"]["size"] > \
SECTIONS[".data"]["paddr"]:
sys.exit(f"{path}: .text overlaps .data")
if SECTIONS[".data"]["paddr"] + SECTIONS[".data"]["size"] > 0x018D8000:
sys.exit(f"{path}: .data crosses into the .bss region")
if SECTIONS[".bss"]["paddr"] + SECTIONS[".bss"]["size"] > 0x018E0000:
sys.exit(f"{path}: .bss crosses into the marker cells at 018E0000")
# Symbol records: the client's data/bss objects must be in the right section,
# and the .data bytes at their symbol offsets must hold the sentinels.
string_base = symptr + nsyms * 18
syms = {}
i = 0
while i < nsyms:
off = symptr + i * 18
if off + 18 > len(d):
sys.exit(f"{path}: symbol {i} past EOF")
name = d[off:off + 8]
if name[:4] == b"\0\0\0\0":
soff, = struct.unpack_from("<I", d, off + 4)
end = d.find(b"\0", string_base + soff)
nm = d[string_base + soff:end].decode("latin1")
else:
nm = name.rstrip(b"\0").decode("latin1")
value, secno, _typ, cls, naux = struct.unpack_from("<IhHBB", d, off + 8)
if cls == 2:
syms[nm] = (value, secno)
i += 1 + naux
def need(nm, sec):
if nm not in syms:
sys.exit(f"{path}: missing symbol {nm}")
value, secno = syms[nm]
if secno != sec:
sys.exit(f"{path}: {nm} is in section {secno}, want {sec}")
return value
def abs_need(nm, sec, want):
value = need(nm, sec)
if value != want:
sys.exit(f"{path}: {nm} is at {value:#x}, want {want:#x}")
return value
# A linked image stores absolute bit addresses in its symbol values, like
# GSPLNK's map (the unlinked llc object used section-relative values).
start = abs_need("_start", SECTIONS[".text"]["index"], 0x018C0000)
magic_addr = abs_need("_d_magic", SECTIONS[".data"]["index"], 0x018D0000)
two_addr = abs_need("_d_two", SECTIONS[".data"]["index"], 0x018D0020)
abs_need("_b_zero", SECTIONS[".bss"]["index"], 0x018D8000)
abs_need("_b_counter", SECTIONS[".bss"]["index"], 0x018D8020)
raw = d[SECTIONS[".data"]["scnptr"]:
SECTIONS[".data"]["scnptr"] + SECTIONS[".data"]["size"] // 8]
def field(addr, want_hex, label):
bitoff = addr - SECTIONS[".data"]["paddr"]
got = raw[bitoff // 8:bitoff // 8 + 4]
if got.hex() != want_hex:
sys.exit(f"{path}: {label} bytes {got.hex()}, want {want_hex}")
field(magic_addr, "efbeadde", "_d_magic")
field(two_addr, "78563412", "_d_two")
print(f" COFF: entry={entry:08X} text={SECTIONS['.text']['paddr']:08X}"
f"/{SECTIONS['.text']['size']} bits "
f"data={SECTIONS['.data']['paddr']:08X}/{SECTIONS['.data']['size']} bits "
f"bss={SECTIONS['.bss']['paddr']:08X}/{SECTIONS['.bss']['size']} bits")
print(f" symbols: _start={start:08X} _d_magic={magic_addr:08X} "
f"_d_two={two_addr:08X} (absolute bits; sentinels exact)")
PY
echo "== hostload.py MARKER_CELLS contract"
python3 - "$HOSTLOAD" <<'PY' || fail "hostload.py marker cells changed"
import importlib.util
import sys
path = sys.argv[1]
spec = importlib.util.spec_from_file_location("hostload", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
want = [
(0x018E0000, "start"),
(0x018E0020, "data"),
(0x018E0040, "data2"),
(0x018E0060, "bss"),
(0x018E0080, "count"),
]
if mod.MARKER_CELLS != want:
sys.exit(f"{path}: MARKER_CELLS {mod.MARKER_CELLS}, want {want}")
print(" MARKER_CELLS: 018E0000 start, 018E0020 data, 018E0040 data2, "
"018E0060 bss, 018E0080 count")
PY
echo "== link the same object with GSPLNK 2.00 (layout oracle)"
if [ ! -f "$SDK/GSPLNK.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPLNK.EXE" ] || fail "GSPLNK.EXE is not extracted in $SDK"
cp "$SDK/GSPLNK.EXE" "$WORK/dos/"
cp "$WORK/hwmark.o" "$WORK/dos/HWMARK.OBJ"
{
printf '%s\n' '-a'
printf '%s\n' '-o HWMARK.OUT'
printf '%s\n' '-m HWMARK.MAP'
printf '%s\n' '-e _start'
printf '%s\n' 'HWMARK.OBJ'
printf '%s\n' 'SECTIONS'
printf '%s\n' '{'
printf '%s\n' ' .text 018C0000h: {}'
printf '%s\n' ' .data 018D0000h: {}'
printf '%s\n' ' .bss 018D8000h: {}'
printf '%s\n' '}'
} > "$WORK/dos/HWMARK.CMD"
sed 's/$/\r/' "$WORK/dos/HWMARK.CMD" > "$WORK/dos/HWMARK.NEW"
mv "$WORK/dos/HWMARK.NEW" "$WORK/dos/HWMARK.CMD"
rm -f "$WORK/dos/HWMARK.OUT" "$WORK/dos/HWMARK.MAP"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $WORK/dos" -c "c:" \
-c "gsplnk HWMARK.CMD" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$WORK/dos/HWMARK.OUT" ] \
|| { tail -30 "$WORK/dosbox.log" >&2; fail "GSPLNK produced no HWMARK.OUT"; }
cp "$WORK/dos/HWMARK.OUT" "$WORK/hwmark-gsplnk.coff"
python3 - "$COFF" "$WORK/hwmark-gsplnk.coff" <<'PY' \
|| fail "tms-link output differs from the GSPLNK oracle"
import struct
import sys
def parse(path):
d = open(path, "rb").read()
machine, nscns, _time, _symptr, _nsyms, opthdr, flags = \
struct.unpack_from("<HHIIIHH", d, 0)
if machine != 0x0090:
sys.exit(f"{path}: machine {machine:#06x}, want 0x0090")
if not (flags & 0x0001):
sys.exit(f"{path}: not executable (flags {flags:#06x})")
entry, = struct.unpack_from("<I", d, 20 + 16)
base = 20 + opthdr
secs = {}
for i in range(nscns):
off = base + i * 40
name = d[off:off + 8].split(b"\0", 1)[0].decode("latin1")
paddr, _vaddr, size, scnptr = struct.unpack_from("<IIII", d, off + 8)
nreloc, = struct.unpack_from("<H", d, off + 32)
if nreloc:
sys.exit(f"{path}: linked {name} still has {nreloc} relocations")
raw = b"" if name == ".bss" else d[scnptr:scnptr + size // 8]
secs[name] = (paddr, size, raw)
return entry, secs
ours_entry, ours = parse(sys.argv[1])
oracle_entry, oracle = parse(sys.argv[2])
if ours_entry != oracle_entry:
sys.exit(f"entry: tms-link {ours_entry:#x}, GSPLNK {oracle_entry:#x}")
if sorted(ours) != sorted(oracle):
sys.exit(f"sections: tms-link {sorted(ours)}, GSPLNK {sorted(oracle)}")
for name in (".text", ".data", ".bss"):
op, osz, oraw = ours[name]
gp, gsz, graw = oracle[name]
if (op, osz) != (gp, gsz):
sys.exit(f"{name}: tms-link {op:#x}/{osz} bits, "
f"GSPLNK {gp:#x}/{gsz} bits")
if oraw != graw:
sys.exit(f"{name}: allocated bytes differ from GSPLNK")
print(" tms-link == GSPLNK: entry, .text/.data/.bss origins, sizes and "
"allocated bytes")
PY
echo "== run the marker COFF in MAME"
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$COFF" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/hw-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; \
fail "COFF loader did not report status 0"; }
grep -qE 'placed \.text at 018C0000: .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -qE 'placed \.data at 018D0000: .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .data bytes"
grep -q '^M7 HW MAME: PASS$' "$WORK/mame.log" \
|| { grep -E '^M7 HW' "$WORK/mame.log" >&2 || true; \
tail -30 "$WORK/mame.log" >&2; \
fail "MAME marker cells or loader status did not match"; }
cp "$WORK/mame.log" "$EVIDENCE/mame.log"
grep '^M7 HW: ' "$WORK/mame.log" | tail -1 | sed 's/^/ /'
grep '^LOADER: marker app: ' "$WORK/mame.log" | tail -1 | sed 's/^/ /' || true
if [ -n "$HOST" ]; then
echo "== real hardware: hostload.py --marker at $HOST"
if ! python3 "$HOSTLOAD" --host "$HOST" --coff "$COFF" --marker \
--out "$EVIDENCE/hostload" --tag hwmark \
> "$EVIDENCE/hostload-hwmark.log" 2>&1; then
cat "$EVIDENCE/hostload-hwmark.log" >&2
fail "real-hardware marker run failed (host $HOST)"
fi
cat "$EVIDENCE/hostload-hwmark.log"
echo "HARDWARE: PASS (host $HOST)"
echo "M7 hardware: PASS (MAME-equivalent + real hardware)"
else
echo "HARDWARE: DEFERRED"
echo "HARDWARE: set VT1200_HOST=<unit-ip> to run hostload.py --marker over rdebug"
echo "M7 hardware: PASS (MAME-equivalent; hardware deferred)"
fi
+31
View File
@@ -0,0 +1,31 @@
/* M7.1 i64-array `.data` gate driver (compiled on both the GSPA and native
* paths). Clang emits a ConstantArray for `long long y[2]`, so this pins the
* i64 array recursion end-to-end.
*
* Markers 30..33 are the two words of each element; the raw 16-byte image is
* copied to 0x018A9000 + 80*8 (data-check.lua compares it byte for byte).
*/
typedef unsigned int u32;
#define MARK(n) (*(volatile u32 *)(0x018A8000u + (u32)(n) * 0x20u))
#define OUTB(n) (*(volatile unsigned char *)(0x018A9000u + (u32)(n) * 8u))
volatile long long y[2] = {
0x1122334455667788LL,
0x99AABBCCDDEEFF00LL,
};
void data64_run(void)
{
const volatile unsigned char *p = (const volatile unsigned char *)y;
u32 i;
MARK(30) = (u32)(unsigned long long)y[0];
MARK(31) = (u32)((unsigned long long)y[0] >> 32);
MARK(32) = (u32)(unsigned long long)y[1];
MARK(33) = (u32)((unsigned long long)y[1] >> 32);
for (i = 0; i < (u32)sizeof(y); i++)
OUTB(80u + i) = p[i];
}
+187
View File
@@ -0,0 +1,187 @@
#!/bin/sh
# M7.4 i64 divide/remainder fast-path performance gate.
#
# scripts/tests/m7/i64div.sh
#
# Compiles scripts/m7/i64div-perf.c with tms-clang/llc, assembles and links
# it with GSPA/GSPLNK 2.00 under DOSBox through scripts/m4/run.sh, loads the
# COFF with the dwt loader and runs it in MAME. The driver runs two
# equal-iteration workloads:
#
# - 16384 iterations with both operands fitting 32 bits after the signed
# magnitude normalization: each i64 div/rem takes the M7.4 fast path and
# the target's single 32-bit DIVU;
# - 16384 iterations with nonzero high words: each i64 div/rem takes the
# 64-step restoring loop;
# - 16384 iterations with a nonzero dividend high word and a 32-bit
# divisor: each i64 div/rem takes the M8.3 two-step 64/32 path (two
# even-destination DIVUs) instead of the loop.
#
# scripts/m7/i64div-perf-check.lua polls the start and per-phase completion
# markers once per MAME frame. A frame is a fixed number of emulated 50 MHz
# cycles, so the frame counts are a reproducible cycle proxy. The gate
# requires the fast phase to complete in materially fewer frames for the same
# iteration count (slow_frames >= 8 * max(fast_frames,1), with the slow phase
# at least 20 frames so it is measurable) and the wide phase to beat the loop
# (slow_frames >= 4 * max(wide_frames,1), wide phase at least 2 frames). All
# three phase checksums must equal the deterministic values computed from the
# same LCG (the driver header and the Lua pin them). The driver's self-check
# status word proves every path first produced the known values, including
# full-width 32-bit magnitudes (0xFFFFFFFF/7, -123/7, INT32_MIN/3) and the
# 64/32 shapes (hi >= d, hi == d, hi < d, INT64_MIN).
#
# The twelve marker cells live at 01A20000h, free RAM above the 4 KiB entry
# stack, outside
# .text/.data/.bss. The gate-local scripts/m7/i64div-link.cmd widens the prog
# region to 40000h (the M4 default 8000h is 4 KiB and the driver's .text is
# larger), and scripts/m7/i64div-map-check.py asserts on both the tms-link and
# GSPLNK maps that the marker cells do not overlap any section. The GSPA link
# phase runs before MAME as a fail-fast check. The loader budget is widened
# from the M6 default (LOADER_AT=200, LOADER_END=4000) to leave room for the
# slow phase; the M7 full-suite loader settings keep 200/1000 and are
# unaffected.
#
# The compile-only preflight (tms-clang + llc asm and obj, no DOSBox/MAME)
# checks that the driver asm has both the fast blocks (i64div.fast, DIVU) and
# the slow loop (i64div.loop), and I64DIV_PERF_LINK_ONLY=1 also checks the
# marker cells against a host tms-link map. I64DIV_PERF_COMPILE_ONLY=1 stops
# after the asm checks.
#
# I64DIV_PERF_OPT=-O2 is an optimizer-level baseline, not the i64 fast-path
# measurement: at -O2 instcombine narrows some of the fast phase's divisions to
# i32, so the default -O0 run is the evidence for TMS34010LowerI64's fast path.
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG TMS_OPT TMS_BITADDR TMS_LINK MAME
# DOSBOX DOSBOX_CONF SDK_IMG I64DIV_PERF_WORK I64DIV_PERF_OPT
# I64DIV_PERF_COMPILE_ONLY I64DIV_PERF_LINK_ONLY LOADER_AT
# LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
SRC=$DIR/i64div-perf.c
CHECK_LUA=$DIR/i64div-perf-check.lua
LINK_CMD=$DIR/i64div-link.cmd
MAP_CHECK=$DIR/i64div-map-check.py
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
WORK=${I64DIV_PERF_WORK:-$ROOT/build/m7-i64div-perf}
OPT=${I64DIV_PERF_OPT:--O0}
LOADER_AT=${LOADER_AT:-200}
LOADER_END=${LOADER_END:-4000}
# The marker base in i64div-perf.c and i64div-perf-check.lua; the map check
# asserts these 12 cells at 0x20 bits apart are outside every linked section.
MARKERS=01A20000
PROG_ORIGIN=018A0000
PROG_LEN=40000
RAM_ORIGIN=01A00000
RAM_LEN=80000
fail() {
echo "m7 i64div perf: FAIL: $*" >&2
exit 1
}
for tool in "$TMS_LLC" "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LINK"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
for f in "$SRC" "$CHECK_LUA" "$LINK_CMD" "$MAP_CHECK"; do
[ -f "$f" ] || fail "missing file: $f"
done
rm -rf "$WORK"
mkdir -p "$WORK"
echo "== compile-only preflight ($OPT): both paths in the driver asm"
export TMS_CLANG TMS_OPT TMS_BITADDR
"$ROOT/scripts/tms-clang" "$OPT" -o "$WORK/i64div-perf.ll" "$SRC" \
|| fail "tms-clang failed for i64div-perf.c"
"$TMS_LLC" -march=tms34010 "$OPT" -filetype=asm "$WORK/i64div-perf.ll" \
-o "$WORK/i64div-perf.s" || fail "llc failed for i64div-perf.ll"
fast=$(grep -c '; %i64div.fast' "$WORK/i64div-perf.s" || true)
loop=$(grep -c '; %i64div.loop' "$WORK/i64div-perf.s" || true)
wide=$(grep -c '; %i64div.wide' "$WORK/i64div-perf.s" || true)
divu=$(grep -c 'DIVU ' "$WORK/i64div-perf.s" || true)
[ "$fast" -ge 1 ] || fail "no i64div.fast block in the driver asm"
[ "$loop" -ge 1 ] || fail "no i64div.loop block in the driver asm"
[ "$wide" -ge 1 ] || fail "no i64div.wide block in the driver asm"
[ "$divu" -ge 1 ] || fail "no 32-bit DIVU in the driver asm"
grep -q "0x${MARKERS}" "$SRC" \
|| fail "i64div-perf.c does not use the marker base 0x$MARKERS"
grep -q "0x${MARKERS}" "$CHECK_LUA" \
|| fail "i64div-perf-check.lua does not use the marker base 0x$MARKERS"
echo " fast blocks=$fast loop blocks=$loop wide blocks=$wide DIVU=$divu markers=$MARKERS"
echo " i64div-perf.s: $(grep -c . "$WORK/i64div-perf.s") lines"
if [ "${I64DIV_PERF_COMPILE_ONLY:-0}" = 1 ]; then
echo "M7 I64DIV PERF COMPILE: PASS"
exit 0
fi
echo "== host link check (tms-link): markers outside .text/.data/.bss"
"$TMS_LLC" -march=tms34010 "$OPT" -filetype=obj "$WORK/i64div-perf.ll" \
-o "$WORK/i64div-perf.o" || fail "llc -filetype=obj failed"
# The entry assembly is not assembler-readable to tms-link; this link checks
# the driver's real .text/.data extents. The entry only adds a few words of
# .text and the 4 KiB _cstack in .bss, and the GSPLNK map below checks the
# complete image.
"$TMS_LINK" -o "$WORK/i64div-perf-tmslink.coff" \
--map "$WORK/i64div-perf-tmslink.map" --entry _i64div_perf_run \
--text "$PROG_ORIGIN" --bss "$RAM_ORIGIN" \
--prog-len "${PROG_LEN}h" --ram-len "${RAM_LEN}h" "$WORK/i64div-perf.o" \
|| fail "tms-link failed"
python3 "$MAP_CHECK" "$WORK/i64div-perf-tmslink.map" "$MARKERS" \
"$PROG_ORIGIN" "$PROG_LEN" "$RAM_ORIGIN" "$RAM_LEN" \
|| fail "marker cells overlap a tms-link section"
if [ "${I64DIV_PERF_LINK_ONLY:-0}" = 1 ]; then
echo "M7 I64DIV PERF LINK: PASS"
exit 0
fi
run_m4() {
skip=$1
shift
M4_WORK="$WORK" \
M4_SDK="$WORK/sdk" \
M4_COFF="$WORK/i64div-perf.coff" \
M4_SOURCES="$SRC" \
M4_ENTRY="$DIR/i64div-perf-entry.asm" \
M4_CHECK_LUA="$CHECK_LUA" \
M4_LINK_CMD="$LINK_CMD" \
M4_CLANG_OPT="$OPT" \
M4_LLC_OPT="$OPT" \
M4_SKIP_MAME="$skip" \
LOADER_AT="$LOADER_AT" \
LOADER_END="$LOADER_END" \
"$ROOT/scripts/m4/run.sh" "$@"
}
echo "== GSPA/GSPLNK link phase: assert the complete image map"
run_m4 1 > "$WORK/link.log" 2>&1 \
|| { tail -60 "$WORK/link.log" >&2; fail "GSPA/GSPLNK link failed"; }
python3 "$MAP_CHECK" "$WORK/m4.map" "$MARKERS" \
"$PROG_ORIGIN" "$PROG_LEN" "$RAM_ORIGIN" "$RAM_LEN" \
|| { tail -40 "$WORK/link.log" >&2; \
fail "marker cells overlap a GSPLNK section"; }
echo "== MAME run"
run_m4 '' > "$WORK/run.log" 2>&1 \
|| { tail -60 "$WORK/run.log" >&2; fail "compile/link/MAME harness failed"; }
grep -q '^M7 MAME: PASS' "$WORK/mame.log" \
|| { grep -E '^M7: i64div perf|^M7 MAME' "$WORK/mame.log" >&2 || true; \
tail -40 "$WORK/run.log" >&2; \
fail "the fast path did not complete in materially fewer frames"; }
echo "== MAME evidence"
grep -E '^M7: i64div perf|^M7 MAME: PASS' "$WORK/mame.log" | sed 's/^/ /'
echo "M7 I64DIV PERF: PASS"
+283
View File
@@ -0,0 +1,283 @@
#!/bin/sh
# M7 native-link oracle gate: link the M5 native object with a GSPA entry
# object using both tms-link and GSPLNK 2.00, then require identical allocated
# section bytes and symbol addresses.
#
# GSPLNK is the format/layout oracle. This gate does not run MAME; the M5
# native gate keeps the GSPLNK/loader/MAME acceptance, and Task 3 owns the
# MAME oracle gate for tms-link.
#
# scripts/tests/m7/link.sh
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG M7_LINK_WORK M7_SDK SDK_IMG
# DOSBOX DOSBOX_CONF
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m5
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M7_LINK_WORK:-$ROOT/build/m7-link}
SDK=${M7_SDK:-$ROOT/build/m4-sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
fail() {
echo "M7 link oracle: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF (set M7COFF=...)"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
mkdir -p "$WORK"
echo "== compile scripts/m5/native-link.c with tms-clang/llc"
"$TMS_CLANG" -O0 -o "$WORK/native-link.ll" "$DIR/native-link.c" \
|| fail "tms-clang failed"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/native-link.ll" -o "$WORK/native.o" \
|| fail "llc -filetype=obj failed"
echo "== extract the GSPA/GSPLNK toolchain"
if [ ! -f "$SDK/GSPA.EXE" ] || [ ! -f "$SDK/GSPLNK.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
[ -f "$SDK/GSPLNK.EXE" ] || fail "GSPLNK.EXE is not extracted in $SDK"
DOS=$WORK/dos
rm -rf "$DOS"
mkdir -p "$DOS"
cp "$SDK/GSPA.EXE" "$SDK/GSPLNK.EXE" "$DOS/"
cp "$WORK/native.o" "$DOS/NATIVE.O"
sed 's/\r$//' "$DIR/native-entry.asm" | sed 's/$/\r/' > "$DOS/ENTRY.ASM"
sed 's/\r$//' "$DIR/native-link.cmd" | sed 's/$/\r/' > "$DOS/NATIVE.CMD"
echo "== assemble ENTRY.ASM and link with GSPLNK 2.00 (oracle)"
rm -f "$DOS/ENTRY.O" "$DOS/ENTRY.LST" "$DOS/NATIVE.OUT" "$DOS/NATIVE.MAP"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa ENTRY ENTRY.O ENTRY.LST -l" \
-c "gsplnk NATIVE.CMD" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/ENTRY.LST" ] || fail "GSPA produced no ENTRY.LST"
sed 's/\r$//' "$DOS/ENTRY.LST" > "$WORK/entry.lst"
grep -q 'No Errors' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
[ -f "$DOS/NATIVE.OUT" ] \
|| { tail -30 "$WORK/dosbox.log" >&2; fail "GSPLNK produced no NATIVE.OUT"; }
cp "$DOS/NATIVE.OUT" "$WORK/oracle.coff"
sed 's/\r$//' "$DOS/NATIVE.MAP" > "$WORK/oracle.map"
echo "== link the same objects with tms-link"
"$TMS_LINK" -o "$WORK/tms-link.coff" --map "$WORK/tms-link.map" \
--entry _native_entry --text 018A0000 --bss 01A00000 \
"$DOS/NATIVE.O" "$DOS/ENTRY.O" \
|| fail "tms-link failed"
# Cheap archive check: wrap the entry object as a small no-index ar member and
# require the same image through both the archive path and -l/. The archive is
# built here rather than with GNU ar so the gate does not depend on whether the
# host ar can index TI-COFF (it cannot).
echo "== archive the entry object and link it with tms-link"
python3 - "$DOS/ENTRY.O" "$WORK/entry.lib" <<'PY'
import sys
src, dst = sys.argv[1:]
data = open(src, "rb").read()
header = (b"ENTRY.O/".ljust(16, b" ") + b"0".ljust(12, b" ") +
b"0".ljust(6, b" ") + b"0".ljust(6, b" ") +
b"644".ljust(8, b" ") +
str(len(data)).encode().ljust(10, b" ") + b"`\n")
out = bytearray(b"!<arch>\n")
out.extend(header)
out.extend(data)
if len(data) & 1:
out.append(0x0A)
open(dst, "wb").write(out)
PY
"$TMS_LINK" -o "$WORK/tms-link-archive.coff" --entry _native_entry \
--text 018A0000 --bss 01A00000 \
"$DOS/NATIVE.O" "$WORK/entry.lib" \
|| fail "tms-link archive link failed"
"$TMS_LINK" -o "$WORK/tms-link-lib.coff" --entry _native_entry \
--text 018A0000 --bss 01A00000 -L "$WORK" -l entry \
"$DOS/NATIVE.O" \
|| fail "tms-link -l link failed"
cmp -s "$WORK/tms-link.coff" "$WORK/tms-link-archive.coff" \
|| fail "archive input changed the tms-link image"
cmp -s "$WORK/tms-link.coff" "$WORK/tms-link-lib.coff" \
|| fail "-l input changed the tms-link image"
python3 - "$M7COFF" "$WORK/oracle.coff" "$WORK/tms-link.coff" \
"$WORK/tms-link.map" "$DOS/NATIVE.O" "$DOS/ENTRY.O" <<'PY' \
|| fail "tms-link output differs from GSPLNK"
import os
import struct
import sys
# The permanent oracle must not use the linker's own reader. Task 1's
# test-local m7coff.py is the independent reference for this COFF subset.
sys.dont_write_bytecode = True
reader_path = sys.argv[1]
sys.path.insert(0, os.path.dirname(reader_path))
import m7coff # noqa: E402
oracle_path, ours_path, map_path = sys.argv[2], sys.argv[3], sys.argv[4]
input_paths = sys.argv[5:]
def align16(value):
return (value + 15) & ~15
def section_size(obj, name):
for sec in obj["sections"]:
if sec["name"] == name:
return sec["size"]
return 0
def is_ext(sym):
return sym["sclass"] == 2 and sym["secno"] > 0
def ext_map(obj):
return {s["name"]: s["value"] for s in obj["symbols"] if is_ext(s)}
def stat_syms(obj):
return [s for s in obj["symbols"]
if s["sclass"] == 3 and s["secno"] > 0]
a = m7coff.parse(oracle_path)
b = m7coff.parse(ours_path)
inputs = [m7coff.parse(path) for path in input_paths]
if [s["name"] for s in a["sections"]] != [s["name"] for s in b["sections"]]:
sys.exit("section names %r != %r"
% ([s["name"] for s in a["sections"]],
[s["name"] for s in b["sections"]]))
if len(a["sections"]) != 3:
sys.exit("oracle has %d sections, want 3" % len(a["sections"]))
for sa, sb in zip(a["sections"], b["sections"]):
if sa["paddr"] != sb["paddr"]:
sys.exit("%s paddr %#x != %#x"
% (sa["name"], sa["paddr"], sb["paddr"]))
if sa["vaddr"] != sb["vaddr"]:
sys.exit("%s vaddr %#x != %#x"
% (sa["name"], sa["vaddr"], sb["vaddr"]))
if sa["size"] != sb["size"]:
sys.exit("%s size %d != %d" % (sa["name"], sa["size"], sb["size"]))
if sa["flags"] != sb["flags"]:
sys.exit("%s flags %#x != %#x"
% (sa["name"], sa["flags"], sb["flags"]))
if sa["raw"] != sb["raw"]:
bad = [i for i in range(min(len(sa["raw"]), len(sb["raw"])))
if sa["raw"][i] != sb["raw"][i]]
sys.exit("%s bytes differ: %d byte(s), first %r"
% (sa["name"],
len(bad) + abs(len(sa["raw"]) - len(sb["raw"])),
[(hex(i), sa["raw"][i], sb["raw"][i]) for i in bad[:8]]))
if sb["nreloc"]:
sys.exit("%s still has %d relocations"
% (sb["name"], sb["nreloc"]))
if a["flags"] != b["flags"]:
sys.exit("file flags %#x != %#x" % (a["flags"], b["flags"]))
if a["opthdr"] != 28 or b["opthdr"] != 28:
sys.exit("optional header sizes %d != %d" % (a["opthdr"], b["opthdr"]))
opt_a = struct.unpack_from("<HHIIIIII", a["data"], 20)
opt_b = struct.unpack_from("<HHIIIIII", b["data"], 20)
if opt_a != opt_b:
sys.exit("optional header %r != %r" % (opt_a, opt_b))
# Exact public C_EXT equality, including the one deliberate tms-link extra:
# the spec's public `cinit` symbol, only when an input contributes bytes.
text_origin = a["sections"][0]["paddr"]
text_size = sum(section_size(o, ".text") for o in inputs)
data_size = sum(section_size(o, ".data") for o in inputs)
cinit_size = sum(section_size(o, ".cinit") for o in inputs)
data_origin = align16(text_origin + text_size)
cinit_origin = align16(data_origin + data_size)
expected = ext_map(a)
if cinit_size:
expected["cinit"] = cinit_origin
actual = ext_map(b)
if actual != expected:
missing = sorted(set(expected) - set(actual))
extra = sorted(set(actual) - set(expected))
wrong = sorted(name for name in set(expected) & set(actual)
if expected[name] != actual[name])
sys.exit("C_EXT set mismatch: missing=%r extra=%r wrong-values=%r"
% (missing, extra,
[(n, hex(expected[n]), hex(actual[n])) for n in wrong]))
# Deliberate C_STAT difference: GSPLNK keeps one section symbol per input
# section (with that input's size/relocation count); tms-link emits one per
# output section with the final size and nreloc 0. The loader uses neither.
a_stat, b_stat = stat_syms(a), stat_syms(b)
if len(b_stat) != len(b["sections"]):
sys.exit("tms-link has %d C_STAT section symbols, want %d"
% (len(b_stat), len(b["sections"])))
for sym in b_stat:
sec = next(s for s in b["sections"] if s["index"] == sym["secno"])
size, nreloc = struct.unpack_from("<II", sym["aux"], 0)
if size != sec["size"] or nreloc != 0:
sys.exit("tms-link section symbol %s aux size=%d nreloc=%d, want "
"%d/0" % (sym["name"], size, nreloc, sec["size"]))
if len(a_stat) != 2 * len(a["sections"]):
sys.exit("GSPLNK has %d C_STAT section symbols, want %d (two inputs)"
% (len(a_stat), 2 * len(a["sections"])))
if len(a_stat) == len(b_stat):
sys.exit("expected GSPLNK's per-input C_STAT symbols to differ from "
"tms-link's output section symbols")
if {s["name"] for s in a_stat} != {s["name"] for s in b_stat}:
sys.exit("C_STAT section names differ: %r vs %r"
% (sorted({s["name"] for s in a_stat}),
sorted({s["name"] for s in b_stat})))
with open(map_path, encoding="latin1") as fh:
map_text = fh.read()
if 'ENTRY POINT SYMBOL: "_native_entry"' not in map_text:
sys.exit("tms-link map has no entry line")
if not any(len(line.split()) >= 2 and line.split()[1] == "_native_entry" and
int(line.split()[0], 16) == actual["_native_entry"]
for line in map_text.splitlines()):
sys.exit("tms-link map has no '_native_entry' address line")
print(" oracle == tms-link: .text=%d bits .data=%d bits .bss=%d bits"
% (a["sections"][0]["size"], a["sections"][1]["size"],
a["sections"][2]["size"]))
print(" public C_EXT set equal (%d names), entry=%08X"
% (len(expected), actual["_native_entry"]))
print(" C_STAT: GSPLNK %d per-input section symbols, tms-link %d output "
"section symbols with final sizes" % (len(a_stat), len(b_stat)))
PY
echo "M7 link oracle: PASS"
+221
View File
@@ -0,0 +1,221 @@
#!/bin/sh
# M7.2 long-public-name gate: a >31-character public function across two TUs.
#
# scripts/tests/m7/longname.sh
#
# scripts/m7/longname-a.c defines the 44-character public function
# tms34010_public_function_name_longer_than_31 (45 with the C `_` prefix);
# longname-b.c declares and calls it from longname_call(). GSPA only sees the
# short entry/wrapper names; tms-link resolves the long external and keeps the
# full name in the linked symbol table and map (GSPA's 31-character truncation
# is an asm-path limitation and is not acceptable here).
#
# MAME loads the tms-link image and the entry stores longname_call()'s result,
# 43, at 018A8000.
#
# Overridable: LLVM_BIN TMS_CLANG TMS_LLC TMS_LINK M7COFF M7_LONGNAME_WORK
# M7_SDK SDK_IMG DOSBOX DOSBOX_CONF MAME MAME_TIMEOUT LOADER_AT
# LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
LONG=tms34010_public_function_name_longer_than_31
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M7_LONGNAME_WORK:-$ROOT/build/m7-longname}
SDK=${M7_SDK:-$WORK/sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "M7 longname: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF (set M7COFF=...)"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing loader payload: $LOADER_BIN"
[ "${#LONG}" -gt 31 ] || fail "test name '$LONG' is not longer than 31"
rm -rf "$WORK"
mkdir -p "$WORK/dos" "$WORK/run/nvram" "$WORK/run/cfg" "$WORK/evidence"
WORK=$(cd "$WORK" && pwd)
echo "== compile the two TUs ($LONG is ${#LONG} characters)"
for tu in longname-a longname-b; do
( cd "$DIR" && "$TMS_CLANG" -O0 -o "$WORK/$tu.ll" "$tu.c" ) \
|| fail "tms-clang failed for $tu.c"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/$tu.ll" -o "$WORK/$tu.o" \
|| fail "llc -filetype=obj failed for $tu.c"
done
python3 - "$M7COFF" "$WORK/longname-a.o" "$WORK/longname-b.o" "$LONG" <<'PY' \
|| fail "the TUs do not define/reference the full long name"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
a = m7coff.parse(sys.argv[2])
b = m7coff.parse(sys.argv[3])
name = sys.argv[4]
want = "_" + name
adef = [s for s in a["symbols"] if s["name"] == want]
bref = [s for s in b["symbols"] if s["name"] == want]
if len(adef) != 1 or adef[0]["secno"] != 1 or adef[0]["sclass"] != 2:
sys.exit("TU A does not define %r in .text: %r" % (want, adef))
if len(bref) != 1 or bref[0]["secno"] != 0 or bref[0]["sclass"] != 2:
sys.exit("TU B does not reference %r as an undefined C_EXT: %r"
% (want, bref))
print(" TU A defines %s; TU B references it as an undefined C_EXT"
% want)
PY
echo "== extract the GSPA toolchain"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
DOS=$WORK/dos
cp "$SDK/GSPA.EXE" "$DOS/"
cp "$WORK/longname-a.o" "$DOS/LONGA.O"
cp "$WORK/longname-b.o" "$DOS/LONGB.O"
sed 's/\r$//' "$DIR/longname-entry.asm" | sed 's/$/\r/' > "$DOS/ENTRY.ASM"
echo "== assemble longname-entry.asm with GSPA 2.00"
rm -f "$DOS/ENTRY.O" "$DOS/ENTRY.LST"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa ENTRY ENTRY.O ENTRY.LST -l" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/ENTRY.LST" ] || fail "GSPA produced no ENTRY.LST"
sed 's/\r$//' "$DOS/ENTRY.LST" > "$WORK/entry.lst"
grep -q 'No Errors' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
echo "== link with tms-link"
"$TMS_LINK" -o "$WORK/longname.coff" --map "$WORK/longname.map" \
--entry _start --text 018A0000 --bss 01A00000 \
"$DOS/ENTRY.O" "$DOS/LONGA.O" "$DOS/LONGB.O" \
|| fail "tms-link failed"
python3 - "$M7COFF" "$WORK/longname.coff" "$WORK/longname.map" "$LONG" \
<<'PY' || fail "the linked symbol table/map does not keep the full name"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
coff = m7coff.parse(sys.argv[2])
map_path, name = sys.argv[3], sys.argv[4]
want = "_" + name
syms = {s["name"]: s for s in coff["symbols"] if s["sclass"] == 2}
if want not in syms:
sys.exit("linked image has no %r; symbols: %r"
% (want, sorted(syms)))
sym = syms[want]
if sym["secno"] != 1:
sys.exit("%r is not in .text (secno %d)" % (want, sym["secno"]))
if "_longname_call" not in syms:
sys.exit("linked image has no _longname_call")
truncated = [n for n in syms if n.startswith(want[:31]) and n != want]
if truncated:
sys.exit("linked image has a truncated variant: %r" % truncated)
lines = open(map_path, encoding="latin1").read().splitlines()
if not any(line.startswith('ENTRY POINT SYMBOL: "_start"') for line in lines):
sys.exit("map has no _start entry line: %r" % lines[:2])
matches = [line for line in lines
if line.split()[1:2] == [want] and
int(line.split()[0], 16) == sym["value"]]
if not matches:
sys.exit("map has no full-name %r line at %#x; map:\n%s"
% (want, sym["value"], "\n".join(lines)))
print(" linked %s at %08X; map keeps the full %d-character name"
% (want, sym["value"], len(want)))
PY
echo "== run the tms-link image in MAME"
cat > "$WORK/longname-check.lua" <<'LUA'
dofile(os.getenv("M4_LOADER_LUA"))
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local value = prog:read_u32(0x018A8000)
print(string.format("LONGNAME: value=%d", value))
if value == 43 then
print("LONGNAME MAME: PASS")
else
print("LONGNAME MAME: FAIL (want 43)")
end
end
end, "longname-check")
LUA
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$WORK/longname.coff" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$WORK/longname-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; \
fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^LONGNAME: value=43$' "$WORK/mame.log" \
|| { grep '^LONGNAME:' "$WORK/mame.log" >&2 || true; \
fail "longname marker is wrong"; }
grep -q '^LONGNAME MAME: PASS$' "$WORK/mame.log" \
|| fail "MAME long-name call check failed"
echo "M7 longname: PASS (44-character public function linked across two TUs,"
echo " full name in the linked symbols and map, call runs in MAME)"
+130
View File
@@ -0,0 +1,130 @@
/* M7.1 `.data` initializer gate driver.
*
* Every global below is `volatile` so the reads at -O0/-O2 really come from
* the linked `.data` image rather than from a folded constant.
*
* The initializers exercise the M7.1 emitter recursion:
* - a 64-bit scalar (LSW first in memory);
* - the 1987 bitfield struct s { a:3; b:5; c:4; d:20; e:4; } (5 bytes,
* Clang's byte storage);
* - a packed record with an interior i64 (<{ i8, i32, i64 }>, 13 bytes);
* - an array of packed records (3 x 6 bytes);
* - a union whose active member is the 6-byte struct and whose allocation
* is the 8-byte i64 (the trailing two bytes are zero);
* - a pointer global, a pointer with a +3-byte addend, and a packed record
* with a pointer field between two scalar fields (the TI-COFF relocation
* and the GSPA `.long _x`).
*
* Markers are at 0x018A8000 + n*0x20; the raw object bytes are at
* 0x018A9000 + n*8. data-check.lua compares them with the exact expected
* values, so both the field reads and the byte image are checked in MAME.
*/
typedef unsigned int u32;
#define MARK(n) (*(volatile u32 *)(0x018A8000u + (u32)(n) * 0x20u))
#define OUTB(n) (*(volatile unsigned char *)(0x018A9000u + (u32)(n) * 8u))
volatile long long x = 0x1122334455667788LL;
struct s {
unsigned a:3;
unsigned b:5;
int c:4;
unsigned d:20;
unsigned e:4;
};
volatile struct s s = { 5, 17, -3, 0xABCDE, 9 };
struct p {
char a;
int b;
long long c;
};
volatile struct p p = { 0x11, 0x22334455, 0x66778899AABBCCDDLL };
struct rec {
int a;
short b;
};
volatile struct rec arr[3] = {
{ 0x11223344, 0x5566 },
{ 0x778899AA, 0xBBCC },
{ 0xDDEEFF00, 0x1122 },
};
union u {
long long l;
char c[6];
struct { int i; short h; } s;
};
volatile union u u = { .s = { 0x12345678, 0x9ABC } };
long long *volatile pp = (long long *)&x;
char *volatile cp = (char *)&x + 3;
struct pt {
int tag;
long long *p;
char c;
};
volatile struct pt pt = { 0x1234, (long long *)&x, 0x5A };
static void dump(const volatile unsigned char *src, u32 n, u32 *out)
{
u32 i;
for (i = 0; i < n; i++)
OUTB((*out)++) = src[i];
}
void data_run(void)
{
u32 o;
MARK(0) = (u32)(unsigned long long)x;
MARK(1) = (u32)((unsigned long long)x >> 32);
MARK(2) = (u32)s.a;
MARK(3) = (u32)s.b;
MARK(4) = (u32)s.c;
MARK(5) = (u32)s.d;
MARK(6) = (u32)s.e;
MARK(7) = (u32)p.a;
MARK(8) = (u32)p.b;
MARK(9) = (u32)p.c;
MARK(10) = (u32)((unsigned long long)p.c >> 32);
MARK(11) = (u32)arr[0].a;
MARK(12) = (u32)arr[1].a;
MARK(13) = (u32)arr[2].a;
MARK(14) = (u32)(unsigned short)arr[0].b;
MARK(24) = (u32)(unsigned short)arr[1].b;
MARK(23) = (u32)(unsigned short)arr[2].b;
MARK(15) = (u32)u.s.i;
MARK(16) = (u32)(unsigned short)u.s.h;
MARK(17) = (u32)((pp == &x) && (*pp == x));
MARK(18) = (u32)(cp - (char *)&x);
MARK(19) = (u32)pt.tag;
MARK(20) = (u32)((pt.p == &x) && (pt.c == 0x5A));
MARK(21) = (u32)u.l;
MARK(22) = (u32)((unsigned long long)u.l >> 32);
/* The linked address of x, for the pointer bytes in the raw image. */
MARK(25) = (u32)(unsigned long)&x;
/* Raw bytes: x, s, p, arr, u are contiguous; pt starts at byte 64. */
o = 0;
dump((const volatile unsigned char *)&x, (u32)sizeof(x), &o);
dump((const volatile unsigned char *)&s, (u32)sizeof(s), &o);
dump((const volatile unsigned char *)&p, (u32)sizeof(p), &o);
dump((const volatile unsigned char *)&arr, (u32)sizeof(arr), &o);
dump((const volatile unsigned char *)&u, (u32)sizeof(u), &o);
o = 64;
dump((const volatile unsigned char *)&pt, (u32)sizeof(pt), &o);
}
+42
View File
@@ -0,0 +1,42 @@
/* M7.1 odd-offset pointer `.data` gate (native path only).
*
* The target packs records, so `struct oddptr { char c; long long *p; }` puts
* the pointer at byte offset 1. GSPA's only 32-bit relocatable directive is
* `.long`, which it implicitly 16-bit aligns, so the raw text path must reject
* this shape loudly. The TI-COFF object path writes the field unaligned and
* emits an R-RELLONG at the odd byte; data.sh links that object with GSPLNK,
* runs it in MAME and checks the pointer value and raw bytes.
*
* Markers 26..29 are c, p == &x, and the two words of *p. The raw 5-byte
* object is copied to 0x018A9000 + 96*8; the pointer bytes are compared with
* the linked address of x from marker 25.
*/
typedef unsigned int u32;
#define MARK(n) (*(volatile u32 *)(0x018A8000u + (u32)(n) * 0x20u))
#define OUTB(n) (*(volatile unsigned char *)(0x018A9000u + (u32)(n) * 8u))
extern volatile long long x;
struct oddptr {
char c;
long long *p;
};
volatile struct oddptr odd = { 0x5A, (long long *)&x };
void data_odd_run(void)
{
const volatile unsigned char *p =
(const volatile unsigned char *)&odd;
u32 i;
MARK(26) = (u32)(unsigned char)odd.c;
MARK(27) = (u32)(odd.p == &x);
MARK(28) = (u32)(unsigned long long)*odd.p;
MARK(29) = (u32)((unsigned long long)*odd.p >> 32);
for (i = 0; i < (u32)sizeof(odd); i++)
OUTB(96u + i) = p[i];
}
+412
View File
@@ -0,0 +1,412 @@
#!/bin/sh
# M7.2 end-to-end oracle gate: GSPLNK 2.00 and tools/tms-link on the same M5
# native objects, then the tms-link image in MAME.
#
# scripts/tests/m7/oracle.sh
#
# 1. scripts/m5/native-link.c -> llc -filetype=obj (NATIVE.O).
# 2. GSPA 2.00 assembles scripts/m5/native-entry.asm (ENTRY.O); GSPLNK 2.00
# links NATIVE.O + ENTRY.O and is the permanent format/layout oracle.
# 3. tms-link links the same two objects with the same origins.
# 4. An independent reader (Task 1's test-local m7coff.py, never tmscoff.py)
# requires identical allocated .text/.data/.bss bytes, paddr/vaddr/size/
# flags, optional header, and the exact public C_EXT name/value set. The
# documented C_STAT shape difference (GSPLNK per-input vs tms-link per-output
# section symbols) is asserted, not ignored.
# 5. The tms-link image is loaded in MAME and must show the M5 native markers
# 018A8000=42, 018A8020=152, 018A8040=1, 018A8060=2, 018A8080=10,
# 018A80A0=77, and dis34 must decode _native_value.
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG TMS_LINK M7COFF M7_ORACLE_WORK
# M7_SDK SDK_IMG DOSBOX DOSBOX_CONF MAME MAME_TIMEOUT DIS34
# LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m5
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M7_ORACLE_WORK:-$ROOT/build/m7-oracle}
SDK=${M7_SDK:-$ROOT/build/m4-sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "M7 oracle: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF (set M7COFF=...)"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -x "$DIS34" ] || fail "missing dis34: $DIS34"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing loader payload: $LOADER_BIN"
rm -rf "$WORK"
mkdir -p "$WORK/dos" "$WORK/run/nvram" "$WORK/run/cfg" "$WORK/evidence"
WORK=$(cd "$WORK" && pwd)
echo "== compile scripts/m5/native-link.c with tms-clang/llc"
"$TMS_CLANG" -O0 -o "$WORK/native-link.ll" "$DIR/native-link.c" \
|| fail "tms-clang failed"
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/native-link.ll" -o "$WORK/native.o" \
|| fail "llc -filetype=obj failed"
echo "== extract the GSPA/GSPLNK toolchain"
if [ ! -f "$SDK/GSPA.EXE" ] || [ ! -f "$SDK/GSPLNK.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
[ -f "$SDK/GSPLNK.EXE" ] || fail "GSPLNK.EXE is not extracted in $SDK"
DOS=$WORK/dos
cp "$SDK/GSPA.EXE" "$SDK/GSPLNK.EXE" "$DOS/"
cp "$WORK/native.o" "$DOS/NATIVE.O"
sed 's/\r$//' "$DIR/native-entry.asm" | sed 's/$/\r/' > "$DOS/ENTRY.ASM"
sed 's/\r$//' "$DIR/native-link.cmd" | sed 's/$/\r/' > "$DOS/NATIVE.CMD"
echo "== assemble ENTRY.ASM and link with GSPLNK 2.00 (oracle)"
rm -f "$DOS/ENTRY.O" "$DOS/ENTRY.LST" "$DOS/NATIVE.OUT" "$DOS/NATIVE.MAP"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa ENTRY ENTRY.O ENTRY.LST -l" \
-c "gsplnk NATIVE.CMD" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/ENTRY.LST" ] || fail "GSPA produced no ENTRY.LST"
sed 's/\r$//' "$DOS/ENTRY.LST" > "$WORK/entry.lst"
grep -q 'No Errors' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/entry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/entry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
[ -f "$DOS/NATIVE.OUT" ] \
|| { tail -30 "$WORK/dosbox.log" >&2; fail "GSPLNK produced no NATIVE.OUT"; }
[ -f "$DOS/NATIVE.MAP" ] || fail "GSPLNK produced no NATIVE.MAP"
cp "$DOS/NATIVE.OUT" "$WORK/oracle.coff"
sed 's/\r$//' "$DOS/NATIVE.MAP" > "$WORK/oracle.map"
echo "== link the same objects with tms-link"
"$TMS_LINK" -o "$WORK/tms-link.coff" --map "$WORK/tms-link.map" \
--entry _native_entry --text 018A0000 --bss 01A00000 \
"$DOS/NATIVE.O" "$DOS/ENTRY.O" \
|| fail "tms-link failed"
echo "== require identical allocated bytes and public symbol values"
python3 - "$M7COFF" "$WORK/oracle.coff" "$WORK/tms-link.coff" \
"$WORK/tms-link.map" "$DOS/NATIVE.O" "$DOS/ENTRY.O" <<'PY' \
|| fail "tms-link output differs from GSPLNK"
import os
import struct
import sys
# The independent reader is Task 1's test-local m7coff.py, never the linker's
# own tmscoff.py.
sys.dont_write_bytecode = True
reader_path = sys.argv[1]
sys.path.insert(0, os.path.dirname(reader_path))
import m7coff # noqa: E402
oracle_path, ours_path, map_path = sys.argv[2], sys.argv[3], sys.argv[4]
input_paths = sys.argv[5:]
def align16(value):
return (value + 15) & ~15
def section_size(obj, name):
for sec in obj["sections"]:
if sec["name"] == name:
return sec["size"]
return 0
def is_ext(sym):
return sym["sclass"] == 2 and sym["secno"] > 0
def ext_map(obj):
return {s["name"]: s["value"] for s in obj["symbols"] if is_ext(s)}
def stat_syms(obj):
return [s for s in obj["symbols"]
if s["sclass"] == 3 and s["secno"] > 0]
a = m7coff.parse(oracle_path)
b = m7coff.parse(ours_path)
inputs = [m7coff.parse(path) for path in input_paths]
if [s["name"] for s in a["sections"]] != [s["name"] for s in b["sections"]]:
sys.exit("section names %r != %r"
% ([s["name"] for s in a["sections"]],
[s["name"] for s in b["sections"]]))
if len(a["sections"]) != 3:
sys.exit("oracle has %d sections, want 3" % len(a["sections"]))
for sa, sb in zip(a["sections"], b["sections"]):
if sa["paddr"] != sb["paddr"]:
sys.exit("%s paddr %#x != %#x"
% (sa["name"], sa["paddr"], sb["paddr"]))
if sa["vaddr"] != sb["vaddr"]:
sys.exit("%s vaddr %#x != %#x"
% (sa["name"], sa["vaddr"], sb["vaddr"]))
if sa["size"] != sb["size"]:
sys.exit("%s size %d != %d" % (sa["name"], sa["size"], sb["size"]))
if sa["flags"] != sb["flags"]:
sys.exit("%s flags %#x != %#x"
% (sa["name"], sa["flags"], sb["flags"]))
if sa["raw"] != sb["raw"]:
bad = [i for i in range(min(len(sa["raw"]), len(sb["raw"])))
if sa["raw"][i] != sb["raw"][i]]
sys.exit("%s bytes differ: %d byte(s), first %r"
% (sa["name"],
len(bad) + abs(len(sa["raw"]) - len(sb["raw"])),
[(hex(i), sa["raw"][i], sb["raw"][i]) for i in bad[:8]]))
if sb["nreloc"]:
sys.exit("%s still has %d relocations"
% (sb["name"], sb["nreloc"]))
if a["flags"] != b["flags"]:
sys.exit("file flags %#x != %#x" % (a["flags"], b["flags"]))
if a["opthdr"] != 28 or b["opthdr"] != 28:
sys.exit("optional header sizes %d != %d" % (a["opthdr"], b["opthdr"]))
opt_a = struct.unpack_from("<HHIIIIII", a["data"], 20)
opt_b = struct.unpack_from("<HHIIIIII", b["data"], 20)
if opt_a != opt_b:
sys.exit("optional header %r != %r" % (opt_a, opt_b))
# Exact public C_EXT equality, including the one deliberate tms-link extra:
# the spec's public `cinit` symbol, only when an input contributes bytes.
text_origin = a["sections"][0]["paddr"]
text_size = sum(section_size(o, ".text") for o in inputs)
data_size = sum(section_size(o, ".data") for o in inputs)
cinit_size = sum(section_size(o, ".cinit") for o in inputs)
data_origin = align16(text_origin + text_size)
cinit_origin = align16(data_origin + data_size)
expected = ext_map(a)
if cinit_size:
expected["cinit"] = cinit_origin
actual = ext_map(b)
# is_ext intentionally covers defined public C_EXT only: absolute symbols
# (secno == -1) and undefined references (secno == 0) are not addresses in the
# linked image. The M5 pair has neither; `_native_external` is defined by
# ENTRY.O and therefore has secno > 0. Assert a floor and the names the MAME
# and dis34 checks depend on so an accidentally empty/short set cannot pass.
required = {"_native_entry", "_native_value", "_native_first", "_native_loop",
"_native_call_external", "_msg", "_native_counter",
"_native_external"}
if len(actual) < 15:
sys.exit("only %d defined public C_EXT symbols; M5 has 18"
% len(actual))
missing_required = sorted(required - set(actual))
if missing_required:
sys.exit("required public C_EXT names missing: %r" % missing_required)
if actual != expected:
missing = sorted(set(expected) - set(actual))
extra = sorted(set(actual) - set(expected))
wrong = sorted(name for name in set(expected) & set(actual)
if expected[name] != actual[name])
sys.exit("C_EXT set mismatch: missing=%r extra=%r wrong-values=%r"
% (missing, extra,
[(n, hex(expected[n]), hex(actual[n])) for n in wrong]))
# Deliberate C_STAT difference: GSPLNK keeps one section symbol per input
# section (with that input's size/relocation count); tms-link emits one per
# output section with the final size and nreloc 0. The loader uses neither.
a_stat, b_stat = stat_syms(a), stat_syms(b)
if len(b_stat) != len(b["sections"]):
sys.exit("tms-link has %d C_STAT section symbols, want %d"
% (len(b_stat), len(b["sections"])))
for sym in b_stat:
sec = next(s for s in b["sections"] if s["index"] == sym["secno"])
size, nreloc = struct.unpack_from("<II", sym["aux"], 0)
if size != sec["size"] or nreloc != 0:
sys.exit("tms-link section symbol %s aux size=%d nreloc=%d, want "
"%d/0" % (sym["name"], size, nreloc, sec["size"]))
if len(a_stat) != 2 * len(a["sections"]):
sys.exit("GSPLNK has %d C_STAT section symbols, want %d (two inputs)"
% (len(a_stat), 2 * len(a["sections"])))
if len(a_stat) == len(b_stat):
sys.exit("expected GSPLNK's per-input C_STAT symbols to differ from "
"tms-link's output section symbols")
if {s["name"] for s in a_stat} != {s["name"] for s in b_stat}:
sys.exit("C_STAT section names differ: %r vs %r"
% (sorted({s["name"] for s in a_stat}),
sorted({s["name"] for s in b_stat})))
with open(map_path, encoding="latin1") as fh:
map_text = fh.read()
if 'ENTRY POINT SYMBOL: "_native_entry"' not in map_text:
sys.exit("tms-link map has no entry line")
if not any(len(line.split()) >= 2 and line.split()[1] == "_native_entry" and
int(line.split()[0], 16) == actual["_native_entry"]
for line in map_text.splitlines()):
sys.exit("tms-link map has no '_native_entry' address line")
print(" oracle == tms-link: .text=%d bits .data=%d bits .bss=%d bits"
% (a["sections"][0]["size"], a["sections"][1]["size"],
a["sections"][2]["size"]))
print(" public C_EXT set equal (%d names), entry=%08X"
% (len(expected), actual["_native_entry"]))
print(" C_STAT: GSPLNK %d per-input section symbols, tms-link %d output "
"section symbols with final sizes" % (len(a_stat), len(b_stat)))
PY
echo "== extract the tms-link .text and disassemble _native_value with dis34"
M7COFF_DIR=$(dirname "$M7COFF")
export M7COFF_DIR
python3 - "$WORK/tms-link.coff" "$WORK/tms-link.text" "$WORK/tms-link.env" \
<<'PY' || fail "could not extract the linked .text/symbols"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.environ["M7COFF_DIR"])
import m7coff # noqa: E402
coff = m7coff.parse(sys.argv[1])
text = m7coff.section(coff, ".text")
with open(sys.argv[2], "wb") as fh:
fh.write(text["raw"])
syms = {s["name"]: s for s in coff["symbols"] if s["sclass"] == 2}
with open(sys.argv[3], "w", encoding="ascii") as fh:
fh.write("TEXT_ADDR=%08X\n" % text["paddr"])
fh.write("VALUE_ADDR=%08X\n" % syms["_native_value"]["value"])
fh.write("FIRST_ADDR=%08X\n" % syms["_native_first"]["value"])
print(" _native_value=%08X _native_first=%08X text=%08X"
% (syms["_native_value"]["value"], syms["_native_first"]["value"],
text["paddr"]))
PY
. "$WORK/tms-link.env"
"$DIS34" -b "$TEXT_ADDR" -l -o "$WORK/tms-link.text" \
> "$WORK/dis34.txt" 2> "$WORK/dis34.err" \
|| { cat "$WORK/dis34.err" >&2; fail "dis34 failed"; }
[ -s "$WORK/dis34.txt" ] || fail "dis34 produced no output"
python3 - "$WORK/dis34.txt" "$VALUE_ADDR" "$FIRST_ADDR" <<'PY' \
|| fail "dis34 did not decode _native_value"
import re
import sys
path, value_addr, first_addr = sys.argv[1], int(sys.argv[2], 16), int(
sys.argv[3], 16)
rows = []
for line in open(path, encoding="latin1"):
m = re.match(r"^([0-9a-fA-F]+):\s+(.*)$", line.strip())
if m:
rows.append((int(m.group(1), 16), m.group(2)))
if not any(addr == value_addr and text.lower().startswith("setf")
for addr, text in rows):
sys.exit(f"dis34 has no SETF at _native_value {value_addr:#x}")
if not any(value_addr <= addr < first_addr and
re.match(r"movi\s+0x2a,\s*a0(\s*;.*)?$", text, re.I)
for addr, text in rows):
sys.exit(f"dis34 has no MOVI 42 in _native_value "
f"[{value_addr:#x}, {first_addr:#x})")
print(f" dis34 decoded _native_value at {value_addr:08x} .. {first_addr:08x}")
PY
echo "== run both linked images in MAME"
cat > "$WORK/oracle-check.lua" <<'LUA'
dofile(os.getenv("M4_LOADER_LUA"))
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local value = prog:read_u32(0x018A8000)
local combo = prog:read_u32(0x018A8020)
local bump1 = prog:read_u32(0x018A8040)
local bump2 = prog:read_u32(0x018A8060)
local loop = prog:read_u32(0x018A8080)
local ext = prog:read_u32(0x018A80A0)
print(string.format(
"ORACLE: value=%d combo=%d bump1=%d bump2=%d loop=%d ext=%d",
value, combo, bump1, bump2, loop, ext))
if value == 42 and combo == 152 and bump1 == 1 and bump2 == 2 and
loop == 10 and ext == 77 then
print("ORACLE MAME: PASS")
else
print("ORACLE MAME: FAIL (want value=42 combo=152 " ..
"bump1=1 bump2=2 loop=10 ext=77)")
end
end
end, "oracle-check")
LUA
run_mame() { # run_mame LABEL IMAGE LOG
label=$1
image=$2
log=$3
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$image" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$WORK/oracle-check.lua" -autoboot_delay 0 \
> "$log" 2>&1 \
|| { tail -30 "$log" >&2; fail "MAME run failed for $label"; }
grep -q 'LOADER: result status=0 (OK)' "$log" \
|| { grep 'LOADER: result' "$log" >&2 || true; \
fail "$label: COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$log" \
|| fail "$label: COFF loader could not verify the placed .text bytes"
grep -q 'placed \.data .* 0 differing' "$log" \
|| fail "$label: COFF loader could not verify the placed .data bytes"
grep -q '^ORACLE: value=42 combo=152 bump1=1 bump2=2 loop=10 ext=77$' \
"$log" \
|| { grep '^ORACLE:' "$log" >&2 || true; \
fail "$label MAME markers are wrong"; }
grep -q '^ORACLE MAME: PASS$' "$log" \
|| fail "MAME marker check failed for $label"
echo " $label: $(grep '^ORACLE:' "$log" | tail -1)"
}
# GSPLNK remains the oracle, but its own image is also loaded so the "same
# MAME markers" claim is directly exercised on both linkers' outputs.
run_mame gsplnk "$WORK/oracle.coff" "$WORK/mame-gsplnk.log"
run_mame tms-link "$WORK/tms-link.coff" "$WORK/mame-tms-link.log"
echo "M7 oracle: PASS (GSPLNK is the oracle; allocated bytes, public symbol"
echo " values, both linkers' MAME markers and dis34 decode agree)"
+100
View File
@@ -0,0 +1,100 @@
-- pointer-check.lua -- read the M7.1 `-O2` pointer gate markers and the exact
-- copy bytes, and compare them with the expected values.
--
-- M4_LOADER_LUA is the dwt loader script. Marker n is at 018A8000 + n*0x20
-- bits (0..12 from the driver, 13 the post-return sentinel); the copy bytes
-- are at 018A9000 + n*8 bits.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local BASE = 0x018A8000
local OUT = 0x018A9000
local N = 13
local SENT = 0x5A5A5A5A
local frames = 0
local checked = false
local expect = {
1, -- a[0..7] == "aabcdefg" after the overlapping backward copy
1, -- a[8] == 'h', a[9] and a[65] untouched
81, -- b[3] == 'Q' after `p += 3; *p = 'Q'`
0, -- b[0] untouched
0, -- b[24] untouched (the old double-scaled byte)
0, -- b[127] untouched
5, -- (q - b) in bytes
40, -- (u32)q - (u32)b in bits
1, -- the forward byte checks
1, -- late64: c + 24 bits == c + 3 bytes (not 192 bits)
1, -- narrow16 keeps (p & 0xffff) + 24
1, -- narrow8 keeps (p & 0xff) + 24
1, -- late64s: the signed i64 form also stays 24 bits
}
local want_bytes = "aabcdefgh"
local function escape(s)
return (s:gsub("\n", "\\n"))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i + 1] then
bad = bad + 1
end
end
local sent = prog:read_u32(BASE + 13 * 0x20)
if sent ~= SENT then
bad = bad + 1
end
local bytes = {}
for i = 0, #want_bytes - 1 do
bytes[#bytes + 1] =
string.char(prog:read_u8(OUT + i * 8))
end
local got_bytes = table.concat(bytes)
io.write("M7 pointer:")
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write(string.format(" %08X\n", sent))
print(string.format("M7 pointer bytes(%d): '%s' want '%s'",
#got_bytes, escape(got_bytes), escape(want_bytes)))
if got_bytes ~= want_bytes then
bad = bad + 1
end
if bad == 0 then
print("M4: pointer gate markers and bytes match")
print("M4 MAME: PASS")
print("M7 POINTER MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i + 1] then
print(string.format(
"M7 pointer: marker %d got %08X want %08X",
i, got[i], expect[i + 1]))
end
end
if sent ~= SENT then
print(string.format(
"M7 pointer: sentinel got %08X want %08X",
sent, SENT))
end
print("M4: pointer gate marker/byte mismatch")
print("M4 MAME: FAIL")
print("M7 POINTER MAME: FAIL")
end
end
end, "m7-pointer-check")
+22
View File
@@ -0,0 +1,22 @@
; pointer-entry.asm -- M7.1 pointer gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver pointer_run(), and writes a post-return sentinel. pointer-o2.sh
; concatenates the compiled driver after this file through scripts/m4/run.sh.
;
; Markers are at 018A8000 + n*0x20 bits (n = 0..12 written by the driver, n = 13
; the post-return sentinel); the copy bytes are at 018A9000 + n*8 bits.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _pointer_run
movi 5A5A5A5Ah, a0
movi 018A81A0h, a2 ; marker 13, the post-return sentinel
move a0, *a2, 1
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+156
View File
@@ -0,0 +1,156 @@
/* M7.1 `-O2` bit-pointer gate driver.
*
* The TMS34010 pointer model uses bit addresses: `p += n` must scale n by 8
* exactly once. The M6 pipeline scaled before and after opt; InstCombine
* canonicalized an already-bit `inttoptr(add(ptrtoint p, n*8))` back into a
* byte GEP when its consumers were integer/icmp-only, and the post-opt
* `--scale` multiplied that n*8 index by 8 again.
*
* The shapes below are the ones that exposed the bug:
* - `p += n; *p = ...` with a volatile n, checking the byte and that the
* double-scaled byte (n*8) was not touched;
* - a runtime pointer difference;
* - the natural overlapping backward-copy shape from the conformance shim's
* memmove (`d += n; s += n; while (n--) *--d = *--s;`);
* - the 64-bit pointer-int shape
* (`(unsigned long long)(unsigned)p + 24` and the signed `long long`
* variant), whose low 32-bit word is the 24-bit addend and must not
* become 192;
* - narrowing pointer-int casts (`(unsigned short)/(unsigned char)` on the
* base), which must keep the `and 0xffff`/`and 0xff` and must NOT be
* barriered into `p + 24`.
*
* Markers are at 0x018A8000 + n*0x20; the copy result bytes are at
* 0x018A9000 + n*8, both fixed writable RAM addresses (the M4/M6 pattern).
* pointer-check.lua compares them with the expected values.
*/
typedef unsigned int u32;
#define MARK(n) (*(volatile u32 *)(0x018A8000u + (u32)(n) * 0x20u))
#define OUTB(n) (*(volatile unsigned char *)(0x018A9000u + (u32)(n) * 8u))
#define BUF 128
char a[BUF];
char b[BUF];
/* The exact natural shape the shim's memmove now uses. The optimizer turns
* `d += n` into a bit pointer; the barrier must keep it from being scaled a
* second time. */
static void __attribute__((noinline)) copy_back(char *dst, const char *src, int n)
{
char *d = dst;
const char *s = src;
d += n;
s += n;
while (n--)
*--d = *--s;
}
/* The 64-bit pointer-int shape: clang widens the ptrtoint to i64, adds the bit
* count, and inttoptrs the result. The pointer is 32-bit, so the low word of
* the addend is the bit offset (24 bits = 3 bytes), not 192 bits. */
static int __attribute__((noinline)) late64(char *p, char *q)
{
return (char *)((unsigned long long)(unsigned int)p + 24) == q;
}
/* The signed-widening form of the same i64 shape. */
static int __attribute__((noinline)) late64s(char *p, char *q)
{
return (char *)((long long)(int)p + 24) == q;
}
/* A narrowing cast on the base changes the value: these must keep the
* `(p & 0xffff)/(p & 0xff)` mask, not be barriered into `p + 24`. */
static unsigned __attribute__((noinline)) narrow16(char *p)
{
return (unsigned)(char *)((unsigned short)(unsigned int)p + 24);
}
static unsigned __attribute__((noinline)) narrow8(char *p)
{
return (unsigned)(char *)((unsigned char)(unsigned int)p + 24);
}
void pointer_run(void)
{
volatile int move_n = 8;
volatile int step_n = 3;
volatile int diff_n = 5;
int n, i;
char *p;
for (i = 0; i < BUF; i++) {
a[i] = 0;
b[i] = 0;
}
for (i = 0; i < 8; i++)
a[i] = (char)('a' + i);
/* Overlapping backward copy: a+1 <- a, 8 bytes. The 8-byte copy starts
* "abcdefgh", so a[1..8] becomes "abcdefgh" and a[0] keeps 'a':
* "aabcdefg" as a string, with a[8] = 'h'. A double scale would take
* the source from a+64 and leave the destination zeroed. */
n = move_n;
copy_back(a + 1, a, n);
MARK(0) = (a[0] == 'a') && (a[1] == 'a') && (a[2] == 'b') &&
(a[3] == 'c') && (a[4] == 'd') && (a[5] == 'e') &&
(a[6] == 'f') && (a[7] == 'g');
MARK(1) = (a[8] == 'h') && (a[9] == 0) && (a[65] == 0);
for (i = 0; i < 9; i++)
OUTB(i) = (unsigned char)a[i];
/* `p += n; *p = ...` with a runtime n. */
n = step_n;
p = b;
p += n;
*p = 'Q';
MARK(2) = (u32)(unsigned char)b[3];
MARK(3) = (u32)(unsigned char)b[0];
MARK(4) = (u32)(unsigned char)b[24];
MARK(5) = (u32)(unsigned char)b[127];
/* The pointer difference is in bytes; the integer difference is bits. */
{
char *q = b;
int m = diff_n;
q += m;
MARK(6) = (u32)(q - b);
MARK(7) = (u32)q - (u32)b;
}
/* A few exact byte checks in the forward direction as well. */
MARK(8) = ((u32)(unsigned char)b[3] == 'Q') &&
((u32)(unsigned char)b[4] == 0) &&
((u32)(unsigned char)b[2] == 0);
/* The i64 pointer-int cast: c + 24 bits is c + 3 bytes. A missed
* barrier over-scales to c + 24 bytes and this is false. */
{
char c[8];
volatile int off = 3;
c[0] = 0;
c[1] = 0;
c[2] = 0;
c[3] = 0;
MARK(9) = (u32)late64(c, c + off);
MARK(12) = (u32)late64s(c, c + off);
}
/* p is a runtime pointer; the mask must stay in the address. */
{
char *volatile vp = (char *)0x018A9000u;
MARK(10) = (u32)(narrow16(vp) ==
((0x018A9000u & 0xFFFFu) + 24u));
MARK(11) = (u32)(narrow8(vp) ==
((0x018A9000u & 0xFFu) + 24u));
}
}
+146
View File
@@ -0,0 +1,146 @@
#!/bin/sh
# M7.1 `-O2` bit-pointer gate.
#
# scripts/tests/m7/pointer-o2.sh
#
# Compiles scripts/tests/m7/pointer-o2.c at the default -O2 through
# scripts/tms-clang (clang -> --bitptr -> opt -> --scale -> --lower-bitptr ->
# instcombine), assembles it with llc, concatenates the M7 entry, then links and
# loads the COFF with the 1987 GSPA/GSPLNK tools, the dwt loader and MAME (the
# scripts/m4/run.sh harness).
#
# The C driver exercises the shapes the M6 pipeline miscompiled or the M7.1
# barrier must not over-apply to:
# - `p += n; *p = ...` with a runtime n;
# - the natural overlapping backward copy `d += n; s += n;
# while (n--) *--d = *--s;` (the shim's memmove body before the workaround
# was removed);
# - 64-bit pointer-int casts, `(unsigned long long)(unsigned)p + 24` and the
# signed `(long long)(int)p + 24`, whose low word is 24 (never 192);
# - narrowing base casts `(unsigned short)/(unsigned char)p + 24`, which must
# keep the mask (`(p & 0xffff)/(p & 0xff) + 24`), not become `p + 24`.
#
# pointer-check.lua checks the marker words and the exact copy bytes. The
# script also checks that the lowered copy has exactly one `shl i32 ..., 3` and
# one `SLL 3` (no second `shl`/`SLL 6`), that no @__tms_bitptr call remains,
# that narrow16/narrow8 keep their `and`, and that late64/late64s carry the
# 24-bit addend rather than 192.
#
# Overridable: LLVM_BIN TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX
# DOSBOX_CONF SDK_IMG M7_POINTER_WORK M7_POINTER_COFF
# LOADER_AT LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/tests/m7
WORK=${M7_POINTER_WORK:-$ROOT/build/m7-pointer-o2}
fail() {
echo "m7 pointer: FAIL: $*" >&2
exit 1
}
rm -rf "$WORK"
mkdir -p "$WORK"
echo "== compile at -O2 and run through the M4 assembler/linker/MAME harness"
M4_WORK="$WORK" \
M4_SDK="$WORK/sdk" \
M4_COFF="${M7_POINTER_COFF:-$WORK/m7-pointer.coff}" \
M4_SOURCES="$DIR/pointer-o2.c" \
M4_ENTRY="$DIR/pointer-entry.asm" \
M4_CHECK_LUA="$DIR/pointer-check.lua" \
M4_CLANG_OPT=-O2 \
M4_LLC_OPT=-O0 \
"$ROOT/scripts/m4/run.sh" > "$WORK/run.log" 2>&1 \
|| { tail -60 "$WORK/run.log" >&2; fail "compile/link/MAME harness failed"; }
grep -q '^M4 MAME: PASS' "$WORK/mame.log" \
|| { tail -40 "$WORK/run.log" >&2; fail "M4 harness link/MAME check failed"; }
grep -q '^M7 POINTER MAME: PASS' "$WORK/mame.log" \
|| { grep -E '^M7 pointer|^M4 MAME' "$WORK/mame.log" >&2 || true; \
tail -40 "$WORK/run.log" >&2; \
fail "pointer markers/bytes did not match in MAME"; }
grep -q '^M4 MAME: PASS' "$WORK/mame.log" \
|| fail "the M4 harness marker did not pass"
echo "== MAME evidence"
grep -E '^M7 pointer' "$WORK/mame.log" | sed 's/^/ /'
IR=$WORK/asm/pointer-o2.ll
ASM=$WORK/asm/pointer-o2.s
[ -f "$IR" ] || fail "missing IR: $IR"
[ -f "$ASM" ] || fail "missing asm: $ASM"
echo "== one-scale IR evidence"
if grep -q '__tms_bitptr' "$IR"; then
fail "$IR still contains @__tms_bitptr (the barrier was not lowered)"
fi
# Isolate copy_back: the red IR has two `shl i32 ..., 3` instructions
# (`shl %n, 3` and `shl %bit.off, 3`); the fixed IR has exactly one.
awk '
/^define .*@copy_back\(/ { in_fn = 1 }
in_fn { print }
in_fn && /^}/ { exit }
' "$IR" > "$WORK/copy_back.ll"
grep -q '@copy_back' "$WORK/copy_back.ll" \
|| fail "IR has no copy_back definition"
SHLS=$(grep -c 'shl i32' "$WORK/copy_back.ll" || true)
[ "$SHLS" -eq 1 ] || { grep -n 'shl i32' "$WORK/copy_back.ll" >&2 || true; \
fail "copy_back has $SHLS 'shl i32', want exactly one"; }
grep -Eq 'shl i32 .*, 3$' "$WORK/copy_back.ll" \
|| { cat "$WORK/copy_back.ll" >&2; \
fail "copy_back's single shl is not by 3"; }
if grep -Eq 'shl i32 .*, (6|[1-9][0-9]+)$' "$WORK/copy_back.ll"; then
cat "$WORK/copy_back.ll" >&2
fail "copy_back bit offset is still multi-scaled in $IR"
fi
grep -n 'shl i32' "$WORK/copy_back.ll" | sed 's/^/ /'
# The barrier must not over-apply to a narrowing base cast, and the i64 forms
# must carry the 24-bit low word, not 192.
echo "== barrier-shape IR evidence"
grep -A8 'define.*@narrow16(' "$IR" | grep -Eq 'and i32 .*, 65535' \
|| { grep -A8 'define.*@narrow16(' "$IR" >&2 || true; \
fail "narrow16 lost its (p & 0xffff) mask"; }
grep -A8 'define.*@narrow8(' "$IR" | grep -Eq 'and i32 .*, 255' \
|| { grep -A8 'define.*@narrow8(' "$IR" >&2 || true; \
fail "narrow8 lost its (p & 0xff) mask"; }
for fn in late64 late64s; do
grep -A8 "define.*@$fn(" "$IR" \
| grep -Eq 'getelementptr i8, ptr %p, i32 24|add i32 %bit[.a-z0-9]*, 24' \
|| { grep -A8 "define.*@$fn(" "$IR" >&2 || true; \
fail "$fn does not carry the 24-bit addend"; }
if grep -A8 "define.*@$fn(" "$IR" | grep -Eq 'i32 192'; then
grep -A8 "define.*@$fn(" "$IR" >&2
fail "$fn over-scaled to 192"
fi
done
grep -A8 'define.*@narrow16(' "$IR" | sed 's/^/ /'
grep -A8 'define.*@narrow8(' "$IR" | sed 's/^/ /'
# Isolate the (noinline) copy_back function in the assembly and require a
# single SLL 3 and no SLL 6 in it.
awk '
/^_copy_back[^:]*:/ { in_fn = 1 }
in_fn && /^_[A-Za-z0-9_.$]*:/ && !/^_copy_back/ { in_fn = 0 }
in_fn { print }
' "$ASM" > "$WORK/copy_back.s"
grep -q '^_copy_back' "$WORK/copy_back.s" \
|| fail "assembly has no separate copy_back function"
# Tight patterns: `SLL 3` must not match `SLL 31`, and any other SLL in
# copy_back is a second scale.
SLL3=$(grep -cE '^[[:space:]]*SLL[[:space:]]+3([^0-9]|$)' "$WORK/copy_back.s" || true)
SLL6=$(grep -cE '^[[:space:]]*SLL[[:space:]]+6([^0-9]|$)' "$WORK/copy_back.s" || true)
SLLANY=$(grep -cE '^[[:space:]]*SLL[[:space:]]' "$WORK/copy_back.s" || true)
[ "$SLL3" -eq 1 ] || { cat "$WORK/copy_back.s" >&2; \
fail "copy_back has $SLL3 'SLL 3', want exactly one"; }
[ "$SLL6" -eq 0 ] || { cat "$WORK/copy_back.s" >&2; \
fail "copy_back still has an 'SLL 6' double scale"; }
[ "$SLLANY" -eq 1 ] || { cat "$WORK/copy_back.s" >&2; \
fail "copy_back has $SLLANY SLL instructions, want one"; }
echo "== one-scale asm evidence"
grep -E '^[[:space:]]*SLL' "$WORK/copy_back.s" | sed 's/^/ /'
echo "M7 POINTER: PASS"
+166
View File
@@ -0,0 +1,166 @@
#!/bin/sh
# M7.1 sub-byte array/nested record stride diagnostic gate.
#
# scripts/tests/m7/stride.sh
#
# The 1987 GSP C compiler advances an array element or nested member by the
# record's *bit content*: struct s below has 36 content bits and sizeof 5, so
# TI's array stride is 36 bits while Clang's byte-addressed layout advances by
# the 40-bit byte-rounded sizeof. A standalone struct s object is fine (the
# allocator rounds it to the same 16-bit unit), so the compiler must diagnose
# only the array and nested-member shapes, and must stay silent for
# byte-multiple records such as struct cross (40 content bits), for standalone
# objects, and for union members (a union member is always at offset 0 and
# never advances; an array of the byte-multiple union is silent too).
#
# The diagnostic is a default-on warning in the tms34010-subbyte-stride group.
# The red test compiles the oracle shapes with -Werror and expects a loud
# diagnostic; the controls must compile cleanly with -Werror. The same oracle
# shapes compile for x86_64 with -Werror and must stay silent, proving the
# target guard.
#
# Overridable: LLVM_BIN TMS_CLANG M7_STRIDE_WORK
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
WORK=${M7_STRIDE_WORK:-$ROOT/build/m7-stride}
fail() {
echo "m7 stride: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing clang: $TMS_CLANG"
rm -rf "$WORK"
mkdir -p "$WORK"
CC_FLAGS="--target=tms34010-unknown-none -ffreestanding -fsyntax-only"
# The oracle structs from the 1987 Task 5 notes (BITS.C / NEST.C).
cat > "$WORK/oracle.h" <<'EOF'
struct s {
unsigned a:3;
unsigned b:5;
int c:4;
unsigned d:20;
unsigned e:4;
};
struct cross { unsigned x:20; unsigned y:20; };
EOF
expect_warn() { # expect_warn NAME SOURCE TEXT
name=$1
src=$2
text=$3
# shellcheck disable=SC2086
if "$TMS_CLANG" $CC_FLAGS -Werror=tms34010-subbyte-stride "$src" \
> "$WORK/$name.log" 2>&1; then
fail "$name: expected a tms34010-subbyte-stride diagnostic"
fi
grep -Fq "error: $text" "$WORK/$name.log" \
|| { cat "$WORK/$name.log" >&2;
fail "$name: did not emit '$text'"; }
echo " $name: $(grep -m1 'tms34010-subbyte-stride' "$WORK/$name.log")"
}
expect_clean() { # expect_clean NAME SOURCE [extra flags...]
name=$1
src=$2
shift 2
# shellcheck disable=SC2086
if ! "$TMS_CLANG" $CC_FLAGS -Werror "$@" "$src" \
> "$WORK/$name.log" 2>&1; then
cat "$WORK/$name.log" >&2
fail "$name: expected a clean compile"
fi
echo " $name: clean"
}
STRIDE='array element or nested member of type '\''struct s'\'' advances by the byte-rounded size 40 bits; the TMS34010 ABI advances by 36 bits'
echo "== the oracle array shape must warn"
cat > "$WORK/array.c" <<'EOF'
#include "oracle.h"
struct s arr[2];
EOF
expect_warn array "$WORK/array.c" "$STRIDE"
echo "== the oracle nested-member shape must warn"
cat > "$WORK/nested.c" <<'EOF'
#include "oracle.h"
struct nest {
struct s a;
int b;
};
EOF
expect_warn nested "$WORK/nested.c" "$STRIDE"
echo "== multi-dimensional and array-member shapes warn exactly once"
cat > "$WORK/multi.c" <<'EOF'
#include "oracle.h"
struct s multi[2][3];
struct holder { struct s a[2]; };
EOF
expect_warn multi "$WORK/multi.c" "$STRIDE"
count=$(grep -c "advances by the byte-rounded size 40 bits" "$WORK/multi.log" || true)
[ "$count" -eq 2 ] \
|| fail "multi: expected 2 diagnostics (one per array type), got $count"
echo "== a standalone sub-byte record, byte-multiple records and unions are silent"
cat > "$WORK/control.c" <<'EOF'
#include "oracle.h"
struct s g;
struct cross carr[2];
struct cross cg;
struct cross_holder {
struct cross a;
int b;
};
struct cross_holder ch;
typedef struct cross crossarr[2];
union u {
struct s a;
int b;
};
union u uarr[2];
struct s *ptrarr[2];
int iarr[2];
EOF
expect_clean control "$WORK/control.c"
expect_clean control_no_warn "$WORK/control.c" -Wno-tms34010-subbyte-stride
echo "== a non-TMS34010 target is silent for the oracle shapes"
cat > "$WORK/host.c" <<'EOF'
#include "oracle.h"
struct s arr[2];
struct nest {
struct s a;
int b;
};
union u {
struct s a;
int b;
};
union u uarr[2];
EOF
# shellcheck disable=SC2086
if ! "$TMS_CLANG" --target=x86_64-unknown-linux-gnu -ffreestanding \
-fsyntax-only -Werror "$WORK/host.c" > "$WORK/host.log" 2>&1; then
cat "$WORK/host.log" >&2
fail "host: the TMS34010 warning fired on a non-TMS34010 target"
fi
echo " host: clean"
echo "== the warning group can suppress the array shape"
# shellcheck disable=SC2086
if "$TMS_CLANG" $CC_FLAGS -Wno-tms34010-subbyte-stride -Werror \
"$WORK/array.c" > "$WORK/suppress.log" 2>&1; then
echo " suppress: clean"
else
cat "$WORK/suppress.log" >&2
fail "suppress: -Wno-tms34010-subbyte-stride did not silence the warning"
fi
echo "stride.sh: PASS (struct s arrays/nested members warn 40 vs 36 bits; struct cross, standalone struct s, unions and non-TMS34010 targets are silent)"
+163
View File
@@ -0,0 +1,163 @@
#!/bin/sh
# M7.3 wider-Xlib gate: compile the xmore client with tms-clang/llc, link it
# through the M4 harness (GSPA/GSPLNK), run it in MAME, and require the wider
# surface markers, the zero X-error count, the screenshot pixels, and the COFF
# loader PASS. Also validates every v2.2 entry, including the six new ones.
#
# scripts/tests/m7/xlib.sh
#
# The client is scripts/m7/xmore.c (one parent + one child):
# XMapSubwindows, XConfigureWindow, XInternAtom("WM_NAME"), XChangeProperty,
# XChangeWindowAttributes(CWBackPixel), XChangeGC, XLoadFont/XDrawString,
# XFillRectangle, and a heap XCreateImage/XPutImage/XGetImage/XPutImage/
# XDestroyImage round trip, then XSync. scripts/m7/xmore-check.lua reads the
# markers at 0x018A8000 + n*0x20 and samples VRAM.
#
# Two signatures are the ROM shapes, not the public X11R4 wrappers (see
# scripts/m4/x11m4.h and symbols/vt1200-v22.syms):
# XConfigureWindow(d,w,x,y,width,height) fixed CWX|CWY|CWWidth|CWHeight
# mask 15 (XMoveResizeWindow shape)
# XChangeGC(d,gc) opcode 56 cache flush, not the
# 4-argument value setter
#
# Evidence beyond the flags: the child is created with background 1 and
# CWBackPixel=0, and the 160x120 fill leaves a margin that is black only if
# XChangeWindowAttributes ran; XDrawString is proven by counting the set pixels
# of an XGetImage band; the image marker (0x13F) requires the full heap round
# trip. XConfigureWindow's move is pixel-proven; its size is client-computed
# (not read back). Markers 4/10 are plain post-call flags (the ROM builders do
# not set A8; there is no server read-back); 11 counts XChangeGC source call
# sites, not runtime entry.
#
# One MAME run only: keep this gate serial with the other MAME gates.
#
# Overridable: M7_XLIB_WORK MAME MAME_TIMEOUT LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m7
WORK=${M7_XLIB_WORK:-$ROOT/build/m7-xlib}
fail() {
echo "m7 xlib: FAIL: $*" >&2
exit 1
}
echo "== validate the v2.2 ROM table (including the M7.3 wider entries)"
"$ROOT/scripts/m4/validate-syms.sh" || fail "ROM symbol validation failed"
echo "== compile, link, and run xmore in MAME"
M4_SOURCES="$DIR/xmore.c $ROOT/scripts/m4/xgfix.c" \
M4_ENTRY="$DIR/xmore-entry.asm" \
M4_CHECK_LUA="$DIR/xmore-check.lua" \
M4_EXTRA_INCLUDES="-I $ROOT/scripts/m4" \
M4_CLANG_OPT=-O2 \
M4_ROM_SYMBOLS=1 \
M4_WORK="$WORK" \
LOADER_AT="${LOADER_AT:-2500}" \
LOADER_END="${LOADER_END:-3400}" \
VT1200_SKIP_LEVEL1=1 \
VT1200_MONITOR=VR319 \
"$ROOT/scripts/m4/run.sh" || fail "M7 wider-Xlib run failed"
LOG=$WORK/mame.log
[ -f "$LOG" ] || fail "no MAME log: $LOG"
MARKER=$(grep -aE '^M7: window=' "$LOG" | tail -1 || true)
[ -n "$MARKER" ] || fail "no M7 marker line"
echo " $MARKER"
case "$MARKER" in
*" configure=0xC80096 "*) ;;
*) fail "XConfigureWindow marker is not (200 << 16) | 150 = 0xC80096" ;;
esac
case "$MARKER" in
*" image=0x13F "*) ;;
*) fail "image round-trip marker is not 0x13F (pixel=1, flags=0x3F)" ;;
esac
case "$MARKER" in
*" errors=0 "*) ;;
*) fail "xmore saw X protocol errors" ;;
esac
# Marker 4 is a post-call flag: the call site ran with zero X errors; there
# is no server read-back (the ROM entry has no defined return value).
field() { # field NAME
echo "$MARKER" | sed -n "s/.* $1=\\([0-9A-Fa-fx]*\\).*/\\1/p"
}
PROP=$(field property_called)
ATTRS=$(field attrs_called)
GCCH=$(field gcchange)
TEXT=$(field text)
DISP=$(field display)
FILL=$(field fill)
[ -n "$PROP" ] && [ -n "$ATTRS" ] && [ -n "$GCCH" ] \
&& [ -n "$TEXT" ] && [ -n "$DISP" ] && [ -n "$FILL" ] \
|| fail "the M7 marker line is missing property_called/attrs_called/gcchange/text/display/fill"
[ "$PROP" -eq 1 ] \
|| fail "XChangeProperty post-call flag is $PROP, want 1"
[ "$ATTRS" -eq 1 ] \
|| fail "XChangeWindowAttributes post-call flag is $ATTRS, want 1"
# The ROM XChangeGC entry is the 2-argument cache flush. Marker 11 counts the
# XChangeGC source call sites; runtime entry is not proven (deleting the call
# but keeping the count would still read 2), and zero X errors is the only
# runtime check.
[ "$GCCH" -eq 2 ] \
|| fail "XChangeGC source call count is $GCCH, want 2"
[ "$TEXT" -gt 0 ] && [ "$TEXT" -lt 1024 ] \
|| fail "XDrawString band has $TEXT set pixels, want 1..1023"
[ $((DISP)) -ne 0 ] \
|| fail "the pre-InternAtom Display marker is zero"
# Pin the fill geometry the margin sample assumes: 160x120 = 0xA00078.
[ $((FILL)) -eq $((0xA00078)) ] \
|| fail "fill geometry marker is $FILL, want 0xA00078 (160x120)"
echo " property_called=$PROP attrs_called=$ATTRS gcchange=$GCCH text_pixels=$TEXT display=$DISP fill=$FILL"
# XInternAtom is the one documented skip: the ROM's _XSend scatter path
# (0x3F9B44C0) does not complete in the loader harness, so the client keeps the
# call last and records 0xFFFFFFFF. The display marker (nonzero, written just
# before the call) proves only that the connection was live before the call; it
# does not prove the call was entered, so stage 14 cannot distinguish the
# intended _XSend block from a crash or wrong import by itself. The isolated
# probe in task-1-report.md is narrative entry evidence, not a gate check.
# Stage 14 means "attempted after everything else"; a real return would use the
# atom and reach stage 15.
ATOM_SKIP=0
case "$MARKER" in
*" atom=0xFFFFFFFF "*) ATOM_SKIP=1 ;;
esac
case "$MARKER" in
*" stage=14"*)
[ "$ATOM_SKIP" = 1 ] || fail "stage 14 without the documented InternAtom skip"
echo " internatom: SKIP (documented: ROM _XSend blocks; property uses predefined atom 39; display marker only proves the connection was live before the call; the isolated probe is narrative entry evidence)"
;;
*" stage=15"*)
[ "$ATOM_SKIP" = 0 ] || fail "stage 15 with the skipped atom"
echo " internatom: returned an atom"
;;
*) fail "xmore did not reach stage 14/15" ;;
esac
# The screenshot: the formatted-rectangle cell, the heap image, the XGetImage
# result put back, and the CWBackPixel margin (the child starts white; the
# 160x120 fill does not reach this sample, so only the attribute makes it
# black). The printed parent(...) coordinate is screen minus the parent
# origin (100,100).
grep -Fq 'M7: pixel screen(128,128) parent(28,28) bit=0x04040080 value=1 white' "$LOG" \
|| fail "the XFillRectangle cell at screen (128,128) is not white"
grep -Fq 'M7: pixel screen(170,162) parent(70,62) bit=0x040510AA value=1 white' "$LOG" \
|| fail "the heap XPutImage cell at screen (170,162) is not white"
grep -Fq 'M7: pixel screen(240,160) parent(140,60) bit=0x040500F0 value=1 white' "$LOG" \
|| fail "the XGetImage put-back cell at screen (240,160) is not white"
grep -Fq 'M7: pixel screen(300,240) parent(200,140) bit=0x0407812C value=0 black' "$LOG" \
|| fail "the CWBackPixel margin at screen (300,240) is not black"
grep -Eq '^M7: text band child\(0,126\) 64x16 set_pixels=[1-9][0-9]* \(ok\)' "$LOG" \
|| fail "the XDrawString band has no counted white pixels"
grep -q '^M7 MAME: PASS' "$LOG" || fail "wider-Xlib marker check did not pass"
grep -q 'LOADER: result status=0 (OK)' "$LOG" || fail "loader status is not OK"
grep -q 'placed \.text .* 0 differing' "$LOG" \
|| fail "COFF loader could not verify the placed .text bytes"
echo "m7 xlib: PASS (6 ROM entries + addresses validated; xmore windows/child/gc/atom/property/configure/font/image, margin/GC/text effects, 0 X errors, stage 14/15)"
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Compare a GSPLNK oracle image with a tms-link image.
Usage: coff-parity.py M7COFF ORACLE OURS
GSPLNK emits a listed-but-empty .cinit for some library links; tms-link
deliberately omits it (the section has no bytes and the loader ignores it), so
zero-size .cinit sections are dropped before the comparison. Everything that
is allocated must match byte-for-byte, and the public C_EXT symbol addresses
must be identical. The reader is the independent M7 test-local m7coff.py, not
the linker's own tmscoff.py.
"""
import os
import struct
import sys
sys.dont_write_bytecode = True
def main(argv):
if len(argv) != 4:
sys.exit("usage: coff-parity.py M7COFF ORACLE OURS")
reader_path, oracle_path, ours_path = argv[1:]
sys.path.insert(0, os.path.dirname(reader_path))
import m7coff # noqa: E402
oracle = m7coff.parse(oracle_path)
ours = m7coff.parse(ours_path)
def allocated(obj):
return [s for s in obj["sections"] if s["size"] != 0]
a_secs = allocated(oracle)
b_secs = allocated(ours)
if [s["name"] for s in a_secs] != [s["name"] for s in b_secs]:
sys.exit("section names %r != %r"
% ([s["name"] for s in a_secs],
[s["name"] for s in b_secs]))
for a, b in zip(a_secs, b_secs):
for field in ("paddr", "vaddr", "size", "flags"):
if a[field] != b[field]:
sys.exit("%s %s %#x != %#x"
% (a["name"], field, a[field], b[field]))
if a["raw"] != b["raw"]:
limit = min(len(a["raw"]), len(b["raw"]))
bad = [i for i in range(limit) if a["raw"][i] != b["raw"][i]]
sys.exit("%s bytes differ: %d byte(s), first %r"
% (a["name"],
len(bad) + abs(len(a["raw"]) - len(b["raw"])),
[(hex(i), a["raw"][i], b["raw"][i]) for i in bad[:8]]))
if b["nreloc"]:
sys.exit("%s still has %d relocations"
% (b["name"], b["nreloc"]))
if oracle["flags"] != ours["flags"]:
sys.exit("file flags %#x != %#x"
% (oracle["flags"], ours["flags"]))
opt_a = struct.unpack_from("<HHIIIIII", oracle["data"], 20)
opt_b = struct.unpack_from("<HHIIIIII", ours["data"], 20)
if opt_a != opt_b:
sys.exit("optional header %r != %r" % (opt_a, opt_b))
def externals(obj):
return {s["name"]: s["value"] for s in obj["symbols"]
if s["sclass"] == 2 and s["secno"] > 0}
expected = externals(oracle)
actual = externals(ours)
if expected != actual:
missing = sorted(set(expected) - set(actual))
extra = sorted(set(actual) - set(expected))
wrong = sorted((n, expected[n], actual[n])
for n in set(expected) & set(actual)
if expected[n] != actual[n])
sys.exit("C_EXT mismatch: missing=%r extra=%r wrong=%r"
% (missing, extra,
[(n, hex(a), hex(b)) for n, a, b in wrong]))
ignored = [s["name"] for s in oracle["sections"] if s["size"] == 0]
print(" parity: %s, %d allocated sections, %d public symbols%s"
% (os.path.basename(ours_path), len(b_secs), len(actual),
" (oracle zero-size %s dropped)" % ",".join(ignored)
if ignored else ""))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+648
View File
@@ -0,0 +1,648 @@
#!/bin/sh
# M8.2 multi-TU DWARF gate: two `-g` objects through tms-link --keep-debug.
#
# scripts/tests/m8/dwarf-multi.sh
#
# 1. Compile scripts/m8/debug-a.c and debug-b.c with `tms-clang -g -O0` and
# `llc -filetype=obj`; both objects must carry the DWARF v5 sections
# (.debug_info/.debug_abbrev/.debug_line/.debug_str/.debug_str_offsets/
# .debug_addr/.debug_line_str).
# 2. GSPA assembles scripts/m8/debug-entry.asm; tms-link links
# debug-a.o debug-b.o entry.o twice, --keep-debug and the default strip.
# 3. The kept .debug_* sections are wrapped in the M7 ELF32 container and read
# by llvm-dwarfdump. The gate asserts, for every TU:
# - both compile-unit names and both .debug_line file tables;
# - every subprogram name and its linked low PC (text origin / 8 +
# protocol offset), high PC byte size and declaration line;
# - line rows at every linked function low PC with the first body line;
# - the second CU's debug_abbrev_offset/str_offsets_base/stmt_list/
# addr_base are rehomed to the first object's merged section sizes,
# proving section-relative offsets were shifted (not just copied).
# 4. The stripped image still runs in MAME: the four markers are 22, 14, 9
# and 36 and the loader reports status 0 with 0 differing .text bytes.
#
# Overridable: LLVM_BIN TMS_CLANG TMS_LLC TMS_LINK M7COFF M8_DWARF_WORK
# M8_DWARF_SDK SDK_IMG DOSBOX DOSBOX_CONF MAME MAME_TIMEOUT
# LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m8
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
TMS_CLANG=${TMS_CLANG:-$ROOT/scripts/tms-clang}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
DWARFDUMP=${DWARFDUMP:-$LLVM_BIN/llvm-dwarfdump}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
WORK=${M8_DWARF_WORK:-$ROOT/build/m8-dwarf}
SDK=${M8_DWARF_SDK:-$WORK/sdk}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
MAME_TIMEOUT=${MAME_TIMEOUT:-900}
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "M8 dwarf-multi: FAIL: $*" >&2
exit 1
}
[ -x "$TMS_CLANG" ] || fail "missing tms-clang: $TMS_CLANG"
[ -x "$TMS_LLC" ] || fail "missing llc: $TMS_LLC"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -x "$DWARFDUMP" ] || fail "missing llvm-dwarfdump: $DWARFDUMP"
[ -f "$M7COFF" ] \
|| fail "independent TI-COFF reader not found: $M7COFF"
[ -f "$DOSBOX_CONF" ] || fail "missing DOSBox config: $DOSBOX_CONF"
command -v "$DOSBOX" >/dev/null 2>&1 || fail "missing DOSBox: $DOSBOX"
[ -x "$MAME" ] || fail "missing MAME binary: $MAME"
[ -f "$LOADER_LUA" ] || fail "missing COFF loader: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "missing loader payload: $LOADER_BIN"
rm -rf "$WORK"
mkdir -p "$WORK/obj" "$WORK/dos" "$WORK/run/nvram" "$WORK/run/cfg" \
"$WORK/evidence"
WORK=$(cd "$WORK" && pwd)
DOS=$WORK/dos
echo "== compile two TUs with tms-clang -g -O0 and llc -filetype=obj"
# Compile from scripts/m8 with relative names so DW_AT_name and the line-table
# file names are exactly debug-a.c / debug-b.c.
( cd "$DIR" && "$TMS_CLANG" -g -O0 -o "$WORK/obj/debug-a.ll" debug-a.c ) \
|| fail "tms-clang -g failed for debug-a.c"
( cd "$DIR" && "$TMS_CLANG" -g -O0 -o "$WORK/obj/debug-b.ll" debug-b.c ) \
|| fail "tms-clang -g failed for debug-b.c"
grep -q '!dbg' "$WORK/obj/debug-a.ll" \
|| fail "debug-a.ll has no !dbg metadata"
grep -q '!dbg' "$WORK/obj/debug-b.ll" \
|| fail "debug-b.ll has no !dbg metadata"
for name in debug-a debug-b; do
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/obj/$name.ll" -o "$WORK/obj/$name.o" \
|| fail "llc -filetype=obj failed for $name"
done
python3 - "$M7COFF" "$WORK/obj/debug-a.o" "$WORK/obj/debug-b.o" <<'PY' \
|| fail "a TU is missing the DWARF v5 sections"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
want = (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr", ".debug_line_str")
for path in sys.argv[2:]:
c = m7coff.parse(path)
debug = [s["name"] for s in c["sections"]
if s["name"].startswith(".debug_")]
for name in want:
if name not in debug:
sys.exit("%s missing %s; got %r" % (path, name, debug))
print(" %s: %s" % (os.path.basename(path), " ".join(debug)))
PY
echo "== extract the GSPA/GSPLNK toolchain"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE is not extracted in $SDK"
cp "$SDK/GSPA.EXE" "$DOS/"
cp "$WORK/obj/debug-a.o" "$DOS/DBGA.O"
cp "$WORK/obj/debug-b.o" "$DOS/DBGB.O"
sed 's/\r$//' "$DIR/debug-entry.asm" | sed 's/$/\r/' > "$DOS/DENTRY.ASM"
echo "== assemble debug-entry.asm with GSPA 2.00"
rm -f "$DOS/DENTRY.O" "$DOS/DENTRY.LST"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $DOS" -c "c:" \
-c "gspa DENTRY DENTRY.O DENTRY.LST -l" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$DOS/DENTRY.LST" ] || fail "GSPA produced no DENTRY.LST"
sed 's/\r$//' "$DOS/DENTRY.LST" > "$WORK/dentry.lst"
grep -q 'No Errors' "$WORK/dentry.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/dentry.lst" >&2 || true; \
fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/dentry.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/dentry.lst" >&2 || true; \
fail "GSPA reported warnings"; }
echo "== link --keep-debug and the default strip"
"$TMS_LINK" -o "$WORK/keep.coff" --keep-debug \
--map "$WORK/keep.map" --entry _start \
--text 018A0000 --bss 01A00000 \
"$WORK/obj/debug-a.o" "$WORK/obj/debug-b.o" "$DOS/DENTRY.O" \
|| fail "tms-link --keep-debug failed"
"$TMS_LINK" -o "$WORK/strip.coff" \
--map "$WORK/strip.map" --entry _start \
--text 018A0000 --bss 01A00000 \
"$WORK/obj/debug-a.o" "$WORK/obj/debug-b.o" "$DOS/DENTRY.O" \
|| fail "tms-link (strip) failed"
echo "== inspect the merged sections and write the expected offsets"
python3 - "$M7COFF" "$WORK/obj/debug-a.o" "$WORK/obj/debug-b.o" \
"$WORK/keep.coff" "$WORK/strip.coff" "$WORK/merge.env" <<'PY' \
|| fail "merged debug layout is wrong"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
a_path, b_path, keep_path, strip_path, env_path = sys.argv[2:7]
a = m7coff.parse(a_path)
b = m7coff.parse(b_path)
keep = m7coff.parse(keep_path)
strip = m7coff.parse(strip_path)
keep_sections = [s["name"] for s in keep["sections"]]
strip_sections = [s["name"] for s in strip["sections"]]
if strip_sections != [".text", ".data", ".bss"]:
sys.exit("default strip has sections %r, want .text/.data/.bss"
% strip_sections)
if keep_sections[:3] != [".text", ".data", ".bss"]:
sys.exit("kept image leading sections %r" % keep_sections[:3])
debug = [n for n in keep_sections[3:] if n.startswith(".debug_")]
if debug != keep_sections[3:] or not debug:
sys.exit("kept image sections after .bss are %r" % keep_sections[3:])
for name in (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr", ".debug_line_str"):
if name not in debug:
sys.exit("kept image missing %s; got %r" % (name, debug))
for sa, sb in zip(keep["sections"][:3], strip["sections"]):
if sa["paddr"] != sb["paddr"] or sa["size"] != sb["size"]:
sys.exit("%s keep/strip paddr/size %#x/%d != %#x/%d"
% (sa["name"], sa["paddr"], sa["size"], sb["paddr"],
sb["size"]))
if sa["flags"] != sb["flags"]:
sys.exit("%s keep/strip flags differ" % sa["name"])
if sa["name"] == ".bss":
continue
if sa["raw"] != sb["raw"]:
sys.exit("%s keep/strip bytes differ" % sa["name"])
for sec in keep["sections"]:
if sec["name"].startswith(".debug_"):
if sec["paddr"] != 0 or sec["vaddr"] != 0:
sys.exit("%s paddr/vaddr %#x/%#x, want 0/0"
% (sec["name"], sec["paddr"], sec["vaddr"]))
if sec["flags"] != 0:
sys.exit("%s flags %#x, want 0" % (sec["name"], sec["flags"]))
if sec["nreloc"]:
sys.exit("%s still has %d relocations"
% (sec["name"], sec["nreloc"]))
elif sec["nreloc"]:
sys.exit("%s still has %d relocations" % (sec["name"], sec["nreloc"]))
# Every merged section is exactly the two inputs' contributions in order,
# except for the 4-byte relocation fields that tms-link intentionally rewrites
# to rehome section-relative references.
for name in debug:
want = 0
raw = b""
for c in (a, b):
sec = m7coff.section(c, name)
want += sec["size"]
raw += sec["raw"]
got = m7coff.section(keep, name)
if got["size"] != want:
sys.exit("%s merged size %d bits, want %d" % (name, got["size"], want))
skip = set()
bases = {id(a): 0, id(b): len(m7coff.section(a, name)["raw"])}
for c in (a, b):
sec = m7coff.section(c, name)
for raddr, _symidx, _rtype in sec["relocs"]:
field = bases[id(c)] + raddr // 8
skip.update(range(field, field + 4))
if got["raw"] != raw:
diff = [i for i in range(len(raw))
if raw[i] != got["raw"][i] and i not in skip]
if diff:
sys.exit("%s merged bytes differ from the object-order "
"concatenation outside relocation fields: %r"
% (name, diff[:8]))
if not any(raw[i] != got["raw"][i] for i in range(len(raw))):
sys.exit("%s has no rewritten relocation fields" % name)
syms = {s["name"]: s for s in keep["symbols"]}
for name in ("_debug_a_mul", "_debug_a_add", "_debug_b_sub", "_debug_b_mul",
"_start", "_debug_a_base", "_debug_b_base"):
if name not in syms:
sys.exit("kept image missing symbol %s" % name)
a_mul = syms["_debug_a_mul"]["value"]
a_add = syms["_debug_a_add"]["value"]
b_sub = syms["_debug_b_sub"]["value"]
b_mul = syms["_debug_b_mul"]["value"]
start = syms["_start"]["value"]
text = m7coff.section(keep, ".text")
text_end = text["paddr"] + text["size"]
if not (text["paddr"] <= a_mul < a_add < b_sub < b_mul < start < text_end):
sys.exit("functions are not at increasing text offsets: "
"%#x %#x %#x %#x %#x %#x %#x"
% (text["paddr"], a_mul, a_add, b_sub, b_mul, start,
text_end))
if b_sub == a_mul:
sys.exit("second TU has no nonzero text offset")
# Rehoming expectations: the second CU's section-relative bases are the first
# object's merged contribution sizes (plus the DWARF5 unit header where the
# attribute points past it).
def raw_len(c, name):
return len(m7coff.section(c, name)["raw"])
expect = {
"B_ABBREV": raw_len(a, ".debug_abbrev"),
"B_STR_OFFSETS": raw_len(a, ".debug_str_offsets") + 8,
"B_STMT_LIST": raw_len(a, ".debug_line"),
"B_ADDR": raw_len(a, ".debug_addr") + 8,
}
with open(env_path, "w", encoding="ascii") as fh:
for key, value in (
("A_MUL_BITS", a_mul), ("A_ADD_BITS", a_add),
("B_SUB_BITS", b_sub), ("B_MUL_BITS", b_mul),
("START_BITS", start), ("TEXT_ORIGIN", text["paddr"]),
("TEXT_END", text_end)):
fh.write("%s=%d\n" % (key, value))
for key, value in expect.items():
fh.write("%s=%d\n" % (key, value))
print(" keep sections: %s" % " ".join(keep_sections))
print(" functions: a_mul=%#x a_add=%#x b_sub=%#x b_mul=%#x _start=%#x "
"(bits)" % (a_mul, a_add, b_sub, b_mul, start))
print(" second-CU bases: abbrev=%d str_offsets=%d stmt_list=%d addr=%d"
% (expect["B_ABBREV"], expect["B_STR_OFFSETS"],
expect["B_STMT_LIST"], expect["B_ADDR"]))
PY
. "$WORK/merge.env"
A_MUL_SIZE=$(((A_ADD_BITS - A_MUL_BITS) / 8))
A_ADD_SIZE=$(((B_SUB_BITS - A_ADD_BITS) / 8))
B_SUB_SIZE=$(((B_MUL_BITS - B_SUB_BITS) / 8))
B_MUL_SIZE=$(((START_BITS - B_MUL_BITS) / 8))
echo "== wrap the kept .debug_* sections in a minimal ELF32 container"
"$ROOT/scripts/m7/elf-debug-wrap.py" -o "$WORK/keep.elf" "$WORK/keep.coff" \
|| fail "elf-debug-wrap failed"
echo "== llvm-dwarfdump"
"$DWARFDUMP" --debug-info --verbose "$WORK/keep.elf" \
> "$WORK/info.txt" 2> "$WORK/info.err" \
|| { cat "$WORK/info.err" >&2; fail "llvm-dwarfdump --debug-info failed"; }
"$DWARFDUMP" --debug-line "$WORK/keep.elf" \
> "$WORK/line.txt" 2> "$WORK/line.err" \
|| { cat "$WORK/line.err" >&2; fail "llvm-dwarfdump --debug-line failed"; }
python3 - "$WORK/info.txt" "$WORK/line.txt" "$A_MUL_BITS" "$A_ADD_BITS" \
"$B_SUB_BITS" "$B_MUL_BITS" "$START_BITS" "$TEXT_ORIGIN" \
"$A_MUL_SIZE" "$A_ADD_SIZE" "$B_SUB_SIZE" "$B_MUL_SIZE" \
"$B_ABBREV" "$B_STR_OFFSETS" "$B_STMT_LIST" "$B_ADDR" <<'PY' \
|| fail "merged DWARF compile units/subprograms/line rows are wrong"
import re
import sys
(info_path, line_path) = sys.argv[1], sys.argv[2]
a_mul_bits, a_add_bits, b_sub_bits, b_mul_bits, start_bits, origin_bits = \
[int(v) for v in sys.argv[3:9]]
a_mul_size, a_add_size, b_sub_size, b_mul_size = \
[int(v) for v in sys.argv[9:13]]
b_abbrev, b_str_offsets, b_stmt_list, b_addr = \
[int(v) for v in sys.argv[13:17]]
origin = origin_bits // 8
lows = {
"debug_a_mul": a_mul_bits // 8,
"debug_a_add": a_add_bits // 8,
"debug_b_sub": b_sub_bits // 8,
"debug_b_mul": b_mul_bits // 8,
"_start": start_bits // 8,
}
if origin != 0x314000:
sys.exit("text origin byte address %#x, want 0x314000" % origin)
if lows["debug_a_mul"] != origin:
sys.exit("debug_a_mul low %#x, want text origin %#x"
% (lows["debug_a_mul"], origin))
cus = []
subs = []
cu = None
cur = None
mode = None
for raw in open(info_path, encoding="latin1"):
line = raw.rstrip("\n")
m = re.search(r"Compile Unit: .*abbr_offset = 0x([0-9a-fA-F]+)", line)
if m:
cu = {"name": None, "low": None, "high": None, "high_form": None,
"abbr": int(m.group(1), 16), "str_offsets": None,
"stmt_list": None, "addr_base": None}
cus.append(cu)
cur = None
mode = None
continue
if "DW_TAG_compile_unit" in line:
cur = cu
mode = "cu"
continue
if "DW_TAG_subprogram" in line:
cur = {"name": None, "low": None, "high": None, "high_form": None,
"line": None, "cu": cu}
subs.append(cur)
mode = "sub"
continue
if "DW_TAG_" in line:
mode = None
continue
if mode is None or cur is None:
continue
m = re.search(r"DW_AT_low_pc.*address = 0x([0-9a-fA-F]+)", line)
if m:
cur["low"] = int(m.group(1), 16)
continue
m = re.search(r"DW_AT_high_pc \[([A-Za-z0-9_]+)\]\s+\(0x([0-9a-fA-F]+)\)",
line)
if m:
cur["high_form"] = m.group(1)
cur["high"] = int(m.group(2), 16)
continue
m = re.search(r'DW_AT_name.*string = "([^"]+)"', line)
if m:
cur["name"] = m.group(1)
continue
m = re.search(r"DW_AT_decl_line \[[A-Za-z0-9_]+\]\s+\((\d+)\)", line)
if m:
cur["line"] = int(m.group(1))
continue
if mode == "cu":
for attr, key in (("str_offsets_base", "str_offsets"),
("stmt_list", "stmt_list"),
("addr_base", "addr_base")):
m = re.search(r"DW_AT_%s .*\(0x([0-9a-fA-F]+)\)" % attr, line)
if m:
cur[key] = int(m.group(1), 16)
if len(cus) != 2:
sys.exit("saw %d compile units, want 2" % len(cus))
by_cu = {c["name"]: c for c in cus if c["name"]}
if set(by_cu) != {"debug-a.c", "debug-b.c"}:
sys.exit("compile unit names %r, want debug-a.c and debug-b.c"
% sorted(by_cu))
cua, cub = by_cu["debug-a.c"], by_cu["debug-b.c"]
if (cua["abbr"], cua["str_offsets"], cua["stmt_list"], cua["addr_base"]) != \
(0, 8, 0, 8):
sys.exit("first CU bases abbr/str_offsets/stmt_list/addr = %r, want "
"(0, 8, 0, 8)"
% ((cua["abbr"], cua["str_offsets"], cua["stmt_list"],
cua["addr_base"]),))
want_b = (b_abbrev, b_str_offsets, b_stmt_list, b_addr)
got_b = (cub["abbr"], cub["str_offsets"], cub["stmt_list"], cub["addr_base"])
if got_b != want_b:
sys.exit("second CU bases abbr/str_offsets/stmt_list/addr = %r, want %r "
"(merged first-object contributions)" % (got_b, want_b))
if cub["abbr"] == 0 or cub["str_offsets"] == 8 or cub["addr_base"] == 8:
sys.exit("second CU bases were not rehomed: %r" % (got_b,))
cus_by_name = {c["name"]: c for c in cus}
for name, low in (("debug-a.c", lows["debug_a_mul"]),
("debug-b.c", lows["debug_b_sub"])):
c = cus_by_name[name]
if c["low"] != low:
sys.exit("%s CU low_pc %#x, want %#x" % (name, c["low"], low))
if c["high_form"] != "DW_FORM_data4":
sys.exit("%s CU high_pc form %r, want DW_FORM_data4"
% (name, c["high_form"]))
size_a = (b_sub_bits - a_mul_bits) // 8
size_b = (start_bits - b_sub_bits) // 8
if cus_by_name["debug-a.c"]["high"] != size_a:
sys.exit("debug-a.c CU high_pc %#x, want %#x"
% (cus_by_name["debug-a.c"]["high"], size_a))
if cus_by_name["debug-b.c"]["high"] != size_b:
sys.exit("debug-b.c CU high_pc %#x, want %#x"
% (cus_by_name["debug-b.c"]["high"], size_b))
by_name = {s["name"]: s for s in subs if s["name"]}
for name, low, size, decl, tu in (
("debug_a_mul", lows["debug_a_mul"], a_mul_size, 3,
"debug-a.c"),
("debug_a_add", lows["debug_a_add"], a_add_size, 8,
"debug-a.c"),
("debug_b_sub", lows["debug_b_sub"], b_sub_size, 3,
"debug-b.c"),
("debug_b_mul", lows["debug_b_mul"], b_mul_size, 8,
"debug-b.c")):
if name not in by_name:
sys.exit("no DW_TAG_subprogram named %s (saw %r)"
% (name, sorted(by_name)))
s = by_name[name]
if s["cu"] is not cus_by_name[tu]:
sys.exit("%s is not attributed to the %s compile unit" % (name, tu))
if s["low"] != low:
sys.exit("%s low_pc %#x, want linked %#x" % (name, s["low"], low))
if s["high_form"] != "DW_FORM_data4" or s["high"] != size:
sys.exit("%s high_pc %r/%#x, want DW_FORM_data4/%#x"
% (name, s["high_form"], s["high"], size))
if s["line"] != decl:
sys.exit("%s DW_AT_decl_line %r, want %d" % (name, s["line"], decl))
# .debug_line: two units, each with its own file table and rows at its TU's
# linked function low PCs. The first body line is 4 in both sources and the
# second function's first body line is 9 in both sources.
units = []
unit = None
for raw in open(line_path, encoding="latin1"):
line = raw.rstrip("\n")
m = re.match(r"^debug_line\[0x([0-9a-fA-F]+)\]", line)
if m:
unit = {"off": int(m.group(1), 16), "names": [], "rows": {}}
units.append(unit)
continue
if unit is None:
continue
m = re.match(r'^\s+name: "([^"]+)"$', line)
if m:
unit["names"].append(m.group(1))
continue
m = re.match(r"^(0x[0-9a-fA-F]+)\s+(\d+)\s+(\d+)\s+(\d+)\s",
line.strip() + " ")
if m:
unit["rows"][int(m.group(1), 16)] = int(m.group(2))
if len(units) != 2:
sys.exit("saw %d .debug_line units, want 2" % len(units))
if units[0]["names"] != ["debug-a.c"]:
sys.exit("first line unit file table %r, want [debug-a.c]"
% units[0]["names"])
if units[1]["names"] != ["debug-b.c"]:
sys.exit("second line unit file table %r, want [debug-b.c]"
% units[1]["names"])
for unit, low, body in ((units[0], lows["debug_a_mul"], 4),
(units[0], lows["debug_a_add"], 9),
(units[1], lows["debug_b_sub"], 4),
(units[1], lows["debug_b_mul"], 9)):
if unit["rows"].get(low) != body:
sys.exit("no line row at %#x with line %d (rows %r)"
% (low, body, unit["rows"]))
if any(low in units[1]["rows"] for low in (lows["debug_a_mul"],
lows["debug_a_add"])):
sys.exit("debug-a functions appear in the debug-b line unit")
print(" compile units: debug-a.c low=%#x high=%#x, debug-b.c low=%#x "
"high=%#x" % (cua["low"], cua["high"], cub["low"], cub["high"]))
print(" subprograms: " + ", ".join(
"%s@%#x+%#x line=%d" % (s["name"], s["low"], s["high"], s["line"])
for s in subs if s["name"] in by_name))
print(" line units: debug-a.c rows at a_mul/a_add, debug-b.c rows at "
"b_sub/b_mul (body lines 4/9)")
PY
echo "== -O2 -g multi-TU merge (location lists)"
( cd "$DIR" && "$TMS_CLANG" -g -O2 -o "$WORK/obj/debug-a-o2.ll" debug-a.c ) \
|| fail "tms-clang -g -O2 failed for debug-a.c"
( cd "$DIR" && "$TMS_CLANG" -g -O2 -o "$WORK/obj/debug-b-o2.ll" debug-b.c ) \
|| fail "tms-clang -g -O2 failed for debug-b.c"
for name in debug-a-o2 debug-b-o2; do
"$TMS_LLC" -march=tms34010 -O0 -filetype=obj \
"$WORK/obj/$name.ll" -o "$WORK/obj/$name.o" \
|| fail "llc -filetype=obj failed for $name"
done
"$TMS_LINK" -o "$WORK/keep-o2.coff" --keep-debug \
--entry _start --text 018A0000 --bss 01A00000 \
"$WORK/obj/debug-a-o2.o" "$WORK/obj/debug-b-o2.o" "$DOS/DENTRY.O" \
|| fail "tms-link --keep-debug failed for the -O2 objects"
"$ROOT/scripts/m7/elf-debug-wrap.py" -o "$WORK/keep-o2.elf" \
"$WORK/keep-o2.coff" >/dev/null \
|| fail "elf-debug-wrap failed for the -O2 link"
"$DWARFDUMP" --debug-info --verbose "$WORK/keep-o2.elf" \
> "$WORK/info-o2.txt" 2> "$WORK/info-o2.err" \
|| { cat "$WORK/info-o2.err" >&2; \
fail "llvm-dwarfdump --debug-info failed for -O2"; }
"$DWARFDUMP" --debug-line "$WORK/keep-o2.elf" \
> "$WORK/line-o2.txt" 2> "$WORK/line-o2.err" \
|| { cat "$WORK/line-o2.err" >&2; \
fail "llvm-dwarfdump --debug-line failed for -O2"; }
python3 - "$M7COFF" "$WORK/obj/debug-a-o2.o" "$WORK/info-o2.txt" \
"$WORK/line-o2.txt" <<'PY' || fail "-O2 multi-TU DWARF is wrong"
import os
import re
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
obj = m7coff.parse(sys.argv[2])
first_loclists = len(m7coff.section(obj, ".debug_loclists")["raw"])
info = open(sys.argv[3], encoding="latin1").read()
line = open(sys.argv[4], encoding="latin1").read()
blocks = info.split("Compile Unit:")[1:]
if len(blocks) != 2:
sys.exit("saw %d compile units at -O2, want 2" % len(blocks))
cus = []
for block in blocks:
name = re.search(r'DW_AT_name.*string = "([^"]+)"', block)
loc = re.search(r"DW_AT_loclists_base .*\(0x([0-9a-fA-F]+)\)", block)
if not name or not loc:
sys.exit("-O2 CU lacks a name or DW_AT_loclists_base")
cus.append((name.group(1), int(loc.group(1), 16)))
if {n for n, _ in cus} != {"debug-a.c", "debug-b.c"}:
sys.exit("-O2 CU names %r" % [n for n, _ in cus])
by_name = {n: b for n, b in cus}
if by_name["debug-a.c"] != 12:
sys.exit("-O2 first CU loclists_base %#x, want 12 (unit header)"
% by_name["debug-a.c"])
want = first_loclists + 12
if by_name["debug-b.c"] != want:
sys.exit("-O2 second CU loclists_base %#x, want %#x (first object's "
".debug_loclists contribution + header)"
% (by_name["debug-b.c"], want))
for name in ("debug_a_mul", "debug_a_add", "debug_b_sub", "debug_b_mul"):
if 'string = "%s"' % name not in info:
sys.exit("-O2 DWARF has no subprogram %s" % name)
for name in ("debug-a.c", "debug-b.c"):
if 'name: "%s"' % name not in line:
sys.exit("-O2 .debug_line has no %s file table" % name)
print(" -O2: both CUs, loclists_base %#x/%#x (first contribution %d B)"
% (by_name["debug-a.c"], by_name["debug-b.c"], first_loclists))
PY
if command -v ar >/dev/null 2>&1; then
echo "== archive-member debug sections are merged, not dropped"
ar rcs "$WORK/dwarf.lib" "$WORK/obj/debug-a.o" "$WORK/obj/debug-b.o" \
|| fail "ar could not create the debug archive"
"$TMS_LINK" -o "$WORK/keep-archive.coff" --keep-debug \
--entry _start --text 018A0000 --bss 01A00000 \
"$DOS/DENTRY.O" "$WORK/dwarf.lib" \
|| fail "tms-link --keep-debug from an archive failed"
python3 - "$M7COFF" "$WORK/keep-archive.coff" <<'PY' \
|| fail "archive-member debug sections are missing"
import os
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(sys.argv[1]))
import m7coff # noqa: E402
c = m7coff.parse(sys.argv[2])
names = [s["name"] for s in c["sections"]]
for name in (".debug_info", ".debug_abbrev", ".debug_line", ".debug_str",
".debug_str_offsets", ".debug_addr", ".debug_line_str"):
if name not in names:
sys.exit("archive link dropped %s; sections %r" % (name, names))
if any(s["nreloc"] for s in c["sections"]):
sys.exit("archive debug link still has relocations")
print(" archive link sections: %s" % " ".join(names))
PY
"$ROOT/scripts/m7/elf-debug-wrap.py" -o "$WORK/archive.elf" \
"$WORK/keep-archive.coff" >/dev/null \
|| fail "elf-debug-wrap failed for the archive link"
"$DWARFDUMP" --debug-info --verbose --debug-line "$WORK/archive.elf" \
> "$WORK/archive-dwarf.txt" 2> "$WORK/archive-dwarf.err" \
|| { cat "$WORK/archive-dwarf.err" >&2; \
fail "llvm-dwarfdump failed on the archive link"; }
for want in 'string = "debug-a.c"' 'string = "debug-b.c"' \
'string = "debug_a_mul"' 'string = "debug_b_mul"'; do
grep -q "$want" "$WORK/archive-dwarf.txt" \
|| fail "archive-link DWARF has no $want"
done
echo " archive link DWARF: both CUs and both TU functions present"
else
echo "== archive-member debug merge: SKIP (no ar command)"
fi
echo "== run the stripped image in MAME"
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$WORK/strip.coff" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "$MAME_TIMEOUT" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/debug-multi-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; \
fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^DEBUG MULTI: a_mul=22 a_add=14 b_sub=9 b_mul=36$' "$WORK/mame.log" \
|| { grep '^DEBUG MULTI:' "$WORK/mame.log" >&2 || true; \
fail "multi-TU debug markers are wrong"; }
grep -q '^DEBUG MULTI MAME: PASS$' "$WORK/mame.log" \
|| fail "MAME marker check failed"
echo "M8 dwarf-multi: PASS (two TUs merged with rehomed CU/abbrev/str/line/"
echo " addr bases, dwarfdump sees both files/functions/lines/"
echo " addresses, and the stripped image runs in MAME)"
+96
View File
@@ -0,0 +1,96 @@
#!/bin/sh
# M8 native-library gate: link a real driver against the 1987 FLIB.LIB and
# RTS.LIB through tools/tms-link, run it in MAME, and compare the allocated
# image and public symbols with the GSPLNK 2.00 oracle.
#
# The driver uses flib FD$ADD/FD$MUL/FD$DTOI (double arithmetic and fptosi)
# and rts.lib _isascii. The GSPLNK run never reaches MAME; the tms-link run
# must report the loader status, place .text with 0 differing bytes, and pass
# the marker check.
#
# scripts/tests/m8/native-lib.sh
#
# Overridable: LLVM_BIN TMS_LLC TMS_CLANG MAME DOSBOX DOSBOX_CONF SDK_IMG
# M8_NATIVE_LIB_WORK M8_NATIVE_LIB_SDK M7COFF
# LOADER_AT LOADER_END MAME_TIMEOUT DOSBOX_TIMEOUT
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m8
WORK=${M8_NATIVE_LIB_WORK:-$ROOT/build/m8-native-lib}
SDK=${M8_NATIVE_LIB_SDK:-$ROOT/build/m4-sdk}
M7COFF=${M7COFF:-$ROOT/build/llvm-clean/llvm/test/CodeGen/TMS34010/m7coff.py}
fail() {
echo "M8 native lib: FAIL: $*" >&2
exit 1
}
[ -f "$DIR/libcheck.c" ] || fail "missing driver: $DIR/libcheck.c"
[ -f "$DIR/lib-entry.asm" ] || fail "missing entry: $DIR/lib-entry.asm"
[ -f "$DIR/lib-check.lua" ] || fail "missing checker: $DIR/lib-check.lua"
[ -f "$M7COFF" ] || fail "independent TI-COFF reader not found: $M7COFF"
rm -rf "$WORK"
mkdir -p "$WORK"
RUN_ENV="M4_NATIVE=1
M4_SOURCES=$DIR/libcheck.c
M4_ENTRY=$DIR/lib-entry.asm
M4_CHECK_LUA=$DIR/lib-check.lua
M4_SDK=$SDK
M4_NATIVE_LIBS=FLIB.LIB
M4_NATIVE_RTS=1"
echo "== GSPLNK oracle link (no MAME)"
# shellcheck disable=SC2086
env $RUN_ENV \
M4_WORK="$WORK/gsplnk" \
M4_COFF="$WORK/gsplnk/m4.coff" \
M4_SKIP_MAME=1 \
"$ROOT/scripts/m4/run.sh" > "$WORK/gsplnk.log" 2>&1 \
|| { tail -30 "$WORK/gsplnk.log" >&2; fail "GSPLNK oracle link failed"; }
grep -q '^M4 LINK: PASS' "$WORK/gsplnk.log" \
|| { tail -30 "$WORK/gsplnk.log" >&2; fail "GSPLNK oracle did not pass"; }
[ -f "$WORK/gsplnk/m4.coff" ] || fail "GSPLNK produced no image"
echo "== tms-link archive link and MAME"
# shellcheck disable=SC2086
env $RUN_ENV \
M4_LINKER=tms-link \
M4_WORK="$WORK/tmslink" \
M4_COFF="$WORK/tmslink/m4.coff" \
LOADER_AT="${LOADER_AT:-2500}" \
LOADER_END="${LOADER_END:-3400}" \
"$ROOT/scripts/m4/run.sh" > "$WORK/tmslink.log" 2>&1 \
|| { tail -40 "$WORK/tmslink.log" >&2; fail "tms-link archive run failed"; }
grep -q '^M8 LIB MAME: PASS' "$WORK/tmslink/mame.log" \
|| { tail -40 "$WORK/tmslink/mame.log" >&2; \
fail "tms-link MAME markers failed"; }
grep -q 'LOADER: result status=0 (OK)' "$WORK/tmslink/mame.log" \
|| fail "loader did not accept the tms-link image"
grep -q 'placed \.text .* 0 differing' "$WORK/tmslink/mame.log" \
|| fail "loader did not verify the placed .text bytes"
echo "== GSPLNK vs raw tms-link allocated bytes and symbols"
[ -f "$WORK/tmslink/M4.RAW.OUT" ] \
|| fail "tms-link did not preserve its pre-repair image"
cmp -s "$WORK/tmslink/M4.RAW.OUT" "$WORK/tmslink/m4.coff" \
|| fail "tms-link image changed during coff-check repair"
python3 "$ROOT/scripts/tests/m8/coff-parity.py" \
"$M7COFF" "$WORK/gsplnk/m4.coff" "$WORK/tmslink/M4.RAW.OUT" \
|| fail "raw tms-link image differs from GSPLNK"
# The library members are visible in the map, and no unrelated member was
# pulled in. (The marker check already proved the actual calls ran.)
MAP=$WORK/tmslink/m4.map
for sym in FD\$ADD FD\$MUL FD\$DTOI _isascii _fp_error; do
grep -q " ${sym}\$" "$MAP" || fail "tms-link map has no $sym"
done
for sym in FD\$DIV FD\$NEG FD\$EQ FS\$ADD _printf; do
if grep -q " ${sym}\$" "$MAP"; then
fail "tms-link map has an unneeded member symbol: $sym"
fi
done
echo "M8 native lib: PASS (FD\$ADD/FD\$MUL/FD\$DTOI + _isascii, GSPLNK parity)"
+78 -43
View File
@@ -1,29 +1,38 @@
#!/bin/sh
# tms-clang -- C IR pipeline: clang IR, --scale to bit addresses, optimize,
# then --scale the late byte-indexed GEPs.
# tms-clang -- C IR pipeline: clang IR, the --bitptr semantic barrier, optimize,
# scale the late byte-indexed GEPs, lower the barrier, and restore the M0
# pointer-difference folding.
#
# Usage: tms-clang [-O0|-O2] [-I dir] -o OUT.ll IN.c
# Usage: tms-clang [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c
#
# -O0: clang IR -> --scale -> OUT (bit-addressed; no optimizer).
# -O2 (the default): clang IR -> --scale -> opt -> --scale -> OUT.
# -O0: clang IR -> --bitptr -> --lower-bitptr -> OUT (bit-addressed).
# -O2 (the default): clang IR -> --bitptr -> opt -> --scale -> --lower-bitptr
# -> opt -passes=instcombine -> OUT.
#
# The pre-opt --scale is required by the M0/M2 pointer model: pointers are bit
# -g passes clang -g through to the IR; the barrier passes copy !dbg
# locations, so llc -filetype=obj emits the DWARF `.debug_*` sections. The
# asm path still has no GSPA-assemblable debug directives.
#
# The barrier is required by the M0/M2 pointer model: pointers are bit
# addresses, so `(int)(p + n) - (int)p` must be 8n at run time (the optimizer's
# DataLayout would otherwise fold it to n). The optimizer consequently sees
# bit-addressed IR. It creates new byte-indexed GEPs (SROA's aggregate splits
# and switch tables), so the post-opt --scale is still needed. `--normalize`
# is not used there: it would treat those byte offsets as already-scaled bits,
# which an aggregate return's `.fca.N.gep` load (+4 bytes, not +4 bits) turns
# into an 8x address bug.
# DataLayout would otherwise fold it to n). `--bitptr` replaces every GEP (and
# an inttoptr of a bit addend over a ptrtoint base) with an opaque
# @__tms_bitptr(i32 bitoff, ptr base) call, so InstCombine cannot canonicalize
# the already-scaled bit offset back into a byte-indexed GEP; the M6 post-opt
# `--scale` then multiplied that index by 8 again (the `p += n` over-scale, and
# the reason the shim's memmove used constant end-pointer steps).
#
# Known M6 limitation: InstCombine can canonicalize a bit-offset
# inttoptr(add(ptrtoint p, n*8)) back into a getelementptr i8 whose index is a
# bit count. The post-opt --scale treats that index as bytes and multiplies it
# by 8 again, so an -O2 C `p += n` whose derived pointer is only used as an
# integer can be over-scaled. The shared conformance shim's memmove avoids the
# shape by advancing end pointers with constant 8-bit steps; a proper fix needs
# a target bit-pointer semantic barrier and is M7 work (see README.md and
# tools/tms-bitaddr/bitscale.cpp).
# The optimizer still creates genuinely byte-indexed GEPs (SROA aggregate
# splits, switch tables), so the post-opt `--scale` is needed for those. By
# then every original GEP is a call, so the pass only sees optimizer-created
# byte GEPs. `--normalize` is not used there: it would treat those byte
# offsets as already-scaled bits, which an aggregate return's `.fca.N.gep`
# load (+4 bytes, not +4 bits) turns into an 8x address bug.
#
# `--lower-bitptr` then replaces each call with inttoptr(add(ptrtoint base,
# bitoff)) and the final instcombine restores the M0 pointer-difference folding
# (`int_diff` 8/32, the pointer-difference divide) and canonicalizes the
# lowered bit GEPs, which llc already treats as bit offsets.
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
@@ -33,6 +42,9 @@ ROOT=$(cd "$(dirname "$0")/.." && pwd)
TMS_CLANG=${TMS_CLANG:-$ROOT/build/llvm-clean-build/bin/clang}
TMS_OPT=${TMS_OPT:-$ROOT/build/llvm-clean-build/bin/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
# Extra language flags from the caller (M4_EXTRA_CFLAGS). The conformance
# c-torture sweep uses this for -std=gnu89; shipped gates leave it empty.
TMS_CLANG_EXTRA_FLAGS=${TMS_CLANG_EXTRA_FLAGS:-}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR"; do
if [ ! -x "$tool" ]; then
@@ -44,12 +56,13 @@ for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR"; do
done
OPTIMIZE=1
DEBUG_FLAGS=
INCLUDES=
OUT=
IN=
usage() {
echo "usage: $0 [-O0|-O2] [-I dir] -o OUT.ll IN.c" >&2
echo "usage: $0 [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c" >&2
exit 2
}
@@ -57,6 +70,7 @@ while [ $# -gt 0 ]; do
case "$1" in
-O0) OPTIMIZE=0; shift ;;
-O2) OPTIMIZE=1; shift ;;
-g) DEBUG_FLAGS=-g; shift ;;
-I) [ $# -ge 2 ] || usage; INCLUDES="$INCLUDES -I $2"; shift 2 ;;
-I*) INCLUDES="$INCLUDES $1"; shift ;;
-o) [ $# -ge 2 ] || usage; OUT=$2; shift 2 ;;
@@ -73,7 +87,8 @@ trap 'rm -rf "$TMP"' EXIT HUP INT TERM
# shellcheck disable=SC2086
"$TMS_CLANG" --target=tms34010-unknown-none -O0 -Xclang -disable-O0-optnone \
-S -emit-llvm -ffreestanding -fno-builtin -nostdinc $INCLUDES \
$DEBUG_FLAGS -S -emit-llvm -ffreestanding -fno-builtin -nostdinc $INCLUDES \
$TMS_CLANG_EXTRA_FLAGS \
-o "$TMP/step1.ll" "$IN"
# A `static` variadic definition is local, so DeadArgumentElimination removes
@@ -114,30 +129,50 @@ if [ "$OPTIMIZE" -eq 1 ]; then
fi
fi
# Scale before the optimizer so integer pointer casts keep the bit-addressed
# model (M0/M2 `int_diff`); the post-opt scale handles the byte-indexed GEPs
# opt creates (SROA aggregate splits, switch tables).
"$TMS_BITADDR" --scale "$TMP/step1.ll" "$TMP/scaled.ll" 2>/dev/null
# Hide every source GEP (and source pointer-int arithmetic) behind the opaque
# bit-pointer barrier before the optimizer, so the bit-addressed model survives
# without being re-canonicalized into byte GEPs.
run_bitaddr() { # run_bitaddr MODE IN OUT
if ! "$TMS_BITADDR" "$1" "$2" "$3" 2> "$TMP/bitaddr.err"; then
cat "$TMP/bitaddr.err" >&2
echo "tms-clang: error: tms-bitaddr $1 failed on $2" >&2
exit 1
fi
cp "$TMP/bitaddr.err" "$TMP/bitaddr-$1.log"
}
run_bitaddr --bitptr "$TMP/step1.ll" "$TMP/bitptr.ll"
mkdir -p "$(dirname "$OUT")"
if [ "$OPTIMIZE" -eq 1 ]; then
# This target has no i64 and no multiply-high. IndVarSimplify's exit-value
# replacement (which rewrites a loop's final value into a closed-form i33
# multiply, e.g. n*(n+1)/2 for sumto) is therefore an unsupported shape.
# -replexitval is an option of IndVarSimplify; disabling only that rewrite
# keeps the loop, which is what ordinary -O2 code needs. This is a driver
# policy, not a target TTI policy: opt runs without a target machine here.
# It stays until i64/M6 removes the workaround; llc diagnoses the raw i33
# shape reached by an opt run that omits this flag (m5-policy.ll).
# i64 exists since M6, but IndVarSimplify's exit-value replacement still
# rewrites a loop's final value into a closed-form i33 multiply (e.g.
# n*(n+1)/2 for sumto), which is an unsupported shape for this 32-bit
# target. -replexitval is an option of IndVarSimplify; disabling only that
# rewrite keeps the loop, which is what ordinary -O2 code needs. This is a
# driver policy, not a target TTI policy: opt runs without a target machine
# here. llc diagnoses the raw i33 shape reached by an opt run that omits
# this flag (m5-policy.ll).
"$TMS_OPT" -passes='default<O2>' -replexitval=never \
-S "$TMP/scaled.ll" -o "$TMP/opt.ll"
mkdir -p "$(dirname "$OUT")"
-S "$TMP/bitptr.ll" -o "$TMP/opt.ll"
# The optimizer may create new byte-indexed GEPs (SROA aggregate splits,
# switch tables), so scale the optimized IR once more. Known M6
# limitation: this same pass can over-scale a bit-offset GEP that
# InstCombine canonicalized from inttoptr(add) -- see the header.
"$TMS_BITADDR" --scale "$TMP/opt.ll" "$OUT" 2>/dev/null
# switch tables), so scale those. Every source GEP is still an opaque call,
# so this pass cannot see (and re-scale) an already-bit offset.
run_bitaddr --scale "$TMP/opt.ll" "$TMP/scaled.ll"
# Lower the barrier and restore the M0 pointer-difference folding. The
# lowered inttoptr(add) shapes canonicalize to GEPs whose index is already
# a bit count; llc treats a GEP index as a bit offset, and no scale follows.
# `no-verify-fixpoint` suppresses only InstCombine's idempotence check: the
# M6 shim's emit_uint64 has a `zext i32 %base to i64` that a second run
# would re-mark `nneg`, which the verifier reports as "did not reach a
# fixpoint". The first run's output is the intended IR and all gates pass
# with it; the flag is the documented escape for this known shape.
run_bitaddr --lower-bitptr "$TMP/scaled.ll" "$TMP/lowered.ll"
"$TMS_OPT" -passes='instcombine<no-verify-fixpoint>' \
-S "$TMP/lowered.ll" -o "$OUT"
else
# `scaled.ll` is already the final bit-offset IR; do not scale it twice.
mkdir -p "$(dirname "$OUT")"
cp "$TMP/scaled.ll" "$OUT"
# No optimizer, so no byte GEPs can be created; lower the barrier directly
# back to the historical bit-addressed inttoptr(add) form.
run_bitaddr --lower-bitptr "$TMP/bitptr.ll" "$OUT"
fi
+13 -7
View File
@@ -12,9 +12,9 @@ runs the gate and also pins the `XMapWindow`/`XRaiseWindow` correction.
The table is consumed through `scripts/m2/gen-rom-imports.sh`, which emits an
ABI-preserving `jauc <address>h` stub for every
`<name> <bit-address>` line. The **30-entry v2.2 table** is the M4 table: the
four M3 connection/window entries plus the drawing, event, `XImage`, XG,
blitter and image-client entries. `scripts/m2/gen-rom-imports.sh` emits every
`<name> <bit-address>` line. The v2.2 table is the M4 table plus the M7.3 additions: the four M3
connection/window entries, the drawing/event/`XImage`/XG/blitter entries and
the six M7.3 request builders. `scripts/m2/gen-rom-imports.sh` emits every
entry; each client links only the stubs it calls. **M5 adds no ROM entry and
changes no address**: the native TI-COFF path consumes the same generated
stubs, and `scripts/tests/m4/symbols.sh` remains the table gate. The M5
@@ -59,9 +59,9 @@ table here is authoritative. `scripts/m4/validate-syms.sh` and
## v2.2 entries validated
The table below has **30 entries**: 12 connection/window/event, 1 blitter
helper, 8 drawing/GC, 6 `XImage`/error-handler and 3 C runtime entries.
`scripts/m4/validate-syms.sh` walks all 30 and prints the count.
The table below has **36 entries**: 17 connection/window/event, 1 blitter
helper, 9 drawing/GC, 6 `XImage`/error-handler and 3 C runtime entries.
`scripts/m4/validate-syms.sh` walks all 36 and prints the count.
### Connection, windows, events
@@ -79,6 +79,11 @@ helper, 8 drawing/GC, 6 `XImage`/error-handler and 3 C runtime entries.
| `XSelectInput` | `0x3FD97D50` | termtris `xlib.h` (`ChangeWindowAttributes`) |
| `XGetInputFocus` | `0x3FD55210` | termtris `xlib.h` |
| `XSetInputFocus` | `0x3FD536B0` | SetInputFocus request opcode `0x2a`; the ROM body reads `0xffe0`/`0xffc0`/`0xffa0` and supplies CurrentTime; sibling of `XGetInputFocus` opcode `0x2b` |
| `XMapSubwindows` | `0x3FD64BF0` | `dwt/notes/GUI_APPS.md`; request opcode 9 (`MapSubwindows`), two arguments |
| `XChangeWindowAttributes` | `0x3FD38770` | `GUI_APPS.md`; opcode 2 plus the value walker `0x3FDAA550`; `xmore` selects `CWBackPixel` |
| `XConfigureWindow` | `0x3FD3A510` | `GUI_APPS.md`; opcode 12 with the fixed mask 15 and x/y/width/height reads (the ROM's move/resize shape, not the generic `XWindowChanges` form) |
| `XInternAtom` | `0x3FD5E420` | `GUI_APPS.md`; opcode 16 plus `strlen` and `_XSend`; the emulated `_XSend` scatter path blocks, so `xmore` records the documented skip |
| `XChangeProperty` | `0x3FD37330` | `GUI_APPS.md`; opcode 18 plus `blit_copy`; `xmore` writes `WM_NAME` with predefined atom 39 |
### Blitter copy helper
@@ -97,6 +102,7 @@ helper, 8 drawing/GC, 6 `XImage`/error-handler and 3 C runtime entries.
| `XLoadFont` | `0x3FD4AE80` | ROM body builds `movi 0x2d` (OpenFont opcode 45) and `movb` to the request buffer; `dwt/notes/GUI_APPS.md` table; **not** in the termtris `xlib.h`; checked by `validate-syms.sh` |
| `XCopyArea` | `0x3FD3E220` | ROM body builds `movi 0x3e` (CopyArea opcode 62) and `movb` to the request buffer; `dwt/notes/GUI_APPS.md` table; **not** in the termtris `xlib.h`; checked by `validate-syms.sh`; the M4 image client copies its aligned pixmap with it |
| `XLookupString` | `0x3F9A9C30` | termtris `xlib.h`; key translation |
| `XChangeGC` | `0x3F999F80` | `GUI_APPS.md`; the 2-argument GC cache-flush shape (`movi 0x38` + serializer `0x3F997AD0`), not the generic 4-argument setter |
| `sleep` | `0x3FB33A20` | termtris `xlib.h`; called directly |
### `XImage` and error handlers (ROM-validated)
@@ -151,7 +157,7 @@ depend on the ROM Xlib entries below.
`XMapWindow 0x3FD64F60`. `scripts/tests/m3/run.sh` runs it before every MAME
run, so the compiled client cannot pass with a stale stub. The M3 and M4
validators are separate scripts (the M3 one is a four-entry regression; the M4
one walks the whole 30-entry table), but they use the same
one walks the whole 36-entry table), but they use the same
range/alignment/prologue rules and the same corrected address. The M4 table
also carries `XCreatePixmap`, `XSetInputFocus`, `blit_copy`, `XImage`,
`XGetImage`/`XDestroyImage` and both error-handler setters; `symbols.sh`
+20
View File
@@ -16,6 +16,26 @@ XCreateSimpleWindow 0x3FD41B90 termtris xlib.h; xhello.asm
# render an aligned pixmap and CopyArea it to the (unaligned) window.
XCreatePixmap 0x3FD416E0 CreatePixmap opcode 0x35
XMapWindow 0x3FD64F60 MapWindow request opcode 8; termtris xlib.h
# --- M7.3 wider surface (GUI_APPS table; request opcodes re-checked with dis34) ---
# XMapSubwindows is the MapSubwindows request builder (opcode 9). The ROM body
# does the Display request-buffer space check and writes opcode 9.
XMapSubwindows 0x3FD64BF0 MapSubwindows opcode 9 (GUI_APPS)
# XConfigureWindow is the ROM's fixed-mask ConfigureWindow builder: opcode 12
# with the constant CWX|CWY|CWWidth|CWHeight mask 15, taking x/y/width/height
# as four scalar arguments (the Xlib XMoveResizeWindow call shape) rather than
# an XWindowChanges pointer.
XConfigureWindow 0x3FD3A510 ConfigureWindow opcode 12, mask 15 (GUI_APPS)
# XChangeWindowAttributes is opcode 2 and calls the XSetWindowAttributes value
# walker at 0x3FDA A550 (mask-selected fields, byte 4 = CWBackPixel).
XChangeWindowAttributes 0x3FD38770 ChangeWindowAttributes opcode 2 (GUI_APPS)
# XInternAtom is opcode 16; it strlens the name and returns the atom id.
XInternAtom 0x3FD5E420 InternAtom opcode 16 (GUI_APPS)
# XChangeProperty is opcode 18; it copies the value bytes with the ROM blitter
# entry blit_copy (0x3FB44400), so the client must prime the blitter first.
XChangeProperty 0x3FD37330 ChangeProperty opcode 18 (GUI_APPS)
# XChangeGC is opcode 56 (0x38); its body flushes the GC's pending value cache
# through 0x3F997AD0 (the drawing primitives call the same serializer).
XChangeGC 0x3F999F80 ChangeGC opcode 56 (GUI_APPS)
XRaiseWindow 0x3FD645B0 ConfigureWindow opcode 12, CWStackMode=Above
XSync 0x3FD9F6B0 termtris xlib.h; xhello.asm
XFlush 0x3F9B1030 termtris xlib.h
+357 -71
View File
@@ -5,10 +5,19 @@
// normal LLVM byte-sized types. --normalize lowers GEPs whose offsets are
// already bit counts (shift 0), except the late switch-table GEP.
//
// tms-clang (scripts/tms-clang) uses --scale twice for C input: before opt, so
// the optimizer sees the M0/M2 bit-addressed pointer model, and after opt, to
// convert the byte-indexed GEPs the optimizer creates (SROA aggregate splits,
// switch tables). --normalize remains for already-bit-addressed input.
// --bitptr is the M7.1 semantic barrier: it replaces every non-vector GEP (and
// an inttoptr of a bit addend over a ptrtoint base) with a call to the opaque
// external @__tms_bitptr(i32 bitoff, ptr base), so the optimizer cannot
// canonicalize the already-scaled bit offset back into a byte getelementptr.
// Constant-expression GEPs cannot hold a call, so they keep the historical
// inttoptr(add(ptrtoint, bits)) form. --lower-bitptr undoes the barrier after
// opt, replacing each call with inttoptr(add(ptrtoint base, bitoff)); a final
// instcombine then restores the M0 int_diff/pointer-difference folding.
//
// tms-clang (scripts/tms-clang) uses --bitptr before opt, --scale on the
// byte-indexed GEPs the optimizer creates (SROA aggregate splits, switch
// tables), --lower-bitptr after that, and a final instcombine. --scale and
// --normalize remain for the tool's own tests and already-scaled input.
//
// Build:
// clang++-19 -std=c++17 $(llvm-config-19 --cxxflags) bitscale.cpp \
@@ -24,6 +33,7 @@
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
@@ -36,25 +46,20 @@ using namespace llvm;
static unsigned GepShift = 3; // 3 for --scale, 0 for --normalize
// Known M6 limitation: --scale cannot distinguish an optimizer-created byte GEP
// from InstCombine's canonicalization of a bit-offset
// inttoptr(add(ptrtoint p, n*8)) back into a getelementptr i8 whose index is a
// bit count. tms-clang's second (post-opt) --scale treats that index as bytes
// and multiplies it by 8 again, so an -O2 C `p += n` whose derived pointer is
// only used as an integer can be over-scaled. The shared conformance shim's
// memmove avoids the shape with constant end-pointer steps; a proper fix needs
// a target bit-pointer semantic barrier (M7).
// M7.1 removed the old ambiguity: tms-clang now runs --bitptr before opt, so
// InstCombine sees an opaque @__tms_bitptr call instead of an already-bit
// inttoptr(add(ptrtoint,...)) it could canonicalize back into a byte GEP.
// The post-opt --scale therefore only sees optimizer-created byte GEPs, and
// the final --lower-bitptr + instcombine restore the M0 folding. --scale's
// own byte-vs-bit distinction is still the old one, so --normalize keeps the
// switch-table exception below.
// SimplifyCFG's switch-to-lookup-table transform runs after --scale and
// creates a byte-indexed GEP into a *new* global whose name starts with
// "switch.table." (SimplifyCFG names it "switch.table." + function name).
// --scale already replaced every pre-existing GEP with base + bits, so any
// GEP still present at --normalize time normally carries an already-bit
// offset. The switch table is the exception: its index is a byte/element
// offset. Treat only that shape as bytes and shift it by 3. (tms-clang no
// longer runs --normalize after opt: it runs --scale again, because SROA's
// aggregate-split loads are also byte-indexed. --normalize remains for
// already-bit-addressed input.)
// SimplifyCFG's switch-to-lookup-table transform runs after the pre-opt
// barrier and creates a byte-indexed GEP into a *new* global whose name starts
// with "switch.table." (SimplifyCFG names it "switch.table." + function name).
// The post-opt --scale scales that GEP from bytes; --normalize is only used
// for already-bit-addressed input and special-cases the same table so its
// index is still shifted by 3. Treat only that shape as bytes.
//
// This intentionally depends on SimplifyCFG's current global naming. Revisit
// it on every LLVM upgrade; normalize-switch-table.ll, the M5 policy gate and
@@ -73,6 +78,40 @@ static unsigned gepShift(Value *Base) {
return GepShift;
}
// Fold `0 + x` / `x * 1` so a byte-offset accumulator stays readable and the
// barrier tests can match a plain `shl %n, 3` instead of `shl (0 + n*1), 3`.
static Value *addByteOffset(IRBuilder<> &B, Value *Acc, Value *Add) {
if (auto *C = dyn_cast<ConstantInt>(Acc))
if (C->isZero())
return Add;
if (auto *C = dyn_cast<ConstantInt>(Add))
if (C->isZero())
return Acc;
return B.CreateAdd(Acc, Add);
}
// The M7.1 barrier: a regular external declaration. It is deliberately not an
// LLVM intrinsic enum, because tms-bitaddr links against the stock LLVM and a
// fork-only intrinsic ID would not be available. `nounwind readnone` lets the
// optimizer CSE/hoist/remove it without letting it look through the pointer.
static FunctionCallee getBitPtrFn(Module &M) {
LLVMContext &Ctx = M.getContext();
FunctionType *FT = FunctionType::get(
PointerType::getUnqual(Ctx),
{Type::getInt32Ty(Ctx), PointerType::getUnqual(Ctx)}, false);
Function *Fn = M.getFunction("__tms_bitptr");
if (!Fn) {
Fn = Function::Create(FT, GlobalValue::ExternalLinkage,
"__tms_bitptr", M);
} else if (Fn->getFunctionType() != FT || !Fn->isDeclaration()) {
report_fatal_error("bitscale: @__tms_bitptr already exists with an "
"unexpected signature or a body");
}
Fn->addFnAttr(Attribute::NoUnwind);
Fn->addFnAttr(Attribute::ReadNone);
return FunctionCallee(FT, Fn);
}
struct Stats {
unsigned geps = 0;
unsigned const_geps = 0;
@@ -218,11 +257,17 @@ static bool scale_gep(GetElementPtrInst *GEP)
if (StructType *STy = GTI.getStructTypeOrNull()) {
unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
uint64_t FieldOff = DL.getStructLayout(STy)->getElementOffset(FieldNo);
ByteOff = B.CreateAdd(ByteOff, ConstantInt::get(B.getInt32Ty(), FieldOff));
if (FieldOff)
ByteOff = addByteOffset(
B, ByteOff, ConstantInt::get(B.getInt32Ty(), FieldOff));
} else {
uint64_t Stride = GTI.getSequentialElementStride(DL);
Value *Scaled = B.CreateMul(Idx32, ConstantInt::get(B.getInt32Ty(), Stride));
ByteOff = B.CreateAdd(ByteOff, Scaled);
Value *Scaled =
Stride == 1
? Idx32
: B.CreateMul(Idx32,
ConstantInt::get(B.getInt32Ty(), Stride));
ByteOff = addByteOffset(B, ByteOff, Scaled);
}
}
@@ -236,6 +281,195 @@ static bool scale_gep(GetElementPtrInst *GEP)
return true;
}
// --bitptr: bitoff is the byte offset computed exactly as --scale's, shifted
// by 3, passed through an opaque call. The optimizer cannot rewrite the call
// into an already-scaled GEP, which is what the second --scale used to mangle.
static bool bitptr_gep(GetElementPtrInst *GEP, FunctionCallee Fn) {
if (GEP->getType()->isVectorTy())
return false;
Value *Base = GEP->getPointerOperand();
const DataLayout &DL = GEP->getModule()->getDataLayout();
IRBuilder<> B(GEP);
Value *ByteOff = ConstantInt::get(B.getInt32Ty(), 0);
for (auto GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); GTI != GTE;
++GTI) {
Value *Idx = GTI.getOperand();
Value *Idx32 = B.CreateSExtOrTrunc(Idx, B.getInt32Ty());
if (StructType *STy = GTI.getStructTypeOrNull()) {
unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
uint64_t FieldOff = DL.getStructLayout(STy)->getElementOffset(FieldNo);
if (FieldOff)
ByteOff = addByteOffset(
B, ByteOff, ConstantInt::get(B.getInt32Ty(), FieldOff));
} else {
uint64_t Stride = GTI.getSequentialElementStride(DL);
Value *Scaled =
Stride == 1
? Idx32
: B.CreateMul(Idx32,
ConstantInt::get(B.getInt32Ty(), Stride));
ByteOff = addByteOffset(B, ByteOff, Scaled);
}
}
Value *BitOff = B.CreateShl(ByteOff, 3, "bit.off");
Value *Call = B.CreateCall(Fn, {BitOff, Base}, "bit.ptr");
GEP->replaceAllUsesWith(Call);
GEP->eraseFromParent();
return true;
}
// Look through the integer *widening* Clang emits around a pointer-int cast: a
// 64-bit pointer-int expression is `inttoptr(add(zext(ptrtoint p), i64 X))`
// (or the `sext` signed form), while the pointer itself is 32-bit. A trunc
// that narrows below the pointer width must NOT be stripped: for
// `(unsigned short)(unsigned)p + 24` clang emits
// `zext i16 (trunc i32 (ptrtoint p))`, and dropping the trunc would change the
// value from `(p & 0xFFFF) + 24` to `p + 24`. A trunc to the pointer width is
// value-preserving for the low word and may be stripped.
static Value *stripWideningCasts(Value *V, unsigned PtrBits) {
while (true) {
unsigned Opc;
Value *Operand = nullptr;
if (auto *CI = dyn_cast<CastInst>(V)) {
Opc = CI->getOpcode();
Operand = CI->getOperand(0);
} else if (auto *CE = dyn_cast<ConstantExpr>(V)) {
Opc = CE->getOpcode();
Operand = CE->getOperand(0);
} else {
break;
}
if (Opc == Instruction::ZExt || Opc == Instruction::SExt) {
V = Operand;
continue;
}
if (Opc == Instruction::Trunc) {
Type *Dst = V->getType();
if (Dst->isIntegerTy() && Dst->getIntegerBitWidth() >= PtrBits) {
V = Operand;
continue;
}
return V; // a trunc below the pointer width changes the address
}
break;
}
return V;
}
static bool matchPtrToIntBase(Value *V, Value *&Base, unsigned PtrBits) {
V = stripWideningCasts(V, PtrBits);
if (auto *P = dyn_cast<PtrToIntOperator>(V)) {
Base = P->getPointerOperand();
return true;
}
return false;
}
// --bitptr also hides an inttoptr of a *bit* addend over a ptrtoint base, the
// shape clang emits for source pointer-to-integer arithmetic such as
// `(char *)((unsigned)p + 24)` under the M0 bit-address model. The addend may
// be widened to i64 (`(unsigned long long)(unsigned)p + 24`); the pointer is
// 32-bit, so truncate the addend to the low word for the @__tms_bitptr(i32,
// ptr) call. Without this, InstCombine canonicalizes the add back into a byte
// GEP and the post-opt --scale scales the bit addend a second time (the old
// `late`/`late64` 192 and shim memmove bug).
static bool bitptr_inttoptr(IntToPtrInst *ITP, FunctionCallee Fn) {
// The barrier interface is i32 bitoff and the TMS34010 pointer is 32-bit.
// Use that fixed width instead of an absent/foreign module DataLayout,
// whose default pointer size would be 64 and would misjudge a trunc to i32
// as narrowing.
unsigned PtrBits = 32;
Value *Expr = stripWideningCasts(ITP->getOperand(0), PtrBits);
auto *BO = dyn_cast<BinaryOperator>(Expr);
if (!BO || (BO->getOpcode() != Instruction::Add &&
BO->getOpcode() != Instruction::Sub))
return false;
Value *Base = nullptr;
Value *Off = nullptr;
bool IsSub = BO->getOpcode() == Instruction::Sub;
Value *LBase = nullptr;
Value *RBase = nullptr;
bool LIsBase = matchPtrToIntBase(BO->getOperand(0), LBase, PtrBits);
bool RIsBase =
!IsSub && matchPtrToIntBase(BO->getOperand(1), RBase, PtrBits);
if (LIsBase && !RIsBase) {
Base = LBase;
Off = BO->getOperand(1);
} else if (RIsBase && !LIsBase) {
Base = RBase;
Off = BO->getOperand(0);
} else if (LIsBase && RIsBase && !IsSub) {
// `add(ptrtoint p, ptrtoint q)`: pointer arithmetic is symmetric, so
// use the left operand as the base and the right one as the bit
// offset. InstCombine can turn this shape into a byte GEP when the
// result is only used as an integer; barriering it keeps the
// post-opt --scale from multiplying q's value by 8.
Base = LBase;
Off = BO->getOperand(1);
} else {
return false; // neither operand is a pointer-int base
}
if (!Base || !Off)
return false;
IRBuilder<> B(ITP);
// inttoptr zero-extends/truncates to the 32-bit pointer width, so the low
// word of the addend is the bit offset that matters.
Value *Off32 = B.CreateZExtOrTrunc(Off, B.getInt32Ty());
if (IsSub)
Off32 =
B.CreateSub(ConstantInt::get(B.getInt32Ty(), 0), Off32, "bit.neg");
Value *Call = B.CreateCall(Fn, {Off32, Base}, "bit.ptr");
ITP->replaceAllUsesWith(Call);
ITP->eraseFromParent();
return true;
}
static unsigned lower_bitptr_calls(Module &M) {
Function *Fn = M.getFunction("__tms_bitptr");
if (!Fn)
return 0;
LLVMContext &Ctx = M.getContext();
FunctionType *Want = FunctionType::get(
PointerType::getUnqual(Ctx),
{Type::getInt32Ty(Ctx), PointerType::getUnqual(Ctx)}, false);
if (Fn->getFunctionType() != Want || !Fn->isDeclaration())
report_fatal_error("bitscale: --lower-bitptr requires a declaration of "
"@__tms_bitptr(i32, ptr)");
std::vector<CallInst *> Calls;
for (User *U : Fn->users()) {
auto *CI = dyn_cast<CallInst>(U);
if (!CI || CI->getCalledFunction() != Fn || CI->arg_size() != 2 ||
CI->getArgOperand(0)->getType() != Type::getInt32Ty(Ctx) ||
CI->getArgOperand(1)->getType() != PointerType::getUnqual(Ctx))
report_fatal_error(
"bitscale: --lower-bitptr found a non-call or mismatched use "
"of @__tms_bitptr");
Calls.push_back(CI);
}
unsigned Lowered = 0;
for (CallInst *CI : Calls) {
IRBuilder<> B(CI);
Value *Off = CI->getArgOperand(0);
Value *Base = CI->getArgOperand(1);
Value *BaseInt = B.CreatePtrToInt(Base, B.getInt32Ty(), "bit.base");
Value *Addr = B.CreateAdd(BaseInt, Off, "bit.addr");
Value *Ptr = B.CreateIntToPtr(Addr, CI->getType(), "bit.ptr");
CI->replaceAllUsesWith(Ptr);
CI->eraseFromParent();
++Lowered;
}
if (Fn->use_empty())
Fn->eraseFromParent();
return Lowered;
}
static void collect_const_geps(Value *V, std::vector<ConstantExpr *> &Out,
unsigned depth = 0)
{
@@ -257,15 +491,14 @@ static void collect_const_geps(Value *V, std::vector<ConstantExpr *> &Out,
// --normalize lowers a GEP offset directly as a bit offset (shift 0). That is
// only correct for input that is already bit-addressed, such as hand-written
// IR or the pre-opt output of --scale. tms-clang does not use it for the
// post-opt pass: after the first --scale every original GEP is gone, so any
// GEP left after opt was created by the optimizer and indexes bytes (SROA
// aggregate-split loads, switch tables); the driver runs --scale again for
// those. A typed GEP still carries a byte offset (DataLayout strides), and a
// vector GEP is not handled at all; treating either as bits would be an 8x
// address bug. The switch-to-lookup table is the one late, genuinely
// byte-indexed GEP that --normalize special-cases; its byte offset is computed
// with DataLayout and shifted by 3, so a typed table (e.g. [N x i32]) is
// accepted as well.
// post-opt pass: the pre-opt --bitptr barrier leaves only optimizer-created
// byte GEPs after opt (SROA aggregate-split loads, switch tables), so the
// driver runs --scale for those. A typed GEP still carries a byte offset
// (DataLayout strides), and a vector GEP is not handled at all; treating either
// as bits would be an 8x address bug. The switch-to-lookup table is the one
// late, genuinely byte-indexed GEP that --normalize special-cases; its byte
// offset is computed with DataLayout and shifted by 3, so a typed table (e.g.
// [N x i32]) is accepted as well.
static bool check_normalize_gep(Value *Base, Type *ResultTy, Type *SourceTy,
std::string &Msg)
{
@@ -339,21 +572,34 @@ int main(int argc, char **argv)
{
if (argc < 3) {
errs() << "usage: " << argv[0]
<< " [--scale|--normalize] input.ll [output.ll]\n";
<< " [--scale|--normalize|--bitptr|--lower-bitptr] input.ll"
" [output.ll]\n";
return 2;
}
enum class Mode { Scale, Normalize, BitPtr, LowerBitPtr };
Mode TheMode = Mode::Scale;
int Arg = 1;
if (StringRef(argv[Arg]) == "--normalize") {
GepShift = 0;
TheMode = Mode::Normalize;
++Arg;
} else if (StringRef(argv[Arg]) == "--scale") {
GepShift = 3;
TheMode = Mode::Scale;
++Arg;
} else if (StringRef(argv[Arg]) == "--bitptr") {
GepShift = 3;
TheMode = Mode::BitPtr;
++Arg;
} else if (StringRef(argv[Arg]) == "--lower-bitptr") {
TheMode = Mode::LowerBitPtr;
++Arg;
}
int Remaining = argc - Arg;
if (Remaining != 1 && Remaining != 2) {
errs() << "usage: " << argv[0]
<< " [--scale|--normalize] input.ll [output.ll]\n";
<< " [--scale|--normalize|--bitptr|--lower-bitptr] input.ll"
" [output.ll]\n";
return 2;
}
@@ -375,49 +621,89 @@ int main(int argc, char **argv)
Stats Before = collect(*M);
// Constant-expression GEPs (e.g. `"hello" + 2`) cannot be replaced by an
// instruction, so rewrite them as constant inttoptr(add(ptrtoint, 8*off)).
unsigned ConstScaled = 0;
unsigned Scaled = 0;
unsigned Lowered = 0;
unsigned GepCalls = 0;
unsigned IntToPtrCalls = 0;
const DataLayout &DL = M->getDataLayout();
bool Changed = true;
while (Changed) {
Changed = false;
std::vector<ConstantExpr *> Work;
for (GlobalVariable &G : M->globals())
if (G.hasInitializer())
collect_const_geps(G.getInitializer(), Work);
for (Function &F : *M)
for (BasicBlock &BB : F)
for (Instruction &I : BB)
for (Value *Op : I.operands())
collect_const_geps(Op, Work);
std::set<ConstantExpr *> Seen;
for (ConstantExpr *CE : Work) {
if (!Seen.insert(CE).second)
continue;
if (scale_constant_gep(CE, DL)) {
++ConstScaled;
Changed = true;
if (TheMode == Mode::LowerBitPtr) {
Lowered = lower_bitptr_calls(*M);
} else {
// Constant-expression GEPs (e.g. `"hello" + 2`) cannot be replaced by
// an instruction, so rewrite them as constant
// inttoptr(add(ptrtoint, 8*off)). --bitptr keeps this form for them.
bool Changed = true;
while (Changed) {
Changed = false;
std::vector<ConstantExpr *> Work;
for (GlobalVariable &G : M->globals())
if (G.hasInitializer())
collect_const_geps(G.getInitializer(), Work);
for (Function &F : *M)
for (BasicBlock &BB : F)
for (Instruction &I : BB)
for (Value *Op : I.operands())
collect_const_geps(Op, Work);
std::set<ConstantExpr *> Seen;
for (ConstantExpr *CE : Work) {
if (!Seen.insert(CE).second)
continue;
if (scale_constant_gep(CE, DL)) {
++ConstScaled;
Changed = true;
}
}
}
if (TheMode == Mode::BitPtr) {
FunctionCallee Fn = getBitPtrFn(*M);
for (Function &F : *M) {
std::vector<GetElementPtrInst *> Work;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
Work.push_back(GEP);
for (GetElementPtrInst *GEP : Work)
if (bitptr_gep(GEP, Fn))
++GepCalls;
}
for (Function &F : *M) {
std::vector<IntToPtrInst *> Work;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *ITP = dyn_cast<IntToPtrInst>(&I))
Work.push_back(ITP);
for (IntToPtrInst *ITP : Work)
if (bitptr_inttoptr(ITP, Fn))
++IntToPtrCalls;
}
} else {
for (Function &F : *M) {
std::vector<GetElementPtrInst *> Work;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
Work.push_back(GEP);
for (GetElementPtrInst *GEP : Work)
if (scale_gep(GEP))
++Scaled;
}
}
}
unsigned Scaled = 0;
for (Function &F : *M) {
std::vector<GetElementPtrInst *> Work;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
Work.push_back(GEP);
for (GetElementPtrInst *GEP : Work)
if (scale_gep(GEP))
++Scaled;
}
Stats After = collect(*M);
errs() << (GepShift ? "bitscale: scaled " : "bitscale: normalized ")
<< Scaled << " GEPs, " << ConstScaled << " constant GEPs\n";
if (TheMode == Mode::LowerBitPtr)
errs() << "bitscale: lowered " << Lowered << " bitptr calls\n";
else if (TheMode == Mode::BitPtr)
errs() << "bitscale: bitptr " << GepCalls << " GEPs, "
<< IntToPtrCalls << " inttoptr, " << ConstScaled
<< " constant GEPs\n";
else
errs() << (GepShift ? "bitscale: scaled " : "bitscale: normalized ")
<< Scaled << " GEPs, " << ConstScaled << " constant GEPs\n";
errs() << " before: geps=" << Before.geps << " const_geps=" << Before.const_geps
<< " vector_geps=" << Before.vector_geps << " allocas=" << Before.allocas
<< " memintrinsics=" << Before.memintrinsics << " va=" << Before.vaarg
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more