From de57ca26dcab95b25415a7145c363fdcc9417c8a Mon Sep 17 00:00:00 2001 From: endercodezz Date: Fri, 6 Nov 2026 17:14:47 +0200 Subject: [PATCH] feat(tools): apply xdelta patches with p3p-cpk patch Mods ship EBOOT patches as VCDIFF, and P3P3DS generates its AOT code from the EBOOT, so it matters what they change. patch applies them with their checksums checked; p3p-bindiff --elf shows the result. Verified: the Russian translation's patch applies to the local EBOOT with a matching Adler-32 and changes 47,707 bytes, 2 of them in .text. tools/cpk/check.py: 31/31 CLI tests, 150 damaged patches included. --- README.md | 1 + docs/CURRENT_STATE.md | 4 +- docs/VERIFICATION.md | 5 + tools/cpk/src/cpk.zig | 4 + tools/cpk/src/main.zig | 21 ++++ tools/cpk/src/vcdiff.zig | 218 +++++++++++++++++++++++++++++++++++++++ tools/cpk/test_cli.py | 87 ++++++++++++++++ 7 files changed, 339 insertions(+), 1 deletion(-) create mode 100644 tools/cpk/src/vcdiff.zig diff --git a/README.md b/README.md index 59421a15..c8bef041 100644 --- a/README.md +++ b/README.md @@ -381,6 +381,7 @@ build/cpk/bin/p3p-cpk check-trace game.iso .tmp/io-trace.csv ms0:/PSP/P3P=.tmp/m - `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`. +- `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/`. diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 7e6dc8a1..30e1c93a 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -8,7 +8,9 @@ This is the current source of truth, newest entries first. Evidence concerns ULU - `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. -- [WRONG] A translation needs no EBOOT patch: the mod's description says the menu text is in the EBOOT. P3P3DS generates its AOT code from the EBOOT, so a patch that touches code has to reach the Builder. [UNVERIFIED] What it changes: not applied yet, no xdelta tool here. +- [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. ## `p3p-cpk diff`: what a mod changes in the game's archives (#76, 2026-11-06) diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index a89a1b52..154dc246 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -6,6 +6,11 @@ Current execution and coverage measurements: [CURRENT_STATE.md](CURRENT_STATE.md --- +## `p3p-cpk patch` (#83, 2026-11-06) + +- [VERIFIED] The Russian translation's EBOOT patch applies to the local decrypted EBOOT with a matching Adler-32 (one window). 47,707 bytes differ: `.rodata` 29,798, `.data` 17,907, `.text` 2. +- [VERIFIED] `python tools/cpk/check.py`: 31/31 CLI tests, with synthetic ADD, COPY, RUN, overlapping copy, bad checksum, secondary compression, truncated input and 150 damaged patches (exit 0 or 2, never a panic). Unit test of the RFC 3284 code table landmarks. + ## `p3p-cpk diff` (#76, 2026-11-06) Local ULUS-10512 ISO, Windows, Zig 0.17.1 `-Doptimize=safe`: diff --git a/tools/cpk/src/cpk.zig b/tools/cpk/src/cpk.zig index 78849c0c..d77c2114 100644 --- a/tools/cpk/src/cpk.zig +++ b/tools/cpk/src/cpk.zig @@ -422,6 +422,10 @@ pub fn safePath(allocator: std.mem.Allocator, dir: []const u8, name: []const u8) const testing = std.testing; +test { + _ = @import("vcdiff.zig"); +} + 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. diff --git a/tools/cpk/src/main.zig b/tools/cpk/src/main.zig index 1079e16c..81444760 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 vcdiff = @import("vcdiff.zig"); const usage = \\Usage: p3p-cpk list [substring] @@ -10,6 +11,7 @@ const usage = \\ p3p-cpk extract [substring] \\ p3p-cpk diff \\ p3p-cpk diff ... + \\ p3p-cpk patch \\ p3p-cpk check-trace [prefix=hostdir ...] \\ p3p-cpk --help | --version \\list prints every file: dir/name, offset, stored and extracted size, compressed. @@ -24,6 +26,8 @@ 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. + \\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 \\.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. @@ -146,6 +150,7 @@ fn dispatch(init: std.process.Init, writer: *std.Io.Writer, args: []const []cons 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, "patch")) return patchCommand(init, writer, rest); if (std.mem.eql(u8, command, "check-trace")) return checkTrace(init, writer, rest); return error.UnknownCommand; } @@ -397,6 +402,22 @@ fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []c return if (diff.added == 0 and diff.in_container == 0 and diff.changed == 0) 0 else 1; } +fn patchCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8) !u8 { + const allocator = init.gpa; + const io = init.io; + if (args.len != 3) return error.ExpectedSourcePatchOutput; + const cwd = std.Io.Dir.cwd(); + const source = try cwd.readFileAlloc(io, args[0], allocator, .limited(vcdiff.max_output_size)); + defer allocator.free(source); + const patch_data = try cwd.readFileAlloc(io, args[1], allocator, .limited(vcdiff.max_output_size)); + defer allocator.free(patch_data); + const result = try vcdiff.apply(allocator, source, patch_data); + defer allocator.free(result.output); + try cwd.writeFile(io, .{ .sub_path = args[2], .data = result.output }); + try writer.print("patched {d} -> {d} bytes, {d} windows\n", .{ source.len, result.output.len, result.windows }); + return 0; +} + const TracedCpk = struct { owned_file: ?std.Io.File, view: *View, diff --git a/tools/cpk/src/vcdiff.zig b/tools/cpk/src/vcdiff.zig new file mode 100644 index 00000000..37aa47eb --- /dev/null +++ b/tools/cpk/src/vcdiff.zig @@ -0,0 +1,218 @@ +//! VCDIFF (RFC 3284) as xdelta3 writes it, for patches shipped with mods: +//! default code table, no secondary compression. Patches are community files: +//! every length and address is checked. +const std = @import("std"); + +pub const max_output_size: u64 = 1024 * 1024 * 1024; + +const Kind = enum { noop, add, run, copy }; +const Op = struct { kind: Kind = .noop, size: u8 = 0, mode: u8 = 0 }; +const Entry = struct { first: Op = .{}, second: Op = .{} }; + +/// RFC 3284 section 5.6. +const code_table: [256]Entry = blk: { + @setEvalBranchQuota(10000); + var table: [256]Entry = @splat(.{}); + table[0].first = .{ .kind = .run }; + for (0..18) |size| table[1 + size].first = .{ .kind = .add, .size = size }; + var index: usize = 19; + for (0..9) |mode| { + table[index].first = .{ .kind = .copy, .mode = mode }; + index += 1; + for (4..19) |size| { + table[index].first = .{ .kind = .copy, .size = size, .mode = mode }; + index += 1; + } + } + for (0..6) |mode| for (1..5) |add| for (4..7) |copy| { + table[index] = .{ .first = .{ .kind = .add, .size = add }, .second = .{ .kind = .copy, .size = copy, .mode = mode } }; + index += 1; + }; + for (6..9) |mode| for (1..5) |add| { + table[index] = .{ .first = .{ .kind = .add, .size = add }, .second = .{ .kind = .copy, .size = 4, .mode = mode } }; + index += 1; + }; + for (0..9) |mode| { + table[index] = .{ .first = .{ .kind = .copy, .size = 4, .mode = mode }, .second = .{ .kind = .add, .size = 1 } }; + index += 1; + } + break :blk table; +}; + +const Reader = struct { + data: []const u8, + position: usize = 0, + + fn byte(self: *Reader) !u8 { + if (self.position >= self.data.len) return error.TruncatedPatch; + self.position += 1; + return self.data[self.position - 1]; + } + + fn take(self: *Reader, size: u64) ![]const u8 { + if (size > self.data.len - self.position) return error.TruncatedPatch; + const start = self.position; + self.position += @intCast(size); + return self.data[start..self.position]; + } + + /// Big-endian base 128, the high bit of each byte means more follow. + fn varint(self: *Reader) !u64 { + var value: u64 = 0; + while (true) { + const next = try self.byte(); + if (value >> 57 != 0) return error.BadPatch; + value = (value << 7) | (next & 0x7F); + if (next & 0x80 == 0) return value; + } + } +}; + +const AddressCache = struct { + near: [4]u64 = @splat(0), + next_near: usize = 0, + same: [3 * 256]u64 = @splat(0), + + fn decode(self: *AddressCache, addresses: *Reader, here: u64, mode: u8) !u64 { + const address = switch (mode) { + 0 => try addresses.varint(), + 1 => std.math.sub(u64, here, try addresses.varint()) catch return error.BadPatch, + 2...5 => std.math.add(u64, self.near[mode - 2], try addresses.varint()) catch return error.BadPatch, + 6...8 => self.same[(@as(usize, mode) - 6) * 256 + try addresses.byte()], + else => return error.BadPatch, + }; + self.near[self.next_near] = address; + self.next_near = (self.next_near + 1) % self.near.len; + self.same[address % self.same.len] = address; + return address; + } +}; + +fn adler32(data: []const u8) u32 { + var a: u32 = 1; + var b: u32 = 0; + for (data) |value| { + a = (a + value) % 65521; + b = (b + a) % 65521; + } + return (b << 16) | a; +} + +const Window = struct { + segment: []const u8, + target: []u8, + written: usize = 0, + data: Reader, + instructions: Reader, + addresses: Reader, + cache: AddressCache = .{}, + + fn apply(self: *Window, op: Op) !void { + if (op.kind == .noop) return; + const size = if (op.size != 0) op.size else try self.instructions.varint(); + if (size > self.target.len - self.written) return error.BadPatch; + const count: usize = @intCast(size); + switch (op.kind) { + .noop => unreachable, + .add => @memcpy(self.target[self.written..][0..count], try self.data.take(size)), + .run => @memset(self.target[self.written..][0..count], try self.data.byte()), + .copy => { + const here = self.segment.len + self.written; + const address = try self.cache.decode(&self.addresses, here, op.mode); + if (address >= here) return error.BadPatch; + // Byte by byte: a copy may read what it has just written. + var from: usize = @intCast(address); + for (self.target[self.written..][0..count], self.written..) |*out, position| { + if (from >= self.segment.len + position) return error.BadPatch; + out.* = if (from < self.segment.len) self.segment[from] else self.target[from - self.segment.len]; + from += 1; + } + }, + } + self.written += count; + } +}; + +pub const Result = struct { output: []u8, windows: u64 }; + +/// Caller frees `output`. +pub fn apply(allocator: std.mem.Allocator, source: []const u8, patch: []const u8) !Result { + var input: Reader = .{ .data = patch }; + if (!std.mem.eql(u8, try input.take(4), "\xD6\xC3\xC4\x00")) return error.NotVcdiff; + const header = try input.byte(); + if (header & 0x03 != 0) return error.UnsupportedCompression; // secondary compressor, custom code table + if (header & 0x04 != 0) _ = try input.take(try input.varint()); // xdelta: file names + if (header & ~@as(u8, 0x07) != 0) return error.BadPatch; + + var output: std.ArrayList(u8) = .empty; + errdefer output.deinit(allocator); + var windows: u64 = 0; + while (input.position < patch.len) : (windows += 1) { + const indicator = try input.byte(); + const from_source = indicator & 0x01 != 0; + const from_target = indicator & 0x02 != 0; + if (from_source and from_target or indicator & ~@as(u8, 0x07) != 0) return error.BadPatch; + var segment: []const u8 = ""; + var segment_start: usize = 0; + if (from_source or from_target) { + const size = try input.varint(); + const position = try input.varint(); + const end = std.math.add(u64, position, size) catch return error.BadPatch; + const base = if (from_source) source else output.items; + if (end > base.len) return error.BadPatch; + segment_start = @intCast(position); + segment = base[segment_start..@intCast(end)]; + } + _ = try input.varint(); // length of the delta encoding + const target_size = try input.varint(); + if (target_size > max_output_size - output.items.len) return error.TooLarge; + if (try input.byte() != 0) return error.UnsupportedCompression; + const data_size = try input.varint(); + const instructions_size = try input.varint(); + const addresses_size = try input.varint(); + var checksum: ?u32 = null; + if (indicator & 0x04 != 0) checksum = std.mem.readInt(u32, (try input.take(4))[0..4], .big); + const data = try input.take(data_size); + const instructions = try input.take(instructions_size); + const addresses = try input.take(addresses_size); + + // A window may copy from output, which growing the list would move. + const target = try allocator.alloc(u8, @intCast(target_size)); + defer allocator.free(target); + var window: Window = .{ + .segment = segment, + .target = target, + .data = .{ .data = data }, + .instructions = .{ .data = instructions }, + .addresses = .{ .data = addresses }, + }; + while (window.instructions.position < instructions.len) { + const entry = code_table[try window.instructions.byte()]; + try window.apply(entry.first); + try window.apply(entry.second); + } + if (window.written != target.len) return error.BadPatch; + if (checksum) |expected| if (adler32(target) != expected) return error.ChecksumMismatch; + try output.appendSlice(allocator, target); + } + return .{ .output = try output.toOwnedSlice(allocator), .windows = windows }; +} + +const testing = std.testing; + +test "default code table landmarks from RFC 3284" { + try testing.expectEqual(Kind.run, code_table[0].first.kind); + try testing.expectEqual(@as(u8, 17), code_table[18].first.size); + try testing.expectEqual(Op{ .kind = .copy, .size = 0, .mode = 0 }, code_table[19].first); + try testing.expectEqual(Op{ .kind = .copy, .size = 18, .mode = 8 }, code_table[162].first); + try testing.expectEqual(Op{ .kind = .add, .size = 1 }, code_table[163].first); + try testing.expectEqual(Op{ .kind = .copy, .size = 4, .mode = 0 }, code_table[163].second); + try testing.expectEqual(Op{ .kind = .copy, .size = 6, .mode = 5 }, code_table[234].second); + try testing.expectEqual(Op{ .kind = .copy, .size = 4, .mode = 6 }, code_table[235].second); + try testing.expectEqual(Op{ .kind = .copy, .size = 4, .mode = 8 }, code_table[255].first); + try testing.expectEqual(Op{ .kind = .add, .size = 1 }, code_table[255].second); +} + +test "adler32" { + try testing.expectEqual(@as(u32, 0x11E60398), adler32("Wikipedia")); +} diff --git a/tools/cpk/test_cli.py b/tools/cpk/test_cli.py index 5f284f86..08c0d186 100644 --- a/tools/cpk/test_cli.py +++ b/tools/cpk/test_cli.py @@ -150,6 +150,34 @@ def fnv(data): return value +def varint(value): + out = [value & 0x7F] + value >>= 7 + while value: + out.insert(0, 0x80 | (value & 0x7F)) + value >>= 7 + return bytes(out) + + +def adler32(data): + a, b = 1, 0 + for byte in data: + a = (a + byte) % 65521 + b = (b + a) % 65521 + return b << 16 | a + + +def vcdiff_window(source_size, target, data, instructions, addresses, checksum=None): + body = varint(len(target)) + b"\0" + varint(len(data)) + varint(len(instructions)) + varint(len(addresses)) + body += struct.pack(">I", adler32(target) if checksum is None else checksum) + data + instructions + addresses + return bytes([1 | 4]) + varint(source_size) + varint(0) + varint(len(body)) + body + + +def vcdiff(*windows, header=4): + app = b"new//old/" + return b"\xD6\xC3\xC4\0" + bytes([header]) + varint(len(app)) + app + b"".join(windows) + + 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") @@ -427,6 +455,65 @@ def test_diff_mutated_mod_never_crashes(self): result = run("diff", path, base) self.assertIn(result.returncode, (0, 1, 2), (round_number, result.stderr[-400:])) + def patch_fixture(self): + source = b"0123456789" + # ADD "ab" (size in the opcode), COPY 4 from address 2 (mode 0, size 4), + # RUN 3 of "z", ADD+COPY pair: ADD "!" then COPY 4 from HERE-5, overlapping the output. + target = b"ab" + b"2345" + b"zzz" + b"!" + target += (bytes(source) + target)[len(source) + len(target) - 5:][:4] + instructions = bytes([3, 19 + 1, 0, 3, 163]) + data = b"ab" + b"z" + b"!" + addresses = varint(2) + varint(0) + return source, target, data, instructions, addresses + + def test_patch(self): + source, target, data, instructions, addresses = self.patch_fixture() + # The pair uses mode 0 here: an absolute address in source + target. + addresses = varint(2) + varint(len(source) + 5) + target = b"ab2345zzz!" + (source + b"ab2345zzz!")[len(source) + 5:][:4] + (self.dir / "source").write_bytes(source) + (self.dir / "patch").write_bytes(vcdiff(vcdiff_window(len(source), target, data, instructions, addresses))) + result = run("patch", self.dir / "source", self.dir / "patch", self.dir / "out") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.dir / "out").read_bytes(), target) + self.assertIn("1 windows", result.stdout) + + def test_patch_refuses_bad_input(self): + source, target, data, instructions, addresses = self.patch_fixture() + addresses = varint(2) + varint(len(source) + 5) + target = b"ab2345zzz!" + (source + b"ab2345zzz!")[len(source) + 5:][:4] + window = vcdiff_window(len(source), target, data, instructions, addresses) + (self.dir / "source").write_bytes(source) + good = vcdiff(window) + cases = { + "checksum": vcdiff(vcdiff_window(len(source), target, data, instructions, addresses, checksum=1)), + "secondary": vcdiff(window, header=5), + "not vcdiff": b"nope" + good[4:], + "truncated": good[:-3], + "address past here": vcdiff(vcdiff_window(len(source), target, data, instructions, varint(2) + varint(500))), + "segment past source": vcdiff(vcdiff_window(len(source) + 1, target, data, instructions, addresses)), + } + for name, patch in cases.items(): + with self.subTest(name): + (self.dir / "patch").write_bytes(patch) + self.assert_clean_error(run("patch", self.dir / "source", self.dir / "patch", self.dir / "out")) + self.assert_clean_error(run("patch", self.dir / "source")) + + def test_patch_mutated_never_crashes(self): + source, target, data, instructions, addresses = self.patch_fixture() + addresses = varint(2) + varint(len(source) + 5) + target = b"ab2345zzz!" + (source + b"ab2345zzz!")[len(source) + 5:][:4] + good = vcdiff(vcdiff_window(len(source), target, data, instructions, addresses)) + (self.dir / "source").write_bytes(source) + rng = random.Random(81) + for round_number in range(150): + mutated = bytearray(good) + for _ in range(rng.randrange(1, 5)): + mutated[rng.randrange(4, len(mutated))] = rng.randrange(256) + (self.dir / "patch").write_bytes(mutated) + result = run("patch", self.dir / "source", self.dir / "patch", self.dir / "out") + self.assertIn(result.returncode, (0, 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))