From 868f5402f812ac0d01e613fefa79ac1bb3e939ab Mon Sep 17 00:00:00 2001 From: endercodezz Date: Thu, 5 Nov 2026 20:27:14 +0200 Subject: [PATCH 1/2] feat(tools): add optional Zig BinDiff CLI for ELF32/PRX Compare positional byte ranges and ELF32 MIPS/PSP metadata through a standalone Zig 0.17.1 host tool with deterministic JSON and explicit errors. Add synthetic regressions and SHA-256-pinned Windows/Linux CI checks. Verified: 4 unit tests in Debug and safe, 14 CLI tests, safe Windows and Linux cross-builds, host Release build and CTest (18 pass, 6 fixture skips). Closes #59. --- .github/workflows/ci.yml | 15 ++ .gitignore | 5 + README.md | 20 ++ docs/CURRENT_STATE.md | 7 + docs/VERIFICATION.md | 8 + tools/bindiff/build.zig | 26 +++ tools/bindiff/check.py | 87 +++++++++ tools/bindiff/src/diff.zig | 365 +++++++++++++++++++++++++++++++++++++ tools/bindiff/src/main.zig | 147 +++++++++++++++ tools/bindiff/test_cli.py | 219 ++++++++++++++++++++++ tools/bindiff/zig-version | 1 + 11 files changed, 900 insertions(+) create mode 100644 tools/bindiff/build.zig create mode 100644 tools/bindiff/check.py create mode 100644 tools/bindiff/src/diff.zig create mode 100644 tools/bindiff/src/main.zig create mode 100644 tools/bindiff/test_cli.py create mode 100644 tools/bindiff/zig-version diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f94df500..d51483df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,21 @@ concurrency: cancel-in-progress: true jobs: + bindiff: + name: BinDiff (Zig 0.17.1, ${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, windows-2022] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: '3.13' + - name: Download verified Zig 0.17.1, build and test + run: python tools/bindiff/check.py --download + linux: name: Linux host build + tests runs-on: ubuntu-24.04 diff --git a/.gitignore b/.gitignore index a26a2bca..631377ee 100644 --- a/.gitignore +++ b/.gitignore @@ -116,3 +116,8 @@ profiles/p3p/input/local/ /tools/*/ # P3P3DS's own tool directories. !/tools/texpack/ +!/tools/bindiff/ + +# Optional Zig host tools (including accidental default build locations). +.zig-cache/ +zig-out/ diff --git a/README.md b/README.md index 58ad72cf..382e0696 100644 --- a/README.md +++ b/README.md @@ -342,11 +342,31 @@ python platform/pc/builder/make_release.py --version 0.1.0 --devkitpro /` and a `.zip` on Windows, `out/P3P3DS-Builder--linux/` and a `.tar.gz` on Linux. `P3P3DS-Builder.exe --cli --iso [--devkitpro ] [--jobs ]` runs the same build without the window. Sources: `platform/pc/builder/` (pipeline, EBOOT decryption, wizard, trivia). +### BinDiff developer tool (Zig 0.17.1) + +`tools/bindiff` is an optional host-only CLI, separate from the CMake/runtime and Builder builds. It compares arbitrary files positionally, or decrypted ELF32 little-endian MIPS/PSP PRX headers, segments and sections with `--elf`. It does not decrypt files, apply relocations or match functions; use the existing preparation and `psp_analyze` tools for those stages. + +From the repository root, with Python 3.12+ and **Zig 0.17.1**: + +```bash +python tools/bindiff/check.py # format check, Debug/safe unit tests, safe build, CLI tests +python tools/bindiff/check.py --download # alternatively download the pinned official Zig, verify SHA-256, then check +build/bindiff/bin/p3p-bindiff --json old.dat new.dat +build/bindiff/bin/p3p-bindiff --elf --json old.elf new.elf +``` + +On Windows use `p3p-bindiff.exe`. `--zig ` selects an existing compiler. The helper keeps compiler downloads and all caches under `.cache/`, temporary fixtures under `.tmp/`, and the executable under `build/bindiff/`; `--download` supports x86-64 Windows/Linux and does not modify PATH. CI uses the same helper on both systems; the compiler version is pinned in `tools/bindiff/zig-version` and enforced by `build.zig`. + +Exit codes: **0** byte-identical, **1** different, **2** usage/input/output error. `--help`, `--version` and `--` (for paths starting with `-`) are supported. Inputs are limited to less than 256 MiB each. Comparison is positional: an insertion can change all subsequent offsets. `changed_bytes` counts mismatches in the common prefix; `added_bytes`/`removed_bytes` count the extra tail. Ranges are half-open `[start,end)` and include missing tails. Only the first 256 ranges are emitted; `range_count` and totals remain complete and `ranges_truncated` signals the limit. + +JSON schema version 1 includes `mode`, input paths, byte equality, `bytes` totals/ranges, and an optional `elf` object with both headers and explicit header/segment/section changes. ELF entries are paired by table index. Added/removed entries have a null side; modified entries include both versions, with file offsets and ELF virtual addresses (no runtime load base added). `content_equal` compares file payloads and is null for missing entries or NOBITS. Section names are UTF-8 strings, or byte arrays when not valid UTF-8. Unsupported ELF class/endianness/machine, extended numbering, encrypted `~PSP`, PBP containers and malformed metadata are rejected with code 2; byte mode can still compare their raw bytes. + ### Continuous integration and releases (GitHub Actions) Without the game files (no `profiles/p3p/game/eboot.elf`) both CMake projects build everything that does not come from the game: the host runtime, tools, P3P3DS Builder and tests (the AOT code, the PC runner and the tests that run game code are left out), and the New 3DS runtime the Builder ships (no `.3dsx`). GitHub Actions uses this: - `.github/workflows/ci.yml`, on every push to `master` and every pull request: Linux (GCC 14) and Windows (MSYS2 UCRT64 GCC) host build + CTest, New 3DS runtime in the `devkitpro/devkitarm` container (which also regenerates the `tools/texpack` fixtures with its `tex3ds` and fails on any difference), and `tools/texpack` clippy + tests with the pinned Rust toolchain. +- The same workflow independently builds/tests BinDiff on Windows/Linux using SHA-256-verified Zig 0.17.1 archives and synthetic fixtures; it requires no game data. - `.github/workflows/automerge.yml`: a pull request opened by the maintainer (not a draft) is merged automatically, with a merge commit, once the three CI jobs pass; `master` requires them and takes changes only through pull requests. - `.github/workflows/release.yml`: pushing a tag `v` that matches `FileVersion` in `platform/pc/builder/builder.rc` builds the New 3DS runtime (debug info stripped), the Windows and Linux Builder packages with `make_release.py`, and publishes them as a GitHub release (an existing release of that tag gets the files replaced). Started by hand (Actions -> Release -> Run workflow, with a branch or commit) it only builds the packages as workflow artifacts, for a dry run. diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index b57548ba..e2255bae 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -2,6 +2,13 @@ This is the current source of truth, newest entries first. Evidence concerns ULUS-10512; each section says whether it was measured on the PC runner, in Azahar or on a real New 3DS. +## Optional BinDiff host CLI in Zig (#59, 2026-11-05) + +- [VERIFIED] `tools/bindiff/src/diff.zig::{compare,parseElf,compareElf}` and `src/main.zig::run` implement positional byte ranges/counts and ELF32 little-endian MIPS/PSP PRX header/segment/section comparison, text/JSON output and exit codes 0/1/2. Metadata entries are paired by table index, without relocation normalization or function matching. The runtime and CMake build do not depend on Zig. +- [VERIFIED] Zig is pinned to 0.17.1 (`tools/bindiff/zig-version`, `build.zig`). `python tools/bindiff/check.py --zig ` passed format checking, 4 Debug and 4 safe unit tests, safe compilation and 14 CLI regression tests on Windows. The CLI tests compare repeated JSON bytes and use a seeded positional oracle, malformed ELF/PRX, NOBITS, Unicode paths, limits and output errors. `.github/workflows/ci.yml::bindiff` runs the same checks on Windows/Linux with pinned official archive SHA-256 verification. +- [VERIFIED] Separate no-game Windows Release host build succeeded; `ctest --test-dir build/host -j6 --output-on-failure --no-tests=error` reported no failures: 18 tests passed, 6 skipped for missing game/reference fixtures. A local ULUS-10512 ELF self-comparison returned 0 with no changes (5,849,468 bytes, 3 segments, 54 sections). Evidence under `.tmp/bindiff-worktree/.tmp/`: `ctest-bindiff.log` and `bindiff-evidence/real-elf.json`. +- [VERIFIED] The exact Windows CI helper path, `python tools/bindiff/check.py --download`, verified the official archive, extracted it and passed all checks (`.tmp/bindiff-worktree/.tmp/bindiff-check.log`). A safe `x86_64-linux` cross-build also passed (`.tmp/bindiff-worktree/.tmp/bindiff-linux-build.log`). [UNVERIFIED] Linux execution until the new CI matrix runs. Next step: inspect both BinDiff CI jobs; no runtime frontier change is claimed. + ## Texture pack converter prototype in Rust (#56, 2026-11-05) - [VERIFIED] Existing P3P texture packs are PPSSPP packs (`textures.ini`, `hash = xxh64`, `ignoreAddress = true`, PNG; 3x/6x upscales in the 2021 Community Expansion), from the PPSSPP forum threads linked in #56. The 3DS limits (1024x1024, no palettes, 6 MiB cache budget, 1,501 KiB linear memory free in battle) mean packs must be converted on the PC; the runtime lookup is #23. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index f92fbdd2..32ee3c1f 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -6,6 +6,14 @@ Current execution and coverage measurements: [CURRENT_STATE.md](CURRENT_STATE.md --- +## BinDiff host CLI (#59, 2026-11-05) + +- [VERIFIED] `tools/bindiff/src/diff.zig::parseElf` checks ELF32/LE/MIPS, table and payload bounds, load sizes, address overflow and section-name termination. It accepts PSP PRX type `0xFFA0` as in `recomp/PSPRecomp/include/psprecomp/elf32.hpp::kElfTypePspPrx`. It deliberately reads metadata only; PSP loading, relocations, imports and Allegrex analysis remain in PSPRecomp. `compareElf` pairs entries by index and compares file payloads; NOBITS has no file payload. +- [VERIFIED] Windows, Zig 0.17.1: `python tools/bindiff/check.py --zig ` passes format checking, 4/4 Debug and 4/4 safe unit tests, safe build and 14/14 Python CLI tests. `tools/bindiff/test_cli.py::pair` compares actual repeated JSON output bytes; `test_randomized_positional_oracle` checks 40 seeded file pairs against an independent Python oracle. Other cases cover structural additions/removals, content and header changes, absent section tables, non-UTF8 names, malformed inputs, read/write errors and input/report limits. No speed comparison with other languages was measured. +- [VERIFIED] The official Windows 0.17.1 archive matches SHA-256 `b03f477a1943673e02aca0f570e8030dffd536ce1f45cbc4d3326ec31159562e` from `https://ziglang.org/download/index.json`. The installed compiler reports 0.17.1 in the installation process and a fresh PowerShell process using the persisted user PATH. Installation file lengths sum to 378,964,486 bytes (19,520 files), excluding archives/build caches. +- [VERIFIED] A separate no-game Windows Release CMake build and full CTest completed (18 passed, 6 skipped, no failures); local evidence: `.tmp/bindiff-worktree/.tmp/ctest-bindiff.log`. Local P3P ELF self-comparison emitted no structural/byte changes and code 0 (`.tmp/bindiff-worktree/.tmp/bindiff-evidence/real-elf.json`). No proprietary fixtures are committed. +- [VERIFIED] `python tools/bindiff/check.py --download` verified/extracted the official Windows archive and passed all checks (`.tmp/bindiff-worktree/.tmp/bindiff-check.log`). A safe `x86_64-linux` cross-build passed (`.tmp/bindiff-worktree/.tmp/bindiff-linux-build.log`). [UNVERIFIED] Linux execution before CI. `.github/workflows/ci.yml::bindiff` installs Python 3.13 and downloads official SHA-256-pinned Zig 0.17.1 for each Windows/Linux runner, then runs the shared checks without game data. + ## Host time audit and Rust candidates (#50, 2026-11-05) - [VERIFIED] Commit `f876554`, Windows 11, i5-12400F (12 threads), host GCC 16.1 (WinLibs), devkitARM GCC 16.1. Each process was measured on its own, single runs unless noted. Logs and the summary are under `.tmp/rust-audit/` (`REPORT.md`, `builder_run1.log`, `ninja_stats.txt`, `ctest.log`, `interp_diff*.txt`/`.log`, `run/`, `python_tools.txt`). diff --git a/tools/bindiff/build.zig b/tools/bindiff/build.zig new file mode 100644 index 00000000..b223d9cc --- /dev/null +++ b/tools/bindiff/build.zig @@ -0,0 +1,26 @@ +const std = @import("std"); +const builtin = @import("builtin"); + +pub fn build(b: *std.Build) void { + if (!std.mem.eql(u8, builtin.zig_version_string, "0.17.1")) + @panic("p3p-bindiff requires Zig 0.17.1"); + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const exe = b.addExecutable(.{ + .name = "p3p-bindiff", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }), + }); + b.installArtifact(exe); + const tests = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path("src/diff.zig"), + .target = target, + .optimize = optimize, + }), + }); + b.step("test", "Test byte comparison and ELF metadata parsing").dependOn(&b.addRunArtifact(tests).step); +} diff --git a/tools/bindiff/check.py b/tools/bindiff/check.py new file mode 100644 index 00000000..aa8ba55c --- /dev/null +++ b/tools/bindiff/check.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Build/test the optional host tool; keep downloads and caches in the workspace.""" +import argparse +import hashlib +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import tarfile +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parents[2] +TOOL = ROOT / "tools/bindiff" +VERSION = (TOOL / "zig-version").read_text().strip() +# SHA-256 from https://ziglang.org/download/index.json, release 0.17.1. +ARCHIVES = { + "Windows": ("windows", "zip", "b03f477a1943673e02aca0f570e8030dffd536ce1f45cbc4d3326ec31159562e"), + "Linux": ("linux", "tar.xz", "3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a"), +} + + +def download_zig(): + if platform.machine().lower() not in ("amd64", "x86_64"): + raise RuntimeError("automatic download supports x86-64 Windows/Linux only; use --zig") + system, ext, expected = ARCHIVES[platform.system()] + cache = ROOT / ".cache/zig" + cache.mkdir(parents=True, exist_ok=True) + name = f"zig-x86_64-{system}-{VERSION}" + archive = cache / f"{name}.{ext}" + url = f"https://ziglang.org/download/{VERSION}/{archive.name}" + if not archive.exists(): + partial = archive.with_suffix(archive.suffix + ".partial") + with urllib.request.urlopen(url, timeout=120) as src, partial.open("wb") as dst: + shutil.copyfileobj(src, dst) + partial.replace(archive) + with archive.open("rb") as src: + actual = hashlib.file_digest(src, "sha256").hexdigest() + if actual != expected: + raise RuntimeError(f"Zig archive SHA-256 mismatch: {actual}") + print(f"Verified {archive.name}: {actual}", flush=True) + if ext == "zip": + with zipfile.ZipFile(archive) as src: + src.extractall(cache) + else: + with tarfile.open(archive) as src: + src.extractall(cache, filter="data") + return cache / name / ("zig.exe" if system == "windows" else "zig") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--zig", default="zig", help="existing Zig 0.17.1 executable") + parser.add_argument("--download", action="store_true", help="download and verify the pinned official compiler") + args = parser.parse_args() + zig = str(download_zig()) if args.download else args.zig + env = os.environ.copy() + for key, relative in { + "ZIG_GLOBAL_CACHE_DIR": ".cache/zig-global", + "ZIG_LOCAL_CACHE_DIR": ".cache/bindiff", + "TEMP": ".tmp/bindiff", + "TMP": ".tmp/bindiff", + "TMPDIR": ".tmp/bindiff", + }.items(): + path = ROOT / relative + path.mkdir(parents=True, exist_ok=True) + env[key] = str(path) + + def run(*command): + print("+", *command, flush=True) + subprocess.run(command, cwd=TOOL, env=env, check=True) + + version = subprocess.check_output([zig, "version"], env=env, text=True).strip() + if version != VERSION: + raise RuntimeError(f"expected Zig {VERSION}, got {version}") + run(zig, "fmt", "--check", "build.zig", "src") + run(zig, "build", "test", "-j4", "--summary", "all") + run(zig, "build", "test", "-Doptimize=safe", "-j4", "--summary", "all") + run(zig, "build", "-Doptimize=safe", "--prefix", str(ROOT / "build/bindiff"), "-j4", "--summary", "all") + exe = ROOT / "build/bindiff/bin" / ("p3p-bindiff.exe" if os.name == "nt" else "p3p-bindiff") + run(sys.executable, str(TOOL / "test_cli.py"), "--exe", str(exe)) + + +if __name__ == "__main__": + main() diff --git a/tools/bindiff/src/diff.zig b/tools/bindiff/src/diff.zig new file mode 100644 index 00000000..fa1fce62 --- /dev/null +++ b/tools/bindiff/src/diff.zig @@ -0,0 +1,365 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const Range = struct { start: usize, end: usize }; +pub const ByteDiff = struct { + left_size: usize, + right_size: usize, + changed_bytes: usize = 0, + added_bytes: usize, + removed_bytes: usize, + range_count: usize = 0, + ranges: std.ArrayList(Range) = .empty, + ranges_truncated: bool = false, + + pub fn deinit(self: *ByteDiff, allocator: Allocator) void { + self.ranges.deinit(allocator); + } + + pub fn equal(self: ByteDiff) bool { + return self.changed_bytes == 0 and self.added_bytes == 0 and self.removed_bytes == 0; + } +}; + +// Positional comparison; ranges are half-open and include a missing tail. +// Keep output bounded without stopping the comparison or losing total counts. +pub fn compare(allocator: Allocator, left: []const u8, right: []const u8) !ByteDiff { + const common = @min(left.len, right.len); + const total = @max(left.len, right.len); + var result: ByteDiff = .{ + .left_size = left.len, + .right_size = right.len, + .added_bytes = right.len - common, + .removed_bytes = left.len - common, + }; + errdefer result.deinit(allocator); + var start: ?usize = null; + for (0..total) |i| { + const different = i >= common or left[i] != right[i]; + if (i < common and different) result.changed_bytes += 1; + if (different and start == null) start = i; + if (!different and start != null) { + try appendRange(allocator, &result, .{ .start = start.?, .end = i }); + start = null; + } + } + if (start) |s| try appendRange(allocator, &result, .{ .start = s, .end = total }); + return result; +} + +fn appendRange(allocator: Allocator, result: *ByteDiff, range: Range) !void { + result.range_count += 1; + if (result.ranges.items.len < 256) { + try result.ranges.append(allocator, range); + } else result.ranges_truncated = true; +} + +pub const Header = struct { + os_abi: u8, + abi_version: u8, + elf_type: u16, + machine: u16, + version: u32, + entry: u32, + program_offset: u32, + section_offset: u32, + flags: u32, + header_size: u16, + program_entry_size: u16, + program_count: u16, + section_entry_size: u16, + section_count: u16, + string_table_index: u16, +}; + +pub const Segment = struct { + kind: u32, + file_offset: u32, + virtual_address: u32, + physical_address: u32, + file_size: u32, + memory_size: u32, + flags: u32, + alignment: u32, +}; + +pub const Section = struct { + name: []const u8, + name_offset: u32, + kind: u32, + flags: u32, + virtual_address: u32, + file_offset: u32, + size: u32, + link: u32, + info: u32, + alignment: u32, + entry_size: u32, +}; + +pub const Elf = struct { + header: Header, + segments: []Segment, + sections: []Section, + bytes: []const u8, + + pub fn deinit(self: Elf, allocator: Allocator) void { + allocator.free(self.segments); + allocator.free(self.sections); + } +}; + +fn span(bytes: []const u8, offset: usize, size: usize) ![]const u8 { + if (offset > bytes.len or size > bytes.len - offset) return error.TruncatedElf; + return bytes[offset..][0..size]; +} + +fn read(comptime T: type, bytes: []const u8, offset: usize) T { + return std.mem.readInt(T, bytes[offset..][0..@sizeOf(T)], .little); +} + +// Only metadata and file bytes are read. Do not reproduce PSPRecomp's +// load/relocate/import/Allegrex pipeline here (elf32.hpp::Elf32Image). +pub fn parseElf(allocator: Allocator, bytes: []const u8) !Elf { + if (std.mem.startsWith(u8, bytes, "~PSP")) return error.EncryptedPsp; + if (std.mem.startsWith(u8, bytes, "\x00PBP")) return error.PbpContainer; + _ = try span(bytes, 0, 52); + if (!std.mem.eql(u8, bytes[0..4], "\x7fELF")) return error.NotElf; + if (bytes[4] != 1 or bytes[5] != 1) return error.UnsupportedElfEncoding; + if (bytes[6] != 1 or read(u32, bytes, 20) != 1) return error.InvalidElfVersion; + if (read(u16, bytes, 18) != 8) return error.UnsupportedMachine; + const h: Header = .{ + .os_abi = bytes[7], + .abi_version = bytes[8], + .elf_type = read(u16, bytes, 16), + .machine = read(u16, bytes, 18), + .version = read(u32, bytes, 20), + .entry = read(u32, bytes, 24), + .program_offset = read(u32, bytes, 28), + .section_offset = read(u32, bytes, 32), + .flags = read(u32, bytes, 36), + .header_size = read(u16, bytes, 40), + .program_entry_size = read(u16, bytes, 42), + .program_count = read(u16, bytes, 44), + .section_entry_size = read(u16, bytes, 46), + .section_count = read(u16, bytes, 48), + .string_table_index = read(u16, bytes, 50), + }; + if (h.header_size != 52) return error.InvalidHeaderSize; + if (h.program_count == 0xffff or h.string_table_index == 0xffff or + (h.section_count == 0 and h.section_offset != 0)) return error.ExtendedNumberingUnsupported; + if ((h.program_count > 0 and h.program_entry_size < 32) or + (h.section_count > 0 and h.section_entry_size < 40)) return error.InvalidTableEntrySize; + // Promote before multiplication, even when compiling for a 32-bit host. + _ = try tableSpan(bytes, h.program_offset, h.program_count, h.program_entry_size); + _ = try tableSpan(bytes, h.section_offset, h.section_count, h.section_entry_size); + const segments = try allocator.alloc(Segment, h.program_count); + errdefer allocator.free(segments); + for (segments, 0..) |*s, i| { + const p = try span(bytes, @as(usize, h.program_offset) + i * h.program_entry_size, 32); + s.* = .{ + .kind = read(u32, p, 0), + .file_offset = read(u32, p, 4), + .virtual_address = read(u32, p, 8), + .physical_address = read(u32, p, 12), + .file_size = read(u32, p, 16), + .memory_size = read(u32, p, 20), + .flags = read(u32, p, 24), + .alignment = read(u32, p, 28), + }; + if (s.file_size > 0) _ = try span(bytes, s.file_offset, s.file_size); + if (s.kind == 1 and s.memory_size < s.file_size) return error.InvalidLoadSize; + if (@as(u64, s.virtual_address) + s.memory_size > 0x100000000) return error.AddressOverflow; + } + const sections = try allocator.alloc(Section, h.section_count); + errdefer allocator.free(sections); + for (sections, 0..) |*s, i| { + const p = try span(bytes, @as(usize, h.section_offset) + i * h.section_entry_size, 40); + s.* = .{ + .name = "", + .name_offset = read(u32, p, 0), + .kind = read(u32, p, 4), + .flags = read(u32, p, 8), + .virtual_address = read(u32, p, 12), + .file_offset = read(u32, p, 16), + .size = read(u32, p, 20), + .link = read(u32, p, 24), + .info = read(u32, p, 28), + .alignment = read(u32, p, 32), + .entry_size = read(u32, p, 36), + }; + if (s.kind != 8 and s.size > 0) _ = try span(bytes, s.file_offset, s.size); + if (@as(u64, s.virtual_address) + s.size > 0x100000000) return error.AddressOverflow; + } + if (h.string_table_index != 0) { + if (h.string_table_index >= sections.len) return error.InvalidStringTable; + const strings = sections[h.string_table_index]; + if (strings.kind != 3) return error.InvalidStringTable; + const names = try span(bytes, strings.file_offset, strings.size); + for (sections) |*s| { + if (s.name_offset >= names.len) return error.InvalidSectionName; + const tail = names[s.name_offset..]; + const end = std.mem.indexOfScalar(u8, tail, 0) orelse return error.InvalidSectionName; + s.name = tail[0..end]; + } + } else { + for (sections) |s| if (s.name_offset != 0) return error.InvalidSectionName; + } + return .{ .header = h, .segments = segments, .sections = sections, .bytes = bytes }; +} + +fn tableSpan(bytes: []const u8, offset: u32, count: u16, stride: u16) ![]const u8 { + if (count == 0) return bytes[0..0]; + if (offset < 52) return error.InvalidTableOffset; + const size = @as(u64, count) * stride; + if (size > std.math.maxInt(usize)) return error.TruncatedElf; + return span(bytes, offset, @intCast(size)); +} + +pub const FieldChange = struct { field: []const u8, left: u64, right: u64 }; +pub fn EntryChange(comptime T: type) type { + return struct { + index: usize, + status: enum { added, removed, modified }, + left: ?T, + right: ?T, + content_equal: ?bool, + }; +} +pub const ElfDiff = struct { + header: std.ArrayList(FieldChange) = .empty, + segments: std.ArrayList(EntryChange(Segment)) = .empty, + sections: std.ArrayList(EntryChange(Section)) = .empty, + + pub fn deinit(self: *ElfDiff, allocator: Allocator) void { + self.header.deinit(allocator); + self.segments.deinit(allocator); + self.sections.deinit(allocator); + } +}; + +pub fn compareElf(allocator: Allocator, left: Elf, right: Elf) !ElfDiff { + var result: ElfDiff = .{}; + errdefer result.deinit(allocator); + inline for (@typeInfo(Header).@"struct".field_names) |name| { + const a = @field(left.header, name); + const b = @field(right.header, name); + if (a != b) try result.header.append(allocator, .{ .field = name, .left = a, .right = b }); + } + try compareEntries(Segment, allocator, left.segments, right.segments, left.bytes, right.bytes, &result.segments); + try compareEntries(Section, allocator, left.sections, right.sections, left.bytes, right.bytes, &result.sections); + return result; +} + +fn payload(comptime T: type, item: T, bytes: []const u8) ?[]const u8 { + if (T == Section) { + if (item.kind == 8) return null; // SHT_NOBITS has no file payload. + if (item.size == 0) return bytes[0..0]; + return bytes[item.file_offset..][0..item.size]; + } else { + if (item.file_size == 0) return bytes[0..0]; + return bytes[item.file_offset..][0..item.file_size]; + } +} + +fn compareEntries(comptime T: type, allocator: Allocator, left: []const T, right: []const T, a_bytes: []const u8, b_bytes: []const u8, out: *std.ArrayList(EntryChange(T))) !void { + for (0..@max(left.len, right.len)) |i| { + const a: ?T = if (i < left.len) left[i] else null; + const b: ?T = if (i < right.len) right[i] else null; + var content_equal: ?bool = null; + if (a != null and b != null) { + const ap = payload(T, a.?, a_bytes); + const bp = payload(T, b.?, b_bytes); + if (ap != null and bp != null) content_equal = std.mem.eql(u8, ap.?, bp.?); + var metadata_equal = true; + inline for (@typeInfo(T).@"struct".field_names) |name| { + if (comptime std.mem.eql(u8, name, "name")) { + if (!std.mem.eql(u8, @field(a.?, name), @field(b.?, name))) metadata_equal = false; + } else if (@field(a.?, name) != @field(b.?, name)) metadata_equal = false; + } + if (metadata_equal and content_equal != false) continue; + } + try out.append(allocator, .{ + .index = i, + .status = if (a == null) .added else if (b == null) .removed else .modified, + .left = a, + .right = b, + .content_equal = content_equal, + }); + } +} + +test "positional differences include missing tails and half-open ranges" { + const a = std.testing.allocator; + var d = try compare(a, "abcdef", "aXcYe!"); + defer d.deinit(a); + try std.testing.expectEqual(@as(usize, 3), d.changed_bytes); + try std.testing.expectEqualSlices(Range, &.{ .{ .start = 1, .end = 2 }, .{ .start = 3, .end = 4 }, .{ .start = 5, .end = 6 } }, d.ranges.items); + var tail = try compare(a, "abc", "aX"); + defer tail.deinit(a); + try std.testing.expectEqual(@as(usize, 1), tail.changed_bytes); + try std.testing.expectEqual(@as(usize, 1), tail.removed_bytes); + try std.testing.expectEqual(@as(usize, 3), tail.ranges.items[0].end); +} + +test "empty inputs and bounded report retain complete counts" { + const a = std.testing.allocator; + var empty = try compare(a, "", ""); + defer empty.deinit(a); + try std.testing.expect(empty.equal()); + const left: [600]u8 = @splat(0); + var right = left; + for (&right, 0..) |*v, i| v.* = @intCast(i % 2); + var d = try compare(a, &left, &right); + defer d.deinit(a); + try std.testing.expectEqual(@as(usize, 300), d.changed_bytes); + try std.testing.expectEqual(@as(usize, 300), d.range_count); + try std.testing.expectEqual(@as(usize, 256), d.ranges.items.len); + try std.testing.expect(d.ranges_truncated); +} + +fn minimalElf() [52]u8 { + var b: [52]u8 = @splat(0); + @memcpy(b[0..7], "\x7fELF\x01\x01\x01"); + std.mem.writeInt(u16, b[16..18], 0xffa0, .little); + std.mem.writeInt(u16, b[18..20], 8, .little); + std.mem.writeInt(u32, b[20..24], 1, .little); + std.mem.writeInt(u16, b[40..42], 52, .little); + return b; +} + +test "PRX without section tables and every truncated header" { + const a = std.testing.allocator; + const bytes = minimalElf(); + const elf = try parseElf(a, &bytes); + defer elf.deinit(a); + try std.testing.expectEqual(@as(u16, 0xffa0), elf.header.elf_type); + for (0..bytes.len) |n| try std.testing.expectError(error.TruncatedElf, parseElf(a, bytes[0..n])); + var change = bytes; + std.mem.writeInt(u32, change[24..28], 0x1234, .little); + const other = try parseElf(a, &change); + defer other.deinit(a); + var d = try compareElf(a, elf, other); + defer d.deinit(a); + try std.testing.expectEqual(@as(usize, 1), d.header.items.len); + try std.testing.expectEqualStrings("entry", d.header.items[0].field); +} + +test "table overflow, invalid stride, extended numbering and encoding" { + const a = std.testing.allocator; + var bytes = minimalElf(); + std.mem.writeInt(u32, bytes[28..32], 0xfffffff0, .little); + std.mem.writeInt(u16, bytes[42..44], 32, .little); + std.mem.writeInt(u16, bytes[44..46], 2, .little); + try std.testing.expectError(error.TruncatedElf, parseElf(a, &bytes)); + bytes[42] = 0; + try std.testing.expectError(error.InvalidTableEntrySize, parseElf(a, &bytes)); + bytes = minimalElf(); + std.mem.writeInt(u16, bytes[50..52], 0xffff, .little); + try std.testing.expectError(error.ExtendedNumberingUnsupported, parseElf(a, &bytes)); + bytes = minimalElf(); + bytes[5] = 2; + try std.testing.expectError(error.UnsupportedElfEncoding, parseElf(a, &bytes)); + try std.testing.expectError(error.EncryptedPsp, parseElf(a, "~PSP")); + try std.testing.expectError(error.PbpContainer, parseElf(a, "\x00PBP")); +} diff --git a/tools/bindiff/src/main.zig b/tools/bindiff/src/main.zig new file mode 100644 index 00000000..dcc04e96 --- /dev/null +++ b/tools/bindiff/src/main.zig @@ -0,0 +1,147 @@ +const std = @import("std"); +const diff = @import("diff.zig"); + +const usage = + \\Usage: p3p-bindiff [--elf] [--json] [--] LEFT RIGHT + \\ p3p-bindiff --help | --version + \\Compare files positionally, optionally comparing ELF32 little-endian MIPS/PSP + \\metadata. Inputs must be smaller than 256 MiB each. Ranges are [start,end). + \\Exit: 0 identical, 1 different, 2 usage/input/output error. + \\Only the first 256 byte ranges are listed; counts cover the entire inputs. + \\--elf requires decrypted ELF/PRX; no decryption or relocation is performed. + \\Sections and segments are matched by table index, not by function or name. + \\ +; + +pub fn main(init: std.process.Init) void { + const code = run(init) catch |err| { + var buffer: [1024]u8 = undefined; + var stderr: std.Io.File.Writer = .init(.stderr(), init.io, &buffer); + stderr.interface.print("p3p-bindiff: {s}\n", .{@errorName(err)}) catch {}; + stderr.interface.flush() catch {}; + std.process.exit(2); + }; + std.process.exit(code); +} + +fn run(init: std.process.Init) !u8 { + const allocator = init.gpa; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + var elf_mode = false; + var json = false; + var literal = false; + var paths: [2][]const u8 = undefined; + var count: usize = 0; + var buffer: [8192]u8 = undefined; + var stdout: std.Io.File.Writer = .init(.stdout(), init.io, &buffer); + const writer = &stdout.interface; + if (args.len == 2 and std.mem.eql(u8, args[1], "--help")) { + try writer.writeAll(usage); + try writer.flush(); + return 0; + } + if (args.len == 2 and std.mem.eql(u8, args[1], "--version")) { + try writer.writeAll("p3p-bindiff 0.1.0 (Zig 0.17.1)\n"); + try writer.flush(); + return 0; + } + for (args[1..]) |arg| { + if (!literal and std.mem.eql(u8, arg, "--")) { + literal = true; + } else if (!literal and std.mem.eql(u8, arg, "--elf")) { + if (elf_mode) return error.DuplicateOption; + elf_mode = true; + } else if (!literal and std.mem.eql(u8, arg, "--json")) { + if (json) return error.DuplicateOption; + json = true; + } else { + if (!literal and std.mem.startsWith(u8, arg, "-")) return error.UnknownOption; + if (count == paths.len) return error.ExpectedTwoPaths; + paths[count] = arg; + count += 1; + } + } + if (count != 2) return error.ExpectedTwoPaths; + const left = try std.Io.Dir.cwd().readFileAlloc(init.io, paths[0], allocator, .limited(256 * 1024 * 1024)); + defer allocator.free(left); + const right = try std.Io.Dir.cwd().readFileAlloc(init.io, paths[1], allocator, .limited(256 * 1024 * 1024)); + defer allocator.free(right); + // Validate both inputs completely before producing any success report. + var a: ?diff.Elf = null; + defer if (a) |elf| elf.deinit(allocator); + var b: ?diff.Elf = null; + defer if (b) |elf| elf.deinit(allocator); + var elf_diff: ?diff.ElfDiff = null; + defer if (elf_diff) |*d| d.deinit(allocator); + if (elf_mode) { + a = try diff.parseElf(allocator, left); + b = try diff.parseElf(allocator, right); + elf_diff = try diff.compareElf(allocator, a.?, b.?); + } + var bytes = try diff.compare(allocator, left, right); + defer bytes.deinit(allocator); + if (json) { + const ElfReport = struct { + left_header: diff.Header, + right_header: diff.Header, + header_changes: []const diff.FieldChange, + segment_changes: []const diff.EntryChange(diff.Segment), + section_changes: []const diff.EntryChange(diff.Section), + }; + try std.json.Stringify.value(.{ + .schema_version = @as(u32, 1), + .mode = @as([]const u8, if (elf_mode) "elf" else "bytes"), + .left = paths[0], + .right = paths[1], + .equal = bytes.equal(), + .bytes = .{ + .left_size = bytes.left_size, + .right_size = bytes.right_size, + .changed_bytes = bytes.changed_bytes, + .added_bytes = bytes.added_bytes, + .removed_bytes = bytes.removed_bytes, + .range_count = bytes.range_count, + .ranges = bytes.ranges.items, + .ranges_truncated = bytes.ranges_truncated, + }, + .elf = @as(?ElfReport, if (elf_diff) |d| .{ + .left_header = a.?.header, + .right_header = b.?.header, + .header_changes = d.header.items, + .segment_changes = d.segments.items, + .section_changes = d.sections.items, + } else null), + }, .{}, writer); + try writer.writeByte('\n'); + } else { + try writer.print("{s}\nleft: {d} bytes; right: {d} bytes\nchanged: {d}; added: {d}; removed: {d}\n", .{ + @as([]const u8, if (bytes.equal()) "identical" else "different"), + bytes.left_size, + bytes.right_size, + bytes.changed_bytes, + bytes.added_bytes, + bytes.removed_bytes, + }); + for (bytes.ranges.items) |range| try writer.print("range: [0x{x}, 0x{x})\n", .{ range.start, range.end }); + if (bytes.ranges_truncated) try writer.print("showing 256 of {d} ranges\n", .{bytes.range_count}); + if (elf_diff) |d| { + for (d.header.items) |field| try writer.print("ELF {s}: 0x{x} -> 0x{x}\n", .{ field.field, field.left, field.right }); + try textEntries(diff.Segment, writer, "segment", d.segments.items); + try textEntries(diff.Section, writer, "section", d.sections.items); + } + } + try writer.flush(); + return if (bytes.equal()) 0 else 1; +} + +fn textEntries(comptime T: type, writer: *std.Io.Writer, kind: []const u8, changes: []const diff.EntryChange(T)) !void { + for (changes) |change| { + try writer.print("ELF {s}[{d}] {s}\n left: ", .{ kind, change.index, @tagName(change.status) }); + try std.json.Stringify.value(change.left, .{}, writer); + try writer.writeAll("\n right: "); + try std.json.Stringify.value(change.right, .{}, writer); + try writer.writeAll("\n content_equal: "); + try std.json.Stringify.value(change.content_equal, .{}, writer); + try writer.writeByte('\n'); + } +} diff --git a/tools/bindiff/test_cli.py b/tools/bindiff/test_cli.py new file mode 100644 index 00000000..f5ee00a5 --- /dev/null +++ b/tools/bindiff/test_cli.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Synthetic, game-independent end-to-end fixtures for p3p-bindiff.""" +import argparse +import json +import os +from pathlib import Path +import random +import struct +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +EXE = None + + +def elf_fixture(prx=True): + """One PT_LOAD and NULL/.text/.shstrtab/.bss; .bss has no file payload.""" + b = bytearray(304) + b[:16] = b"\x7fELF\x01\x01\x01" + bytes(9) + struct.pack_into("= min(len(left), len(right)) or left[i] != right[i]} + actual = {i for r in d["ranges"] for i in range(r["start"], r["end"])} + self.assertEqual(actual, expected) + + def test_bounded_ranges(self): + d = self.pair(bytes(600), b"\x00\x01" * 300)["bytes"] + self.assertEqual(d["range_count"], 300) + self.assertEqual(d["changed_bytes"], 300) + self.assertEqual(len(d["ranges"]), 256) + self.assertTrue(d["ranges_truncated"]) + + def test_unicode_paths_and_option_terminator(self): + name = '-данные "quote".dat' if os.name != "nt" else "-данные space.dat" + (self.dir / name).write_bytes(b"same") + result = self.run_cli("--json", "--", name, name) + self.assertEqual(json.loads(result.stdout)["left"], name) + + def test_missing_file_and_directory(self): + self.run_cli("missing", "missing", code=2) + self.run_cli(".", ".", code=2) + + def test_input_limit(self): + # Sparse/extended file: exercise rejection without reading 256 MiB. + with (self.dir / "large").open("wb") as f: + f.truncate(256 * 1024 * 1024 + 1) + self.run_cli("large", "large", code=2) + + def test_elf_and_prx_equal(self): + for prx in (True, False): + b = elf_fixture(prx) + d = self.pair(b, b, elf=True) + self.assertEqual(d["elf"]["section_changes"], []) + self.assertEqual(d["elf"]["segment_changes"], []) + self.assertEqual(d["elf"]["header_changes"], []) + self.assertEqual(d["elf"]["left_header"]["elf_type"], 0xFFA0 if prx else 2) + + def test_content_and_metadata_changes(self): + a = elf_fixture() + b = bytearray(a) + b[97] = ord("!") + struct.pack_into(" Date: Thu, 5 Nov 2026 20:34:16 +0200 Subject: [PATCH 2/2] fix(tools): preserve LF for Zig formatter on Windows --- .gitattributes | 3 +++ docs/CURRENT_STATE.md | 1 + docs/VERIFICATION.md | 1 + 3 files changed, 5 insertions(+) diff --git a/.gitattributes b/.gitattributes index c9a394a8..6a274d14 100644 --- a/.gitattributes +++ b/.gitattributes @@ -14,3 +14,6 @@ references/azahar/dist/qt_themes/qdarkstyle_midnight_blue/LICENSE.rst conflict-m # p3p-texpack reference texture data (tex3ds output). tools/texpack/tests/fixtures/*.tex binary + +# Zig fmt requires LF, including on Windows checkouts with core.autocrlf=true. +tools/bindiff/** text eol=lf diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index faaa8bc5..f3d33e21 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -8,6 +8,7 @@ This is the current source of truth, newest entries first. Evidence concerns ULU - [VERIFIED] Zig is pinned to 0.17.1 (`tools/bindiff/zig-version`, `build.zig`). `python tools/bindiff/check.py --zig ` passed format checking, 4 Debug and 4 safe unit tests, safe compilation and 14 CLI regression tests on Windows. The CLI tests compare repeated JSON bytes and use a seeded positional oracle, malformed ELF/PRX, NOBITS, Unicode paths, limits and output errors. `.github/workflows/ci.yml::bindiff` runs the same checks on Windows/Linux with pinned official archive SHA-256 verification. - [VERIFIED] Separate no-game Windows Release host build succeeded; after merging `origin/master` (`0b4845e`), `ctest --test-dir build/host -j6 --output-on-failure --no-tests=error` reported no failures: 19 tests passed, 6 skipped for missing game/reference fixtures. All BinDiff checks passed again. A local ULUS-10512 ELF self-comparison returned 0 with no changes (5,849,468 bytes, 3 segments, 54 sections). Evidence under `.tmp/bindiff-worktree/.tmp/`: `ctest-bindiff-merged.log`, `bindiff-check-merged.log` and `bindiff-evidence/real-elf.json`. - [VERIFIED] The exact Windows CI helper path, `python tools/bindiff/check.py --download`, verified the official archive, extracted it and passed all checks (`.tmp/bindiff-worktree/.tmp/bindiff-check.log`). A safe `x86_64-linux` cross-build also passed (`.tmp/bindiff-worktree/.tmp/bindiff-linux-build.log`). [UNVERIFIED] Linux execution until the new CI matrix runs. Next step: inspect both BinDiff CI jobs; no runtime frontier change is claimed. +- [VERIFIED] The first Windows CI checkout failed `zig fmt --check` because of CRLF conversion. `.gitattributes` now pins LF for `tools/bindiff/**`; `git -c core.autocrlf=true checkout-index --prefix=.tmp/bindiff-eol/ -- ` followed by `zig fmt --check` passed, and all BinDiff tests passed again (`.tmp/bindiff-worktree/.tmp/bindiff-check-eol.log`). The formatter gate remains enabled. ## PPSSPP-compatible texture keys find a real P3P pack (#23, 2026-11-05) diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 19c41c08..1f47d76c 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -11,6 +11,7 @@ Current execution and coverage measurements: [CURRENT_STATE.md](CURRENT_STATE.md - [VERIFIED] `tools/bindiff/src/diff.zig::parseElf` checks ELF32/LE/MIPS, table and payload bounds, load sizes, address overflow and section-name termination. It accepts PSP PRX type `0xFFA0` as in `recomp/PSPRecomp/include/psprecomp/elf32.hpp::kElfTypePspPrx`. It deliberately reads metadata only; PSP loading, relocations, imports and Allegrex analysis remain in PSPRecomp. `compareElf` pairs entries by index and compares file payloads; NOBITS has no file payload. - [VERIFIED] Windows, Zig 0.17.1: `python tools/bindiff/check.py --zig ` passes format checking, 4/4 Debug and 4/4 safe unit tests, safe build and 14/14 Python CLI tests. `tools/bindiff/test_cli.py::pair` compares actual repeated JSON output bytes; `test_randomized_positional_oracle` checks 40 seeded file pairs against an independent Python oracle. Other cases cover structural additions/removals, content and header changes, absent section tables, non-UTF8 names, malformed inputs, read/write errors and input/report limits. No speed comparison with other languages was measured. - [VERIFIED] The official Windows 0.17.1 archive matches SHA-256 `b03f477a1943673e02aca0f570e8030dffd536ce1f45cbc4d3326ec31159562e` from `https://ziglang.org/download/index.json`. The installed compiler reports 0.17.1 in the installation process and a fresh PowerShell process using the persisted user PATH. Installation file lengths sum to 378,964,486 bytes (19,520 files), excluding archives/build caches. +- [VERIFIED] Windows `GetFileInformationByHandleEx(FileStandardInfo).AllocationSize` summed across those files reports 407,097,752 allocated bytes; local measurement: `.tmp/zig-install/disk-usage.json`. The first Windows CI formatter failure was CRLF checkout conversion; `.gitattributes` pins LF for the tool. A clean `core.autocrlf=true` index checkout passed the unchanged formatter gate, followed by all BinDiff checks (`.tmp/bindiff-worktree/.tmp/bindiff-check-eol.log`). - [VERIFIED] After merging `origin/master` (`0b4845e`), a separate no-game Windows Release CMake build and full CTest completed (19 passed, 6 skipped, no failures); local evidence: `.tmp/bindiff-worktree/.tmp/ctest-bindiff-merged.log`. BinDiff checks also passed again (`bindiff-check-merged.log` in the same directory). Local P3P ELF self-comparison emitted no structural/byte changes and code 0 (`.tmp/bindiff-worktree/.tmp/bindiff-evidence/real-elf.json`). No proprietary fixtures are committed. - [VERIFIED] `python tools/bindiff/check.py --download` verified/extracted the official Windows archive and passed all checks (`.tmp/bindiff-worktree/.tmp/bindiff-check.log`). A safe `x86_64-linux` cross-build passed (`.tmp/bindiff-worktree/.tmp/bindiff-linux-build.log`). [UNVERIFIED] Linux execution before CI. `.github/workflows/ci.yml::bindiff` installs Python 3.13 and downloads official SHA-256-pinned Zig 0.17.1 for each Windows/Linux runner, then runs the shared checks without game data.