docs: mwdbg unblock notes and regsim verdicts for three ties #1262

Merged
coah80 merged 1 commits from agent/w0929/opus-mwdbg-land into main 2026-10-08 19:29:18 +00:00
3 changed files with 158 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
# opus-mwdbg: unblocking mwdbg for large C++ units, and regsim verdicts (base d9d33ca0)
These are tool changes only. No source file in this worktree was edited. The tool changes are in `_mwdbg` (see its README section "Emulator limits, sjiswrap, and the socket stub").
## Why mwdbg stopped (follow-up to opus-ties.attempts.md)
1. The 1 MB stack overflowed. The emulator now reads `RETROWIN32_MEMORY_MB` and `RETROWIN32_MIN_STACK_MB`, and mwdbg.py sets them to 1024 and 32 by default (`--memory-mb`, `--stack-mb`).
2. `ws2_32!send` was missing. I added a builtin ws2_32 that logs every call to `<capture>/socket.log`. With that log, the message turned out to be `(10430) system does not support converting from 'SHIFT-JIS', treating as ASCII`. Afterwards the compiler longjmps through an empty jmp_buf (`WRITE_UNMAPPED @40495a`, esp 0).
3. The cause of that message: mwdbg drops `wibo sjiswrap.exe` from the Ninja command, so the compiler read UTF-8 sources directly and could not convert them. retrowin32 now emulates sjiswrap when `RETROWIN32_SJISWRAP=1`, and mwdbg.py turns it on automatically when the Ninja command uses sjiswrap. The emulation re-encodes source files to Shift JIS, makes `GetACP` return 932, has `IsValidCodePage(932)` succeed, and decodes code pages 0 and 932 in MultiByteToWideChar.
4. Then iplESMisc failed with `(10151) the file 'nw4r/lyt/textbox.h' cannot be opened`. The file on disk is `textBox.h`, and wibo matches paths case-insensitively. retrowin32 now falls back to a case-insensitive match when the exact path is missing.
5. regsim reproduced the iplESMisc capture only 157/161. The capture needed a second pass with a spill candidate, and regsim picked the spill node by maximum degree. MWCC picks by minimum `cost/degree`, with ties going to the later node in scan order. After fixing that, the capture reproduces 161/161, and `examples/pressure` goes from 108/126 to 126/126. None of the other 76 stored runs changed.
## Validation (data-d4, build/43U objects rebuilt before comparing)
| capture | regsim | unit.o vs ninja object |
|---|---|---|
| kbd_lib / kbdProcMod | 156/156 | identical (sha256 6a85c207…) |
| iplESMisc / DeleteUnauthorizedData__Q33ipl7utility6ESMiscFPQ23EGG4Heap | 161/161 (2 GPR passes) | identical (8a31efdb…) |
| tiZiString / update__Q39textinput8tistring6WithZiFv | 161/161 | identical (da68c526…) |
| www_wiisetting / Getter___Q23www10wiisettingFP14WWWJSPluginObjPCcP16WWWJSPluginValue | 312/312 | identical (ff8f136d…) |
## Verdicts
Method: `_mwdbg/scratch_opusmwdbg/vmap2.py` builds the want-list. It aligns the scheduled PCode with our object using difflib, because opus-ties.vmap.py's index alignment drifted and left 210 operand mismatches on tiZiString. Each want is keyed by virtual number, since names such as `candidate`, `output` and `i` repeat. A virtual is kept when at least 75% of its uses agree on one target register. `_mwdbg/scratch_opusmwdbg/regsim_locals.py` then anneals over the numbering of real source locals only, leaving `@` temps, parameters and unnamed values in place. For www_wiisetting I enumerated every ordering of its 8 locals instead.
| function | wants | as built | best with source locals reordered | best with `@` values reordered too | verdict |
|---|---|---|---|---|---|
| DeleteUnauthorizedData | 64 | 54 | 60 | 64 | structural |
| WithZi::update | 98 | 83 | 92 | 98 | structural (callee-saved part fixable by order) |
| wiisetting::Getter_ | 159 | 156 | 156 (exhaustive, 8! orders) | not needed | structural |
- **DeleteUnauthorizedData** is `return InitSavedata(heap);`. Every mismatched value is a local of an inlined function, which is why they all have `@` names.
- InitSavedata: v33 `titleIds`, v34 `ret`, v35 `ticketScratch`, v36 `i`.
- verifySavedataZD: v37/38 `titleId` parameter (hi/lo), v39/40 `block`, v41 `valid`, v42 `j`, v43 `offset`, v44 `deleteSaveData`, v45 `fileOpen`, v46 `saveData`, v47 `ret`.
- DeleteTicketsForce: v49/50 `titleId`, v51 `j`, v52 `ret`, v53 `ticketViewList`.
Reordering locals inside each inlinee reaches 60/64. That search was exhaustive over InitSavedata × DeleteTicketsForce and annealed over verifySavedataZD. The four misses are `titleId` v37/v38 (wants r19/r20) against `saveData`/`deleteSaveData` (want r30/r31). Reaching 64/64 requires numbering the inlined `titleId` parameter after verifySavedataZD's locals, and declaration order can't do that. A possible lever, still untested: copy `titleId` into a local in verifySavedataZD that is declared last, or change how titleId is passed.
- **WithZi::update**: reordering locals fixes the 9 callee-saved mismatches (index, destination, source, length v44, count, elementCount, v64, v70, v175). The order regsim found, lowest number first: index, character, length(v37), position, keyIndex, source, copied, wordLength, elementCount, count, candidate(v34), output(v38), candidate(v47), length(v44), destination, candidateOutput, output(v49), output(v36). It is untested and may conflict with nested scopes.
Six volatile-register misses remain: copied r4→r5, wordLength r7→r4, @1343 r6→r7, @1338 r5→r4, @1330 r5→r6, v148 r5→r4. @1343/@1341, @1338/@1336 and @1349 are the induction pointers of the 8-way unrolled copy loop, and @1330 is `length-8`. All of these are optimizer temps. They reach 98/98 only when the temps are renumbered, so this is structural, and it needs a loop shape that makes the unroller create its temps in a different order.
- **wiisetting::Getter_**: no ordering of the 8 locals (str, val, i ×3, kbLang, staIdx, retVal) improves on 156/159. The misses are `i`(v35) r25→r31, `i`(v38) r25→r26 and temp `@17419`(v42) r26→r25. This confirms opus-ties' result that swapping `strBuf`/`i` changes nothing, so the function is structural.

