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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <source> <patch.xdelta> <output>` 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/`.
Expand Down
4 changes: 3 additions & 1 deletion docs/CURRENT_STATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
4 changes: 4 additions & 0 deletions tools/cpk/src/cpk.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions tools/cpk/src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 <image.iso> <cpk path on image> [substring]
Expand All @@ -10,6 +11,7 @@ const usage =
\\ p3p-cpk extract <file.cpk> [substring] <out dir>
\\ p3p-cpk diff <mod.cpk|mod dir> <base.cpk>
\\ p3p-cpk diff <mod.cpk|mod dir> <image.iso> <cpk path on image>...
\\ p3p-cpk patch <source> <patch.xdelta> <output>
\\ p3p-cpk check-trace <image.iso> <io-trace.csv> [prefix=hostdir ...]
\\ p3p-cpk --help | --version
\\list prints every file: dir/name, offset, stored and extracted size, compressed.
Expand All @@ -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.
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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,
Expand Down
218 changes: 218 additions & 0 deletions tools/cpk/src/vcdiff.zig
Original file line number Diff line number Diff line change
@@ -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"));
}
Loading