From 7690e6f27f1e5fb09ccaa8a81d5b4d7f0027a080 Mon Sep 17 00:00:00 2001 From: endercodezz Date: Fri, 6 Nov 2026 17:30:47 +0200 Subject: [PATCH] feat(tools): build a bind folder from a mod with p3p-cpk bind Most of a translation lies inside the game's containers, which only Aemulus could rebuild. bind writes a bind/ folder with the changed files and the containers, nested ones too, with the mod's files put in. A file it can't place is listed as unresolved. Verified: 185 of 185 real containers rebuild byte for byte. The Russian translation v0.8.3 places 266 of 336 files (the rest is .tmx inside .spr), and its first dialogue shows in Russian on the PC runner. tools/cpk/check.py: 37/37 CLI tests. --- .agents/skills/p3p-modding-vfs/SKILL.md | 2 +- .claude/skills/p3p-modding-vfs/SKILL.md | 2 +- README.md | 4 +- docs/CURRENT_STATE.md | 17 ++- tools/cpk/src/cpk.zig | 1 + tools/cpk/src/main.zig | 155 +++++++++++++++++++- tools/cpk/src/pak.zig | 187 ++++++++++++++++++++++++ tools/cpk/test_cli.py | 76 ++++++++++ 8 files changed, 431 insertions(+), 13 deletions(-) create mode 100644 tools/cpk/src/pak.zig diff --git a/.agents/skills/p3p-modding-vfs/SKILL.md b/.agents/skills/p3p-modding-vfs/SKILL.md index 4b5a93b3..a99eac2d 100644 --- a/.agents/skills/p3p-modding-vfs/SKILL.md +++ b/.agents/skills/p3p-modding-vfs/SKILL.md @@ -31,7 +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, and `diff` shows which game files a mod, a `bind/` folder or an Aemulus package replaces (`build/cpk/bin/p3p-cpk --help`). +- `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, `diff` shows which game files a mod, a `bind/` folder or an Aemulus package replaces, `bind` builds a `bind/` folder from such a package, and `patch` applies an EBOOT xdelta (`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-modding-vfs/SKILL.md b/.claude/skills/p3p-modding-vfs/SKILL.md index 4b5a93b3..a99eac2d 100644 --- a/.claude/skills/p3p-modding-vfs/SKILL.md +++ b/.claude/skills/p3p-modding-vfs/SKILL.md @@ -31,7 +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, and `diff` shows which game files a mod, a `bind/` folder or an Aemulus package replaces (`build/cpk/bin/p3p-cpk --help`). +- `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, `diff` shows which game files a mod, a `bind/` folder or an Aemulus package replaces, `bind` builds a `bind/` folder from such a package, and `patch` applies an EBOOT xdelta (`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/README.md b/README.md index c8bef041..412e3415 100644 --- a/README.md +++ b/README.md @@ -375,16 +375,18 @@ 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 diff mods/mod.cpk game.iso /PSP_GAME/USRDIR/umd0.cpk /PSP_GAME/USRDIR/umd1.cpk build/cpk/bin/p3p-cpk diff mods/bind game.iso /PSP_GAME/USRDIR/umd0.cpk /PSP_GAME/USRDIR/umd1.cpk +build/cpk/bin/p3p-cpk bind mods/bind my-mod game.iso /PSP_GAME/USRDIR/umd0.cpk /PSP_GAME/USRDIR/umd1.cpk 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. - `diff` shows what a `mod.cpk`, a `bind/` folder or an Aemulus package does to the game's archives: each file is `added`, `changed` or `same`, by extracted content, so a stored copy of a compressed file counts as the same. A file under a folder named after a game file, such as `data/init/a.tmx` for `data/init.bin`, is `in-container`: a mod manager has to build it into that file first. Names match without regard to case, and a match that differs in case is marked `case-differs`. +- `bind` makes a mod usable without Aemulus: it writes a `bind/` folder with the changed files and rebuilds the game's containers around the `in-container` files. A file it can't place, such as one inside an `.spr`, is listed as `unresolved`, and the exit code is 1. - `patch ` applies the VCDIFF patches that mods ship, such as an EBOOT patch, and checks their checksums; `p3p-bindiff --elf` then shows what changed. - `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 or `diff` found anything but `same`, **2** usage/input/output error. On Windows use `p3p-cpk.exe`. Keep game files and extracts under `.tmp/`. +Exit codes: **0** success, **1** `check-trace` found differences, `diff` found anything but `same`, or `bind` left files `unresolved`, **2** usage/input/output error. On Windows use `p3p-cpk.exe`. Keep game files and extracts under `.tmp/`. ### Continuous integration and releases (GitHub Actions) diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 30e1c93a..9f400062 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -2,16 +2,27 @@ 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. +## Russian translation runs on the PC runner, without Aemulus (#87, #23, 2026-11-06) + +- `tools/cpk`: `bind ` writes a `bind/` folder: changed files, and the game's containers (nested ones too) with the mod's files put in. `tools/cpk/src/pak.zig` reads and rebuilds the two PAK layouts of the game. +- [VERIFIED] Containers: 252-byte names, data padded to 64 bytes, zero tail; or a 32-bit count, 32-byte names, unpadded. The padding is not always zeros (`data/init_2.bin`). Game files can share a name with another extension (`f021_000.fpc`, `f021_000.pac`), and a folder belongs to the one that holds the file. +- [VERIFIED] The folder rule of `in-container` is Aemulus' own: `Utilities/BinMerging/BinMerger.cs`, `Path.ChangeExtension(file, null)`. +- [VERIFIED] Round trip: 185 of 185 real containers rebuild byte for byte when a file's own data is put back. +- [VERIFIED] Translation v0.8.3: 1,369 changed files and 183 containers written, 266 of 336 in-container files placed. The other 70 are `.tmx` inside `.spr` (interface graphics): `bind` lists them as `unresolved`, and `.spr` is not supported yet. +- [VERIFIED] PC runner, `--mods` with that folder, `profiles/p3p/input/new_game.txt`, stopped at vblank 9600: the game reads `ms0:/PSP/P3P/bind/data/init.bin`, `init_free.bin` and `title/sex_select.bin`, and the first dialogue shows in Russian in Cyrillic, with no runtime change and the original EBOOT. +- [VERIFIED] The two `.text` words of the EBOOT patch are `addiu a0,a0,imm` with another immediate, which fits a moved string. [INFERRED] Not logic. +- [UNVERIFIED] Menus with the patched EBOOT, and anything past the first dialogue. New 3DS: not run. + ## First real translation compared: Russian v0.8.3 (#80, #23, 2026-11-06) - [VERIFIED] [P3P Russian Translation (PSP Version)](https://gamebanana.com/mods/449730) v0.8.3 by Kotone Team, MD5 `5fc0fa81f932311d0988ec4385c0b3b6`: an Aemulus package (`Package.xml`, 1,705 files under `data/`), `texture_override/ULUS10512` (126 files) and an EBOOT patch (`rus_eboot_patch_v0.8.2.xdelta`, source `EBOOT_DEC.BIN`). Not a `mod.cpk`. Game data, kept under `.tmp/` only. - `tools/cpk`: `diff` accepts a directory as the mod, and a file under a folder named after a game file is `in-container`, not `added`. - [VERIFIED] `diff` of the package against `umd0.cpk` and `umd1.cpk`: 1,369 `changed` (1,258 `.bf`, 98 `.abin`), 336 `in-container` (229 `.bf`, 72 `.tmx`, 20 `.bmd`, `data/init/font/font0.fnt` under `data/init.bin`), 128 `added` (the texture folder, `Package.xml`, `Preview.png`). -- [INFERRED] The `in-container` files must first be built into their containers, which Aemulus does, so the package can't simply be copied to `mods/bind/`. Not yet checked against Aemulus or run. +- [VERIFIED] The `in-container` files must first be built into their containers (`p3p-cpk bind`), so the package can't simply be copied to `mods/bind/`. - [WRONG] A translation needs no EBOOT patch: the mod's description says the menu text is in the EBOOT. - `tools/cpk`: `patch` applies xdelta (VCDIFF) patches (#83). -- [VERIFIED] `rus_eboot_patch_v0.8.2.xdelta` applies to `profiles/p3p/game/eboot.elf` with its Adler-32 matching, so this is its source. It changes 47,707 of 5,849,468 bytes in 611 ranges, size unchanged: 29,798 in `.rodata`, 17,907 in `.data`, 2 in `.text` (file offsets 0x154578: 0x2484E8C0 -> 0x2484E8BF; 0x154688: 0x2484E8B0 -> 0x2484E8AE). P3P3DS generates its AOT code from the EBOOT, so those 2 bytes need the generated code to change, or a profile patch. [UNVERIFIED] What the two instructions do. -- [INFERRED] Cyrillic is drawn through a replaced font with Latin character codes: the patch holds `Kluwka dlq lakrossa` ("lacrosse stick" in Russian). One string only. +- [VERIFIED] `rus_eboot_patch_v0.8.2.xdelta` applies to `profiles/p3p/game/eboot.elf` with its Adler-32 matching, so this is its source. It changes 47,707 of 5,849,468 bytes in 611 ranges, size unchanged: 29,798 in `.rodata`, 17,907 in `.data`, 2 in `.text` (file offsets 0x154578: 0x2484E8C0 -> 0x2484E8BF; 0x154688: 0x2484E8B0 -> 0x2484E8AE). P3P3DS generates its AOT code from the EBOOT, so those 2 bytes need the generated code to change, or a profile patch. +- [INFERRED] Cyrillic comes from a replaced font on Latin character codes: the patch holds `Kluwka dlq lakrossa` ("lacrosse stick" in Russian). One string only. ## `p3p-cpk diff`: what a mod changes in the game's archives (#76, 2026-11-06) diff --git a/tools/cpk/src/cpk.zig b/tools/cpk/src/cpk.zig index d77c2114..c96352b1 100644 --- a/tools/cpk/src/cpk.zig +++ b/tools/cpk/src/cpk.zig @@ -424,6 +424,7 @@ const testing = std.testing; test { _ = @import("vcdiff.zig"); + _ = @import("pak.zig"); } test "literal and copy blocks decompress from the end" { diff --git a/tools/cpk/src/main.zig b/tools/cpk/src/main.zig index 81444760..d4847124 100644 --- a/tools/cpk/src/main.zig +++ b/tools/cpk/src/main.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const cpk = @import("cpk.zig"); const iso = @import("iso.zig"); +const pak = @import("pak.zig"); const vcdiff = @import("vcdiff.zig"); const usage = @@ -11,6 +12,8 @@ const usage = \\ p3p-cpk extract [substring] \\ p3p-cpk diff \\ p3p-cpk diff ... + \\ p3p-cpk bind + \\ p3p-cpk bind ... \\ p3p-cpk patch \\ p3p-cpk check-trace [prefix=hostdir ...] \\ p3p-cpk --help | --version @@ -26,6 +29,9 @@ const usage = \\in-container: a mod manager has to build it into that file. Names match without \\regard to case; a match that differs in case is marked case-differs. With \\several base archives the first that has a file wins. + \\bind runs diff and writes a folder for the mod chain's bind/: changed files, and + \\the base containers (nested ones too) with in-container files put in. A file it + \\can't put in, such as one inside an .spr, is listed as unresolved, and exit is 1. \\patch applies a VCDIFF patch as xdelta3 writes it, checking its checksums; patches \\with secondary compression are refused. Compare with p3p-bindiff --elf. \\check-trace verifies the reads of p3p_pc_bootstrap --io-trace: each read of a @@ -149,7 +155,11 @@ fn dispatch(init: std.process.Init, writer: *std.Io.Writer, args: []const []cons 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, "diff")) return diffCommand(init, writer, rest); + if (std.mem.eql(u8, command, "diff")) return diffCommand(init, writer, rest, null); + if (std.mem.eql(u8, command, "bind")) { + if (rest.len < 3) return error.ExpectedOutputModAndBase; + return diffCommand(init, writer, rest[1..], rest[0]); + } if (std.mem.eql(u8, command, "patch")) return patchCommand(init, writer, rest); if (std.mem.eql(u8, command, "check-trace")) return checkTrace(init, writer, rest); return error.UnknownCommand; @@ -247,7 +257,106 @@ fn sameContent(allocator: std.mem.Allocator, mod_source: cpk.Source, mod: cpk.Fi return std.mem.eql(u8, left, right); } +const Inner = struct { + /// Lower-case path of the base container, and of the file inside it. + container: []const u8, + path: []const u8, + /// `dir/name` as the mod has it, for the report. + shown: []const u8, + data: []const u8, +}; + +fn innerLessThan(_: void, a: Inner, b: Inner) bool { + return std.mem.lessThan(u8, a.container, b.container); +} + +fn writeBound(io: std.Io, out: std.Io.Dir, path: []const u8, data: []const u8) !void { + if (std.fs.path.dirnamePosix(path)) |parent| try out.createDirPath(io, parent); + try out.writeFile(io, .{ .sub_path = path, .data = data }); +} + +const Bind = struct { + io: std.Io, + out: std.Io.Dir, + arena: std.mem.Allocator, + inner: std.ArrayList(Inner) = .empty, + written: u64 = 0, + containers: u64 = 0, + unresolved: u64 = 0, + + /// A changed container of the mod comes first, then the base's. + fn loadContainer(self: *Bind, allocator: std.mem.Allocator, diff: *const Diff, key: []const u8, path: []const u8) ![]u8 { + return self.out.readFileAlloc(self.io, path, allocator, .limited(cpk.max_file_size)) catch |err| switch (err) { + error.FileNotFound => { + const found = diff.base_files.get(key) orelse return error.ContainerNotFound; + return cpk.extract(allocator, found.source, found.file); + }, + else => return err, + }; + } + + fn accepts(self: *Bind, allocator: std.mem.Allocator, diff: *const Diff, key: []const u8, item: Inner) !bool { + const found = diff.base_files.get(key) orelse return false; + const path = try cpk.safePath(allocator, found.file.dir, found.file.name); + defer allocator.free(path); + const bytes = try self.loadContainer(allocator, diff, key, path); + defer allocator.free(bytes); + const rebuilt = try pak.replace(allocator, bytes, item.path, item.data) orelse return false; + allocator.free(rebuilt); + return true; + } + + /// Game files can share a name and differ in extension, like f021_000.fpc and + /// f021_000.pac: the folder belongs to the one that holds the file. + fn pickContainer(self: *Bind, allocator: std.mem.Allocator, diff: *const Diff, item: *Inner) !void { + if (try self.accepts(allocator, diff, item.container, item.*)) return; + const stem = item.container[0 .. std.mem.lastIndexOfScalar(u8, item.container, '.') orelse return]; + for ([_][]const u8{ ".pac", ".fpc", ".bin", ".abin", ".pak", ".arc" }) |extension| { + const key = try std.fmt.allocPrint(self.arena, "{s}{s}", .{ stem, extension }); + if (std.mem.eql(u8, key, item.container)) continue; + if (try self.accepts(allocator, diff, key, item.*)) { + item.container = key; + return; + } + } + } + + fn finish(self: *Bind, allocator: std.mem.Allocator, writer: *std.Io.Writer, diff: *const Diff) !void { + for (self.inner.items) |*item| try self.pickContainer(allocator, diff, item); + std.mem.sort(Inner, self.inner.items, {}, innerLessThan); + var start: usize = 0; + while (start < self.inner.items.len) { + const key = self.inner.items[start].container; + var end = start; + while (end < self.inner.items.len and std.mem.eql(u8, self.inner.items[end].container, key)) end += 1; + const found = diff.base_files.get(key) orelse return error.ContainerNotFound; + const path = try cpk.safePath(allocator, found.file.dir, found.file.name); + defer allocator.free(path); + var bytes = try self.loadContainer(allocator, diff, key, path); + defer allocator.free(bytes); + var changed = false; + for (self.inner.items[start..end]) |item| { + if (try pak.replace(allocator, bytes, item.path, item.data)) |next| { + allocator.free(bytes); + bytes = next; + changed = true; + } else { + self.unresolved += 1; + try writer.print("unresolved {s} container={s}\n", .{ item.shown, path }); + } + } + if (changed) { + try writeBound(self.io, self.out, path, bytes); + self.containers += 1; + } + start = end; + } + try writer.print("bind files={d} containers={d} unresolved={d}\n", .{ self.written, self.containers, self.unresolved }); + } +}; + const Diff = struct { + bind: ?*Bind = null, base_files: *const std.StringHashMapUnmanaged(BaseFile), /// Lower-case base paths without their extension -> the base file's path. stems: *const std.StringHashMapUnmanaged([]const u8), @@ -258,12 +367,13 @@ const Diff = struct { same: u64 = 0, case_differs: u64 = 0, - /// The deepest folder of `key` that is named after a base file. - fn container(self: *const Diff, key: []const u8) ?[]const u8 { + /// The deepest folder of `key` that is named after a base file: that file, + /// and where in `key` the path inside it starts. + fn container(self: *const Diff, key: []const u8) ?struct { path: []const u8, inner: usize } { var end = key.len; while (std.mem.lastIndexOfScalar(u8, key[0..end], '/')) |slash| { if (slash == 0) return null; - if (self.stems.get(key[0..slash])) |found| return found; + if (self.stems.get(key[0..slash])) |found| return .{ .path = found, .inner = slash + 1 }; end = slash; } return null; @@ -274,9 +384,18 @@ const Diff = struct { const key = try lowerKey(allocator, file); defer allocator.free(key); const found = self.base_files.get(key) orelse { - if (self.container(key)) |container_path| { + if (self.container(key)) |found_container| { self.in_container += 1; - try writer.print("in-container {s}/{s} container={s}\n", .{ file.dir, file.name, container_path }); + try writer.print("in-container {s}/{s} container={s}\n", .{ file.dir, file.name, found_container.path }); + if (self.bind) |bind| { + const data = try cpk.extract(bind.arena, source, file); + try bind.inner.append(bind.arena, .{ + .container = try std.ascii.allocLowerString(bind.arena, found_container.path), + .path = try bind.arena.dupe(u8, key[found_container.inner..]), + .shown = try std.fmt.allocPrint(bind.arena, "{s}/{s}", .{ file.dir, file.name }), + .data = data, + }); + } } else { self.added += 1; try writer.print("added {s}/{s} extract=0x{X}\n", .{ file.dir, file.name, file.extract_size }); @@ -292,6 +411,15 @@ const Diff = struct { } else { self.changed += 1; try writer.print("changed {s}/{s} extract=0x{X} -> 0x{X}{s}\n", .{ file.dir, file.name, found.file.extract_size, file.extract_size, mark }); + if (self.bind) |bind| { + // Under the base's name: that is the one the game asks for. + const path = try cpk.safePath(allocator, found.file.dir, found.file.name); + defer allocator.free(path); + const data = try cpk.extract(allocator, source, file); + defer allocator.free(data); + try writeBound(bind.io, bind.out, path, data); + bind.written += 1; + } } } }; @@ -329,7 +457,7 @@ fn diffDirectory(init: std.process.Init, writer: *std.Io.Writer, diff: *Diff, di } } -fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8) !u8 { +fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8, bind_dir: ?[]const u8) !u8 { const allocator = init.gpa; const io = init.io; if (args.len < 2) return error.ExpectedModAndBase; @@ -390,6 +518,15 @@ fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []c } var diff: Diff = .{ .base_files = &base_files, .stems = &stems }; + var bind: Bind = undefined; + var bind_out: ?std.Io.Dir = null; + defer if (bind_out) |dir| dir.close(io); + if (bind_dir) |path| { + try std.Io.Dir.cwd().createDirPath(io, path); + bind_out = try std.Io.Dir.cwd().openDir(io, path, .{}); + bind = .{ .io = io, .out = bind_out.?, .arena = arena }; + diff.bind = &bind; + } if (mod_dir) |dir| { try diffDirectory(init, writer, &diff, dir); } else { @@ -399,6 +536,10 @@ fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []c for (archive.files) |file| try diff.compare(allocator, writer, mod_source, file); } try writer.print("mod files={d} added={d} in_container={d} changed={d} same={d} case_differs={d} base files={d}\n", .{ diff.files, diff.added, diff.in_container, diff.changed, diff.same, diff.case_differs, base_files.count() }); + if (diff.bind) |active| { + try active.finish(allocator, writer, &diff); + return if (active.unresolved == 0) 0 else 1; + } return if (diff.added == 0 and diff.in_container == 0 and diff.changed == 0) 0 else 1; } diff --git a/tools/cpk/src/pak.zig b/tools/cpk/src/pak.zig new file mode 100644 index 00000000..7cbaed47 --- /dev/null +++ b/tools/cpk/src/pak.zig @@ -0,0 +1,187 @@ +//! Atlus PAK containers of P3P (.bin, .pac, .fpc, ...), in the two layouts the +//! game uses. Long names: per file a 252-byte name, a 32-bit size and the data +//! padded to 64 bytes, then zeros. Counted: a 32-bit file count, then per file a +//! 32-byte name, a 32-bit size and the data, unpadded. All little-endian. +const std = @import("std"); + +const Layout = struct { + name_size: usize, + alignment: usize, + counted: bool, +}; +const long_names: Layout = .{ .name_size = 252, .alignment = 64, .counted = false }; +const counted: Layout = .{ .name_size = 32, .alignment = 1, .counted = true }; + +const Entry = struct { + raw_name: []const u8, + name: []const u8, + data: []const u8, + /// What followed the data up to the next file: kept for an exact rebuild. + padding: []const u8, +}; + +const Pak = struct { + layout: Layout, + entries: []Entry, + tail: []const u8, +}; + +fn isName(name: []const u8) bool { + if (name.len == 0) return false; + for (name) |byte| if (byte < 0x20 or byte > 0x7E) return false; + return true; +} + +fn parseLayout(allocator: std.mem.Allocator, bytes: []const u8, layout: Layout) !?Pak { + var entries: std.ArrayList(Entry) = .empty; + errdefer entries.deinit(allocator); + var position: usize = 0; + var remaining: usize = std.math.maxInt(usize); + if (layout.counted) { + if (bytes.len < 4) return null; + remaining = std.mem.readInt(u32, bytes[0..4], .little); + if (remaining == 0 or remaining > bytes.len / (layout.name_size + 4)) { + entries.deinit(allocator); + return null; + } + position = 4; + } + const header = layout.name_size + 4; + while (remaining != 0 and bytes.len - position >= header) : (remaining -= 1) { + const raw_name = bytes[position..][0..layout.name_size]; + const name = raw_name[0 .. std.mem.indexOfScalar(u8, raw_name, 0) orelse raw_name.len]; + if (name.len == 0 and !layout.counted) break; + const size = std.mem.readInt(u32, bytes[position + layout.name_size ..][0..4], .little); + const data_start = position + header; + if (!isName(name) or size > bytes.len - data_start) { + entries.deinit(allocator); + return null; + } + const data_end = data_start + size; + const next = @min(std.mem.alignForward(usize, data_end, layout.alignment), bytes.len); + try entries.append(allocator, .{ .raw_name = raw_name, .name = name, .data = bytes[data_start..data_end], .padding = bytes[data_end..next] }); + position = next; + } + if (entries.items.len == 0 or (layout.counted and remaining != 0)) { + entries.deinit(allocator); + return null; + } + return .{ .layout = layout, .entries = try entries.toOwnedSlice(allocator), .tail = bytes[position..] }; +} + +fn parse(allocator: std.mem.Allocator, bytes: []const u8) !?Pak { + if (try parseLayout(allocator, bytes, long_names)) |pak| return pak; + return parseLayout(allocator, bytes, counted); +} + +fn build(allocator: std.mem.Allocator, pak: Pak, index: usize, data: []const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(allocator); + var word: [4]u8 = undefined; + if (pak.layout.counted) { + std.mem.writeInt(u32, &word, @intCast(pak.entries.len), .little); + try out.appendSlice(allocator, &word); + } + for (pak.entries, 0..) |entry, position| { + const content = if (position == index) data else entry.data; + try out.appendSlice(allocator, entry.raw_name); + std.mem.writeInt(u32, &word, std.math.cast(u32, content.len) orelse return error.TooLarge, .little); + try out.appendSlice(allocator, &word); + try out.appendSlice(allocator, content); + // The game's padding is not always zeros: it stays unless the size changes. + if (content.len == entry.data.len) { + try out.appendSlice(allocator, entry.padding); + } else { + try out.appendNTimes(allocator, 0, std.mem.alignForward(usize, out.items.len, pak.layout.alignment) - out.items.len); + } + } + try out.appendSlice(allocator, pak.tail); + return out.toOwnedSlice(allocator); +} + +fn stem(name: []const u8) []const u8 { + const slash = if (std.mem.lastIndexOfScalar(u8, name, '/')) |at| at + 1 else 0; + const dot = std.mem.lastIndexOfScalar(u8, name[slash..], '.') orelse return name; + return name[0 .. slash + dot]; +} + +/// `container` with the file at `path` replaced, or null when no file answers to +/// it. A path enters a nested container through a folder named after it, as in +/// mod managers: `panel/a.tmx` for `a.tmx` in `panel.bin`. Caller frees. +pub fn replace(allocator: std.mem.Allocator, container: []const u8, path: []const u8, data: []const u8) !?[]u8 { + const pak = try parse(allocator, container) orelse return null; + defer allocator.free(pak.entries); + for (pak.entries, 0..) |entry, index| { + if (std.ascii.eqlIgnoreCase(entry.name, path)) return try build(allocator, pak, index, data); + } + for (pak.entries, 0..) |entry, index| { + const prefix = stem(entry.name); + if (path.len <= prefix.len or path[prefix.len] != '/') continue; + if (!std.ascii.eqlIgnoreCase(path[0..prefix.len], prefix)) continue; + const inner = try replace(allocator, entry.data, path[prefix.len + 1 ..], data) orelse continue; + defer allocator.free(inner); + return try build(allocator, pak, index, inner); + } + return null; +} + +const testing = std.testing; + +fn longFile(out: *std.ArrayList(u8), name: []const u8, data: []const u8) !void { + var header: [256]u8 = @splat(0); + @memcpy(header[0..name.len], name); + std.mem.writeInt(u32, header[252..256], @intCast(data.len), .little); + try out.appendSlice(testing.allocator, &header); + try out.appendSlice(testing.allocator, data); + try out.appendNTimes(testing.allocator, 0, std.mem.alignForward(usize, out.items.len, 64) - out.items.len); +} + +fn countedFile(out: *std.ArrayList(u8), name: []const u8, data: []const u8) !void { + var header: [36]u8 = @splat(0); + @memcpy(header[0..name.len], name); + std.mem.writeInt(u32, header[32..36], @intCast(data.len), .little); + try out.appendSlice(testing.allocator, &header); + try out.appendSlice(testing.allocator, data); +} + +test "replacing a file with itself rebuilds the same bytes" { + var pak: std.ArrayList(u8) = .empty; + defer pak.deinit(testing.allocator); + try longFile(&pak, "a.bf", "first"); + try longFile(&pak, "dir/b.bmd", "second file"); + try pak.appendNTimes(testing.allocator, 0, 256); + const same = (try replace(testing.allocator, pak.items, "DIR/B.BMD", "second file")).?; + defer testing.allocator.free(same); + try testing.expectEqualSlices(u8, pak.items, same); +} + +test "a new size moves what follows, and nested containers are rebuilt" { + var inner: std.ArrayList(u8) = .empty; + defer inner.deinit(testing.allocator); + try inner.appendSlice(testing.allocator, &[_]u8{ 2, 0, 0, 0 }); + try countedFile(&inner, "x.bin", "xx"); + try countedFile(&inner, "y.bin", "yy"); + var outer: std.ArrayList(u8) = .empty; + defer outer.deinit(testing.allocator); + try longFile(&outer, "panel.bin", inner.items); + try longFile(&outer, "last.bin", "last"); + + const out = (try replace(testing.allocator, outer.items, "panel/x.bin", "longer data")).?; + defer testing.allocator.free(out); + const parsed = (try parse(testing.allocator, out)).?; + defer testing.allocator.free(parsed.entries); + try testing.expectEqualStrings("last", parsed.entries[1].data); + const nested = (try parse(testing.allocator, parsed.entries[0].data)).?; + defer testing.allocator.free(nested.entries); + try testing.expectEqualStrings("longer data", nested.entries[0].data); + try testing.expectEqualStrings("yy", nested.entries[1].data); +} + +test "paths without a file and data that is no container give null" { + var pak: std.ArrayList(u8) = .empty; + defer pak.deinit(testing.allocator); + try longFile(&pak, "a.bf", "first"); + try testing.expectEqual(@as(?[]u8, null), try replace(testing.allocator, pak.items, "b.bf", "x")); + try testing.expectEqual(@as(?[]u8, null), try replace(testing.allocator, "\x01\x00\x00\x00not a container", "a", "x")); + try testing.expectEqual(@as(?[]u8, null), try replace(testing.allocator, "", "a", "x")); +} diff --git a/tools/cpk/test_cli.py b/tools/cpk/test_cli.py index 08c0d186..34b78eef 100644 --- a/tools/cpk/test_cli.py +++ b/tools/cpk/test_cli.py @@ -514,6 +514,82 @@ def test_patch_mutated_never_crashes(self): result = run("patch", self.dir / "source", self.dir / "patch", self.dir / "out") self.assertIn(result.returncode, (0, 2), (round_number, result.stderr[-400:])) + def pak_entry(self, name, data): + padded = data + bytes(-(256 + len(data)) % 64) + return name.encode().ljust(252, b"\0") + struct.pack("", + }) + out = self.dir / "out" + result = run("bind", out, root, base) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("bind files=1 containers=1 unresolved=0", result.stdout) + self.assertEqual((out / "data/plain.bin").read_bytes(), b"new") + built = (out / "data/pack.bin").read_bytes() + self.assertIn(b"first, translated", built) + self.assertIn(b"yy translated", built) + self.assertIn(b"xx", built) + self.assertEqual(sorted(p.name for p in out.rglob("*") if p.is_file()), ["pack.bin", "plain.bin"]) + + def test_bind_with_the_same_data_rebuilds_the_same_container(self): + base, container = self.bind_fixture() + root = self.mod_directory({"data/pack/a.bf": b"first", "data/pack/panel/x.bmd": b"xx"}) + out = self.dir / "out" + self.assertEqual(run("bind", out, root, base).returncode, 0) + self.assertEqual((out / "data/pack.bin").read_bytes(), container) + + def test_bind_keeps_padding_that_is_not_zero(self): + container = bytearray(self.pak_entry("a.bf", b"first") + self.pak_entry("b.bf", b"second")) + container[256 + 5:320] = b"\xAB" * (320 - 256 - 5) + base = self.diff_fixture([("data", "pack.bin", bytes(container), len(container))], "base.cpk") + out = self.dir / "out" + self.assertEqual(run("bind", out, self.mod_directory({"data/pack/a.bf": b"FIRST"}), base).returncode, 0) + container[256:261] = b"FIRST" + self.assertEqual((out / "data/pack.bin").read_bytes(), bytes(container)) + + def test_bind_finds_the_file_among_containers_of_the_same_name(self): + fpc = self.pak_entry("model.gmo", b"model") + pac = self.pak_entry("script.bf", b"script") + base = self.diff_fixture([("data", "f021.fpc", fpc, len(fpc)), ("data", "f021.pac", pac, len(pac))], "base.cpk") + out = self.dir / "out" + result = run("bind", out, self.mod_directory({"data/f021/script.bf": b"translated"}), base) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(b"translated", (out / "data/f021.pac").read_bytes()) + self.assertFalse((out / "data/f021.fpc").exists()) + + def test_bind_names_what_it_cannot_put_in(self): + base, _ = self.bind_fixture() + root = self.mod_directory({"data/image/a.tmx": b"tmx", "data/pack/missing.bf": b"x"}) + result = run("bind", self.dir / "out", root, base) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("unresolved data/image/a.tmx container=data/image.spr", result.stdout) + self.assertIn("unresolved data/pack/missing.bf container=data/pack.bin", result.stdout) + self.assertIn("unresolved=2", result.stdout) + + def test_bind_mutated_container_never_crashes(self): + _, container = self.bind_fixture() + root = self.mod_directory({"data/pack/panel/y.bmd": b"new"}) + rng = random.Random(84) + for round_number in range(150): + mutated = bytearray(container) + for _ in range(rng.randrange(1, 6)): + mutated[rng.randrange(len(mutated))] = rng.choice((0, 0x7F, 0x80, 0xFF, rng.randrange(256))) + base = self.diff_fixture([("data", "pack.bin", bytes(mutated), len(mutated))], "base.cpk") + result = run("bind", self.dir / "out", root, base) + self.assertIn(result.returncode, (0, 1, 2), (round_number, result.stderr[-400:])) + def trace(self, rows): path = self.dir / "trace.csv" path.write_text("path,offset,size,fnv1a64,time_us\n" + "".join(f"{p},{o},{s},0x{h:016X},0\n" for p, o, s, h in rows))