packing/extract: reject truncated PFS0 payloads (PR #2122)

Check each entry against the original PFS0 payload before mounting or
adding a virtual filename terminator. Extraction reports a named
error and exits 3 when the package declares bytes it does not contain.

Rebuild both native extractor slices and test valid boundaries,
truncation, overflow and the damaged-input diagnostic. Update the
packing reference and link it from the Diablo II note.

Co-authored-by: Eliran Zach <[email protected]>
This commit is contained in:
seeddsandEliran Zach committed 2026-11-18 02:09:41 +08:00
1 parent f15d65850c
commit e4b0d9b75d
7 files changed
+67 -2

No files matched your search

+2
View File
@@ -31,6 +31,8 @@ On the Mac (2026-11-12, from a fresh save): the Blizzard logo movie, the title,
General tool changes first needed here; each applies to every game:
- **Truncated PFS0 payloads** (resolved, package validation): [PFS0 files extend beyond a truncated package](../../../docs/reference/packing.md#pfs0-files-extend-beyond-a-truncated-package).
- **Blizzard's CASC storage and SHAD containers** (`dm/gfx/tools/casc.py`, `casc_jobs` / `casc_shaders` / `shad_shaders` in `shader_split.py`, and `raw_shaders`'s records in `main`): [Blizzard's CASC storage and SHAD containers](../../../docs/reference/shaders.md#blizzards-casc-storage-and-shad-containers).
Game behaviour:
+15 -2
View File
@@ -50,6 +50,7 @@ static class P {
}
try { return Run(a); }
catch (KeysMissing e) { Console.WriteLine($"[RED] {e.Message}"); return 6; }
catch (PackageDamaged e) { Console.WriteLine($"[RED] the NSP is damaged: {e.Message}"); return 3; }
// The tables a filesystem opens from fail the hash check (Mario & Luigi: Brothership's update: its Program NCA does not match its content ID): no file can be listed, so no file can be
// named or written as read. Exit code 3, as for damaged files, not an unhandled exception's stack trace
catch (HorizonResultException e) when (HashError(e)) {
@@ -275,6 +276,7 @@ static class P {
}
}
sealed class PackageDamaged : Exception { public PackageDamaged(string m) : base(m) { } }
internal static IStorage PackageStorage(IStorage source) {
source.GetSize(out long size).ThrowIfFailure();
if (size < 16) throw new InvalidDataException("truncated PFS0 header");
@@ -287,6 +289,13 @@ static class P {
byte[] header = new byte[(int)headerSize + 1];
source.Read(0, header.AsSpan(0, (int)headerSize)).ThrowIfFailure();
for (int i = 0; i < count; i++) {
ulong fileOffset = BinaryPrimitives.ReadUInt64LittleEndian(header.AsSpan(16 + 24 * i));
ulong fileSize = BinaryPrimitives.ReadUInt64LittleEndian(header.AsSpan(16 + 24 * i + 8));
ulong available = (ulong)(size - headerSize);
// Check against the original payload before the optional virtual NUL is inserted.
// Subtraction avoids wrapping a damaged 64-bit offset/size into an apparently valid range.
if (fileOffset > available || fileSize > available - fileOffset)
throw new InvalidDataException($"PFS0 entry {i} lies outside the package payload (offset {fileOffset}, size {fileSize}, available {available})");
uint offset = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(16 + 24 * i + 16));
if (offset >= strings) throw new InvalidDataException("PFS0 file-name offset outside the string table");
}
@@ -305,13 +314,17 @@ static class P {
// first 0x4000 bytes (the NCA header and section headers, which nsz keeps as they were): enough for the key check, not for reading
static List<Nca> OpenNsp(KeySet ks, string path, ContentMetaType? only = null, ulong? id = null, bool ncz = false) {
IFileSystem pfs; var st0 = new LocalStorage(path, FileAccess.Read);
byte[] magic = new byte[4]; st0.Read(0x100, magic).ThrowIfFailure();
st0.GetSize(out long packageSize).ThrowIfFailure();
byte[] magic = new byte[4]; if (packageSize >= 0x104) st0.Read(0x100, magic).ThrowIfFailure();
if (System.Text.Encoding.ASCII.GetString(magic) == "HEAD") { // XCI: the card header's magic at 0x100
var xci = new Xci(ks, st0);
if (!xci.HasPartition(XciPartitionType.Secure)) throw new Exception($"no secure partition in {path}");
pfs = xci.OpenPartition(XciPartitionType.Secure);
} else {
var p = new PartitionFileSystem(); p.Initialize(PackageStorage(st0)).ThrowIfFailure(); pfs = p;
IStorage storage;
try { storage = PackageStorage(st0); }
catch (InvalidDataException e) { throw new PackageDamaged($"{Path.GetFileName(path)}: {e.Message}; copy or download the complete package again"); }
var p = new PartitionFileSystem(); p.Initialize(storage).ThrowIfFailure(); pfs = p;
}
var ncas = new List<Nca>(); var ids = new List<string>(); // ids: content IDs (the file names' hex)
foreach (DirectoryEntryEx e in pfs.EnumerateEntries("*", SearchOptions.Default)) {
Binary file not shown.
+40
View File
@@ -3,6 +3,8 @@ using System.Buffers.Binary;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Path = System.IO.Path;
using LibHac.Common;
using LibHac.Fs;
using LibHac.Fs.Fsa;
@@ -51,6 +53,44 @@ class Pfs0StorageTests {
try { P.PackageStorage(storage); throw new Exception("invalid header accepted"); }
catch (InvalidDataException) { }
}
foreach (bool terminated in new[] {true, false}) {
byte[] shortPayload = Package(terminated)[..^1];
using var shortStorage = new MemoryStorage(shortPayload);
try { P.PackageStorage(shortStorage); throw new Exception("truncated PFS0 payload accepted"); }
catch (InvalidDataException e) { Check(e.Message.Contains("entry 1")); }
foreach (var range in new[] {(7UL, 0UL), (5UL, 2UL), (ulong.MaxValue, 1UL), (1UL, ulong.MaxValue)}) {
byte[] bad = Package(terminated);
BinaryPrimitives.WriteUInt64LittleEndian(bad.AsSpan(40), range.Item1);
BinaryPrimitives.WriteUInt64LittleEndian(bad.AsSpan(48), range.Item2);
using var storage = new MemoryStorage(bad);
try { P.PackageStorage(storage); throw new Exception("out-of-bounds PFS0 entry accepted"); }
catch (InvalidDataException) { }
}
byte[] edge = Package(terminated);
BinaryPrimitives.WriteUInt64LittleEndian(edge.AsSpan(40), 6);
BinaryPrimitives.WriteUInt64LittleEndian(edge.AsSpan(48), 0);
using var edgeStorage = new MemoryStorage(edge);
using var accepted = P.PackageStorage(edgeStorage); // empty file exactly at EOF is valid
}
// Exercise the production CLI entry, not just its parser, without game files or keys.
string tmp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tmp);
TextWriter saved = Console.Out;
try {
string keys = Path.Combine(tmp, "empty.keys"), nsp = Path.Combine(tmp, "truncated.nsp");
File.WriteAllText(keys, "");
foreach (byte[] bad in new[] {Package(true)[..^1], Package(false)[..^1], "PFS0"u8.ToArray()}) {
File.WriteAllBytes(nsp, bad);
foreach (bool allow in new[] {false, true}) {
string[] args = new[] {keys, "--aoc", nsp, Path.Combine(tmp, "out")};
if (allow) args = args.Append("--allow-damaged").ToArray();
using var log = new StringWriter(); Console.SetOut(log);
int rc = (int)typeof(P).GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] {args});
Console.SetOut(saved);
Check(rc == 3 && log.ToString().Contains("[RED] the NSP is damaged") && log.ToString().Contains("truncated.nsp"));
Check(!Directory.Exists(Path.Combine(tmp, "out")));
}
}
} finally { Console.SetOut(saved); Directory.Delete(tmp, true); }
Console.WriteLine("PFS0 storage checks passed");
}
}
+1
View File
@@ -5,6 +5,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
## Packing
- after the shader build, `build_ipa.sh` stops at `copy shader tables` because `pso_manifest.tsv` does not exist. This also stops the shell's game-framework build. → [An iOS build stops when the profile has no prewarm seed list](../reference/packing.md#an-ios-build-stops-when-the-profile-has-no-prewarm-seed-list)
- `nx_extract --aoc` aborts with an unhandled `ResultFsOutOfRange (2002-3005)` when a package's file table declares bytes that are not present. → [PFS0 files extend beyond a truncated package](../reference/packing.md#pfs0-files-extend-beyond-a-truncated-package)
- package identification stops with `ValueError: subsection not found` in `pfs0_names`, or LibHac reports `ResultFsPathNotFound` opening the last file of an NSP. → [PFS0 file-name table missing its final NUL](../reference/packing.md#pfs0-file-name-table-missing-its-final-nul)
- `no base game, only update packages: pack the base game and its update into one NUP`, even when the update carries the complete game's files (issue #1195). → [A NUP with complete standalone updates stops at "no base game"](../reference/packing.md#a-nup-with-complete-standalone-updates-stops-at-no-base-game)
- `[RED] a NUP packs only a game with a profile, and <title ID> has none: the survey that makes a provisional profile reads NSPs`, or the same line for a dump folder (issue #1265). A folder holding `exefs/` and `romfs/` directly, or only `updates/<version>/`, was not taken for a dump at all: the script asks for `prod.keys`, then stops with `no NSP with a readable title ID`. → [A NUP or a dump of a game with no profile stops before the survey](../reference/packing.md#a-nup-or-a-dump-of-a-game-with-no-profile-stops-before-the-survey)
+1
View File
@@ -433,6 +433,7 @@ What the script does:
0. Before it extracts anything it checks the environment (`check_prereqs`, `check_native_python`): the Python modules and tools (glslang too, which an OpenGL game needs), the iOS SDK for an iPhone build (a separate download in Xcode's Components), the Metal compiler, and the shader translator, which it starts once with `--source-sha`, so a translator that does not start stops it here, not as an empty `xlate_source` at the shader step. A Python under Rosetta (an Intel Homebrew's) stops it too: the tools it starts run as Intel code, the Mac host's compile among them. No .NET is needed: the translator and `nx_extract` are committed native executables, and the script checks that `nx_extract` was built from the sources beside it ([native tools](reference/packing.md#building-needed-net-and-finding-its-runtime-kept-failing)).
1. It finds the game profile from the title ID. Every package's title ID and version are its content metas', read with the keys through `nx_extract --contents`, never its file name ([An update is taken for the version in its file name](reference/packing.md#an-update-is-taken-for-the-version-in-its-file-name)). The update is optional: it packs the newest version in the folder (`-p` / `PACKAGE` picks another).
2. It extracts ExeFS and streams the merged, integrity-checked RomFS directly into `<id>_build/extract/<version>/RomFS.img`. No RomFS folder or individual resource files are written. Shader scanners, profile discovery and NRO collection read bounded file ranges from that image through `dm/tools/romfs.py`; archive readers map only the archive's range. This requires Python 3.12 or newer. An old folder extraction is replaced atomically after the new extraction succeeds. Each DLC similarly becomes `aoc/<index>.img`.
A PFS0 package whose file table extends beyond its payload stops before extraction with a named `[RED] the NSP is damaged` diagnostic and exit code 3. `--allow-damaged` does not bypass missing container bytes; replace the truncated package ([PFS0 payload bounds](reference/packing.md#pfs0-files-extend-beyond-a-truncated-package)).
3. It rewrites the code modules, checking each build ID against the profile. A version the profile does not register (the base game alone when the profile was brought up on an update, another update, or files whose build IDs differ), or one whose shader tables need a version that is not in the folder, is built from a profile derived from it in `<id>_build/profile/<id>/` (under `--work-dir`, `<work dir>/profile/<id>/`): the profile's keys, that version's build row, and shader tables, chain header, `c1_full.tsv` and `cb_extent.tsv` made from that version's own files (as for a provisional profile, without the heap check; with the address region check below). The rewriter's cuts and the host's fixes for a registered build do not reach a module of another build; the script says which modules those are. A title ID no profile has is first looked up by build: when its `main` (of the base game with its newest update, else of the base game alone, read from a code-only extraction) is a build a profile registers, a regional release of the same build (Advance Wars 1+2: Re-Boot Camp under `0100300012FFF000`, issue #114), it packs from a profile derived from that one, with the folder's title ID and `main.npdm`'s program ID (`same_build`, `game.py` `by_build`); only otherwise is it surveyed. A provisional profile (a game without one in `dm/games`) then gets `mem_used` from the rewritten modules, and, when the game has virtual address memory and sets a heap, a heap check: the Mac host is built into `<id>_build/tools/dmhost` and the game boots in it until its first heap request (a few seconds, log `<id>_build/logs/heap_check.log`), which sizes the heap region, and boots again on the resized region to reach the app pool check behind the request (see [dm/games/README.md](../dm/games/README.md), Adding a game). For a game with virtual address memory, with a provisional or a derived profile, a second boot, the address region check, runs with a Switch-sized alias region for 15 s into `nnMain` (log `<id>_build/logs/region_check.log`, table `regions.tsv`) and reports the address regions the game takes, who asks for each and where they reach against the profile's alias region, in red when past it; when the regions made after a `StandardAllocator` region need more room than the host's cap leaves them, it sets `stdalloc_cap` in the profile ([memory.md, Measuring address regions and commits](reference/memory.md#measuring-address-regions-and-commits)).
4. For a game whose `main` holds GLSL sources and calls `glslcCompile` (Three Houses), it captures the shaders the game compiles at run time, which no game file holds. It builds the Mac host into `<id>_build/tools/dmhost` and boots the game in it, headless and silent, with `DM_GLSLC_CAPTURE` pointing at `<id>_build/extract/<version>/glslc_capture`. The save, temporary storage and log all stay in `<id>_build/`. It stops the game as soon as every capture file named in the profile's shader map is there (Three Houses: 9, about a second after launch), and gives up after 30 s. A folder that already holds them all is reused.
A Vulkan game without SPIR-V files in its RomFS (Super Mario Galaxy) gets the same kind of run: the game boots in the Mac host with `DM_VK_CAPTURE` pointing at `<id>_build/extract/<version>/vk_capture` until every SPIR-V key in the profile's `vk_capture.tsv` is there (Galaxy: 3,089, about 7 s after launch), and gives up after 120 s.
+8
View File
@@ -9,6 +9,14 @@
- **Fix:** copy a recorded seed list when present and report its absence otherwise. Required shader tables and a failed copy of an existing seed list still stop the build. No seed records are invented, and shader cache inputs are unchanged. This does not change shader rebuild or resume decisions.
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md), [NX2Apple issue #922](https://github.com/LNPANDY/NX2Apple/issues/922). The separate report of repeated shader compilation remains open.
### PFS0 files extend beyond a truncated package
- **Symptom:** `nx_extract --aoc` aborts with an unhandled `ResultFsOutOfRange (2002-3005)` when a package's file table declares bytes that are not present.
- **Cause:** the PFS0 header and name table were checked, but each payload-relative file offset and size was trusted. LibHac later tried to read the missing bytes, before the extractor could issue its normal damaged-package diagnostic.
- **Fix:** `PackageStorage` validates every file range against the original payload before mounting or adding a virtual final name terminator. The size check uses subtraction to avoid 64-bit overflow, and accepts an empty file at EOF. `OpenNsp` probes the XCI header only when enough bytes exist, then routes malformed PFS0 headers and payload ranges to a named `[RED] the NSP is damaged` message and exit code 3. `--allow-damaged` cannot supply missing container bytes, so it does not bypass this check. The source is never changed.
- **Found on:** [Diablo II: Resurrected](../../dm/games/0100726014352000/README.md), whose separate licence-only DLC package was truncated ([issue #2013](https://github.com/seedds/nxnative/issues/2013)). Main now has the shared [CASC/SHAD reader](shaders.md#blizzards-casc-storage-and-shad-containers); that separate shader-discovery fix does not repair missing package bytes. The reported base game alone (v0) remains unchecked, as the game note records.
- **Check:** `dm/tools/tests/test_pfs0_storage.py` exercises synthetic payload truncation, out-of-range and overflowing spans, an empty file at EOF, and the CLI's damaged-input exit with and without `--allow-damaged`, with both normal and missing-final-NUL name tables.
### PFS0 file-name table missing its final NUL
- **Symptom:** package identification stops with `ValueError: subsection not found` in `pfs0_names`, or LibHac reports `ResultFsPathNotFound` opening the last file of an NSP.