Repository navigation
Expand file tree
/
Copy path_sw.py
More file actions
209 lines (184 loc) · 8.59 KB
/
Copy path_sw.py
File metadata and controls
209 lines (184 loc) · 8.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""
eqcheck -- build the decomp source tree and score every function in it.
This is the Phase 3 driver. `eqsweep.py` searches for one function's source;
this one is the regression harness over everything already found: it compiles
`src/*.cpp` with the settled toolchain and diffs every global function symbol
in the objects against the target image.
./eqcheck.py # score everything
./eqcheck.py -f Rotate # only symbols matching a regex
./eqcheck.py --wrong Sca # and show the instruction diff for mismatches
A symbol that is in the source but NOT in the target image is reported as
`no-target`, never skipped silently -- a typo'd mangled name would otherwise
read as "nothing to do". Likewise a function that fails to build is a loud
row, not an absent one. MATCHED.txt records what is currently byte-exact;
`--baseline` rewrites it and a regression against it is a non-zero exit, so a
source change made for function N cannot quietly break function N-1.
"""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import eqdecomp as E
import eqdiff as D
SRC = HERE / "src"
BUILD = HERE / "build"
MATCHED = SRC / "MATCHED.txt"
# Settled in Phase 1/2: ee-gcc 2.95.x at -O2. -G0 follows from the fingerprint
# (zero gp-relative accesses in 219,910 instructions).
#
# Phase 3: the ASSEMBLER is SN Systems' ps2eeas, NOT the GNU `as` bundled with
# the 2.95 packages, and the VERSION of ps2eeas matters too.
#
# * GNU as vs ps2eeas: after `mtc1` writes an FPR, an R5900 COP1 instruction
# reading it needs one slot. gcc emits `#nop` -- a COMMENT -- and leaves the
# insertion to the assembler. Every GNU as in toolchains/ drops it; every
# ps2eeas inserts it. Both ConvertToEuler functions are one instruction
# short under GNU as and byte-exact under ps2eeas.
# * ps2eeas 1.9.25.758 (in ee-gcc2.9-991111 and 2.95.3-136) auto-pads a `div`
# that follows a branch delay slot with two nops -- the R5900 DIV errata,
# `-Wdivbug-on` reports it. The target has NO padding there, so the build
# predates that fix. The 2.95.3-114 copy is the one that agrees.
# (2.95.2-273a's 1.8.19.316 does not pad either, but it breaks Transpose and
# Debug, so it is not the one.)
TOOLCHAIN = "ee-gcc2.95.3-107"
ASSEMBLER = HERE / "toolchains/ee-gcc2.95.3-114/lib/gcc-lib/ee/2.95.3/ps2eeas.exe"
#
# Phase 5: -fno-exceptions. VIQuat::ConvertTo has a stack VIMatrix44, which has
# a destructor, so with exceptions ON gcc 2.95 emits a cleanup region -- three
# copies of the `_$_10VIMatrix44(this, 2)` call reached by `b`. The target has
# exactly one. Nothing else in the tree has a local with a non-trivial dtor, so
# this is invisible until a function does. RTTI stays ON: the module carries
# __rtti / __tf<n> symbols.
FLAGS = ["-O2", "-G0", "-fno-exceptions", "-fno-caller-saves"]
def driver(name: str):
d = HERE / "toolchains" / name
for c in ("bin/ee-gcc", "bin/ee-gcc.exe", "ee/bin/gcc"):
p = d / c
if p.is_file():
return ["wine", str(p)] if p.suffix == ".exe" else [str(p)]
raise SystemExit(f"no driver in toolchain {name}")
def build(tc: str, flags: list[str], gnu_as: bool = False) -> tuple[list[Path], str]:
BUILD.mkdir(exist_ok=True)
srcs = sorted(SRC.glob("*.cpp"))
if not srcs:
raise SystemExit(f"no sources in {SRC}")
objs, err = [], []
for s in srcs:
o = BUILD / (s.stem + ".o")
if o.exists():
o.unlink()
objs.append(o)
if gnu_as:
r = subprocess.run(driver(tc) + ["-c"] + flags + [str(s), "-o", str(o)],
capture_output=True, text=True, cwd=BUILD)
err.append(r.stderr)
continue
asm = BUILD / (s.stem + ".s")
r = subprocess.run(driver(tc) + ["-S"] + flags + [str(s), "-o", str(asm)],
capture_output=True, text=True, cwd=BUILD)
err.append(r.stderr)
if asm.exists():
r = subprocess.run(["wine", str(ASSEMBLER), "-o", str(o), str(asm)],
capture_output=True, text=True, cwd=BUILD)
err.append(r.stderr)
return objs, "\n".join(x.strip() for x in err if x and x.strip())
def obj_functions(obj: Path) -> list[str]:
"""Global function symbols defined in a .text section of the object."""
out = subprocess.run([E._find_objdump(), "-t", str(obj)],
capture_output=True, text=True).stdout
names = []
for line in out.splitlines():
# 00000000 g F .text 0000003c Scale__10VIMatrix44f
m = re.match(r"^[0-9a-f]+\s+(\S*)\s+F\s+(\S+)\s+[0-9a-f]+\s+(\S+)", line)
if m and ".text" in m.group(2):
names.append(m.group(3))
return names
def score(st, img, obj: Path, symbol: str):
"""('match'|'wrong'|'no-target', wrong, total, diffreport)"""
try:
sym = st.get(symbol)
except KeyError:
return ("no-target", 0, 0, None)
target = img.func(sym, trim=True)
cand, sec, at = D.elf_function_at(obj, symbol)
# the object's own relocation table says which fields the linker writes;
# the image is linked and the object is not, so those words can only agree
# by accident. Masked sites are counted and shown, never hidden.
relocs = D.elf_relocations(obj, sec)
res = D.diff(target, cand, symbol, sym.addr, modes={"j26"},
relocs=relocs, span=(at, at + len(cand)))
if res.ok:
return ("match", 0, res.insns_target, res)
a = [w for _, w, _ in E.disasm(target, sym.addr)]
b = [w for _, w, _ in E.disasm(cand, sym.addr)]
same = sum(1 for x, y in zip(a, b) if x == y)
return ("wrong", max(len(a), len(b)) - same, max(len(a), len(b)), res)
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("-f", "--filter", default="", help="regex over symbol names")
p.add_argument("-w", "--wrong", action="store_true", help="show diffs for mismatches")
p.add_argument("-t", "--toolchain", default=TOOLCHAIN)
p.add_argument("--flags", default=" ".join(FLAGS))
p.add_argument("--baseline", action="store_true", help="rewrite MATCHED.txt")
p.add_argument("--gnu-as", action="store_true",
help="assemble with the toolchain's GNU as instead of Ps2EeAs")
a = p.parse_args(argv)
objs, err = build(a.toolchain, a.flags.split(), a.gnu_as)
if err:
print(err, file=sys.stderr)
_, st, img = E.load("SUPPORT")
rx = re.compile(a.filter) if a.filter else None
rows, matched = [], []
for o in objs:
if not o.exists():
print(f"BUILD FAILED {o.stem}", file=sys.stderr)
rows.append(("build-failed", 0, 0, o.stem, None))
continue
for name in obj_functions(o):
if rx and not rx.search(name):
continue
kind, wrong, tot, res = score(st, img, o, name)
rows.append((kind, wrong, tot, name, res))
if kind == "match":
matched.append(name)
rows.sort(key=lambda r: (r[0] != "match", r[1], r[3]))
ok = sum(1 for r in rows if r[0] == "match")
for kind, wrong, tot, name, res in rows:
if kind == "match":
note = ""
if res is not None and res.reloc is not None and res.reloc.masked:
note = f" [{res.reloc}]"
print(f" MATCH {tot:>4}i {name}{note}")
elif kind == "no-target":
print(f" NO-TGT {name} (not a symbol in SUPPORT)")
elif kind == "build-failed":
print(f" BUILD FAILED {name}")
else:
print(f" wrong {wrong:>3}/{tot:<3} {name}")
print(f"\n{ok}/{len(rows)} byte-exact")
if a.wrong:
for kind, wrong, tot, name, res in rows:
if kind == "wrong":
print("\n" + "=" * 72)
print(D.report(res))
prev = set(MATCHED.read_text().split()) if MATCHED.exists() else set()
if a.baseline:
MATCHED.write_text("\n".join(sorted(matched)) + "\n")
print(f"baseline written: {len(matched)} symbols")
return 0
lost = sorted(prev - set(matched) - ({n for _, _, _, n, _ in rows} - {r[3] for r in rows}))
lost = [n for n in sorted(prev - set(matched)) if rx is None or rx.search(n)]
if lost:
print("\nREGRESSION -- these were byte-exact and are not now:")
for n in lost:
print(f" {n}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())