View File

@@ -0,0 +1,31 @@
# opus-ties: one-function-from-linking triage (base f9ebd2f4)
Full build at base: DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d. Diff counts are from `odiff.py` (differing / total).
Result: no new exact function, and no source changes kept.
| unit | function | diff | class | regsim verdict | result |
|---|---|---|---|---|---|
| src/utility/iplESMisc | DeleteUnauthorizedData | 74/449 | GPR register-only | n.a. (trace blocked, see below) | unchanged |
| src/iplwww/www_wiisetting | Getter_ | 14/609 | GPR register-only (two named loop counters: `i`/`strBuf` in DUMMY_SECURITY_KEY, `i` in EUR 0x3b loop -> r31) | n.a. (trace blocked) | swapping `strBuf`/`i` declarations: no change (14) |
| src/keyboard/tiZiString | WithZi::update | 85/446 | GPR register-only plus 2 dependent swaps (163/164, 291/292) | n.a. (trace blocked) | unchanged |
| libs/RVL_SDK/src/nup/nup | __nupParseServerInfo | 66/452 | GPR register-only | structural: every named local already matches; all mismatches are @-temps of the inlined `__nupFindTag`/`strlen` (@1858,@1852,@1849,@1807,@1805,@1804,@1798,@1795 + unnamed r114/r120/r128/r134/r140/r150/r158/r166/r170). Best 7/8 needs @-temps interleaved with named locals | swapping `start`/`end` in `__nupFindTag`: no change (66) |
| libs/NW4R/src/lyt/lyt_window | Window::DrawFrame | 119/376 | GPR + FPR register | structural: unnamed temp v92 (`lis/addi` table base, wants r21 instead of r31) shifts this/basePt/frameSize/alpha/bUseVtxCol and v95..v124 up by one; regsim best 4/11; FPR diffs also | unchanged |
| src/scene/memoryCard/iplMemoryCardManager | _create_icon | 37/100 | scheduling + register (same count) | n.a. | target recomputes `&mFileCell[slot][file].icon` / `.iconTlut` adds after each GX call (keeps row base and index*0x15c in separate registers); ours CSEs the full address. `texObj` local assigned before GXLoadTexObj: 61/101 (worse) |
| src/keyboard/tiString | Decolated::inputChar | 73/136 (0x1f8 vs 0x220) | instruction count | n.a. | first diff: mode-3 (`CharacterOutput`) path; target keeps a runtime index (`sthx` at count*2, dead `cmplwi ch,10`, `clrlwi` count), ours folds to constant stores. Not attempted again (see tiString.attempts.md) |
| libs/RevoEX/src/nhttp/NHTTP_recvbuf | NHTTPi_compareTokenN_HdrRecvBuf | 5/124 | scheduling only (same registers) | n.a. | loop-preheader order: target `li 0x41, li 0x5a, extsb delim, addi limit-1, li 0`, ours `extsb, addi, li 0x41, li 0, li 0x5a`. Tried: for(;;)+break 63, swap LowerCase operands 40, `<= 'Z'` first 34, constants on the left 5, if/return form 40, `inline` 5, macro 5, s8 param 5 |
| libs/RVLMiddleware/TMC_JPEG/.../Texture_MCUtoY8U8V8 | TMCJPEGDEC_set_converterY8U8V8 | 195/196 (0x30c vs 0x310) | instruction count | n.a. | target materializes `work->convBuf` (`addi r4,r3,0x1858`) at entry and adds row offsets to it; ours folds into each offset. Already covered by tex1/g5/fz15; IRO and pragma sweep (irosweep --all): no hit |
| libs/RVLMiddleware/TMC_JPEG/.../Texture_MCUtoRGB565 | TMCJPEGDEC_set_converterRGB565 | 169/170 (0x2a4 vs 0x2a8) | instruction count | n.a. | same as Y8U8V8 (convBuf base kept at entry); irosweep --all: no hit |
| libs/RVL_SDK/src/fa/pdm_partition | pdm_part_is_master_boot_sector | 84/86 (0x158 vs 0x150) | scheduling + register pressure (extra saved r29 -> frame 0x40) | n.a. | byte loads of `read_partition_u32` scheduled differently, so one more live value; perm8/perm8d already tried 4950 permutations. irosweep --all: no hit |
## mwdbg on the three blocked units
`mwdbg.py` fails before reaching the function for iplESMisc, tiZiString and www_wiisetting (also with the stock tool):
1. Stock retrowin32: `WRITE_UNMAPPED @47e090` / `READ_UNMAPPED @46da46` with esp near 0xf18. The emulated compiler overflows its 1 MB stack (the PE's SizeOfStackReserve is 0x100000).
2. A private copy (`/tmp/ot/rw32`) with the stack raised to 32 MB and memory to 1 GB (`win32/src/pe/loader.rs` stack_size max(32<<20); `machine_unicorn.rs` MemImpl::new(1024<<20)) gets further. The compiler then calls its `UCBReportMessage` callback, which goes through `ws2_32!send` (ordinal 19, the call at 0x42c8b1), and retrowin32 has no ws2_32 shim.
3. The message is not the iplTree.h "return value expected" warning. Adding `-w off`, or an include override that fixes the warning, compiles silently under wibo but still hits `send` under the emulator.
The shared `_mwdbg` tool was not modified. To unblock these units, the next step is either a ws2_32 `send` shim that writes to stderr (to read the message) or a fix for whatever emulator difference triggers it.
nup and lyt_window traced fine; regsim reproduced 162/162 and 197/197.
`tools/decomp-assist/opus-ties.vmap.py <capdir> <unit> <symbol>` maps each traced virtual register to our physical register and the target's, by aligning backend-04 with after-color PCode and the two objects. That gives the `--want` list.

View File

@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""vmap.py <capdir> <unit> <symbol> [--project DIR]: map each GPR virtual to (our phys, target phys)."""
import json, re, sys, collections
sys.path.insert(0, '/home/cole/projects/tests')
from capstone import Cs, CS_ARCH_PPC, CS_MODE_32, CS_MODE_BIG_ENDIAN
from elftools.elf.elffile import ELFFile
cap, unit, sym = sys.argv[1:4]
proj = '/mnt/drive2/projects/wii-ipl-workers/data-d4'
if '--project' in sys.argv: proj = sys.argv[sys.argv.index('--project') + 1]
def fn_insns(path):
with open(path, 'rb') as f:
e = ELFFile(f)
st = e.get_section_by_name('.symtab')
s = [x for x in st.iter_symbols() if x.name == sym][0]
sec = e.get_section(s['st_shndx'])
data = sec.data()[s['st_value']:s['st_value'] + s['st_size']]
md = Cs(CS_ARCH_PPC, CS_MODE_32 + CS_MODE_BIG_ENDIAN)
out = []
for i in range(0, len(data), 4):
l = list(md.disasm(data[i:i+4], i))
out.append((l[0].mnemonic, re.findall(r'\br(\d+)\b', l[0].op_str)) if l else ('?', []))
return out
ours = fn_insns(f'{proj}/build/43U/src/{unit}.o')
targ = fn_insns(f'{proj}/build/43U/obj/{unit}.o')
assert len(ours) == len(targ), (len(ours), len(targ))
def gprs(ins):
return [o['reg'] for o in ins['operands'] if o.get('kind') == 0 and o.get('reg_class') == 4]
bc = json.load(open(f'{cap}/regalloc-gpr-pass-1-before-color.json'))
ac = json.load(open(f'{cap}/regalloc-gpr-pass-1-after-color.json'))
# use last successful pass if present
import glob
passes = sorted(glob.glob(f'{cap}/regalloc-gpr-pass-*-before-color.json'))
bc = json.load(open(passes[-1])); ac = json.load(open(passes[-1].replace('before', 'after')))
b4 = json.load(open(f'{cap}/backend-04-after-scheduling.json'))
names = {}
for line in open(passes[-1].replace('before-color.json', 'all.txt')):
m = re.match(r'r(\d+) -> r(\d+) (\S*)', line)
if m: names[int(m.group(1))] = m.group(3)
# per block: list of (key, virtual regs) from after-color/before-color
blk = {}
for B, A in zip(bc, ac):
lst = []
for ib, ia in zip(B['instructions'], A['instructions']):
lst.append([ia['mnemonic'], gprs(ia), gprs(ib), False])
blk[A['index']] = lst
seq = [] # final instruction order: list of virtual-reg lists (or None)
for B in b4:
pool = blk.get(B['index'], [])
for ins in B['instructions']:
key = (ins['mnemonic'], gprs(ins))
hit = None
for c in pool:
if not c[3] and c[0] == key[0] and c[1] == key[1]:
hit = c; break
if hit:
hit[3] = True; seq.append((ins['mnemonic'], hit[2], key[1]))
else:
seq.append((ins['mnemonic'], None, key[1]))
# align seq with ours by mnemonic order
res = collections.defaultdict(lambda: collections.Counter())
ourp = {}
j = 0
mis = 0
for mn, virt, phys in seq:
if j >= len(ours): break
# skip pcode pseudo instructions that don't emit
if virt is None and mn.lower() not in [o[0].rstrip('.') for o in ours[j:j+1]]:
pass
o = ours[j]; t = targ[j]; j += 1
if virt is None: continue
# register operands only compare if counts match
if [int(x) for x in o[1]] != phys[:len(o[1])] and [int(x) for x in o[1]] != phys:
mis += 1; continue
for k, v in enumerate(virt[:len(o[1])]):
if v >= 32 and k < len(t[1]):
res[v][int(t[1][k])] += 1
ourp[v] = int(o[1][k])
print(f'# aligned {len(seq)} pcode vs {len(ours)} insns, operand mismatches {mis}')
for v in sorted(res):
tgt = res[v].most_common()
flag = '' if len(tgt) == 1 and tgt[0][0] == ourp[v] else ' *'
print(f'r{v} {names.get(v, "?")} ours=r{ourp[v]} target={",".join(f"r{r}x{c}" for r, c in tgt)}{flag}')