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
1 change: 1 addition & 0 deletions .agents/skills/p3p-modding-vfs/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Do **not** assume all mods are purely asset replacements. For every modification

- `p3p/p3p-patches/ULUS10512.ini` — Verified memory offsets for intro skip and mod loader string pointers.
- `p3p/Persona-3-Portable-Mod-Menu/` — Field script hooks (`.flow` / `.bf`) and menu initialization.
- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable (`build/cpk/bin/p3p-cpk --help`).
- `tools/CriFsV2Lib/` — Modern C# library for reading and parsing CriWare CPK archives.
- `tools/CriPakTools/` — C# CLI tool for unpacking and repacking CPK files with CRILAYLA compression.
- `tools/AtlusFileSystemLibrary/` — Comprehensive library for Atlus PAC, BIN, GIM, and TMX containers.
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/p3p-run-triage/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ Profile the shipped configuration, not the diagnostic one: configure `build/prod

## 6. Guest data hygiene

Copies of game files (movies, CPK extracts) go only to `.tmp/` and are deleted when no longer needed; never stage them. `experiments/cpk-check` lists/extracts CPK contents: `build/cpk-check/CpkCheck.exe <iso> --list PSP_GAME/USRDIR/umd0.cpk [substring] [outdir]` (build it offline with `DOTNET_CLI_HOME=$PWD/.cache/dotnet NUGET_PACKAGES=$PWD/.cache/nuget dotnet build -c Release -o ../../build/cpk-check`).
Copies of game files (movies, CPK extracts) go only to `.tmp/` and are deleted when no longer needed; never stage them. `tools/cpk` lists/extracts CPK contents and checks `--io-trace` reads: `python tools/cpk/check.py`, then `build/cpk/bin/p3p-cpk list <iso> /PSP_GAME/USRDIR/umd0.cpk [substring]`, `extract <iso> <cpk path> [substring] <out dir>`, `check-trace <iso> <io-trace.csv>` (`--help`). `experiments/cpk-check` (CriFsV2Lib) stays as the independent oracle for it: `build/cpk-check/CpkCheck.exe <iso> --list /PSP_GAME/USRDIR/umd0.cpk [substring] [outdir]`; from Git Bash set `MSYS_NO_PATHCONV=1` for paths on the image (build it offline with `DOTNET_CLI_HOME=$PWD/.cache/dotnet NUGET_PACKAGES=$PWD/.cache/nuget dotnet build -c Release -o ../../build/cpk-check`).
1 change: 1 addition & 0 deletions .claude/skills/p3p-modding-vfs/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Do **not** assume all mods are purely asset replacements. For every modification

- `p3p/p3p-patches/ULUS10512.ini` — Verified memory offsets for intro skip and mod loader string pointers.
- `p3p/Persona-3-Portable-Mod-Menu/` — Field script hooks (`.flow` / `.bf`) and menu initialization.
- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable (`build/cpk/bin/p3p-cpk --help`).
- `tools/CriFsV2Lib/` — Modern C# library for reading and parsing CriWare CPK archives.
- `tools/CriPakTools/` — C# CLI tool for unpacking and repacking CPK files with CRILAYLA compression.
- `tools/AtlusFileSystemLibrary/` — Comprehensive library for Atlus PAC, BIN, GIM, and TMX containers.
Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/p3p-run-triage/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ Profile the shipped configuration, not the diagnostic one: configure `build/prod

## 6. Guest data hygiene

