From fb7d42f7be7552b11257b0c20c75a28bffb8786b Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:38:05 -0500 Subject: [PATCH] Isolate the CHANSVm blob copy and padding block --- src/channelScript/CHANSVm.c | 32 +- .../CHANSVm.blob-copy-padded-attempts.md | 96 ++++ .../verify_vm_blob_copy_padded.py | 529 ++++++++++++++++++ 3 files changed, 644 insertions(+), 13 deletions(-) create mode 100644 tools/decomp-assist/CHANSVm.blob-copy-padded-attempts.md create mode 100644 tools/decomp-assist/verify_vm_blob_copy_padded.py diff --git a/src/channelScript/CHANSVm.c b/src/channelScript/CHANSVm.c index 003ff406..6fb98a1a 100644 --- a/src/channelScript/CHANSVm.c +++ b/src/channelScript/CHANSVm.c @@ -4975,6 +4975,24 @@ exit: return curPos; } +static inline void VmBlobCopyPadded(BlobHeader* parentBlob, const BlobHeader* srcBlob, s32 copySize) { + u32 srcOff; + u32 dataSize; + u8* dest; + + srcOff = srcBlob->offset; + dataSize = srcBlob->size - srcOff; + dest = parentBlob->pData + parentBlob->offset; + if (dataSize > copySize) { + dataSize = copySize; + } + memmove(dest, srcBlob->pData + srcOff, dataSize); + if (dataSize < copySize) { + memset(dest + dataSize, 0, copySize - dataSize); + } + parentBlob->offset += copySize; +} + static vmBoolInt VmBlobPackCommon(CHANSVm* VmInst, CHANSVmObjHdr* VmParentObj, CHANSVmObjHdr* VmReturnObj, vmU32 flag) { u32 packBuf[2]; BlobHeader* parentBlob; @@ -4990,8 +5008,6 @@ static vmBoolInt VmBlobPackCommon(CHANSVm* VmInst, CHANSVmObjHdr* VmParentObj, C CHANSVmObjHdr* obj; BlobHeader* srcBlob; s32 copySize; - u32 dataSize; - u32 srcOff; CHANSVmObjHdr* strObj; u8* srcData; u32 charCount; @@ -5213,17 +5229,7 @@ static vmBoolInt VmBlobPackCommon(CHANSVm* VmInst, CHANSVmObjHdr* VmParentObj, C goto error; } - srcOff = srcBlob->offset; - dataSize = srcBlob->size - srcOff; - dest = parentBlob->pData + parentBlob->offset; - if (dataSize > copySize) { - dataSize = copySize; - } - memmove(dest, srcBlob->pData + srcOff, dataSize); - if (dataSize < copySize) { - memset(dest + dataSize, 0, copySize - dataSize); - } - parentBlob->offset += copySize; + VmBlobCopyPadded(parentBlob, srcBlob, copySize); break; } case 5: { diff --git a/tools/decomp-assist/CHANSVm.blob-copy-padded-attempts.md b/tools/decomp-assist/CHANSVm.blob-copy-padded-attempts.md new file mode 100644 index 00000000..21e198e1 --- /dev/null +++ b/tools/decomp-assist/CHANSVm.blob-copy-padded-attempts.md @@ -0,0 +1,96 @@ +# VmBlobPackCommon copy/padding lifetime boundary + +43U only. Base `4508f455dbd44de4f512618e91692a9b6115d6e8`, tree +`28f9b61d3f0bed89a5086a4a813ee52a462b1504`. One fixed candidate; no permutations. + +The existing blob copy, bounded overlap-safe `memmove`, optional zero-fill and +offset commit now have a small inline helper. This is an independently +reconstructed candidate, not recovery of the historical helper in +`a5h.attempts.md:47–48`. The historical source hashes could not be recovered. + +## Actual measurements + +- Fresh baseline default build reproduced all 1,027 source objects and the + complete official report byte-for-byte +- One candidate compile: `VmBlobPackCommon` **97.949104 → 97.97156%**; + 2,672 bytes / 668 instructions unchanged; target instruction differences 244 → 242 +- Selected-source recompile through full default Ninja reproduced the candidate + source, object and full report; explicit `build/43U/ok` passes +- Only CHANSVm.o changes. All 232 sibling function bytes/scores and all other + 1,026 units unchanged; 224 exact functions preserved +- Unit fuzzy **99.45986 → 99.46098%**; exact code 39,908/53,564 and data + 6,904/6,904 unchanged; link classifications unchanged +- Pool 125/125 identical; literal audit 233 functions/40 arguments, zero errors, + candidates or skips; `git diff --check` passes +- DOL SHA1 `26116613f624061ba99c8d1a299aaa6efa85670d` + +Candidate source SHA256: +`d52e12d7c154c61dc49ffb0ef125764fb8714a7d6f71631e810fd3a57d88d536` + +Candidate object SHA256: +`a60ea527623793184e6e3edd0584e0e335c534248a5a9902dfe217cefdf39999` + +This remains a fuzzy improvement, not an exact match or a completed linked unit. + +## Semantics and metadata + +Source and destination may share a header or contained overlapping payloads. +The existing declaration-level volatile offset reads retain their order, +including the fresh destination-offset reload after copy/padding. Const adds +no restrict/disjointness promise. Parser, allocation, conversion, callback, +validation and error paths stay in place. Removed locals belonged only to the +copied block. No compiler option, layout or link setting changed. + +49 instructions differ from baseline, all register allocation. Raw ELF symbol +entries and relocation sections are identical. Every nontext section except +`.strtab` is identical; exactly 79 local `@number` object-name replacements +reconstruct that section. No helper body or extra function symbol is emitted. + +## Standalone verification + +`verify_vm_blob_copy_padded.py` needs preinstalled pyelftools and capstone. +It reads caller-supplied files and writes only a fresh output directory: + +```sh +python tools/decomp-assist/verify_vm_blob_copy_padded.py \ + --baseline-object /path/to/baseline-CHANSVm.o \ + --candidate-object build/43U/src/src/channelScript/CHANSVm.o \ + --original-object build/43U/obj/src/channelScript/CHANSVm.o \ + --dol /path/to/authorized-original-43U.dol \ + --symbols config/43U/symbols.txt \ + --output-dir /path/to/new-verification-output +``` + +The checker compares corresponding CFG edges with a must-equality relation, +intersecting predecessor states at branch and loop joins. Both baseline versus +candidate and baseline versus original pass 944 explicit/implicit uses. CR0, +XER.CA, CTR, LR, memory, stack addressing and SDA21 bases are accounted for. +Ordinary calls kill equality for undocumented caller-saved scratch registers; +only documented results and coupled memory effects are retained. + +The callee contracts follow the actual CHANSVm.c definitions: word/pointer +arguments occupy their listed r3..r9 registers and all results use r3 except +the u64 MakeU64 result in r3:r4. BlobHasSpace's signed64 argument is aligned in +r5:r6, skipping r4. There are no stack-passed arguments. VmBoolInt is BOOL/int, +not byte-sized vmBool (VmTypes.h and revolution/types.h). MSL string.h declares +the pointer results and size_t arguments of memcpy/memmove/memset. The original +save/restore helper tails are independently decoded from the DOL. + +The original DOL copy slice at +0x4BC..+0x518 is exactly 23 instructions. There +are 5,456 bounded cases, each compared across baseline/candidate/direct-DOL +instructions: 16,368 complete-memory and ordered-trace comparisons. Coverage +includes 136 same-header, 2,352 padding, 1,508 zero-copy, 395 forward-overlap and 429 +backward-overlap cases. Negative controls reject a missing volatile reload, +overlap-unsafe forward copying and undocumented scratch use after a call. + +These are bounded custom instruction/source checks with opaque fixed callee +contracts and modeled libc operations, not general formal verification or +complete VM/Wii runtime testing. Malformed header-overwriting payload pointers +are not asserted valid. Full project/report gates remain separate requirements. + +Harness-development failures were retained separately: the first metadata +assertion exposed local-name renumbering, and a DOL call loader restricted to +`.text` rejected memset at 0x81330334. Its exact `.init` symbol declaration fixed +the resolver; no name was guessed. An initial save-helper textual check also +rejected Capstone's decimal `-8` spelling; numeric operand checks replaced it. +These were verifier fixes, not additional source candidates or compiler trials. diff --git a/tools/decomp-assist/verify_vm_blob_copy_padded.py b/tools/decomp-assist/verify_vm_blob_copy_padded.py new file mode 100644 index 00000000..5fceb063 --- /dev/null +++ b/tools/decomp-assist/verify_vm_blob_copy_padded.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +"""Bounded 43U VmBlobPackCommon candidate verifier. + +Requires preinstalled pyelftools and capstone. Reads only the supplied objects, +DOL and symbols; writes a JSON report in a new output directory. This does not +compile, download, publish binaries or claim complete VM/Wii runtime coverage. +""" + +import argparse +from pathlib import Path +import hashlib +import json +import random +import re +import struct +from collections import deque + +from elftools.elf.elffile import ELFFile +from capstone import Cs, CS_ARCH_PPC, CS_MODE_32, CS_MODE_BIG_ENDIAN + + +def object_instructions(path, name): + """Decode one defined ELF function, resolving instruction relocations.""" + with path.open('rb') as stream: + elf = ELFFile(stream) + symbols = elf.get_section_by_name('.symtab') + candidates = [s for s in symbols.get_symbol_by_name(name) or [] + if isinstance(s['st_shndx'], int)] + assert len(candidates) == 1, (path, name, len(candidates)) + symbol = candidates[0] + section_index = symbol['st_shndx'] + offset, size = symbol['st_value'], symbol['st_size'] + assert size == 2672 + code = elf.get_section(section_index).data()[offset:offset + size] + relocations = {} + for section in elf.iter_sections(): + if section['sh_type'] != 'SHT_RELA' or section['sh_info'] != section_index: + continue + table = elf.get_section(section['sh_link']) + for relocation in section.iter_relocations(): + at = relocation['r_offset'] + if not offset <= at < offset + size: + continue + target = table.get_symbol(relocation['r_info_sym']) + label, addend = target.name, relocation['r_addend'] + if isinstance(target['st_shndx'], int) and target['st_info']['type'] in ('STT_OBJECT', 'STT_SECTION', 'STT_NOTYPE'): + label = elf.get_section(target['st_shndx']).name + addend += target['st_value'] + if not label and isinstance(target['st_shndx'], int): + label = elf.get_section(target['st_shndx']).name + instruction_offset = at // 4 * 4 + assert instruction_offset not in relocations + relocations[instruction_offset] = (relocation['r_info_type'], label, addend) + decoder = Cs(CS_ARCH_PPC, CS_MODE_32 | CS_MODE_BIG_ENDIAN) + result = [] + for instruction in decoder.disasm(code, offset): + operand = instruction.op_str + if instruction.mnemonic.startswith('b') and not instruction.mnemonic.endswith(('lr', 'ctr')): + operand = re.sub(r'0x[0-9a-f]+$', lambda m: hex(int(m.group(), 16) - offset), operand) + relocation = relocations.get(instruction.address) + if relocation: + kind, label, addend = relocation + target = f'{label}{addend:+d} [reloc {kind}]' + if instruction.mnemonic.startswith('b'): + operand = target + else: + operand = re.sub(r'(?64I', dol[:256]) + regions = list(zip(header[:7], header[18:25], header[36:43])) + list(zip(header[7:18], header[25:36], header[43:54])) + address = 0x81453670 + fileoff = next(fo + address - va for fo, va, size in regions if va <= address and address + 0xA70 <= va + size) + function = dol[fileoff:fileoff + 0xA70] + with paths[2].open('rb') as stream: + elf = ELFFile(stream) + symbol = elf.get_section_by_name('.symtab').get_symbol_by_name(name)[0] + section_index, value = symbol['st_shndx'], symbol['st_value'] + original_code = elf.get_section(section_index).data()[value:value + 0xA70] + relocated_words = set() + for section in elf.iter_sections(): + if section['sh_type'] == 'SHT_RELA' and section['sh_info'] == section_index: + for relocation in section.iter_relocations(): + if value <= relocation['r_offset'] < value + 0xA70: + relocated_words.add((relocation['r_offset'] - value) // 4) + assert len(relocated_words) == 65 + assert all(function[i * 4:i * 4 + 4] == original_code[i * 4:i * 4 + 4] + for i in range(668) if i not in relocated_words) + symbols = dict((int(addr, 16), n) for n, addr in re.findall(r'^(\w+) = \.(?:text|init):0x([0-9A-Fa-f]+);', args.symbols.read_text(), re.M)) + md = Cs(CS_ARCH_PPC, CS_MODE_32 | CS_MODE_BIG_ENDIAN) + start, stop = 0x4BC, 0x518 + dol_ins = [None] * 668 + for i in md.disasm(function[start:stop], address + start): + operand = i.op_str + if i.mnemonic == 'bl': + target = int(operand, 16) + operand = symbols[target] + '+0 [reloc 10]' + elif i.mnemonic.startswith('b') and i.mnemonic != 'blr': + operand = re.sub(r'0x[0-9a-f]+$', lambda m: hex(int(m.group(), 16) - address), operand) + dol_ins[(i.address - address) // 4] = (i.mnemonic, operand) + assert dol_ins[start // 4:stop // 4] == ins[2][start // 4:stop // 4] + helper_tails = {} + for helper_name in ['_savegpr_17', '_restgpr_17']: + helper_address = next(addr for addr, label in symbols.items() if label == helper_name) + offset = next(fo + helper_address - va for fo, va, size in regions if va <= helper_address < va + size) + code = list(md.disasm(dol[offset:offset + 64], helper_address)) + assert len(code) == 16 and code[-1].mnemonic == 'blr' + for j, instruction in enumerate(code[:-1]): + assert instruction.mnemonic == ('stw' if helper_name.startswith('_save') else 'lwz') + match = re.fullmatch(r'r(\d+), (-?(?:0x[0-9a-f]+|\d+))\(r11\)', instruction.op_str) + assert match and int(match[1]) == 17 + j and int(match[2], 0) == -(15 - j) * 4 + helper_tails[helper_name] = {'address': hex(helper_address), 'size': 64, 'operations': 15, 'first_register': 17, 'last_register': 31, 'base': 'r11', 'return': 'blr'} + + def getword(memory, address): + return struct.unpack_from('>I', memory, address)[0] + + def putword(memory, address, value): + struct.pack_into('>I', memory, address, value & 0xFFFFFFFF) + + def execute(a, memory, dst, src, count, register_map, faulty_forward_copy=False): + memory = bytearray(memory) + r = [0] * 32 + for reg, val in zip(register_map, [dst, src, count]): + r[reg] = val + pc = start + comparison = 0 + trace = [] + iterations = 0 + while pc < stop: + iterations += 1 + assert iterations <= 32 + m, o = a[pc // 4] + args = o.split(', ') + reg = lambda t: int(t[1:]) + nextpc = pc + 4 + if m in ('lwz', 'stw'): + match = re.fullmatch(r'(-?(?:0x[0-9a-f]+|\d+))\(r(\d+)\)', args[1]) + address = (r[int(match[2])] + int(match[1], 0)) & 0xFFFFFFFF + if m == 'lwz': + value = getword(memory, address) + r[reg(args[0])] = value + trace.append(('read32', address, value)) + else: + value = r[reg(args[0])] + putword(memory, address, value) + trace.append(('write32', address, value)) + elif m in ('add', 'subf'): + left, right = r[reg(args[1])], r[reg(args[2])] + r[reg(args[0])] = (left + right if m == 'add' else right - left) & 0xFFFFFFFF + elif m == 'mr': + r[reg(args[0])] = r[reg(args[1])] + elif m == 'li': + r[reg(args[0])] = int(args[1], 0) & 0xFFFFFFFF + elif m == 'cmplw': + comparison = (r[reg(args[0])] > r[reg(args[1])]) - (r[reg(args[0])] < r[reg(args[1])]) + elif m in ('ble', 'bge'): + if comparison <= 0 if m == 'ble' else comparison >= 0: + nextpc = int(o, 16) + elif m == 'bl': + target = o.split('+')[0] + dest, argument, length = r[3], r[4], r[5] + assert 0 <= length <= 128 and dest + length <= len(memory) + trace.append((target, dest, argument, length)) + if target == 'memmove': + assert argument + length <= len(memory) + # Directional byte implementation, separate from the reference's snapshot. + indices = range(length - 1, -1, -1) if not faulty_forward_copy and argument < dest < argument + length else range(length) + for j in indices: + memory[dest + j] = memory[argument + j] + elif target == 'memset': + for j in range(length): + memory[dest + j] = argument & 255 + else: + raise AssertionError(target) + for j in [0] + list(range(3, 13)): + r[j] = 0xDEAD0000 + j + r[3] = dest + else: + raise AssertionError((pc, m, o)) + pc = nextpc + assert pc == stop + return bytes(memory), trace + + def reference(memory, dst, src, count): + memory = bytearray(memory) + trace = [] + def read(address): + value = getword(memory, address) + trace.append(('read32', address, value)) + return value + offset = read(src) + size = read(src + 4) + data = read(dst + 8) + extent = (size - offset) & 0xFFFFFFFF + output = data + read(dst) + available = min(extent, count) + input_start = read(src + 8) + offset + trace.append(('memmove', output, input_start, available)) + snapshot = bytes(memory[input_start:input_start + available]) + memory[output:output + available] = snapshot + if available < count: + trace.append(('memset', output + available, 0, count - available)) + memory[output + available:output + count] = bytes(count - available) + final = (read(dst) + count) & 0xFFFFFFFF + putword(memory, dst, final) + trace.append(('write32', dst, final)) + return bytes(memory), trace + + rng = random.Random(0x81453670) + cases = [] + for same in [False, True]: + for source_base in [0x400, 0x410, 0x440]: + for dest_base in [0x400, 0x408, 0x440]: + for source_offset in [0, 1, 15, 32]: + for dest_offset in [0, 1, 15, 32]: + for available in [0, 1, 15, 32, 64]: + for count in [0, 1, 15, 16, 32, 64]: + if same and (source_base != dest_base or source_offset != dest_offset or count > available): + continue + cases.append((same, source_base, dest_base, source_offset, dest_offset, available, count)) + for _ in range(1000): + cases.append((False, rng.randrange(0x400, 0x480), rng.randrange(0x400, 0x480), rng.randrange(33), rng.randrange(33), rng.randrange(65), rng.randrange(65))) + + counts = dict(total=0, same_header=0, padding=0, zero_copy=0, overlap_forward=0, overlap_backward=0, identical_range=0) + for case in cases: + same, sp, dp, so, do, available, count = case + memory = bytearray((i * 37 + 13) & 255 for i in range(0x800)) + src, dst = (0x100, 0x100) if same else (0x100, 0x180) + for hdr, offset, size, data in [(src, so, so + available, sp), (dst, do, so + available if same else do + 128, dp)]: + for field, value in [(0, offset), (4, size), (8, data)]: + putword(memory, hdr + field, value) + expected = reference(memory, dst, src, count) + for a, registers in [(ins[0], [31, 25, 18]), (ins[1], [31, 25, 18]), (dol_ins, [21, 29, 24])]: + actual = execute(a, memory, dst, src, count, registers) + assert actual == expected, case + trace = expected[1] + assert trace[-2][0:2] == ('read32', dst) and trace[-1][0:2] == ('write32', dst) + assert [e[0] for e in trace].count('memmove') == 1 + assert [e[0] for e in trace].count('memset') == int(available < count) + counts['total'] += 1 + counts['same_header'] += same + counts['padding'] += available < count + counts['zero_copy'] += min(available, count) == 0 + first, output, length = sp + so, dp + do, min(available, count) + counts['overlap_forward'] += first < output < first + length + counts['overlap_backward'] += output < first < output + length + counts['identical_range'] += first == output + + # Independent negative controls exercise the checks themselves, not additional + # C candidates or compiler experiments. + memory = bytearray((i * 37 + 13) & 255 for i in range(0x800)) + src, dst, count = 0x100, 0x180, 16 + for hdr, offset, size, data in [(src, 0, 32, 0x400), (dst, 1, 128, 0x400)]: + for field, value in [(0, offset), (4, size), (8, data)]: + putword(memory, hdr + field, value) + expected = reference(memory, dst, src, count) + assert execute(ins[1], memory, dst, src, count, [31, 25, 18], faulty_forward_copy=True) != expected + negative_controls['overlap_unsafe_forward_copy_rejected'] = True + omitted_read = list(ins[1]) + omitted_read[0x50C // 4] = ('mr', 'r0, r0') + omitted_result = execute(omitted_read, memory, dst, src, count, [31, 25, 18]) + assert omitted_result != expected + assert ('read32', dst, 1) not in omitted_result[1][-2:] + negative_controls['omitted_volatile_postcopy_read_rejected'] = True + + result = { + 'inputs_sha256': {label: hashlib.sha256(path.read_bytes()).hexdigest() for label, path in [('baseline_object', paths[0]), ('candidate_object', paths[1]), ('original_object', paths[2]), ('dol', args.dol), ('symbols', args.symbols)]}, + 'instructions': 668, 'candidate_target_diffs': sum(a != b for a, b in zip(ins[1], ins[2])), + 'baseline_candidate_instruction_diffs': sum(a != b for a, b in zip(ins[0], ins[1])), + 'gpr_normalized_full_function_equal': True, + 'full_function_reaching_definition_uses_checked': uses_checked, + 'must_equality_uses_baseline_vs_candidate_and_target': must_uses, + 'must_equality_scope': 'Corresponding CFG edges; predecessor intersection, explicit GPRs plus CR0, XER.CA, CTR, LR and complete memory; fixed opaque ABI/callee contracts. Memory operations and caller saves/restores included. This is a bounded custom checker, not a general verified PPC semantics implementation.', + 'cfg_calls_stack_offsets_and_operation_order_equal': True, + 'all_nontext_sections_except_strtab_byte_identical': True, + 'raw_symbol_entries_and_all_relocations_byte_identical': True, + 'strtab_differences_exhaustively_accounted_local_object_names': renamed_symbols, + 'all_232_sibling_functions_byte_identical': True, + 'original_dol_sha1': hashlib.sha1(dol).hexdigest(), + 'full_original_function_nonrelocated_words_checked': 603, + 'full_original_function_relocated_words_excluded': 65, + 'direct_original_dol_slice': [hex(start), hex(stop)], + 'copy_slice_instructions': (stop - start) // 4, + 'cases': counts, + 'case_comparisons': counts['total'] * 3, + 'original_save_restore_helpers_verified': helper_tails, + 'negative_controls': negative_controls, + 'call_clobbers': 'Kill GPR0, GPR3..12, CR0, XER.CA, CTR, LR at ordinary calls. Establish equality only for documented r3 returns, additionally r4 for CHANSVmMakeU64, and coupled memory effects. Exact save/restore helper tails have separate verified effects.', + 'limits': 'Bounded instruction interpretation with modeled libc calls; no complete VM/Wii runtime claim. Aliased payload views are contained in a shared valid memory allocation; constructors ordinarily own their payload. Header-overwriting malformed pointers are not asserted valid.', + } + (out / 'semantic-proof.json').write_text(json.dumps(result, indent=2) + '\n') + print(json.dumps(result, indent=2)) + + +if __name__ == '__main__': + main() -- 2.49.1