Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,11 +342,31 @@ python platform/pc/builder/make_release.py --version 0.1.0 --devkitpro <devkitPr

`make_release.py` needs the host build (`psp_recomp.exe`) and the New 3DS build in `build/3ds/` (runtime objects, CWCheat patch list); it packages the build of the platform it runs on: `out/P3P3DS-Builder-<version>/` and a `.zip` on Windows, `out/P3P3DS-Builder-<version>-linux/` and a `.tar.gz` on Linux. `P3P3DS-Builder.exe --cli --iso <iso> [--devkitpro <dir>] [--jobs <n>]` 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 <path>` 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<version>` 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.

Expand Down
8 changes: 8 additions & 0 deletions docs/CURRENT_STATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

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 <compiler>` 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/ -- <Zig sources>` 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)

- `core/src/ge/xxhash.cpp` (XXH32/XXH64 from the specification) and `core/src/ge/texture_replacement.cpp`: the texture key PPSSPP packs use, reproduced from PPSSPP's behaviour (`references/ppsspp/GPU/Common/TextureCacheCommon.cpp`, `TextureReplacer.cpp`; behavioural reference only). cachekey = (address << 32 | TEXSIZE & 0xF0F) ^ CLUT hash; CLUT hash = XXH32 of min(last load + start index bytes, largest load) palette bytes, seed 0xC0108888, xored with the CLUTFORMAT command word including its 0xC5 byte; data hash = low 32 bits of XXH64, seed 0xBACD7814, row-wise when the buffer is wider, maxSeenV rows for 512-tall textures; lookup order with zeroed-part fallbacks. PC runner: `--texture-keys <file>` (keys from `p3p-texpack keys`) and `--texture-keys-report <csv>` wrap the renderer and report matches; nothing is replaced yet.
Expand Down
9 changes: 9 additions & 0 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ 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 <compiler>` 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.

## 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`).
Expand Down
26 changes: 26 additions & 0 deletions tools/bindiff/build.zig
Original file line number Diff line number Diff line change
@@ -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);
}
87 changes: 87 additions & 0 deletions tools/bindiff/check.py
Original file line number Diff line number Diff line change
@@ -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()
Loading