Copies of game files (movies, CPK extracts) go only to `.tmp/` and are deleted when no longer needed; never stage them. `experiments/cpk-check` lists/extracts CPK contents: `build/cpk-check/CpkCheck.exe <iso> --list PSP_GAME/USRDIR/umd0.cpk [substring] [outdir]` (build it offline with `DOTNET_CLI_HOME=$PWD/.cache/dotnet NUGET_PACKAGES=$PWD/.cache/nuget dotnet build -c Release -o ../../build/cpk-check`).
Copies of game files (movies, CPK extracts) go only to `.tmp/` and are deleted when no longer needed; never stage them. `tools/cpk` lists/extracts CPK contents and checks `--io-trace` reads: `python tools/cpk/check.py`, then `build/cpk/bin/p3p-cpk list <iso> /PSP_GAME/USRDIR/umd0.cpk [substring]`, `extract <iso> <cpk path> [substring] <out dir>`, `check-trace <iso> <io-trace.csv>` (`--help`). `experiments/cpk-check` (CriFsV2Lib) stays as the independent oracle for it: `build/cpk-check/CpkCheck.exe <iso> --list /PSP_GAME/USRDIR/umd0.cpk [substring] [outdir]`; from Git Bash set `MSYS_NO_PATHCONV=1` for paths on the image (build it offline with `DOTNET_CLI_HOME=$PWD/.cache/dotnet NUGET_PACKAGES=$PWD/.cache/nuget dotnet build -c Release -o ../../build/cpk-check`).
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ tools/texpack/tests/fixtures/*.tex binary

# Zig fmt requires LF, including on Windows checkouts with core.autocrlf=true.
tools/bindiff/** text eol=lf
tools/cpk/** 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 @@ -31,6 +31,21 @@ jobs:
- name: Download verified Zig 0.17.1, build and test
run: python tools/bindiff/check.py --download

cpk:
name: CPK tool (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/cpk/check.py --download

linux:
name: Linux host build + tests
runs-on: ubuntu-24.04
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ profiles/p3p/input/local/
# P3P3DS's own tool directories.
!/tools/texpack/
!/tools/bindiff/
!/tools/cpk/

# Optional Zig host tools (including accidental default build locations).
.zig-cache/
Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ To build the PC runner and development tools:
- **C++20 Compiler** (measured with GCC 16.1 / MinGW-w64; other compilers are untested)
- **Python 3.10+** (code generation helpers, analysis and verification scripts)
- About **5 GB of RAM** and ~11 minutes on a 12-thread CPU for a clean build of the 237 generated units (`-j10`)
- Optional: .NET SDK for `experiments/cpk-check` (CPK inspection)
- Optional: **Zig 0.17.1** for `tools/bindiff` and `tools/cpk` (CPK inspection); .NET SDK only for `experiments/cpk-check`, the independent check of `tools/cpk`
- For the New 3DS build: [devkitPro](https://devkitpro.org/wiki/Getting_Started) with the `3ds-dev` packages (devkitARM, libctru, citro3d, picasso, 3dsxtool)

---
Expand Down Expand Up @@ -363,12 +363,31 @@ Exit codes: **0** byte-identical, **1** different, **2** usage/input/output erro

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.

### CPK tool (Zig 0.17.1)

`tools/cpk` is an optional host-only CLI that reads CPK archives straight from the ISO, or a loose `.cpk` such as a `mod.cpk`, without the .NET SDK. Build and test it from the repository root, with Python 3.12+ and **Zig 0.17.1**:

```bash
python tools/cpk/check.py # format check, Debug/safe unit tests, safe build, CLI tests
python tools/cpk/check.py --download # alternatively download the pinned official Zig, verify SHA-256, then check
build/cpk/bin/p3p-cpk list game.iso /PSP_GAME/USRDIR/umd0.cpk .bmd
build/cpk/bin/p3p-cpk list mods/mod.cpk
build/cpk/bin/p3p-cpk extract game.iso /PSP_GAME/USRDIR/umd0.cpk data/battle .tmp/extract
build/cpk/bin/p3p-cpk check-trace game.iso .tmp/io-trace.csv ms0:/PSP/P3P=.tmp/mods
```

- `list` prints directory and name, offset, stored and extracted size, and whether the file is CRILAYLA-compressed; the optional last argument is a case-insensitive substring of `dir/name`. An archive it can't read fully is an error, which makes it a quick check of a community `mod.cpk`.
- `extract` writes files under their CPK directories and decompresses them. All output paths are checked before the first write: `..`, absolute paths and names that are unsafe on Windows stop the extraction.
- `check-trace` verifies `p3p_pc_bootstrap --io-trace`: each read of a `.cpk` must be metadata or lie inside one file with the same FNV-1a 64.

Exit codes: **0** success, **1** `check-trace` found differences, **2** usage/input/output error. On Windows use `p3p-cpk.exe`. Keep game files and extracts under `.tmp/`.

### 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.
- The same workflow independently builds/tests BinDiff and the CPK tool 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 All @@ -395,7 +414,7 @@ The runner prints the stop reason and a summary; `--dump-events` writes a JSON t
| `--profile` | wall-time split between HLE, GE rendering and interpreter |
| `--frames-dir <dir>` `--frame-every <n>` | write displayed frames as BMP |
| `--wav <file>` | mix all game audio on the virtual clock into a 44.1 kHz stereo WAV |
| `--dump-events <json>` / `--io-trace <csv>` | execution trace / file reads (for `experiments/cpk-check`) |
| `--dump-events <json>` / `--io-trace <csv>` | execution trace / file reads (for `p3p-cpk check-trace`) |
| `--no-interpreter` | stop at PCs without AOT code instead of interpreting |
| `--verify-bootstrap` | fixed early-boot checkpoint used by CTest |

Expand Down
7 changes: 7 additions & 0 deletions docs/CURRENT_STATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

## CPK tool in Zig without .NET: `tools/cpk` (#65, 2026-11-06)

- `tools/cpk` (Zig 0.17.1, host only, one 1.0 MiB executable on Windows): `list`, `extract` and `check-trace` for a CPK on the ISO or a loose `.cpk`. `experiments/cpk-check` stays as the independent oracle. The numbers are in `docs/VERIFICATION.md`.
- [VERIFIED] Same results as CriFsV2Lib on ULUS-10512: all 6,198 listed files, all 6,198 extracted files byte for byte, and the `check-trace` verdict.
- [VERIFIED] Zig 0.17.1 panics when stdout is an asynchronous pipe that fills up (Git Bash/MSYS): `.PENDING => unreachable` in `std/Io/Threaded.zig`, positional and streaming writers alike. `tools/cpk` writes stdout through `WriteFile` on Windows. `tools/bindiff` had the same panic: #74.
- [UNVERIFIED] Community `mod.cpk` files and fan translation archives: only the game's two archives and synthetic fixtures were read so far (#23).

## No report.txt writes during play on the New 3DS (#71, #66, 2026-11-06)

- [VERIFIED] User reports on #66 (New 2DS XL, 0.3.2 build 2f91246, same Samsung EVO Plus 64 GB, attached report.txt and profile_seconds.csv): a run with freezes about 5 s apart had `sd max 2656 ms`, `io 36` (last 10 s), speed 64-74 %; a run without freezes had `sd max 78 ms`, `io 0`, speed 96-99 %.
Expand Down
14 changes: 14 additions & 0 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ Current execution and coverage measurements: [CURRENT_STATE.md](CURRENT_STATE.md

---

## CPK host CLI (#65, 2026-11-06)

Local ULUS-10512 ISO, Windows, Zig 0.17.1 `-Doptimize=safe`, oracle `experiments/cpk-check` (CriFsV2Lib):

- [VERIFIED] `list`: `umd0.cpk` (5,860 files) and `umd1.cpk` (338) match the oracle's listing line for line in name, offset, stored and extracted size.
- [VERIFIED] `extract`: all 6,198 files are byte-identical to the oracle's extraction, one oracle process per file and `cmp`; 5,018 of them are CRILAYLA-compressed.
- [VERIFIED] `check-trace` on an `--io-trace` from the 20M replay: both print `cpk reads=40 header/toc=4 file_matched=36 mismatched=0 unclassified=0 non_cpk=2493`, exit 0. With the hash of one file read changed, both print the same `MISMATCH` line and `mismatched=1`, exit 1.
- [VERIFIED] `list` flags a file as compressed from the TOC (`ExtractSize` differs from `FileSize`), the same 5,018 files as reading each file's `CRILAYLA` magic. `extract` still decides by the magic.
- [INFERRED] Reading the magic of every file made a first `list` take 33.2 s, against 0.13-0.14 s when repeated: 5,860 reads across the image on a cold disk. Only that one cold run was seen.
- [VERIFIED] Warm file cache, final build: `list umd0.cpk` 46-67 ms against the oracle's 89-142 ms (5 runs each); `check-trace` 47-56 ms against 217-865 ms (3 runs each). Both are mostly process startup. What matters here is that the tool needs no .NET SDK or NuGet restore.
- [VERIFIED] `python tools/cpk/check.py`: format check, Debug and safe unit tests, 18/18 CLI tests on synthetic fixtures: stored and CRILAYLA files, masked tables, an ISO, path traversal, truncated tables, 250 randomly damaged archives through `list` and `extract` (exit 0 or 2, never a panic).
- [VERIFIED] The build before the stdout fix exits with code 3 (panic) in `test_output_to_a_full_asynchronous_pipe`, so the test detects the bug. The pipes of Python's `subprocess` are synchronous and never showed it.
- [VERIFIED] CI job `CPK tool` passes on `ubuntu-24.04` and `windows-2022`, including the CLI tests. On Linux the asynchronous pipe test is skipped.

## 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.
Expand Down
26 changes: 26 additions & 0 deletions tools/cpk/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-cpk requires Zig 0.17.1");
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "p3p-cpk",
.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/cpk.zig"),
.target = target,
.optimize = optimize,
}),
});
b.step("test", "Test CPK tables, CRILAYLA and path sanitising").dependOn(&b.addRunArtifact(tests).step);
}
59 changes: 59 additions & 0 deletions tools/cpk/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Build/test the optional CPK tool; keep downloads and caches in the workspace."""
import argparse
import importlib.util
import os
from pathlib import Path
import subprocess
import sys

ROOT = Path(__file__).resolve().parents[2]
TOOL = ROOT / "tools/cpk"
VERSION = (TOOL / "zig-version").read_text().strip()


def download_zig():
# One pinned compiler for both Zig tools: bindiff's helper holds the archive hashes.
spec = importlib.util.spec_from_file_location("bindiff_check", ROOT / "tools/bindiff/check.py")
bindiff = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bindiff)
if bindiff.VERSION != VERSION:
raise RuntimeError(f"tools/bindiff pins Zig {bindiff.VERSION}, tools/cpk pins {VERSION}")
return bindiff.download_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/cpk",
"TEMP": ".tmp/cpk",
"TMP": ".tmp/cpk",
"TMPDIR": ".tmp/cpk",
}.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/cpk"), "-j4", "--summary", "all")
exe = ROOT / "build/cpk/bin" / ("p3p-cpk.exe" if os.name == "nt" else "p3p-cpk")
run(sys.executable, str(TOOL / "test_cli.py"), "--exe", str(exe))


if __name__ == "__main__":
main()
Loading