diff --git a/.agents/skills/p3p-modding-vfs/SKILL.md b/.agents/skills/p3p-modding-vfs/SKILL.md index c680b6cc..5a19f914 100644 --- a/.agents/skills/p3p-modding-vfs/SKILL.md +++ b/.agents/skills/p3p-modding-vfs/SKILL.md @@ -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. diff --git a/.agents/skills/p3p-run-triage/SKILL.md b/.agents/skills/p3p-run-triage/SKILL.md index 2b76bd87..b406158c 100644 --- a/.agents/skills/p3p-run-triage/SKILL.md +++ b/.agents/skills/p3p-run-triage/SKILL.md @@ -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 --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 /PSP_GAME/USRDIR/umd0.cpk [substring]`, `extract [substring] `, `check-trace ` (`--help`). `experiments/cpk-check` (CriFsV2Lib) stays as the independent oracle for it: `build/cpk-check/CpkCheck.exe --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`). diff --git a/.claude/skills/p3p-modding-vfs/SKILL.md b/.claude/skills/p3p-modding-vfs/SKILL.md index c680b6cc..5a19f914 100644 --- a/.claude/skills/p3p-modding-vfs/SKILL.md +++ b/.claude/skills/p3p-modding-vfs/SKILL.md @@ -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. diff --git a/.claude/skills/p3p-run-triage/SKILL.md b/.claude/skills/p3p-run-triage/SKILL.md index 2b76bd87..b406158c 100644 --- a/.claude/skills/p3p-run-triage/SKILL.md +++ b/.claude/skills/p3p-run-triage/SKILL.md @@ -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 --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 /PSP_GAME/USRDIR/umd0.cpk [substring]`, `extract [substring] `, `check-trace ` (`--help`). `experiments/cpk-check` (CriFsV2Lib) stays as the independent oracle for it: `build/cpk-check/CpkCheck.exe --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`). diff --git a/.gitattributes b/.gitattributes index 6a274d14..8143a63a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d51483df..0963a6b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index 631377ee..13e7fca6 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/README.md b/README.md index 1ea64dad..db96afcf 100644 --- a/README.md +++ b/README.md @@ -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) --- @@ -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` 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. @@ -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 ` `--frame-every ` | write displayed frames as BMP | | `--wav ` | mix all game audio on the virtual clock into a 44.1 kHz stereo WAV | -| `--dump-events ` / `--io-trace ` | execution trace / file reads (for `experiments/cpk-check`) | +| `--dump-events ` / `--io-trace ` | 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 | diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index c6aa3d93..4ff33c49 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. +## 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 %. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 1f47d76c..3f5feae0 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -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. diff --git a/tools/cpk/build.zig b/tools/cpk/build.zig new file mode 100644 index 00000000..e2f5ade2 --- /dev/null +++ b/tools/cpk/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-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); +} diff --git a/tools/cpk/check.py b/tools/cpk/check.py new file mode 100644 index 00000000..1c379b01 --- /dev/null +++ b/tools/cpk/check.py @@ -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() diff --git a/tools/cpk/src/cpk.zig b/tools/cpk/src/cpk.zig new file mode 100644 index 00000000..470e10af --- /dev/null +++ b/tools/cpk/src/cpk.zig @@ -0,0 +1,479 @@ +//! CRI CPK archives: @UTF tables, the TOC file list and CRILAYLA decompression. +//! Inputs are community files: every offset is checked, and bad data is an +//! error, never a crash. experiments/cpk-check (CriFsV2Lib) is the independent +//! oracle this tool is compared with. +const std = @import("std"); + +pub const max_table_size: u64 = 256 * 1024 * 1024; +pub const max_file_size: u64 = 1024 * 1024 * 1024; + +/// Random-access bytes: a host file or a range of an ISO. +pub const Source = struct { + context: *const anyopaque, + readFn: *const fn (context: *const anyopaque, offset: u64, buffer: []u8) anyerror!void, + size: u64, + + pub fn read(self: Source, offset: u64, buffer: []u8) !void { + const end = std.math.add(u64, offset, buffer.len) catch return error.OutOfBounds; + if (end > self.size) return error.OutOfBounds; + return self.readFn(self.context, offset, buffer); + } + + pub fn alloc(self: Source, allocator: std.mem.Allocator, offset: u64, size: u64, limit: u64) ![]u8 { + if (size > limit or size > self.size) return error.TooLarge; + const buffer = try allocator.alloc(u8, @intCast(size)); + errdefer allocator.free(buffer); + try self.read(offset, buffer); + return buffer; + } +}; + +const ColumnKind = enum(u4) { + u8, + i8, + u16, + i16, + u32, + i32, + u64, + i64, + f32, + f64, + string, + raw, + guid, + _, + + fn size(kind: ColumnKind) !usize { + return switch (kind) { + .u8, .i8 => 1, + .u16, .i16 => 2, + .u32, .i32, .f32, .string => 4, + .u64, .i64, .f64, .raw => 8, + .guid => 16, + _ => error.BadColumnType, + }; + } +}; + +const Column = struct { + name: []const u8, + kind: ColumnKind, + default_offset: ?usize, + row_offset: ?usize, +}; + +const has_name = 0x10; +const has_default = 0x20; +const has_row_storage = 0x40; + +fn be(comptime T: type, data: []const u8, offset: usize) !T { + const end = std.math.add(usize, offset, @sizeOf(T)) catch return error.OutOfBounds; + if (end > data.len) return error.OutOfBounds; + return std.mem.readInt(T, data[offset..][0..@sizeOf(T)], .big); +} + +const Table = struct { + data: []const u8, + columns: []Column, + rows_offset: usize, + strings_offset: usize, + row_size: usize, + row_count: usize, + + fn parse(allocator: std.mem.Allocator, data: []const u8) !Table { + if (data.len < 0x20 or !std.mem.eql(u8, data[0..4], "@UTF")) return error.BadTable; + const rows_offset = @as(usize, try be(u16, data, 0x0A)) + 8; + const strings_offset = @as(usize, try be(u32, data, 0x0C)) + 8; + const column_count = try be(u16, data, 0x18); + const row_size = try be(u16, data, 0x1A); + const row_count = try be(u32, data, 0x1C); + const rows_bytes = std.math.mul(usize, row_size, row_count) catch return error.BadTable; + const rows_end = std.math.add(usize, rows_offset, rows_bytes) catch return error.BadTable; + if (rows_end > data.len or strings_offset > data.len) return error.BadTable; + + var table: Table = .{ + .data = data, + .columns = try allocator.alloc(Column, column_count), + .rows_offset = rows_offset, + .strings_offset = strings_offset, + .row_size = row_size, + .row_count = row_count, + }; + errdefer allocator.free(table.columns); + var cursor: usize = 0x20; + var row_offset: usize = 0; + for (table.columns) |*column_entry| { + if (cursor >= data.len) return error.BadTable; + const flags = data[cursor]; + cursor += 1; + const kind: ColumnKind = @fromBackingInt(@intCast(@as(u4, @truncate(flags)))); + const size = try kind.size(); + column_entry.* = .{ .name = "", .kind = kind, .default_offset = null, .row_offset = null }; + if (flags & has_name != 0) { + column_entry.name = try table.stringAt(try be(u32, data, cursor)); + cursor += 4; + } + if (flags & has_default != 0) { + if (cursor + size > data.len) return error.BadTable; + column_entry.default_offset = cursor; + cursor += size; + } + if (flags & has_row_storage != 0) { + column_entry.row_offset = row_offset; + row_offset += size; + } + } + if (row_offset > row_size) return error.BadTable; + return table; + } + + fn deinit(table: Table, allocator: std.mem.Allocator) void { + allocator.free(table.columns); + } + + fn stringAt(table: Table, offset: u32) ![]const u8 { + const start = std.math.add(usize, table.strings_offset, offset) catch return error.BadString; + if (start >= table.data.len) return error.BadString; + const length = std.mem.indexOfScalar(u8, table.data[start..], 0) orelse return error.BadString; + return table.data[start..][0..length]; + } + + fn column(table: Table, name: []const u8) ?*const Column { + for (table.columns) |*candidate| + if (std.mem.eql(u8, candidate.name, name)) return candidate; + return null; + } + + fn valueOffset(table: Table, col: *const Column, row: usize) ?usize { + if (col.row_offset) |offset| return table.rows_offset + row * table.row_size + offset; + return col.default_offset; + } + + /// Null when the column has neither a row value nor a default. + fn number(table: Table, col: *const Column, row: usize) !?u64 { + const offset = table.valueOffset(col, row) orelse return null; + return switch (col.kind) { + .u8, .i8 => try be(u8, table.data, offset), + .u16, .i16 => try be(u16, table.data, offset), + .u32, .i32 => try be(u32, table.data, offset), + .u64, .i64 => try be(u64, table.data, offset), + else => error.BadColumnType, + }; + } + + fn string(table: Table, col: *const Column, row: usize) ![]const u8 { + const offset = table.valueOffset(col, row) orelse return ""; + if (col.kind != .string) return error.BadColumnType; + return table.stringAt(try be(u32, table.data, offset)); + } +}; + +/// Tables may be masked with a byte stream that starts at 0x5F and multiplies by 0x15. +fn unmask(data: []u8) void { + var mask: u8 = 0x5F; + for (data) |*byte| { + byte.* ^= mask; + mask *%= 0x15; + } +} + +/// A chunk is `magic`, 4 bytes of flags, a 64-bit little-endian size, then the table. +fn readChunk(allocator: std.mem.Allocator, source: Source, offset: u64, magic: *const [4]u8) ![]u8 { + var header: [16]u8 = undefined; + try source.read(offset, &header); + if (!std.mem.eql(u8, header[0..4], magic)) return error.BadChunk; + const size = std.mem.readInt(u64, header[8..16], .little); + const data = try source.alloc(allocator, offset + header.len, size, max_table_size); + errdefer allocator.free(data); + if (data.len >= 4 and std.mem.eql(u8, data[0..4], "\x1F\x9E\xF3\xF5")) unmask(data); + return data; +} + +pub const File = struct { + dir: []const u8, + name: []const u8, + /// From the start of the CPK. + offset: u64, + /// Stored size; `extract_size` is the size the TOC gives after decompression. + size: u64, + extract_size: u64, + + /// From the TOC alone: `extract` decides by the data, but reading it for every + /// file of a listing means thousands of seeks across the image. + pub fn listedCompressed(file: File) bool { + return file.extract_size != 0 and file.extract_size != file.size; + } + + /// Case-insensitive substring of `dir/name`. + pub fn matches(file: File, allocator: std.mem.Allocator, filter: []const u8) !bool { + if (filter.len == 0) return true; + const key = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ file.dir, file.name }); + defer allocator.free(key); + return std.ascii.findIgnoreCase(key, filter) != null; + } +}; + +pub const Archive = struct { + toc: []u8, + files: []File, + + pub fn open(allocator: std.mem.Allocator, source: Source) !Archive { + const header_data = try readChunk(allocator, source, 0, "CPK "); + defer allocator.free(header_data); + const header = try Table.parse(allocator, header_data); + defer header.deinit(allocator); + if (header.row_count == 0) return error.BadTable; + const toc_column = header.column("TocOffset") orelse return error.NoToc; + const content_column = header.column("ContentOffset") orelse return error.MissingColumn; + const toc_offset = try header.number(toc_column, 0) orelse return error.NoToc; + var content_offset = try header.number(content_column, 0) orelse return error.MissingColumn; + if (toc_offset == 0) return error.NoToc; + // File offsets count from the TOC when it comes before the content. + content_offset = @min(content_offset, toc_offset); + + const toc_data = try readChunk(allocator, source, toc_offset, "TOC "); + errdefer allocator.free(toc_data); + const toc = try Table.parse(allocator, toc_data); + defer toc.deinit(allocator); + const name = toc.column("FileName") orelse return error.MissingColumn; + const size = toc.column("FileSize") orelse return error.MissingColumn; + const offset = toc.column("FileOffset") orelse return error.MissingColumn; + const dir = toc.column("DirName"); + const extract_column = toc.column("ExtractSize"); + + const files = try allocator.alloc(File, toc.row_count); + errdefer allocator.free(files); + for (files, 0..) |*file, row| { + file.* = .{ + .dir = if (dir) |col| try toc.string(col, row) else "", + .name = try toc.string(name, row), + .size = try toc.number(size, row) orelse return error.MissingColumn, + .offset = 0, + .extract_size = if (extract_column) |col| try toc.number(col, row) orelse 0 else 0, + }; + const relative = try toc.number(offset, row) orelse return error.MissingColumn; + file.offset = std.math.add(u64, relative, content_offset) catch return error.OutOfBounds; + const end = std.math.add(u64, file.offset, file.size) catch return error.OutOfBounds; + if (end > source.size and file.size != 0) return error.OutOfBounds; + } + return .{ .toc = toc_data, .files = files }; + } + + pub fn deinit(archive: Archive, allocator: std.mem.Allocator) void { + allocator.free(archive.files); + allocator.free(archive.toc); + } +}; + +const layla_prefix = 0x100; +const layla_header = 0x10; + +fn isCompressed(source: Source, file: File) !bool { + if (file.size < layla_header) return false; + var magic: [8]u8 = undefined; + try source.read(file.offset, &magic); + return std.mem.eql(u8, &magic, "CRILAYLA"); +} + +/// The file's content, decompressed when it is CRILAYLA. Caller frees. +pub fn extract(allocator: std.mem.Allocator, source: Source, file: File) ![]u8 { + if (file.size == 0) return allocator.alloc(u8, 0); + if (!try isCompressed(source, file)) return source.alloc(allocator, file.offset, file.size, max_file_size); + var header: [layla_header]u8 = undefined; + try source.read(file.offset, &header); + // Some archives store a size smaller than the compressed data: trust the data's header. + const stream_size = @as(u64, std.mem.readInt(u32, header[12..16], .little)) + layla_header + layla_prefix; + const raw = try source.alloc(allocator, file.offset, @max(file.size, stream_size), max_file_size); + defer allocator.free(raw); + return decompress(allocator, raw); +} + +const BitReader = struct { + data: []const u8, + position: usize, + bits_left: u4 = 0, + + /// The stream runs backwards from the prefix to the end of the header, MSB first. + fn take(self: *BitReader, count: u4) !u16 { + var result: u16 = 0; + var remaining = count; + while (remaining != 0) { + if (self.bits_left == 0) { + if (self.position == layla_header) return error.TruncatedStream; + self.position -= 1; + self.bits_left = 8; + } + const now = @min(remaining, self.bits_left); + const shift: u3 = @intCast(self.bits_left - now); + const mask = (@as(u16, 1) << now) - 1; + result = (result << now) | ((self.data[self.position] >> shift) & mask); + self.bits_left -= now; + remaining -= now; + } + return result; + } +}; + +/// LZSS written from the end of the output; the first 0x100 bytes are stored +/// uncompressed after the stream. +pub fn decompress(allocator: std.mem.Allocator, data: []const u8) ![]u8 { + if (data.len < layla_header or !std.mem.eql(u8, data[0..8], "CRILAYLA")) return error.BadStream; + const body_size: u64 = std.mem.readInt(u32, data[8..12], .little); + const prefix_offset = @as(u64, std.mem.readInt(u32, data[12..16], .little)) + layla_header; + if (prefix_offset + layla_prefix > data.len) return error.TruncatedStream; + if (body_size + layla_prefix > max_file_size) return error.TooLarge; + + const start: usize = @intCast(prefix_offset); + const out = try allocator.alloc(u8, @intCast(body_size + layla_prefix)); + errdefer allocator.free(out); + @memcpy(out[0..layla_prefix], data[start..][0..layla_prefix]); + + var bits: BitReader = .{ .data = data, .position = start }; + var write = out.len; // one past the next byte to write + while (write > layla_prefix) { + if (try bits.take(1) == 0) { + write -= 1; + out[write] = @intCast(try bits.take(8)); + continue; + } + const distance = @as(usize, try bits.take(13)) + 3; + var length: usize = 3; + const widths = [_]u4{ 2, 3, 5, 8 }; + var level: usize = 0; + while (true) { + const width = widths[level]; + const value = try bits.take(width); + length += value; + if (value != (@as(u16, 1) << width) - 1) break; + level = @min(level + 1, widths.len - 1); + } + if (length > write - layla_prefix) return error.CorruptStream; + for (0..length) |_| { + write -= 1; + const from = write + distance; + if (from >= out.len) return error.CorruptStream; + out[write] = out[from]; + } + } + return out; +} + +pub const fnv_offset: u64 = 0xCBF29CE484222325; + +pub fn fnv1a(hash: u64, data: []const u8) u64 { + var result = hash; + for (data) |byte| { + result ^= byte; + result *%= 0x100000001B3; + } + return result; +} + +fn isReservedName(component: []const u8) bool { + const stem = component[0 .. std.mem.indexOfScalar(u8, component, '.') orelse component.len]; + const names = [_][]const u8{ "con", "prn", "aux", "nul" }; + for (names) |name| if (std.ascii.eqlIgnoreCase(stem, name)) return true; + if (stem.len == 4 and std.ascii.isDigit(stem[3])) + return std.ascii.eqlIgnoreCase(stem[0..3], "com") or std.ascii.eqlIgnoreCase(stem[0..3], "lpt"); + return false; +} + +/// A relative path for `dir/name` that stays inside the output directory on +/// Windows and Linux, or error.UnsafePath. Bytes above ASCII (Shift-JIS names) +/// become %XX. Caller frees. +pub fn safePath(allocator: std.mem.Allocator, dir: []const u8, name: []const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(allocator); + const parts = [_][]const u8{ dir, name }; + for (parts, 0..) |part, index| { + if (index == 0 and part.len == 0) continue; + var components = std.mem.splitAny(u8, part, "/\\"); + while (components.next()) |component| { + if (component.len == 0 or isReservedName(component)) return error.UnsafePath; + const last = component[component.len - 1]; + if (last == '.' or last == ' ') return error.UnsafePath; // also `.` and `..` + if (out.items.len != 0) try out.append(allocator, '/'); + for (component) |byte| { + if (byte < 0x20 or byte == 0x7F or std.mem.indexOfScalar(u8, "<>:\"|?*", byte) != null) + return error.UnsafePath; + if (byte < 0x80) { + try out.append(allocator, byte); + } else { + var hex: [3]u8 = undefined; + try out.appendSlice(allocator, try std.fmt.bufPrint(&hex, "%{X:0>2}", .{byte})); + } + } + } + } + return out.toOwnedSlice(allocator); +} + +const testing = std.testing; + +test "literal and copy blocks decompress from the end" { + // Written backwards: literals 'c', 'b', 'a', then 3 bytes copied from + // distance 3, which gives "abcabc" after the prefix. + var stream: [layla_header + 8 + layla_prefix]u8 = @splat(0); + @memcpy(stream[0..8], "CRILAYLA"); + std.mem.writeInt(u32, stream[8..12], 6, .little); + std.mem.writeInt(u32, stream[12..16], 8, .little); + for (stream[layla_header + 8 ..], 0..) |*byte, index| byte.* = @truncate(index); + const bit_text = "0" ++ "01100011" ++ "0" ++ "01100010" ++ "0" ++ "01100001" ++ "1" ++ "0000000000000" ++ "00"; + var position: usize = layla_header + 8; + var used: u4 = 8; + for (bit_text) |bit| { + if (used == 8) { + position -= 1; + used = 0; + } + if (bit == '1') stream[position] |= @as(u8, 0x80) >> @intCast(used); + used += 1; + } + const out = try decompress(testing.allocator, &stream); + defer testing.allocator.free(out); + try testing.expectEqual(@as(usize, layla_prefix + 6), out.len); + try testing.expectEqualStrings("abcabc", out[layla_prefix..]); + try testing.expectEqual(@as(u8, 0xFF), out[0xFF]); +} + +test "a short stream is an error" { + var stream: [layla_header + 1 + layla_prefix]u8 = @splat(0xFF); + @memcpy(stream[0..8], "CRILAYLA"); + std.mem.writeInt(u32, stream[8..12], 6, .little); + std.mem.writeInt(u32, stream[12..16], 1, .little); + try testing.expectError(error.TruncatedStream, decompress(testing.allocator, &stream)); + std.mem.writeInt(u32, stream[12..16], 0x7FFF_FFFF, .little); + try testing.expectError(error.TruncatedStream, decompress(testing.allocator, &stream)); +} + +test "unsafe paths are refused" { + const bad = [_][2][]const u8{ + .{ "..", "a" }, .{ "a/../..", "b" }, .{ "", "../a" }, .{ "/etc", "a" }, + .{ "C:", "a" }, .{ "a\\..", "b" }, .{ "", "" }, .{ "a", "b/" }, + .{ "", "NUL.txt" }, .{ "", "com1" }, .{ "", "a." }, .{ "", "a b " }, + .{ "", "a\x01" }, .{ "", "a:b" }, .{ ".", "a" }, + }; + for (bad) |pair| try testing.expectError(error.UnsafePath, safePath(testing.allocator, pair[0], pair[1])); +} + +test "safe paths keep their directories" { + const path = try safePath(testing.allocator, "data\\battle", "a.bin"); + defer testing.allocator.free(path); + try testing.expectEqualStrings("data/battle/a.bin", path); + const encoded = try safePath(testing.allocator, "", "\x83\xA0.bin"); + defer testing.allocator.free(encoded); + try testing.expectEqualStrings("%83%A0.bin", encoded); +} + +test "table masking is its own inverse" { + var data = "@UTF....".*; + unmask(&data); + try testing.expectEqualSlices(u8, "\x1F\x9E\xF3\xF5", data[0..4]); + unmask(&data); + try testing.expectEqualStrings("@UTF....", &data); +} + +test "fnv1a 64" { + try testing.expectEqual(@as(u64, 0xAF63DC4C8601EC8C), fnv1a(fnv_offset, "a")); +} diff --git a/tools/cpk/src/iso.zig b/tools/cpk/src/iso.zig new file mode 100644 index 00000000..fd1fa3b3 --- /dev/null +++ b/tools/cpk/src/iso.zig @@ -0,0 +1,56 @@ +//! Minimal ISO9660 path lookup (case-insensitive) for a CPK on a UMD image. +const std = @import("std"); +const cpk = @import("cpk.zig"); + +pub const sector = 2048; +const max_directory_size = 64 * 1024 * 1024; +const directory_flag = 2; + +pub const Extent = struct { offset: u64, size: u64 }; + +fn entryExtent(record: []const u8) Extent { + return .{ + .offset = @as(u64, std.mem.readInt(u32, record[2..6], .little)) * sector, + .size = std.mem.readInt(u32, record[10..14], .little), + }; +} + +fn findEntry(directory: []const u8, name: []const u8) ?[]const u8 { + var offset: usize = 0; + while (offset < directory.len) { + const length = directory[offset]; + if (length == 0) { // records never cross a sector: padding up to the next one + offset = (offset / sector + 1) * sector; + continue; + } + if (length < 34 or offset + length > directory.len) return null; + const record = directory[offset..][0..length]; + const name_length = record[32]; + if (33 + @as(usize, name_length) > length) return null; + const full = record[33..][0..name_length]; + const stem = full[0 .. std.mem.indexOfScalar(u8, full, ';') orelse full.len]; + if (std.ascii.eqlIgnoreCase(stem, name)) return record; + offset += length; + } + return null; +} + +/// `path` like `/PSP_GAME/USRDIR/umd0.cpk`. +pub fn find(allocator: std.mem.Allocator, source: cpk.Source, path: []const u8) !Extent { + var descriptor: [sector]u8 = undefined; + try source.read(16 * sector, &descriptor); + if (descriptor[0] != 1 or !std.mem.eql(u8, descriptor[1..6], "CD001")) return error.NotIso; + var extent = entryExtent(descriptor[156..190]); + var is_directory = true; + var parts = std.mem.tokenizeScalar(u8, path, '/'); + while (parts.next()) |part| { + if (!is_directory) return error.NotFoundOnImage; + const directory = try source.alloc(allocator, extent.offset, extent.size, max_directory_size); + defer allocator.free(directory); + const record = findEntry(directory, part) orelse return error.NotFoundOnImage; + extent = entryExtent(record); + is_directory = record[25] & directory_flag != 0; + } + if (is_directory) return error.NotFoundOnImage; + return extent; +} diff --git a/tools/cpk/src/main.zig b/tools/cpk/src/main.zig new file mode 100644 index 00000000..a54e803b --- /dev/null +++ b/tools/cpk/src/main.zig @@ -0,0 +1,389 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const cpk = @import("cpk.zig"); +const iso = @import("iso.zig"); + +const usage = + \\Usage: p3p-cpk list [substring] + \\ p3p-cpk list [substring] + \\ p3p-cpk extract [substring] + \\ p3p-cpk extract [substring] + \\ p3p-cpk check-trace [prefix=hostdir ...] + \\ p3p-cpk --help | --version + \\list prints every file: dir/name, offset, stored and extracted size, compressed. + \\extract writes files under their CPK directories, decompressing CRILAYLA. + \\Every output path is checked before anything is written; `..`, absolute + \\paths and names unsafe on Windows are refused. Bytes above ASCII become %XX. + \\check-trace verifies the reads of p3p_pc_bootstrap --io-trace: each read of a + \\.cpk must be metadata or lie in one file with the same FNV-1a 64. prefix=hostdir + \\maps traced paths to host files, e.g. ms0:/PSP/P3P=.tmp/mods. + \\Exit: 0 success, 1 check-trace found differences, 2 usage/input/output error. + \\ +; + +/// A range of an open host file. +const View = struct { + io: std.Io, + file: std.Io.File, + base: u64, + + fn readAt(context: *const anyopaque, offset: u64, buffer: []u8) anyerror!void { + const view: *const View = @ptrCast(@alignCast(context)); + const count = try view.file.readPositionalAll(view.io, buffer, view.base + offset); + if (count != buffer.len) return error.EndOfFile; + } + + fn source(view: *const View, size: u64) cpk.Source { + return .{ .context = view, .readFn = readAt, .size = size }; + } +}; + +const Container = struct { + file: std.Io.File, + view: View, + size: u64, + is_cpk: bool, + + fn open(self: *Container, io: std.Io, path: []const u8) !void { + self.file = try std.Io.Dir.cwd().openFile(io, path, .{}); + errdefer self.file.close(io); + self.size = try self.file.length(io); + self.view = .{ .io = io, .file = self.file, .base = 0 }; + self.is_cpk = false; + var magic: [4]u8 = undefined; + if (self.size >= magic.len) { + try self.view.source(self.size).read(0, &magic); + self.is_cpk = std.mem.eql(u8, &magic, "CPK "); + } + } + + /// Narrows the view to a CPK on the image. + fn select(self: *Container, allocator: std.mem.Allocator, path: []const u8) !void { + const extent = try iso.find(allocator, self.view.source(self.size), path); + const end = std.math.add(u64, extent.offset, extent.size) catch return error.OutOfBounds; + if (end > self.size) return error.OutOfBounds; + self.view.base = extent.offset; + self.size = extent.size; + } +}; + +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 = .initStreaming(.stderr(), init.io, &buffer); + stderr.interface.print("p3p-cpk: {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 args = try init.minimal.args.toSlice(init.arena.allocator()); + var output: std.Io.Writer.Allocating = .init(init.gpa); + defer output.deinit(); + const code = dispatch(init, &output.writer, args) catch |err| { + writeStdout(init.io, output.written()) catch {}; + return err; + }; + try writeStdout(init.io, output.written()); + return code; +} + +extern "kernel32" fn WriteFile(file: std.os.windows.HANDLE, buffer: [*]const u8, size: u32, written: *u32, overlapped: ?*anyopaque) callconv(.winapi) c_int; +extern "kernel32" fn GetLastError() callconv(.winapi) u32; + +/// Pipes of Git Bash/MSYS are asynchronous, and the Zig 0.17.1 file writers panic +/// when such a pipe fills up (`.PENDING => unreachable`); WriteFile waits instead. +/// A reader that went away (`| head`) is not an error. +fn writeStdout(io: std.Io, bytes: []const u8) !void { + const stdout = std.Io.File.stdout(); + if (builtin.os.tag != .windows) { + stdout.writeStreamingAll(io, bytes) catch |err| switch (err) { + error.BrokenPipe => {}, + else => return err, + }; + return; + } + var rest = bytes; + while (rest.len != 0) { + var written: u32 = 0; + const count: u32 = @intCast(@min(rest.len, 1 << 20)); + if (WriteFile(stdout.handle, rest.ptr, count, &written, null) == 0) { + const broken_pipe = 109; + const no_data = 232; + const code = GetLastError(); + if (code == broken_pipe or code == no_data) return; + return error.WriteFailed; + } + rest = rest[written..]; + } +} + +fn dispatch(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8) !u8 { + if (args.len < 2) return error.ExpectedCommand; + const command = args[1]; + if (std.mem.eql(u8, command, "--help")) { + try writer.writeAll(usage); + return 0; + } + if (std.mem.eql(u8, command, "--version")) { + try writer.writeAll("p3p-cpk 0.1.0 (Zig 0.17.1)\n"); + return 0; + } + const rest = args[2..]; + if (std.mem.eql(u8, command, "list")) return archiveCommand(init, writer, rest, false); + if (std.mem.eql(u8, command, "extract")) return archiveCommand(init, writer, rest, true); + if (std.mem.eql(u8, command, "check-trace")) return checkTrace(init, writer, rest); + return error.UnknownCommand; +} + +fn archiveCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8, is_extract: bool) !u8 { + const allocator = init.gpa; + if (args.len == 0) return error.ExpectedPath; + var container: Container = undefined; + try container.open(init.io, args[0]); + defer container.file.close(init.io); + var operands = args[1..]; + if (!container.is_cpk) { + if (operands.len == 0) return error.ExpectedCpkPathOnImage; + try container.select(allocator, operands[0]); + operands = operands[1..]; + } + var out_dir: []const u8 = ""; + if (is_extract) { + if (operands.len == 0) return error.ExpectedOutputDirectory; + out_dir = operands[operands.len - 1]; + operands = operands[0 .. operands.len - 1]; + } + if (operands.len > 1) return error.TooManyArguments; + const filter = if (operands.len == 1) operands[0] else ""; + + const source = container.view.source(container.size); + const archive = try cpk.Archive.open(allocator, source); + defer archive.deinit(allocator); + if (is_extract) return extractFiles(init, writer, source, archive, filter, out_dir); + for (archive.files) |file| { + if (!try file.matches(allocator, filter)) continue; + try writer.print("{s}/{s} offset=0x{X} size=0x{X} extract=0x{X} compressed={d}\n", .{ + file.dir, + file.name, + file.offset, + file.size, + file.extract_size, + @intFromBool(file.listedCompressed()), + }); + } + return 0; +} + +fn extractFiles(init: std.process.Init, writer: *std.Io.Writer, source: cpk.Source, archive: cpk.Archive, filter: []const u8, out_dir: []const u8) !u8 { + const allocator = init.gpa; + const io = init.io; + var paths: std.ArrayList([]u8) = .empty; + defer { + for (paths.items) |path| allocator.free(path); + paths.deinit(allocator); + } + var selected: std.ArrayList(cpk.File) = .empty; + defer selected.deinit(allocator); + // Refuse a bad archive before the first byte is written. + for (archive.files) |file| { + if (!try file.matches(allocator, filter)) continue; + const path = try cpk.safePath(allocator, file.dir, file.name); + errdefer allocator.free(path); + try paths.append(allocator, path); + try selected.append(allocator, file); + } + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, out_dir); + var out = try cwd.openDir(io, out_dir, .{}); + defer out.close(io); + for (selected.items, paths.items) |file, path| { + const data = try cpk.extract(allocator, source, file); + defer allocator.free(data); + if (std.fs.path.dirnamePosix(path)) |parent| try out.createDirPath(io, parent); + try out.writeFile(io, .{ .sub_path = path, .data = data }); + } + try writer.print("extracted {d} files\n", .{selected.items.len}); + return 0; +} + +const TracedCpk = struct { + owned_file: ?std.Io.File, + view: *View, + size: u64, + archive: cpk.Archive, +}; + +fn hashRange(source: cpk.Source, offset: u64, size: u64) !u64 { + var hash = cpk.fnv_offset; + var buffer: [65536]u8 = undefined; + var done: u64 = 0; + while (done < size) { + const count: usize = @intCast(@min(size - done, buffer.len)); + try source.read(offset + done, buffer[0..count]); + hash = cpk.fnv1a(hash, buffer[0..count]); + done += count; + } + return hash; +} + +fn hostPath(allocator: std.mem.Allocator, maps: []const []const u8, path: []const u8) !?[]u8 { + for (maps) |map| { + const split = std.mem.indexOfScalar(u8, map, '=') orelse return error.BadPrefixMap; + const prefix = map[0..split]; + if (path.len < prefix.len or !std.ascii.eqlIgnoreCase(path[0..prefix.len], prefix)) continue; + const relative = std.mem.trimStart(u8, path[prefix.len..], "/"); + return try std.fmt.allocPrint(allocator, "{s}/{s}", .{ map[split + 1 ..], relative }); + } + return null; +} + +fn openTraced(init: std.process.Init, writer: *std.Io.Writer, image: *const Container, maps: []const []const u8, path: []const u8) !TracedCpk { + const allocator = init.gpa; + const io = init.io; + const view = try allocator.create(View); + errdefer allocator.destroy(view); + var owned_file: ?std.Io.File = null; + errdefer if (owned_file) |file| file.close(io); + var size: u64 = 0; + if (try hostPath(allocator, maps, path)) |host| { + defer allocator.free(host); + const file = try std.Io.Dir.cwd().openFile(io, host, .{}); + owned_file = file; + size = try file.length(io); + view.* = .{ .io = io, .file = file, .base = 0 }; + } else { + const start = if (std.mem.indexOfScalar(u8, path, ':')) |colon| colon + 1 else 0; + const extent = try iso.find(allocator, image.view.source(image.size), path[start..]); + size = extent.size; + view.* = .{ .io = io, .file = image.file, .base = extent.offset }; + } + const archive = try cpk.Archive.open(allocator, view.source(size)); + errdefer archive.deinit(allocator); + var first_data = size; + if (archive.files.len != 0) { + first_data = std.math.maxInt(u64); + for (archive.files) |file| first_data = @min(first_data, file.offset); + } + try writer.print("{s}: {d} files, first data at 0x{X}, size 0x{X}\n", .{ path, archive.files.len, first_data, size }); + return .{ .owned_file = owned_file, .view = view, .size = size, .archive = archive }; +} + +fn lessThan(_: void, a: []const u8, b: []const u8) bool { + return std.mem.lessThan(u8, a, b); +} + +fn checkTrace(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8) !u8 { + const allocator = init.gpa; + const io = init.io; + if (args.len < 2) return error.ExpectedImageAndTrace; + var image: Container = undefined; + try image.open(io, args[0]); + defer image.file.close(io); + const maps = args[2..]; + const trace = try std.Io.Dir.cwd().readFileAlloc(io, args[1], allocator, .limited(cpk.max_file_size)); + defer allocator.free(trace); + + var opened: std.StringHashMapUnmanaged(TracedCpk) = .empty; + defer { + var values = opened.valueIterator(); + while (values.next()) |traced| { + traced.archive.deinit(allocator); + if (traced.owned_file) |file| file.close(io); + allocator.destroy(traced.view); + } + opened.deinit(allocator); + } + var per_file: std.StringHashMapUnmanaged(u32) = .empty; + defer { + var keys = per_file.keyIterator(); + while (keys.next()) |key| allocator.free(key.*); + per_file.deinit(allocator); + } + + var total: u64 = 0; + var header: u64 = 0; + var matched: u64 = 0; + var mismatched: u64 = 0; + var unclassified: u64 = 0; + var skipped: u64 = 0; + var lines = std.mem.splitScalar(u8, trace, '\n'); + _ = lines.next(); // column names + while (lines.next()) |raw_line| { + const line = std.mem.trimEnd(u8, raw_line, "\r"); + var fields = std.mem.splitScalar(u8, line, ','); + const path = fields.next() orelse continue; + const offset_text = fields.next() orelse continue; + const size_text = fields.next() orelse continue; + const hash_text = fields.next() orelse continue; + if (!std.ascii.endsWithIgnoreCase(path, ".cpk")) { + skipped += 1; + continue; + } + const offset = try std.fmt.parseInt(u64, offset_text, 10); + const size = try std.fmt.parseInt(u64, size_text, 10); + const hex = if (std.mem.startsWith(u8, hash_text, "0x")) hash_text[2..] else hash_text; + const hash = try std.fmt.parseInt(u64, hex, 16); + const end = std.math.add(u64, offset, size) catch return error.OutOfBounds; + total += 1; + + if (!opened.contains(path)) { + var traced = try openTraced(init, writer, &image, maps, path); + errdefer { + traced.archive.deinit(allocator); + if (traced.owned_file) |file| file.close(io); + allocator.destroy(traced.view); + } + try opened.put(allocator, path, traced); + } + const traced = opened.getPtr(path).?; + + var overlaps = false; + var hits: usize = 0; + var hit: cpk.File = undefined; + for (traced.archive.files) |file| { + const file_end = file.offset + file.size; + if (offset < file_end and file.offset < end) overlaps = true; + if (offset >= file.offset and end <= file_end) { + hits += 1; + hit = file; + } + } + // Metadata (header, TOC, ITOC/ETOC) is every byte outside file data. + if (!overlaps) { + header += 1; + continue; + } + if (hits != 1) { + unclassified += 1; + if (unclassified <= 10) try writer.print("UNCLASSIFIED {s} 0x{X}+0x{X}\n", .{ path, offset, size }); + continue; + } + const key = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ hit.dir, hit.name }); + const count = try per_file.getOrPut(allocator, key); + if (count.found_existing) { + allocator.free(key); + count.value_ptr.* += 1; + } else { + count.value_ptr.* = 1; + } + if (try hashRange(traced.view.source(traced.size), offset, size) == hash) { + matched += 1; + } else { + mismatched += 1; + if (mismatched <= 10) try writer.print("MISMATCH {s} 0x{X}+0x{X}\n", .{ count.key_ptr.*, offset, size }); + } + } + + var keys: std.ArrayList([]const u8) = .empty; + defer keys.deinit(allocator); + var key_iterator = per_file.keyIterator(); + while (key_iterator.next()) |key| try keys.append(allocator, key.*); + std.mem.sort([]const u8, keys.items, {}, lessThan); + for (keys.items[0..@min(keys.items.len, 20)]) |key| + try writer.print(" read {d}x {s}\n", .{ per_file.get(key).?, key }); + try writer.print("cpk reads={d} header/toc={d} file_matched={d} mismatched={d} unclassified={d} non_cpk={d}\n", .{ total, header, matched, mismatched, unclassified, skipped }); + return if (mismatched == 0 and unclassified == 0) 0 else 1; +} diff --git a/tools/cpk/test_cli.py b/tools/cpk/test_cli.py new file mode 100644 index 00000000..112cbba8 --- /dev/null +++ b/tools/cpk/test_cli.py @@ -0,0 +1,375 @@ +#!/usr/bin/env python3 +"""Synthetic, game-independent end-to-end fixtures for p3p-cpk.""" +import argparse +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +import tempfile +import unittest + +EXE = None +U16, U32, U64, STRING = 2, 4, 6, 10 +ROW = 0x50 +DEFAULT = 0x30 + + +def utf_table(columns, rows): + """columns: (name, kind, storage[, default]); rows: value per ROW column.""" + strings = bytearray(b"\0") + + def text(value): + offset = len(strings) + strings.extend(value.encode("latin-1") + b"\0") + return offset + + def packed(kind, value): + if kind == STRING: + return struct.pack(">I", text(value)) + return struct.pack({U16: ">H", U32: ">I", U64: ">Q"}[kind], value) + + schema = bytearray() + row_columns = [] + for column in columns: + name, kind, storage = column[:3] + schema.append(storage | kind) + schema += struct.pack(">I", text(name)) + if storage == DEFAULT: + schema += packed(kind, column[3]) + else: + row_columns.append(kind) + data = b"".join(packed(kind, value) for row in rows for kind, value in zip(row_columns, row)) + row_size = len(data) // len(rows) if rows else 0 + rows_offset = 0x20 + len(schema) + strings_offset = rows_offset + len(data) + size = strings_offset + len(strings) + header = b"@UTF" + struct.pack(">IHHIIIHHI", size - 8, 1, rows_offset - 8, strings_offset - 8, size - 8, 0, len(columns), row_size, len(rows)) + return header + bytes(schema) + data + bytes(strings) + + +def chunk(magic, table): + return magic + b"\xFF\0\0\0" + struct.pack("> shift) & 1 for shift in range(width - 1, -1, -1)) + + position = len(body) + while position > 0: + if position >= 8 and position + 3 <= len(body) and body[position - 3:position] == body[position:position + 3]: + put(1, 1) + put(0, 13) # distance 3 + put(0, 2) # length 3 + position -= 3 + else: + position -= 1 + put(0, 1) + put(body[position], 8) + bits.extend([0] * (-len(bits) % 8)) + stream = bytearray(len(bits) // 8) + for index, bit in enumerate(bits): + stream[len(stream) - 1 - index // 8] |= bit << (7 - index % 8) + return b"CRILAYLA" + struct.pack("I", sector) + body[10:18] = struct.pack("I", size) + body[25] = 2 if directory else 0 + body[32] = len(name) + body[33:33 + len(name)] = name + return bytes(body) + + +def iso(cpk_bytes): + """Image with /PSP_GAME/GAME.CPK;1.""" + sector = 2048 + root, game, data = 18, 19, 20 + image = bytearray(data * sector + cpk_bytes.__len__()) + descriptor = bytearray(sector) + descriptor[0] = 1 + descriptor[1:6] = b"CD001" + descriptor[156:156 + 34] = iso_record(b"\0", root, sector, True) + image[16 * sector:17 * sector] = descriptor + root_dir = iso_record(b"\0", root, sector, True) + iso_record(b"\1", root, sector, True) + iso_record(b"PSP_GAME", game, sector, True) + game_dir = iso_record(b"\0", game, sector, True) + iso_record(b"\1", root, sector, True) + iso_record(b"GAME.CPK;1", data, len(cpk_bytes), False) + image[root * sector:root * sector + len(root_dir)] = root_dir + image[game * sector:game * sector + len(game_dir)] = game_dir + image[data * sector:] = cpk_bytes + return bytes(image) + + +def fnv(data): + value = 0xCBF29CE484222325 + for byte in data: + value = ((value ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return value + + +def run(*args): + # Names are printed as stored, and damaged ones are not valid text. + return subprocess.run([EXE, *map(str, args)], capture_output=True, encoding="utf-8", errors="replace") + + +PLAIN = bytes(range(256)) * 3 +ORIGINAL = bytes(random.Random(1).randrange(256) for _ in range(0x100)) + b"abcabcabcabc" * 40 +COMPRESSED = layla(ORIGINAL) +ENTRIES = [("data/a", "plain.bin", PLAIN, len(PLAIN)), ("data/b", "packed.bin", COMPRESSED, len(ORIGINAL)), ("", "root.txt", b"hello", 5), ("data/a", "empty.bin", b"", 0)] + + +class Cli(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.cpk = self.dir / "mod.cpk" + self.cpk.write_bytes(cpk(ENTRIES)) + + def assert_clean_error(self, result): + self.assertEqual(result.returncode, 2, (result.returncode, result.stdout, result.stderr)) + self.assertTrue(result.stderr.startswith("p3p-cpk: "), result.stderr) + + def test_list_loose(self): + result = run("list", self.cpk) + self.assertEqual(result.returncode, 0, result.stderr) + lines = result.stdout.splitlines() + self.assertEqual(len(lines), 4) + self.assertRegex(lines[0], r"^data/a/plain\.bin offset=0x[0-9A-F]+ size=0x300 extract=0x300 compressed=0$") + self.assertRegex(lines[1], rf"^data/b/packed\.bin .* extract=0x{len(ORIGINAL):X} compressed=1$") + self.assertTrue(lines[2].startswith("/root.txt ")) + + def test_list_reads_no_file_data(self): + data = bytearray(self.cpk.read_bytes()) + first = int(run("list", self.cpk, "plain").stdout.split("offset=0x")[1].split()[0], 16) + data[first:] = bytes([0xEE]) * (len(data) - first) + self.cpk.write_bytes(data) + self.assertEqual(sum("compressed=1" in line for line in run("list", self.cpk).stdout.splitlines()), 1) + + def many_files(self): + path = self.dir / "many.cpk" + path.write_bytes(cpk([("some/long/directory/name", f"file_{index:05}.bin", b"x", 1) for index in range(3000)])) + return path + + def test_output_larger_than_a_pipe_buffer(self): + result = run("list", self.many_files()) + self.assertEqual(result.returncode, 0, result.stderr[-400:]) + self.assertEqual(len(result.stdout.splitlines()), 3000) + + @unittest.skipUnless(os.name == "nt", "Windows pipes") + def test_output_to_a_full_asynchronous_pipe(self): + # Git Bash gives programs pipes like this one; the pipes of subprocess are synchronous. + import ctypes + from ctypes import wintypes + import msvcrt + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateNamedPipeW.restype = wintypes.HANDLE + kernel32.CreateFileW.restype = wintypes.HANDLE + name = rf"\\.\pipe\p3p-cpk-test-{os.getpid()}" + inbound, overlapped, generic_write, open_existing = 1, 0x40000000, 0x40000000, 3 + server = kernel32.CreateNamedPipeW(name, inbound, 0, 1, 4096, 4096, 0, None) + client = kernel32.CreateFileW(name, generic_write, 0, None, open_existing, overlapped, None) + self.assertNotIn(wintypes.HANDLE(-1).value, (server, client)) + descriptor = msvcrt.open_osfhandle(client, 0) + process = subprocess.Popen([EXE, "list", self.many_files()], stdout=descriptor, stderr=subprocess.PIPE, text=True) + os.close(descriptor) + received = bytearray() + chunk_buffer = ctypes.create_string_buffer(65536) + count = wintypes.DWORD() + while kernel32.ReadFile(wintypes.HANDLE(server), chunk_buffer, len(chunk_buffer), ctypes.byref(count), None): + received += chunk_buffer.raw[:count.value] + kernel32.CloseHandle(wintypes.HANDLE(server)) + stderr = process.communicate()[1] + self.assertEqual(process.returncode, 0, stderr[-400:]) + self.assertEqual(received.count(b"\n"), 3000) + + def test_filter_spans_directory_and_name(self): + self.assertEqual(len(run("list", self.cpk, "A/PLAIN").stdout.splitlines()), 1) + self.assertEqual(run("list", self.cpk, "missing").stdout, "") + + def test_extract_loose(self): + out = self.dir / "out" + result = run("extract", self.cpk, out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((out / "data/a/plain.bin").read_bytes(), PLAIN) + self.assertEqual((out / "data/b/packed.bin").read_bytes(), ORIGINAL) + self.assertEqual((out / "root.txt").read_bytes(), b"hello") + self.assertEqual((out / "data/a/empty.bin").read_bytes(), b"") + + def test_extract_filtered(self): + out = self.dir / "out" + self.assertEqual(run("extract", self.cpk, "packed", out).returncode, 0) + self.assertEqual([p.name for p in out.rglob("*") if p.is_file()], ["packed.bin"]) + + def test_masked_tables(self): + path = self.dir / "masked.cpk" + path.write_bytes(cpk(ENTRIES, encrypted=True)) + self.assertEqual(run("list", path).stdout, run("list", self.cpk).stdout) + + def test_cpk_inside_iso(self): + image = self.dir / "game.iso" + image.write_bytes(iso(cpk(ENTRIES))) + result = run("list", image, "/psp_game/game.cpk", "packed") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, run("list", self.cpk, "packed").stdout) + out = self.dir / "out" + self.assertEqual(run("extract", image, "/PSP_GAME/GAME.CPK", out).returncode, 0) + self.assertEqual((out / "data/b/packed.bin").read_bytes(), ORIGINAL) + self.assert_clean_error(run("list", image, "/PSP_GAME/NOPE.CPK")) + self.assert_clean_error(run("list", image, "/PSP_GAME")) + self.assert_clean_error(run("list", image)) + + def test_traversal_writes_nothing(self): + for directory, name in [("..", "evil"), ("a/../..", "evil"), ("/abs", "evil"), ("C:", "evil"), ("a\\..\\..", "evil"), ("", "../evil"), ("", "NUL")]: + with self.subTest(directory=directory, name=name): + path = self.dir / "bad.cpk" + path.write_bytes(cpk([("safe", "first.bin", b"x", 1), (directory, name, b"y", 1)])) + out = self.dir / "sandbox" / "out" + self.assert_clean_error(run("extract", path, out)) + self.assertFalse((self.dir / "sandbox").exists()) + self.assertFalse((self.dir / "evil").exists()) + + def test_truncated_input_is_an_error(self): + data = self.cpk.read_bytes() + path = self.dir / "cut.cpk" + for size in list(range(4, 0x60, 7)) + [len(data) // 2, len(data) - 1]: + with self.subTest(size=size): + path.write_bytes(data[:size]) + self.assert_clean_error(run("list", path)) + + def test_mutated_input_never_crashes(self): + data = self.cpk.read_bytes() + rng = random.Random(65) + path = self.dir / "mutated.cpk" + out = self.dir / "out" + for round_number in range(250): + mutated = bytearray(data) + for _ in range(rng.randrange(1, 9)): + mutated[rng.randrange(4, len(mutated))] = rng.choice((0, 1, 0x7F, 0x80, 0xFF, rng.randrange(256))) + path.write_bytes(mutated) + for args in (("list", path), ("extract", path, out)): + result = run(*args) + self.assertIn(result.returncode, (0, 2), (round_number, args[0], result.stderr[-400:])) + + def test_corrupt_stream_is_an_error(self): + stream = bytearray(COMPRESSED) + stream[12:16] = struct.pack("