From 3970afecc6fc3a952e10ec0db4cc21fa6cb7a71d Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Thu, 26 Nov 2026 11:24:25 -0800 Subject: [PATCH] feat(artifacts): inventory Nintendo Switch NSO and NRO executables offline (#14655) * feat(artifacts): inventory Nintendo Switch NSO and NRO executables offline Detection uses the bytes: NSO0 at the start of the file, or NRO0 at offset 0x10. Inventory records the module id, flags, and MOD0 offset, lists the text, rodata, and data segments, and for an NRO adds the ASET icon, NACP, and RomFS when that trailer is present. Compressed NSO segments are raw LZ4 blocks decoded under artifact_limits.expanded_bytes, with the stored size and the decoded size both reserved before allocation, and hash_status is match, mismatch, not-checked, or unavailable. Truncated, over-budget, and invalid-LZ4 entries stay listed while their bytes are refused, and a positional reader can stream those decoded bytes instead of the stored file range. * fix(artifacts): keep valid NRO assets when one ASET range is unsafe * docs: move the Switch executables guide under guides/firmware * Address review feedback * Address review feedback * fix(artifacts): unify Switch NSO budget admission and test deadlines - Remove the duplicate NSO decoded-only budget pre-check in #prepareNso so #admitStoredInput owns all compressed-segment admission and reports an accurate required_value covering both stored and decoded bytes. - Use testWaitDeadline() in SwitchExecutableArtifactReader.boundaries.test.ts instead of a hardcoded 2_000 ms timeout. - Reuse tests/fixtures/lz4LiteralBlock.ts in switchExecutable.fixture.ts. * test(domain): throw typed parse errors in Switch parser tests and fix doc formatting --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: Matt Van Horn Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- .../references/native-and-artifacts.md | 10 + .../references/native-and-artifacts.md | 10 + docs/.vitepress/documentation.ts | 5 + docs/README.md | 1 + docs/getting-started/cli.md | 10 + docs/guides/firmware/switch-executables.md | 92 +++ docs/reference/limits-and-recovery.md | 12 +- docs/reference/supported-targets.md | 1 + .../binary/TargetFormatVocabularies.test.ts | 2 + src/artifacts/Iso9660ArtifactReader.test.ts | 5 +- src/artifacts/OwnedArtifactStream.ts | 13 +- src/artifacts/PositionalArtifactReader.ts | 25 +- ...xecutableArtifactReader.boundaries.test.ts | 721 ++++++++++++++++++ .../SwitchExecutableArtifactReader.test.ts | 187 +++++ .../SwitchExecutableArtifactReader.ts | 612 +++++++++++++++ src/artifacts/artifactFormats.ts | 22 + src/artifacts/inventory/scanReader.ts | 5 +- .../analysisView/artifactInventoryView.ts | 2 + src/domain/artifactFormatMetadata.ts | 12 + src/domain/artifactFormatRecognition.ts | 5 + src/domain/artifactGraph.ts | 4 + .../formatMetadata/packageAndGameMetadata.ts | 61 +- src/domain/switchExecutable.fixture.ts | 119 +++ src/domain/switchExecutable.test.ts | 282 +++++++ src/domain/switchExecutable.ts | 328 ++++++++ src/domain/targetFormats.ts | 2 + src/resources/ArtifactReader.ts | 2 + 27 files changed, 2535 insertions(+), 15 deletions(-) create mode 100644 docs/guides/firmware/switch-executables.md create mode 100644 src/artifacts/SwitchExecutableArtifactReader.boundaries.test.ts create mode 100644 src/artifacts/SwitchExecutableArtifactReader.test.ts create mode 100644 src/artifacts/SwitchExecutableArtifactReader.ts create mode 100644 src/domain/switchExecutable.fixture.ts create mode 100644 src/domain/switchExecutable.test.ts create mode 100644 src/domain/switchExecutable.ts diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index 68314fba95..2a3ad15ec6 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -1018,6 +1018,16 @@ and DONT_CARE blocks are written as zeros. The expanded child is classified again. See [Android sparse images](https://github.com/morluto/rea/blob/main/docs/guides/firmware/android-sparse-image.md). +Nintendo Switch NSO modules (`NSO0`) and NRO executables (`NRO0` at `0x10`) +use the same inspection and extraction workflows, without running or +disassembling them. Root metadata holds the `module_id` build id and MOD0 +offset for matching crash logs. Entries are the text, rodata and data +segments, plus NRO `ASET` icon, NACP and RomFS. Compressed NSO segments are +LZ4-decoded within `artifact_limits.expanded_bytes` and their SHA-256 compared +with the header (`hash_status`). Truncated or over-budget segments stay listed +with unavailable content. See +[Switch executables](https://github.com/morluto/rea/blob/main/docs/guides/firmware/switch-executables.md). + ## ESP images For an ESP32-family app or bootloader image, `open_binary` then diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md index 68314fba95..2a3ad15ec6 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -1018,6 +1018,16 @@ and DONT_CARE blocks are written as zeros. The expanded child is classified again. See [Android sparse images](https://github.com/morluto/rea/blob/main/docs/guides/firmware/android-sparse-image.md). +Nintendo Switch NSO modules (`NSO0`) and NRO executables (`NRO0` at `0x10`) +use the same inspection and extraction workflows, without running or +disassembling them. Root metadata holds the `module_id` build id and MOD0 +offset for matching crash logs. Entries are the text, rodata and data +segments, plus NRO `ASET` icon, NACP and RomFS. Compressed NSO segments are +LZ4-decoded within `artifact_limits.expanded_bytes` and their SHA-256 compared +with the header (`hash_status`). Truncated or over-budget segments stay listed +with unavailable content. See +[Switch executables](https://github.com/morluto/rea/blob/main/docs/guides/firmware/switch-executables.md). + ## ESP images For an ESP32-family app or bootloader image, `open_binary` then diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index 8fb8509c67..a4d44f6af0 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -543,6 +543,11 @@ export const documentationSections = [ source: "tar-archives.md", route: "/tar-archives", }, + { + text: "Nintendo Switch NSO and NRO executables", + source: "guides/firmware/switch-executables.md", + route: "/switch-executables", + }, { text: "GPU asset headers: DDS, GLB, KTX and KTX2", source: "gpu-asset-headers.md", diff --git a/docs/README.md b/docs/README.md index 3c2a82d3c6..d44aec40f9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -137,6 +137,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages. - [WeChat mini-program wxapkg archives](wxapkg.md) - [ISO 9660 disc images](guides/firmware/iso9660-images.md) - [tar and gzip-compressed tar archives](tar-archives.md) +- [Nintendo Switch NSO and NRO executables](guides/firmware/switch-executables.md) - [GPU asset headers: DDS, GLB, KTX and KTX2](gpu-asset-headers.md) ## WebAssembly diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index ce7cb82c40..421641dd9d 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -465,6 +465,16 @@ rea extract-artifact ./installer.iso --json See [ISO 9660 disc images](../guides/firmware/iso9660-images.md) for volume facts, Joliet names, multi-extent and interleaved files, and what is not decoded. +Inventory and extract a Nintendo Switch NSO module or NRO executable: + +```sh +rea inspect-artifact ./main.nso --json +rea extract-artifact ./main.nso --json +``` + +See [Switch executables](../guides/firmware/switch-executables.md) for header facts, segment +hashes, LZ4 decompression limits and NRO assets. + Inventory and extract a uClinux bFLT flat executable: ```sh diff --git a/docs/guides/firmware/switch-executables.md b/docs/guides/firmware/switch-executables.md new file mode 100644 index 0000000000..edc5dabec4 --- /dev/null +++ b/docs/guides/firmware/switch-executables.md @@ -0,0 +1,92 @@ +# Nintendo Switch NSO and NRO executables + +`inspect-artifact` and `extract-artifact` read Nintendo Switch NSO modules +and NRO homebrew executables without running, patching or disassembling +them. The reader reports the header facts that pair a module with crash logs +and patches, splits the file into its text, rodata and data segments, and +for NRO lists the icon, NACP and RomFS ranges in the `ASET` trailer. + +Detection uses the bytes, not the file name. A file is `nso` when it starts +with `NSO0`, and `nro` when `NRO0` sits at offset `0x10`. + +## What inventory reports + +The root occurrence's `format_metadata` (`kind: "switch-executable"`) +records: + +- `format`: `nso` or `nro`. +- `version`, `flags` and, for NSO, `unknown_flags`: flag bits outside the six + that mark per-segment LZ4 compression and hash checks. Unknown bits are + reported and add a limitation; they are not interpreted. +- `module_id`: the 32-byte build id, as lowercase hex. +- `bss_size`, and the `embedded`, `dynstr` and `dynsym` offset and size pairs + as the header declares them. +- `mod0_offset`: the MOD0 header offset. For NSO it is read from the loaded + text at `text+4` and is relative to the start of text; `mod0_present` is + `null`. For NRO it is the header field at file offset `0x4`, relative to the + start of the file, and `mod0_present` says whether `MOD0` is at that file + offset. +- `image_size` (NRO only) and `asset_section`: the `ASET` offset and version, + or `null` when the NRO has no asset trailer. + +Each entry's `format_metadata` (`kind: "switch-executable-entry"`) records +its `role` (`text`, `rodata`, `data`, `icon`, `nacp`, `romfs`), file offset, +memory offset for segments, stored size and whether it is compressed. Entries +are named `text.bin`, `rodata.bin`, `data.bin`, `assets/icon.jpg`, +`assets/control.nacp` and `assets/romfs.bin`. + +## Compressed segments and hashes + +NSO segments flagged as compressed are raw LZ4 blocks. The reader decodes +them in memory so it can hash and extract the loaded bytes. The stored +compressed bytes and the decompressed bytes are both charged to +`artifact_limits.expanded_bytes` before those buffers are allocated. A +segment that would exceed the remaining allowance is still listed with its +declared sizes, its +`hash_status` is `unavailable`, coverage becomes `unknown`, and the entry +carries a limitation that names the setting. Opening it reports the content as +unavailable, with the limit failure as its cause. `artifact_limits.expanded_bytes` +is a per-call parameter (`update_analysis_settings` does not accept it): pass a +larger value on the next `inspect_artifact` or `extract_artifact` call, for +example `rea inspect-artifact main.nso --artifact-limits '{"expanded_bytes":1073741824}' --json`. + +For NSO, `declared_sha256` is the header's SHA-256 of the loaded segment and +`observed_sha256` is the digest REA computed. `hash_status` is: + +- `match` or `mismatch` when the header's flag asks for a check; +- `not-checked` when it does not (both digests are still reported); +- `unavailable` when the segment was truncated, over budget or not valid LZ4. + +A mismatch is a limitation on that entry and on the inventory. It does not +drop the segment. + +## Truncated and malformed files + +A missing magic or a header shorter than `0x100` bytes (NSO) or `0x80` bytes +(NRO) refuses the file as malformed. So does an NSO segment that overlaps the +header, or an NRO segment that ends past the declared image size. + +A segment or asset whose stored range ends past the end of the file is listed +with a `truncated` limitation, and opening it is refused while the rest of the +inventory is kept. An NRO file shorter than its declared image size adds a +limitation. Bytes after an NRO image that do not start with `ASET`, and an +`ASET` header cut short, are reported as uninterpreted; the segments are still +listed. + +## CLI + +```sh +rea inspect-artifact main.nso --json +rea extract-artifact main.nso --json +``` + +The extracted `text.bin` holds the decompressed code that a disassembler can +load at the reported memory offset. + +## Verification scope + +Synthetic fixtures built in the tests cover NSO files with compressed and +stored segments, a hash mismatch, unchecked hashes, unknown flag bits, a +truncated segment, invalid LZ4 data and the expansion allowance, and NRO +files with and without an `ASET` trailer, a truncated asset and trailing +bytes. No retail or homebrew files were checked. diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index 6cd0e6d2f1..67628ee480 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -757,12 +757,12 @@ one domain-owned default policy. See [.NET bundles](../dotnet-bundles.md), [Android sparse images](../guides/firmware/android-sparse-image.md) for format semantics. `artifact_limits.expanded_bytes` selects aggregate plaintext work for ZIP, Bun, -SEA, PCK, ISO 9660, Deno, wxapkg, tar and Android sparse image readers, and -bFLT gzip decompression (which is also capped at a fixed 128 MiB in-memory -inflation ceiling), including repeated readable logical occurrences. -Omission retains each archive's encoded-size-derived default. The .NET bundle -group's own `expanded_bytes` controls its independently enforced bundle -expansion. +SEA, PCK, ISO 9660, Deno, wxapkg, tar and Android sparse image readers, NSO +segment decompression, and bFLT gzip decompression (which is also capped at a +fixed 128 MiB in-memory inflation ceiling), including repeated readable logical +occurrences. Omission retains each archive's encoded-size-derived default. The +.NET bundle group's own `expanded_bytes` controls its independently enforced +bundle expansion. `artifact.member_count` (launch seed `REA_ARTIFACT_MEMBER_COUNT`, default 100,000, range 1 to 2,147,483,647) is the session default for the per-call diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index 54af536c89..bfcbe82364 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -14,6 +14,7 @@ The table lists what REA returns for each target and which tools or host it requ | IL2CPP metadata | Unity global-metadata.dat assembly images, type and method names and index ranges | Built-in static decoding of versions 24, 27, 29, 31 and 39; no Unity required | | Godot PCK | Archive inventory and extraction, original header/directory facts and selected content identities | Built-in static formats 2, 3 and 4; no Godot required | | tar archives | Member inventory and extraction for stored and gzip tar, including `.unitypackage` | Built-in static ustar, pax and GNU headers; [tar archives](../tar-archives.md) | +| Switch NSO/NRO | Module id, segment layout and hashes, NRO icon/NACP/RomFS ranges; LZ4 segments decompressed | Built-in static header parsing; [Switch executables](../guides/firmware/switch-executables.md) | | GPU asset headers | DDS (incl. DX10), GLB, KTX and KTX2 header facts and declared regions; payloads not decoded | Built-in static header parsing; [GPU asset headers](../gpu-asset-headers.md) | | Nintendo DS ROMs | Cartridge header, ARM9/ARM7 load facts, overlay tables and FNT/FAT file ranges; nothing decrypted | Built-in static header and table parsing; [Nintendo DS ROMs](../guides/firmware/nds-roms.md) | | Rust binaries | Embedded cargo-auditable crate names, versions, sources and dependency edges | Built-in static ELF/PE/thin Mach-O/WebAssembly module inspection; [Rust binaries](../rust-binaries.md) | diff --git a/src/application/binary/TargetFormatVocabularies.test.ts b/src/application/binary/TargetFormatVocabularies.test.ts index 4236544f87..16bf327b00 100644 --- a/src/application/binary/TargetFormatVocabularies.test.ts +++ b/src/application/binary/TargetFormatVocabularies.test.ts @@ -133,6 +133,8 @@ const TARGETS: TargetFixtures = { ktx: { ...archive, format: "ktx" }, ktx2: { ...archive, format: "ktx2" }, uimage: { ...archive, format: "uimage" }, + nso: { ...archive, format: "nso" }, + nro: { ...archive, format: "nro" }, "android-boot-image": { ...archive, format: "android-boot-image" }, iso9660: { ...archive, format: "iso9660" }, "android-ota-payload": { ...archive, format: "android-ota-payload" }, diff --git a/src/artifacts/Iso9660ArtifactReader.test.ts b/src/artifacts/Iso9660ArtifactReader.test.ts index 56f0da4073..56de9290b3 100644 --- a/src/artifacts/Iso9660ArtifactReader.test.ts +++ b/src/artifacts/Iso9660ArtifactReader.test.ts @@ -267,7 +267,10 @@ it("concatenates contiguous extents and refuses separated or interleaved ones", const snapshot = await scanCanonicalArtifactInventory(path); expect( snapshot.occurrences.find((row) => row.logical_path === "units.bin"), - ).toMatchObject({ hash_status: "unavailable" }); + ).toMatchObject({ + hash_status: "unavailable", + limitations: [expect.stringContaining("interleaved")], + }); expect( snapshot.occurrences.find((row) => row.logical_path === "big.bin"), ).toMatchObject({ hash_status: "verified" }); diff --git a/src/artifacts/OwnedArtifactStream.ts b/src/artifacts/OwnedArtifactStream.ts index 8baad7e085..eea3ae686d 100644 --- a/src/artifacts/OwnedArtifactStream.ts +++ b/src/artifacts/OwnedArtifactStream.ts @@ -85,20 +85,29 @@ export const ownArtifactStream = ( output.on("error", () => undefined); streams?.add(output); let producerComplete = false; + const canRetireOnAbort = (): boolean => + producerComplete || + (source.readableEnded && !source.errored && output.writableLength > 0); const onAbort = (): void => { // Active I/O and validation own failure precedence; cancellation also - // retires buffered output after production completes. - if (!producerComplete || output.destroyed) return; + // retires buffered output after production completes or when the source + // has ended and output is stalled on readable backpressure before flush. + if (!canRetireOnAbort() || output.destroyed) return; output.destroy(cancellationFailure(signal?.reason)); }; + const onSourceEnd = (): void => { + if (signal?.aborted) onAbort(); + }; const retired = new Promise((resolve) => { output.once("close", () => { streams?.delete(output); signal?.removeEventListener("abort", onAbort); + source.removeListener("end", onSourceEnd); resolve(); }); }); signal?.addEventListener("abort", onAbort, { once: true }); + source.once("end", onSourceEnd); if (signal?.aborted) onAbort(); output.once("finish", () => { // A successful writable finish follows the transform's final validation. diff --git a/src/artifacts/PositionalArtifactReader.ts b/src/artifacts/PositionalArtifactReader.ts index b88dd71dba..1864de94c9 100644 --- a/src/artifacts/PositionalArtifactReader.ts +++ b/src/artifacts/PositionalArtifactReader.ts @@ -166,7 +166,7 @@ export abstract class PositionalArtifactReader< ); // A changed carrier is reported as changed before cached facts refuse // the entry's content. - const { handle } = await this.verifyCarrier(signal); + const carrier = await this.verifyCarrier(signal); this.assertOpen(signal); const refusal = this.contentRefusal(stored); if (refusal !== undefined) throw refusal; @@ -175,14 +175,15 @@ export abstract class PositionalArtifactReader< const lifecycle = this.#lifecycle.member(signal); const { signal: streamSignal, cancellationFailure } = lifecycle; const source = - stored.declaredSize === 0 + this.entrySource(stored, carrier, lifecycle) ?? + (stored.declaredSize === 0 ? Readable.from([]) - : readFileHandleChunks(handle, { + : readFileHandleChunks(carrier.handle, { start: stored.byteOffset, end: stored.byteOffset + stored.declaredSize - 1, signal: streamSignal, cancellationFailure, - }); + })); const output = this.#entryStream(stored, lifecycle); ownArtifactStream(source, output, { scope: this.#scope, @@ -219,6 +220,22 @@ export abstract class PositionalArtifactReader< : undefined; } + /** + * The bytes to serve for an entry that is not one stored carrier range, + * such as a decoded segment; undefined serves the stored range. The source + * must honor the member's signal and report cancellation through its + * `cancellationFailure`. The base reader owns the returned stream like any + * other member: close waits for it, and its length is checked against the + * entry's `declaredSize` after the carrier is rechecked. + */ + protected entrySource( + _entry: Entry, + _carrier: StableRegularFileDescriptor, + _member: ArtifactMemberLifecycle, + ): Readable | undefined { + return undefined; + } + /** Recheck the carrier's identity and borrow its descriptor. */ protected verifyCarrier( signal?: AbortSignal, diff --git a/src/artifacts/SwitchExecutableArtifactReader.boundaries.test.ts b/src/artifacts/SwitchExecutableArtifactReader.boundaries.test.ts new file mode 100644 index 0000000000..cafc4642b5 --- /dev/null +++ b/src/artifacts/SwitchExecutableArtifactReader.boundaries.test.ts @@ -0,0 +1,721 @@ +import { once } from "node:events"; +import { buffer } from "node:stream/consumers"; +import { finished } from "node:stream/promises"; + +import { expect, it, vi } from "vitest"; + +import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js"; +import { createTestTempFile } from "../../tests/fixtures/temporaryDirectory.js"; +import { phaseGate } from "../../tests/support/lifecycleHarness.js"; +import { testWaitDeadline } from "../../tests/support/testWait.js"; +import { resolveArtifactReaderLimits } from "../domain/artifactReaderLimits.js"; +import { openRegularFile } from "../filesystem/RegularFile.js"; +import { + ArtifactEntryContentUnavailable, + ArtifactReaderFailure, +} from "../resources/index.js"; +import { buildNro, buildNso } from "../domain/switchExecutable.fixture.js"; +import { SwitchExecutableArtifactReader } from "./SwitchExecutableArtifactReader.js"; + +const fixture = (bytes: Buffer): Promise => + createTestTempFile("rea-switch-boundary-", "image", bytes); + +const collect = async (reader: SwitchExecutableArtifactReader) => { + const entries = []; + let coverage: { status: string; limitations: readonly string[] } | undefined; + for await (const entry of reader.entries(undefined, { + onCoverage: (value) => (coverage = value), + })) + entries.push(entry); + return { entries, coverage }; +}; + +it("refuses a file without a full NSO header", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture(buildNso().subarray(0, 0x40)), + "nso", + ); + try { + const failure = await collect(reader).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "truncated", + message: expect.stringContaining("truncated"), + parseFailure: { + kind: "truncated", + format: "nso", + offset: 0, + field: "header", + extent: { availableBytes: 0x40, requiredBytes: 0x100 }, + }, + }); + } finally { + await reader.close(); + } +}); + +it("preserves parse failure facts for malformed NSO and NRO headers", async () => { + const overlap = buildNso(); + overlap.writeUInt32LE(0x20, 0x10); + const nsoReader = new SwitchExecutableArtifactReader( + await fixture(overlap), + "nso", + ); + try { + const failure = await collect(nsoReader).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "malformed", + message: expect.stringContaining("overlaps the header"), + parseFailure: { + kind: "malformed", + format: "nso", + offset: 0x10, + field: "text_segment.file_offset", + }, + }); + } finally { + await nsoReader.close(); + } + + const badNro = buildNro(); + badNro.writeUInt32LE(0x1000, 0x34); + const nroReader = new SwitchExecutableArtifactReader( + await fixture(badNro), + "nro", + ); + try { + const failure = await collect(nroReader).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "malformed", + message: expect.stringContaining("past the declared image size"), + parseFailure: { + kind: "malformed", + format: "nro", + offset: 0x30, + field: "data_segment", + }, + }); + } finally { + await nroReader.close(); + } +}); + +it("lists a truncated segment with a limitation and refuses its content", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture(buildNso({ truncateBy: 3 })), + "nso", + ); + try { + const { entries, coverage } = await collect(reader); + const data = entries.find((entry) => entry.path === "data.bin"); + expect(data?.limitations.join(" ")).toContain("truncated"); + expect(data?.formatMetadata).toMatchObject({ hash_status: "unavailable" }); + expect(coverage?.status).toBe("unknown"); + await expect(reader.open(data!)).rejects.toThrow(/truncated/u); + const rodata = entries.find((entry) => entry.path === "rodata.bin"); + expect((await buffer(await reader.open(rodata!))).toString()).toBe( + "read-only data segment", + ); + } finally { + await reader.close(); + } +}); + +it("refuses to decompress a segment over the expansion budget", async () => { + const big = Buffer.alloc(4096, 7); + const path = await fixture( + buildNso({ + segments: [big, Buffer.from("ro"), Buffer.from("rw")], + compress: [true, false, false], + }), + ); + const reader = new SwitchExecutableArtifactReader( + path, + "nso", + undefined, + 1024, + ); + let requiredValue: number | undefined; + try { + const { entries, coverage } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(text?.declaredSize).toBe(4096); + expect(text?.limitations.join(" ")).toContain( + "artifact_limits.expanded_bytes", + ); + expect(text?.formatMetadata).toMatchObject({ hash_status: "unavailable" }); + expect(coverage?.status).toBe("unknown"); + const failure = await reader.open(text!).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactEntryContentUnavailable); + const cause = (failure as Error).cause; + expect(cause).toBeInstanceOf(ArtifactReaderFailure); + const expectedRequired = text!.byteLength! + 4096; + expect(cause).toMatchObject({ + readerLimit: { + parameter: "artifact_limits.expanded_bytes", + effective_value: 1024, + required_value: expectedRequired, + }, + }); + requiredValue = expectedRequired; + } finally { + await reader.close(); + } + const retried = new SwitchExecutableArtifactReader( + path, + "nso", + undefined, + requiredValue, + ); + try { + const { entries, coverage } = await collect(retried); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(coverage?.status).toBe("complete"); + expect(text?.formatMetadata).toMatchObject({ hash_status: "match" }); + expect((await buffer(await retried.open(text!))).equals(big)).toBe(true); + } finally { + await retried.close(); + } +}); + +const storedNso = ( + parts: readonly [ + { readonly stored: number; readonly decoded: number }, + { readonly stored: number; readonly decoded: number }, + { readonly stored: number; readonly decoded: number }, + ], + compress: readonly [boolean, boolean, boolean], +): Buffer => { + const header = Buffer.alloc(0x100); + header.write("NSO0", 0, "latin1"); + let flags = 0; + const payloads: Buffer[] = []; + let fileOffset = 0x100; + parts.forEach((part, index) => { + if (compress[index]) flags |= 1 << index; + const bytes = compress[index] ? part.stored : part.decoded; + header.writeUInt32LE(fileOffset, 0x10 + index * 0x10); + header.writeUInt32LE(index * 0x1000, 0x14 + index * 0x10); + header.writeUInt32LE(part.decoded, 0x18 + index * 0x10); + header.writeUInt32LE(part.stored, 0x60 + index * 4); + payloads.push(Buffer.alloc(bytes, 0xab)); + fileOffset += bytes; + }); + header.writeUInt32LE(flags >>> 0, 0x0c); + return Buffer.concat([header, ...payloads]); +}; + +const empty = { stored: 0, decoded: 0 }; + +it("refuses a stored range larger than the expansion budget before reading it", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + storedNso( + [{ stored: 64 * 1024, decoded: 16 }, empty, empty], + [true, false, false], + ), + ), + "nso", + undefined, + 1024, + ); + try { + const { entries, coverage } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(text?.declaredSize).toBe(16); + expect(text?.limitations.join(" ")).toContain( + "artifact_limits.expanded_bytes", + ); + expect(text?.limitations.join(" ")).not.toContain("LZ4"); + expect(text?.formatMetadata).toMatchObject({ hash_status: "unavailable" }); + expect(coverage?.status).toBe("unknown"); + const failure = await reader.open(text!).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactEntryContentUnavailable); + expect((failure as Error).cause).toMatchObject({ + readerLimit: { + parameter: "artifact_limits.expanded_bytes", + effective_value: 1024, + required_value: 64 * 1024 + 16, + }, + }); + } finally { + await reader.close(); + } +}); + +it("refuses when stored and decoded bytes together exceed the expansion budget", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + storedNso( + [{ stored: 600, decoded: 600 }, empty, empty], + [true, false, false], + ), + ), + "nso", + undefined, + 1000, + ); + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(text?.limitations.join(" ")).toContain( + "artifact_limits.expanded_bytes", + ); + expect(text?.limitations.join(" ")).not.toContain("LZ4"); + const failure = await reader.open(text!).catch((cause: unknown) => cause); + expect((failure as Error).cause).toMatchObject({ + readerLimit: { + parameter: "artifact_limits.expanded_bytes", + effective_value: 1000, + required_value: 1200, + }, + }); + } finally { + await reader.close(); + } +}); + +it("charges a segment's stored bytes against the budget shared with later segments", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + storedNso( + [{ stored: 800, decoded: 4 }, { stored: 800, decoded: 4 }, empty], + [true, true, false], + ), + ), + "nso", + undefined, + 1000, + ); + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + const rodata = entries.find((entry) => entry.path === "rodata.bin"); + expect(text?.limitations.join(" ")).toContain("LZ4 data is invalid"); + expect(rodata?.limitations.join(" ")).toContain( + "artifact_limits.expanded_bytes", + ); + const failure = await reader.open(rodata!).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ArtifactEntryContentUnavailable); + expect((failure as Error).cause).toMatchObject({ + readerLimit: { + parameter: "artifact_limits.expanded_bytes", + effective_value: 1000, + required_value: 1608, + }, + }); + } finally { + await reader.close(); + } +}); + +it("reports invalid LZ4 data as a segment limitation", async () => { + const bytes = buildNso(); + // The text segment's literal-run length claims more literals than stored. + bytes[0x101] = 200; + const reader = new SwitchExecutableArtifactReader( + await fixture(bytes), + "nso", + ); + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(text?.limitations.join(" ")).toContain("LZ4 data is invalid"); + await expect(reader.open(text!)).rejects.toThrow(/LZ4/u); + } finally { + await reader.close(); + } +}); + +it("lists a truncated NRO asset with a limitation", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + buildNro({ + assets: { romfs: Buffer.from("romfs-bytes") }, + truncateBy: 2, + }), + ), + "nro", + ); + try { + const { entries, coverage } = await collect(reader); + const romfs = entries.find((entry) => entry.path === "assets/romfs.bin"); + const text = entries.find((entry) => entry.path === "text.bin"); + expect(romfs?.limitations.join(" ")).toContain("truncated"); + expect(romfs?.formatMetadata).toMatchObject({ hash_status: "unavailable" }); + expect(text?.formatMetadata).toMatchObject({ hash_status: "not-checked" }); + expect(coverage?.status).toBe("unknown"); + await expect(reader.open(romfs!)).rejects.toThrow(/NRO is malformed/u); + } finally { + await reader.close(); + } + + const truncatedSegment = new SwitchExecutableArtifactReader( + await fixture(buildNro({ truncateBy: 2 })), + "nro", + ); + try { + const { entries, coverage } = await collect(truncatedSegment); + const data = entries.find((entry) => entry.path === "data.bin"); + expect(data?.limitations.join(" ")).toContain("truncated"); + expect(data?.formatMetadata).toMatchObject({ hash_status: "unavailable" }); + expect(coverage?.status).toBe("unknown"); + await expect(truncatedSegment.open(data!)).rejects.toThrow( + /NRO is malformed/u, + ); + } finally { + await truncatedSegment.close(); + } +}); + +it("lists valid NRO assets and reports a skipped unsafe range", async () => { + const bytes = buildNro({ + assets: { icon: Buffer.from("jpeg"), nacp: Buffer.alloc(16, 1) }, + }); + const offset = bytes.readUInt32LE(0x18); + bytes.writeBigUInt64LE(BigInt(Number.MAX_SAFE_INTEGER), offset + 0x28); + bytes.writeBigUInt64LE(1n, offset + 0x30); + const reader = new SwitchExecutableArtifactReader( + await fixture(bytes), + "nro", + ); + try { + const { entries, coverage } = await collect(reader); + expect( + entries + .map((entry) => entry.path) + .filter((path) => path.startsWith("assets/")), + ).toEqual(["assets/icon.jpg", "assets/control.nacp"]); + expect(coverage).toEqual({ + status: "unknown", + limitations: [ + "NRO romfs asset range exceeds a safe file offset; that asset is not listed.", + ], + }); + } finally { + await reader.close(); + } +}); + +it("reports uninterpreted bytes after an NRO without ASET", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture(buildNro({ trailing: Buffer.from("JUNKJUNK") })), + "nro", + ); + try { + const { coverage } = await collect(reader); + expect(coverage?.limitations.join(" ")).toContain("without an ASET header"); + } finally { + await reader.close(); + } +}); + +const occurrence = ( + snapshot: Awaited>, + path: string, +) => snapshot.occurrences.find((row) => row.logical_path === path); + +it("keeps the NSO inventory when segment content is refused", async () => { + const truncated = await scanCanonicalArtifactInventory( + await fixture(buildNso({ truncateBy: 3 })), + ); + expect(truncated.coverage.status).toBe("unknown"); + expect(occurrence(truncated, "data.bin")).toMatchObject({ + hash_status: "unavailable", + }); + // The entry's limitation and the refusal's name one reason, reported once. + expect(occurrence(truncated, "data.bin")?.limitations).toEqual([ + expect.stringContaining("data segment is truncated"), + ]); + expect(occurrence(truncated, "rodata.bin")?.artifact_id).not.toBeNull(); + + const invalid = buildNso(); + invalid[0x101] = 200; + const lz4 = await scanCanonicalArtifactInventory(await fixture(invalid)); + expect(occurrence(lz4, "text.bin")?.limitations.join(" ")).toContain( + "LZ4 data is invalid", + ); + + const overBudget = await scanCanonicalArtifactInventory( + await fixture( + buildNso({ + segments: [Buffer.alloc(4096, 7), Buffer.from("ro"), Buffer.from("rw")], + compress: [true, false, false], + }), + ), + { + readerLimits: resolveArtifactReaderLimits({ expanded_bytes: 1024 }), + }, + ); + expect(occurrence(overBudget, "text.bin")).toMatchObject({ + hash_status: "unavailable", + }); + expect(occurrence(overBudget, "text.bin")?.limitations).toEqual([ + expect.stringContaining("artifact_limits.expanded_bytes"), + ]); +}); + +it("keeps NRO segments when the ASET header is cut short", async () => { + const full = buildNro({ assets: { icon: Buffer.from("icon") } }); + // Keep "ASET" and a few header bytes, well short of the 0x38-byte header. + const imageSize = full.readUInt32LE(0x18); + const reader = new SwitchExecutableArtifactReader( + await fixture(full.subarray(0, imageSize + 0x10)), + "nro", + ); + try { + const { entries, coverage } = await collect(reader); + expect(entries.map((entry) => entry.path)).toEqual([ + "text.bin", + "rodata.bin", + "data.bin", + ]); + expect(coverage?.status).toBe("unknown"); + expect(coverage?.limitations.join(" ")).toContain( + "NRO asset header is truncated", + ); + expect(reader.formatMetadata()).toMatchObject({ asset_section: null }); + } finally { + await reader.close(); + } +}); + +it("reports 1-3 bytes after an NRO image as uninterpreted", async () => { + for (const length of [1, 3]) { + const reader = new SwitchExecutableArtifactReader( + await fixture(buildNro({ trailing: Buffer.alloc(length, 0x41) })), + "nro", + ); + try { + const { coverage } = await collect(reader); + expect(coverage?.status).toBe("unknown"); + expect(coverage?.limitations.join(" ")).toContain( + `${String(length)} bytes follow the NRO image without an ASET header`, + ); + } finally { + await reader.close(); + } + } +}); + +it("reports an NRO shorter than its declared image size", async () => { + const full = buildNro(); + const header = Buffer.from(full); + // Declare 16 bytes more image than the file holds; segments still fit. + header.writeUInt32LE(full.readUInt32LE(0x18) + 16, 0x18); + const reader = new SwitchExecutableArtifactReader( + await fixture(header), + "nro", + ); + try { + const { entries, coverage } = await collect(reader); + expect(entries).toHaveLength(3); + expect(coverage?.status).toBe("unknown"); + expect(coverage?.limitations.join(" ")).toContain( + "missing 16 bytes were not read", + ); + } finally { + await reader.close(); + } +}); + +it("retires a compressed segment's decode when the reader closes", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + buildNso({ + segments: [ + Buffer.alloc(8 * 1024 * 1024, 7), + Buffer.from("ro"), + Buffer.from("rw"), + ], + compress: [true, false, false], + }), + ), + "nso", + ); + let closed = false; + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + const stream = await reader.open(text!); + const read = buffer(stream).catch((cause: unknown) => cause); + // Let the owned stream start its carrier read and decode before close. + await new Promise((resolve) => setImmediate(resolve)); + await reader.close(); + closed = true; + // Close waited for the owned member stream, as it does for stored ranges. + expect(stream.destroyed).toBe(true); + const failure = await read; + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "unavailable", + message: "NSO reader closed", + }); + } finally { + if (!closed) await reader.close(); + } +}); + +it("cancels a decoded segment when the caller aborts", async () => { + const reader = new SwitchExecutableArtifactReader( + await fixture(buildNso()), + "nso", + ); + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + const controller = new AbortController(); + const stream = await reader.open(text!, controller.signal); + controller.abort(new Error("caller stopped")); + await expect(buffer(stream)).rejects.toMatchObject({ + reason: "cancelled", + }); + } finally { + await reader.close(); + } +}); + +const withDeadline = async ( + operation: Promise, + label: string, + timeoutMs = testWaitDeadline(), +): Promise => { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + operation, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), + timeoutMs, + ); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +}; + +it.for([ + { label: "with no chunks read", chunksToRead: 0, action: "close" as const }, + { + label: "after reading one chunk", + chunksToRead: 1, + action: "close" as const, + }, + { label: "with no chunks read", chunksToRead: 0, action: "abort" as const }, + { + label: "after reading one chunk", + chunksToRead: 1, + action: "abort" as const, + }, +])( + "retires a paused compressed segment on $action $label", + async ({ chunksToRead, action }) => { + const reader = new SwitchExecutableArtifactReader( + await fixture( + buildNso({ + segments: [ + Buffer.alloc(512 * 1024, 0x5a), + Buffer.from("ro"), + Buffer.from("rw"), + ], + compress: [true, false, false], + }), + ), + "nso", + ); + let closed = false; + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + const controller = new AbortController(); + const callerReason = new Error("caller stopped reading"); + const stream = await reader.open(text!, controller.signal); + const settled = finished(stream, { cleanup: true }).catch( + (cause: unknown) => cause, + ); + await withDeadline(once(stream, "readable"), "initial buffer fill"); + for (let index = 0; index < chunksToRead; index++) { + const chunk = stream.read() as Buffer | null; + expect(chunk).not.toBeNull(); + expect(chunk!.length).toBeGreaterThan(0); + await withDeadline(once(stream, "readable"), "buffer refill"); + } + expect(stream.readableLength).toBeGreaterThan(0); + if (action === "close") { + await withDeadline(reader.close(), "reader.close()"); + closed = true; + expect(stream.destroyed).toBe(true); + const failure = await withDeadline(settled, "stream settlement"); + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "unavailable", + message: "NSO reader closed", + }); + } else { + controller.abort(callerReason); + const failure = await withDeadline( + settled, + "aborted stream settlement", + ); + expect(stream.destroyed).toBe(true); + expect(failure).toBeInstanceOf(ArtifactReaderFailure); + expect(failure).toMatchObject({ + reason: "cancelled", + cause: callerReason, + }); + await withDeadline(reader.close(), "reader.close() after abort"); + closed = true; + } + } finally { + if (!closed) await reader.close(); + } + }, +); + +it("surfaces the original error when a pending compressed segment read rejects", async () => { + const path = await fixture(buildNso()); + const descriptor = await openRegularFile(path, { symlinks: "reject" }); + const reader = new SwitchExecutableArtifactReader(path, "nso", descriptor); + const gate = phaseGate(); + const ioFailure = Object.assign(new Error("physical descriptor I/O failed"), { + code: "EIO", + }); + let closed = false; + try { + const { entries } = await collect(reader); + const text = entries.find((entry) => entry.path === "text.bin"); + const { handle } = descriptor; + const read = handle.read.bind(handle); + vi.spyOn(handle, "read").mockImplementation((...args: unknown[]) => + Promise.resolve(Reflect.apply(read, handle, args)).then( + async (result) => { + await gate.hold(); + return result; + }, + ), + ); + const controller = new AbortController(); + const stream = await reader.open(text!, controller.signal); + const settled = finished(stream, { cleanup: true }).catch( + (cause: unknown) => cause, + ); + stream.resume(); + await gate.reached(settled, "compressed segment read"); + controller.abort(new Error("caller cancelled during pending read")); + const closing = reader.close().then(() => { + closed = true; + }); + gate.reject(ioFailure); + const failure = await withDeadline(settled, "pending read rejection"); + await withDeadline(closing, "reader.close() after read rejection"); + expect(failure).toBe(ioFailure); + } finally { + gate.release(); + if (!closed) await reader.close(); + await descriptor.handle.close(); + } +}); diff --git a/src/artifacts/SwitchExecutableArtifactReader.test.ts b/src/artifacts/SwitchExecutableArtifactReader.test.ts new file mode 100644 index 0000000000..edcb8f234f --- /dev/null +++ b/src/artifacts/SwitchExecutableArtifactReader.test.ts @@ -0,0 +1,187 @@ +import { buffer } from "node:stream/consumers"; + +import { expect, it } from "vitest"; + +import { classifyArtifactBytesAtPath } from "../../tests/fixtures/artifactClassification.js"; +import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js"; +import { createTestTempFile } from "../../tests/fixtures/temporaryDirectory.js"; +import { + buildNro, + buildNso, + defaultText, + MODULE_ID, +} from "../domain/switchExecutable.fixture.js"; +import { SwitchExecutableArtifactReader } from "./SwitchExecutableArtifactReader.js"; + +const writeCarrier = (name: string, bytes: Buffer): Promise => + createTestTempFile("rea-switch-", name, bytes); + +it("classifies NSO and NRO executables by magic", () => { + expect(classifyArtifactBytesAtPath("main", buildNso())).toEqual({ + kind: "container", + format: "nso", + }); + expect(classifyArtifactBytesAtPath("app.nro", buildNro())).toEqual({ + kind: "container", + format: "nro", + }); +}); + +it("inventories NSO segments with module id, offsets and hash status", async () => { + const path = await writeCarrier("main.nso", buildNso()); + const snapshot = await scanCanonicalArtifactInventory(path); + expect(snapshot.manifest.root_format).toBe("nso"); + expect(snapshot.coverage.status).toBe("complete"); + const root = snapshot.occurrences.find((row) => row.logical_path === "."); + expect(root?.format_metadata).toMatchObject({ + kind: "switch-executable", + format: "nso", + module_id: MODULE_ID.toString("hex"), + mod0_offset: 0x10, + unknown_flags: 0, + asset_section: null, + }); + const segments = snapshot.occurrences + .filter((row) => row.logical_path !== ".") + .map((row) => [row.logical_path, row.format_metadata]) + .sort(); + expect(segments).toEqual([ + [ + "data.bin", + expect.objectContaining({ + role: "data", + compressed: true, + hash_status: "match", + memory_offset: 0x2000, + }), + ], + [ + "rodata.bin", + expect.objectContaining({ + role: "rodata", + compressed: false, + hash_status: "match", + }), + ], + [ + "text.bin", + expect.objectContaining({ + role: "text", + compressed: true, + hash_status: "match", + file_offset: 0x100, + }), + ], + ]); +}); + +it("serves compressed NSO segments as their decompressed bytes", async () => { + const path = await writeCarrier("main.nso", buildNso()); + const reader = new SwitchExecutableArtifactReader(path, "nso"); + try { + const contents = new Map(); + for await (const entry of reader.entries()) + contents.set(entry.path, await buffer(await reader.open(entry))); + expect(contents.get("text.bin")?.equals(defaultText())).toBe(true); + expect(contents.get("rodata.bin")?.toString()).toBe( + "read-only data segment", + ); + expect(contents.get("data.bin")?.toString()).toBe("writable data"); + } finally { + await reader.close(); + } +}); + +it("reports a hash mismatch as a limitation without dropping the segment", async () => { + const path = await writeCarrier("bad-hash.nso", buildNso({ corruptHash: 1 })); + const reader = new SwitchExecutableArtifactReader(path, "nso"); + try { + const entries = []; + let coverage; + for await (const entry of reader.entries(undefined, { + onCoverage: (value) => (coverage = value), + })) + entries.push(entry); + expect(entries.map((entry) => entry.path)).toEqual([ + "text.bin", + "rodata.bin", + "data.bin", + ]); + expect(entries[1]?.formatMetadata).toMatchObject({ + hash_status: "mismatch", + }); + expect(entries[1]?.limitations.join(" ")).toContain("does not match"); + expect(coverage).toMatchObject({ status: "unknown" }); + } finally { + await reader.close(); + } +}); + +it("reports not-checked when the header does not ask for a hash check", async () => { + const path = await writeCarrier( + "nocheck.nso", + buildNso({ hashCheck: [false, false, false], corruptHash: 0 }), + ); + const reader = new SwitchExecutableArtifactReader(path, "nso"); + try { + const statuses = []; + for await (const entry of reader.entries()) + statuses.push( + (entry.formatMetadata as { hash_status: string }).hash_status, + ); + expect(statuses).toEqual(["not-checked", "not-checked", "not-checked"]); + } finally { + await reader.close(); + } +}); + +it("inventories NRO segments and ASET icon, NACP and RomFS", async () => { + const path = await writeCarrier( + "app.nro", + buildNro({ + assets: { + icon: Buffer.from("icon-bytes"), + nacp: Buffer.from("nacp-bytes"), + romfs: Buffer.from("romfs-bytes"), + }, + }), + ); + const snapshot = await scanCanonicalArtifactInventory(path); + expect(snapshot.manifest.root_format).toBe("nro"); + expect(snapshot.coverage.status).toBe("complete"); + const root = snapshot.occurrences.find((row) => row.logical_path === "."); + expect(root?.format_metadata).toMatchObject({ + kind: "switch-executable", + format: "nro", + mod0_offset: 0x80, + mod0_present: true, + asset_section: { offset: 0xb2, version: 0 }, + }); + expect(snapshot.occurrences.map((row) => row.logical_path).sort()).toEqual([ + ".", + "assets/control.nacp", + "assets/icon.jpg", + "assets/romfs.bin", + "data.bin", + "rodata.bin", + "text.bin", + ]); + const reader = new SwitchExecutableArtifactReader(path, "nro"); + try { + for await (const entry of reader.entries()) + if (entry.path === "assets/romfs.bin") + expect((await buffer(await reader.open(entry))).toString()).toBe( + "romfs-bytes", + ); + } finally { + await reader.close(); + } +}); + +it("marks the NRO asset section absent when no ASET follows", async () => { + const path = await writeCarrier("plain.nro", buildNro()); + const snapshot = await scanCanonicalArtifactInventory(path); + const root = snapshot.occurrences.find((row) => row.logical_path === "."); + expect(root?.format_metadata).toMatchObject({ asset_section: null }); + expect(snapshot.coverage.status).toBe("complete"); +}); diff --git a/src/artifacts/SwitchExecutableArtifactReader.ts b/src/artifacts/SwitchExecutableArtifactReader.ts new file mode 100644 index 0000000000..46ce9e6199 --- /dev/null +++ b/src/artifacts/SwitchExecutableArtifactReader.ts @@ -0,0 +1,612 @@ +import { createHash } from "node:crypto"; +import { Readable } from "node:stream"; + +import { decodeLz4Block } from "../compression/Lz4Block.js"; +import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js"; +import { + BinaryFormatFailure, + BinaryResourceFailure, +} from "../domain/binaryContainer.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; +import type { + SwitchExecutableEntryMetadata, + SwitchExecutableMetadata, +} from "../domain/formatMetadata/packageAndGameMetadata.js"; +import { + hasMod0Magic, + NRO_ASSET_HEADER_SIZE, + NRO_HEADER_SIZE, + nroMod0MagicExtent, + NSO_HEADER_SIZE, + parseNroAssetSection, + parseNroHeader, + parseNsoHeader, + parseTextMod0Offset, + SWITCH_TEXT_PREFIX_SIZE, + type NroAssetSection, + type NroHeader, + type NsoHeader, + type NsoSegment, +} from "../domain/switchExecutable.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; +import { + ArtifactEntryContentUnavailable, + ArtifactReaderFailure, + artifactParseFailure, + artifactReadCancelledBy, + artifactReaderLimitFailure, + malformedArtifact, +} from "../resources/index.js"; +import { readArtifactFileBytes } from "./ArtifactFileRange.js"; +import type { ArtifactMemberLifecycle } from "./OwnedArtifactStream.js"; +import { + PositionalArtifactReader, + type PositionalArtifactEntries, + type PositionalArtifactEntry, +} from "./PositionalArtifactReader.js"; + +const READ_CHUNK_BYTES = 64 * 1024; +const SEGMENT_PATHS = { + text: "text.bin", + rodata: "rodata.bin", + data: "data.bin", +} as const; +const ASSET_PATHS = { + icon: "assets/icon.jpg", + nacp: "assets/control.nacp", + romfs: "assets/romfs.bin", +} as const; + +type SwitchEntry = PositionalArtifactEntry & { + readonly formatMetadata: SwitchExecutableEntryMetadata; +}; + +/** + * Why a listed entry's bytes cannot be served, decided at preparation. The + * entry stays in the inventory with its limitation, so the refusal is + * per-member unavailable content rather than a reader failure. + */ +type Refusal = () => ArtifactEntryContentUnavailable; + +const unavailable = ( + limitation: string, + cause: ArtifactReaderFailure, +): ArtifactEntryContentUnavailable => + new ArtifactEntryContentUnavailable(cause.message, limitation, { cause }); + +/** + * Read a Nintendo Switch NSO or NRO executable without running or patching + * it. NSO segments compressed with LZ4 are decompressed within the expansion + * budget. Stored input and decompressed output are both charged before + * allocation, so a small declared output cannot force a large read. + */ +export class SwitchExecutableArtifactReader extends PositionalArtifactReader< + SwitchExecutableMetadata, + SwitchEntry +> { + override readonly format: "nso" | "nro"; + readonly #expandedBytes: number | undefined; + readonly #refusals = new Map(); + /** Compressed segments already reserved against the expansion budget. */ + readonly #admittedStored = new Set(); + #budget = 0; + #charged = 0; + + constructor( + path: string, + format: "nso" | "nro", + admitted?: StableRegularFileDescriptor, + expandedBytes?: number, + ) { + const label = format === "nso" ? "NSO" : "NRO"; + super(path, label, admitted, `Switch ${label} executable`); + this.format = format; + this.#expandedBytes = expandedBytes; + } + + formatMetadata(): SwitchExecutableMetadata | undefined { + const metadata = this.preparedFormatMetadata; + return metadata === undefined ? undefined : structuredClone(metadata); + } + + protected override contentRefusal( + entry: SwitchEntry, + ): ArtifactReaderFailure | undefined { + return ( + this.#refusals.get(entry.adapterKey)?.() ?? super.contentRefusal(entry) + ); + } + + /** Serve a compressed NSO segment as its decompressed, loaded bytes. */ + protected override entrySource( + entry: SwitchEntry, + carrier: StableRegularFileDescriptor, + member: ArtifactMemberLifecycle, + ): Readable | undefined { + if (!entry.formatMetadata.compressed) return undefined; + const { signal, cancellationFailure } = member; + let readState: "idle" | "pending" | "failed" = "idle"; + const source = Readable.from( + this.#decodedSegment(entry, carrier, member, (state) => { + readState = state; + }), + { objectMode: false }, + ); + const onAbort = (): void => { + // A pending carrier read or decode owns its failure; once idle (such as + // paused on backpressure), destroy the source immediately so pipeline + // and reader.close() retire promptly. + if (readState === "idle" && !source.destroyed) + source.destroy(cancellationFailure(signal.reason)); + }; + signal.addEventListener("abort", onAbort, { once: true }); + source.once("close", () => signal.removeEventListener("abort", onAbort)); + if (signal.aborted) onAbort(); + return source; + } + + async *#decodedSegment( + entry: SwitchEntry, + { handle, initial }: StableRegularFileDescriptor, + member: ArtifactMemberLifecycle, + onStateChange: (state: "idle" | "pending" | "failed") => void, + ): AsyncIterable { + const { signal, cancellationFailure } = member; + let decoded: Buffer | undefined; + onStateChange("pending"); + try { + if (signal.aborted) throw cancellationFailure(signal.reason); + const stored = entry.formatMetadata.file_size; + const refused = this.#admitStoredInput( + entry.adapterKey, + entry.formatMetadata.role, + stored, + entry.declaredSize, + ); + if (refused !== undefined) throw refused.failure; + const input = await readArtifactFileBytes( + "nso", + handle, + entry.formatMetadata.file_offset, + stored, + initial.size, + signal, + ); + decoded = await decodeLz4Block( + input, + entry.declaredSize, + entry.declaredSize, + signal, + ); + onStateChange("idle"); + } catch (cause) { + onStateChange("failed"); + if (artifactReadCancelledBy(cause, signal)) + throw cancellationFailure(signal.reason); + if ( + !( + cause instanceof BinaryFormatFailure || + cause instanceof BinaryResourceFailure + ) + ) + throw cause; + // Preparation decoded these bytes, so a changed carrier reports that + // change before the stored data is blamed. + await member.verify((verifySignal) => this.verifyCarrier(verifySignal)); + throw malformedArtifact( + "nso", + `NSO is malformed: ${entry.formatMetadata.role} segment LZ4 data is invalid: ${cause.message}`, + { cause }, + ); + } + try { + if (signal.aborted) throw cancellationFailure(signal.reason); + for ( + let offset = 0; + offset < decoded.length; + offset += READ_CHUNK_BYTES + ) { + if (signal.aborted) throw cancellationFailure(signal.reason); + yield decoded.subarray(offset, offset + READ_CHUNK_BYTES); + } + } finally { + decoded = undefined; + } + } + + protected override async prepareEntries( + signal?: AbortSignal, + ): Promise> { + this.#refusals.clear(); + this.#admittedStored.clear(); + this.#charged = 0; + const { handle, initial } = await this.verifyCarrier(signal); + this.#budget = + this.#expandedBytes ?? artifactExpansionBudgetBytes(initial.size); + const read = (offset: number, length: number): Promise => + readArtifactFileBytes( + this.format, + handle, + offset, + length, + initial.size, + signal, + ); + const headerSize = + this.format === "nso" ? NSO_HEADER_SIZE : NRO_HEADER_SIZE; + const headerBytes = await read(0, Math.min(initial.size, headerSize)); + return this.format === "nso" + ? this.#prepareNso(headerBytes, initial.size, read, signal) + : this.#prepareNro(headerBytes, initial.size, read, signal); + } + + async #prepareNso( + headerBytes: Buffer, + fileSize: number, + read: (offset: number, length: number) => Promise, + signal?: AbortSignal, + ): Promise> { + const parsed = parseNsoHeader(headerBytes, fileSize); + if (!parsed.ok) throw artifactParseFailure(parsed.error, signal); + const header = parsed.value; + const entries: SwitchEntry[] = []; + const limitations: string[] = []; + let textPrefix: Buffer | undefined; + for (const segment of header.segments) { + const adapterKey = `nso:${segment.name}`; + const path = SEGMENT_PATHS[segment.name]; + const entryLimitations: string[] = []; + let observed: string | null = null; + if (segment.truncated) { + const detail = `${segment.name} segment is truncated: it declares ${String(segment.fileSize)} stored bytes at offset ${String(segment.fileOffset)} but the file has ${String(fileSize)} bytes`; + entryLimitations.push(detail); + this.#refusals.set(adapterKey, () => + unavailable( + detail, + malformedArtifact("nso", `NSO is malformed: ${detail}`), + ), + ); + } else { + const loaded = await this.#loadNsoSegment(segment, read, signal); + if (loaded.ok) { + observed = loaded.sha256; + if (segment.name === "text") textPrefix = loaded.prefix; + } else { + entryLimitations.push(loaded.detail); + const cause = + loaded.limit ?? + malformedArtifact("nso", `NSO is malformed: ${loaded.detail}`); + this.#refusals.set(adapterKey, () => + unavailable(loaded.detail, cause), + ); + } + } + const hashStatus = + observed === null + ? "unavailable" + : !segment.hashChecked + ? "not-checked" + : observed === segment.sha256 + ? "match" + : "mismatch"; + if (hashStatus === "mismatch") + entryLimitations.push( + `${segment.name} segment SHA-256 ${observed ?? ""} does not match the header's ${segment.sha256}`, + ); + limitations.push(...entryLimitations); + const entry: SwitchEntry = { + path, + sourcePath: path, + kind: "file", + declaredSize: segment.size, + compressedSize: segment.compressed ? segment.fileSize : null, + byteLength: segment.fileSize, + executable: segment.name === "text", + encrypted: false, + byteOffset: segment.fileOffset, + declaredIntegrity: null, + unpacked: false, + limitations: entryLimitations, + adapterKey, + formatMetadata: { + kind: "switch-executable-entry", + role: segment.name, + file_offset: segment.fileOffset, + memory_offset: segment.memoryOffset, + file_size: segment.fileSize, + compressed: segment.compressed, + declared_sha256: segment.sha256, + observed_sha256: observed, + hash_status: hashStatus, + }, + }; + entries.push(entry); + } + if (header.unknownFlags !== 0) + limitations.push( + `NSO flags set unknown bits 0x${header.unknownFlags.toString(16)}; they are reported but not interpreted.`, + ); + const mod0Offset = + textPrefix === undefined ? null : parseTextMod0Offset(textPrefix); + return { + entries, + coverage: { + status: limitations.length === 0 ? "complete" : "unknown", + limitations, + }, + formatMetadata: nsoMetadata(header, mod0Offset), + }; + } + + /** Read one NSO segment, decompressing it when flagged, and hash it. */ + async #loadNsoSegment( + segment: NsoSegment, + read: (offset: number, length: number) => Promise, + signal?: AbortSignal, + ): Promise< + | { readonly ok: true; readonly sha256: string; readonly prefix: Buffer } + | { + readonly ok: false; + readonly detail: string; + readonly limit: ArtifactReaderFailure | undefined; + } + > { + if (segment.compressed) { + const refused = this.#admitStoredInput( + `nso:${segment.name}`, + segment.name, + segment.fileSize, + segment.size, + ); + if (refused !== undefined) + return { ok: false, detail: refused.detail, limit: refused.failure }; + const input = await read(segment.fileOffset, segment.fileSize); + let decoded: Buffer; + try { + decoded = await decodeLz4Block( + input, + segment.size, + segment.size, + signal, + ); + } catch (cause) { + if ( + cause instanceof BinaryFormatFailure || + cause instanceof BinaryResourceFailure + ) + return { + ok: false, + detail: `${segment.name} segment LZ4 data is invalid: ${cause.message}`, + limit: undefined, + }; + throw cause; + } + return { + ok: true, + sha256: sha256Hex(decoded), + prefix: decoded.subarray(0, SWITCH_TEXT_PREFIX_SIZE), + }; + } + const hash = createHash("sha256"); + let prefix = Buffer.alloc(0); + for (let done = 0; done < segment.size;) { + this.assertOpen(signal); + const chunk = await read( + segment.fileOffset + done, + Math.min(READ_CHUNK_BYTES, segment.size - done), + ); + if (done === 0) + prefix = Buffer.from(chunk.subarray(0, SWITCH_TEXT_PREFIX_SIZE)); + hash.update(chunk); + done += chunk.length; + } + return { ok: true, sha256: hash.digest("hex"), prefix }; + } + + async #prepareNro( + headerBytes: Buffer, + fileSize: number, + read: (offset: number, length: number) => Promise, + signal?: AbortSignal, + ): Promise> { + const parsed = parseNroHeader(headerBytes, fileSize); + if (!parsed.ok) throw artifactParseFailure(parsed.error, signal); + const header = parsed.value; + const limitations: string[] = []; + const entries: SwitchEntry[] = []; + const add = ( + role: SwitchExecutableEntryMetadata["role"], + path: string, + fileOffset: number, + size: number, + truncated: boolean, + memoryOffset: number | null, + ): void => { + const adapterKey = `nro:${role}`; + const entryLimitations: string[] = []; + if (truncated) { + const detail = `${role} ${memoryOffset === null ? "asset" : "segment"} is truncated: it declares ${String(size)} bytes at offset ${String(fileOffset)} but the file has ${String(fileSize)} bytes`; + entryLimitations.push(detail); + limitations.push(detail); + this.#refusals.set(adapterKey, () => + unavailable( + detail, + malformedArtifact("nro", `NRO is malformed: ${detail}`), + ), + ); + } + entries.push({ + path, + sourcePath: path, + kind: "file", + declaredSize: size, + compressedSize: null, + executable: role === "text", + encrypted: false, + byteOffset: fileOffset, + declaredIntegrity: null, + unpacked: false, + limitations: entryLimitations, + adapterKey, + formatMetadata: { + kind: "switch-executable-entry", + role, + file_offset: fileOffset, + memory_offset: memoryOffset, + file_size: size, + compressed: false, + declared_sha256: null, + observed_sha256: null, + hash_status: truncated ? "unavailable" : "not-checked", + }, + }); + }; + for (const segment of header.segments) + add( + segment.name, + SEGMENT_PATHS[segment.name], + segment.fileOffset, + segment.size, + segment.truncated, + segment.fileOffset, + ); + let assets: NroAssetSection | undefined; + const trailing = fileSize - header.size; + if (trailing < 0) + limitations.push( + `NRO declares an image size of ${String(header.size)} bytes but the file has ${String(fileSize)} bytes; the missing ${String(-trailing)} bytes were not read.`, + ); + else if (trailing > 0) { + const assetBytes = await read( + header.size, + Math.min(NRO_ASSET_HEADER_SIZE, trailing), + ); + const parsedAssets = parseNroAssetSection( + assetBytes, + header.size, + fileSize, + ); + // A damaged trailer does not invalidate the segments before it. + if (!parsedAssets.ok) + limitations.push( + `${parsedAssets.error.message}; the ${String(trailing)} bytes after the NRO image are not interpreted.`, + ); + else { + assets = parsedAssets.value; + if (assets === undefined) + limitations.push( + `${String(trailing)} bytes follow the NRO image without an ASET header; they are not interpreted.`, + ); + } + } + for (const message of assets?.rejected ?? []) + limitations.push(`${message}; that asset is not listed.`); + for (const asset of assets?.assets ?? []) + add( + asset.name, + ASSET_PATHS[asset.name], + asset.fileOffset, + asset.size, + asset.truncated, + null, + ); + const mod0Extent = nroMod0MagicExtent(header, fileSize); + const mod0Present = + mod0Extent === undefined + ? null + : hasMod0Magic(await read(mod0Extent.offset, mod0Extent.size)); + return { + entries, + coverage: { + status: limitations.length === 0 ? "complete" : "unknown", + limitations, + }, + formatMetadata: nroMetadata(header, assets, mod0Present), + }; + } + + /** + * Reserve the stored input and the decoded output of one compressed + * segment, or refuse before either buffer is allocated. A later open of an + * admitted segment does not reserve again; it still refuses a read the + * budget cannot hold. + */ + #admitStoredInput( + key: string, + name: string, + stored: number, + decoded: number, + ): + | { readonly detail: string; readonly failure: ArtifactReaderFailure } + | undefined { + if ( + this.#admittedStored.has(key) && + stored <= this.#budget && + decoded <= this.#budget + ) + return undefined; + const remaining = this.#budget - this.#charged; + if (decoded > remaining || stored > remaining - decoded) { + const detail = `${name} segment allocates ${String(stored)} stored bytes and ${String(decoded)} decoded bytes, over the remaining artifact_limits.expanded_bytes budget of ${String(remaining)}`; + return { + detail, + failure: artifactReaderLimitFailure( + "artifact_limits.expanded_bytes", + this.#budget, + "bytes", + this.#charged + stored + decoded, + "memory", + ), + }; + } + this.#charged += stored + decoded; + this.#admittedStored.add(key); + return undefined; + } +} + +const nsoMetadata = ( + header: NsoHeader, + mod0Offset: number | null, +): SwitchExecutableMetadata => ({ + kind: "switch-executable", + format: "nso", + version: header.version, + flags: header.flags, + unknown_flags: header.unknownFlags, + module_id: header.moduleId, + bss_size: header.bssSize, + mod0_offset: mod0Offset, + // Checking the magic needs the loaded segment that holds the offset; only + // the offset is reported for NSO. + mod0_present: null, + embedded: { ...header.embedded }, + dynstr: { ...header.dynstr }, + dynsym: { ...header.dynsym }, + image_size: null, + asset_section: null, +}); + +const nroMetadata = ( + header: NroHeader, + assets: NroAssetSection | undefined, + mod0Present: boolean | null, +): SwitchExecutableMetadata => ({ + kind: "switch-executable", + format: "nro", + version: header.version, + flags: header.flags, + unknown_flags: 0, + module_id: header.moduleId, + bss_size: header.bssSize, + mod0_offset: header.mod0Offset, + mod0_present: mod0Present, + embedded: { ...header.embedded }, + dynstr: { ...header.dynstr }, + dynsym: { ...header.dynsym }, + image_size: header.size, + asset_section: + assets === undefined + ? null + : { offset: assets.offset, version: assets.version }, +}); diff --git a/src/artifacts/artifactFormats.ts b/src/artifacts/artifactFormats.ts index a36830ab8d..a0ef6f0225 100644 --- a/src/artifacts/artifactFormats.ts +++ b/src/artifacts/artifactFormats.ts @@ -56,6 +56,7 @@ import { AndroidOtaPayloadArtifactReader } from "./AndroidOtaPayloadArtifactRead import { AndroidSparseImageArtifactReader } from "./AndroidSparseImageArtifactReader.js"; import { UImageArtifactReader } from "./UImageArtifactReader.js"; import { BfltArtifactReader } from "./BfltArtifactReader.js"; +import { SwitchExecutableArtifactReader } from "./SwitchExecutableArtifactReader.js"; import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js"; import { WxapkgArtifactReader } from "./WxapkgArtifactReader.js"; import { TarArtifactReader } from "./tar/TarArtifactReader.js"; @@ -264,6 +265,25 @@ const gpuAsset = (id: Id) => new GpuAssetArtifactReader(path, id, sourceOf(options)), }); +const switchExecutable = (id: Id) => + container(id, { + roleContainer: true, + retainClassifiedSource: true, + extractable: true, + absentInventory: "unavailable", + readerLimitation: + id === "nso" + ? "NSO inventory reports header facts and text, rodata and data segments. LZ4-compressed segments are decompressed within artifact_limits.expanded_bytes and hashed against the header; code is not disassembled or executed." + : "NRO inventory reports header facts, text, rodata and data segments and the ASET icon, NACP and RomFS ranges. Asset contents are not interpreted, and code is not disassembled or executed.", + createReader: (path, options) => + new SwitchExecutableArtifactReader( + path, + id, + sourceOf(options), + options.readerLimits?.expanded_bytes, + ), + }); + const NON_ZIP_FORMATS = { "dotnet-bundle": container("dotnet-bundle", { retainClassifiedSource: true, @@ -434,6 +454,8 @@ const NON_ZIP_FORMATS = { createReader: (path, options) => new UImageArtifactReader(path, sourceOf(options), options.integrity), }), + nso: switchExecutable("nso"), + nro: switchExecutable("nro"), "android-boot-image": container("android-boot-image", { roleContainer: true, retainClassifiedSource: true, diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 61d903e55a..61f8e7e997 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -383,7 +383,10 @@ const visitArtifactEntries = async ( : { status: "unknown" as const, limitations: [limitation] }; if (traversal !== undefined) context.traversal.record(traversal); occurrence.hash_status = "unavailable"; - occurrence.limitations.push(limitation); + // A reader that refuses content it already listed with a limitation + // names the same reason on the entry and on the refusal. + if (!occurrence.limitations.includes(limitation)) + occurrence.limitations.push(limitation); } if (digested === undefined) noteUnreadContainerSuffix(occurrence); else { diff --git a/src/domain/analysisView/artifactInventoryView.ts b/src/domain/analysisView/artifactInventoryView.ts index f2fda2f7b8..66bee37191 100644 --- a/src/domain/analysisView/artifactInventoryView.ts +++ b/src/domain/analysisView/artifactInventoryView.ts @@ -317,6 +317,8 @@ export const projectArtifactInventoryView = ( inventory.manifest.root_format === "wxapkg" || inventory.manifest.root_format === "iso9660" || inventory.manifest.root_format === "tar" || + inventory.manifest.root_format === "nso" || + inventory.manifest.root_format === "nro" || inventory.manifest.root_format === "pyinstaller" || inventory.manifest.root_format === "node-sea" || inventory.manifest.root_format === "intel-hex" || diff --git a/src/domain/artifactFormatMetadata.ts b/src/domain/artifactFormatMetadata.ts index e1d82d6767..aa71959e6e 100644 --- a/src/domain/artifactFormatMetadata.ts +++ b/src/domain/artifactFormatMetadata.ts @@ -17,6 +17,8 @@ import { wxapkgMetadataSchema, tarMetadataSchema, tarEntryMetadataSchema, + switchExecutableMetadataSchema, + switchExecutableEntryMetadataSchema, } from "./formatMetadata/packageAndGameMetadata.js"; import { bfltMetadataSchema, @@ -65,6 +67,8 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [ wxapkgEntryMetadataSchema, tarMetadataSchema, tarEntryMetadataSchema, + switchExecutableMetadataSchema, + switchExecutableEntryMetadataSchema, pyInstallerMetadataSchema, pyInstallerEntryMetadataSchema, dotnetBundleEntryMetadataSchema, @@ -232,6 +236,14 @@ const declarationsByKind: { notCompared: "start_address and end_address restate the region's path, and length follows from them; record and line counts are layout.", }, + "switch-executable": { + notCompared: + "Its header facts come from the executable's own bytes, which content comparison covers.", + }, + "switch-executable-entry": { + notCompared: + "role restates the entry's path, offsets and sizes are layout, and declared and observed hashes come from the executable's bytes, which content comparison covers.", + }, uimage: { notCompared: "Its header facts come from the image's own bytes, which content comparison covers.", diff --git a/src/domain/artifactFormatRecognition.ts b/src/domain/artifactFormatRecognition.ts index 161149a685..cdd4423abb 100644 --- a/src/domain/artifactFormatRecognition.ts +++ b/src/domain/artifactFormatRecognition.ts @@ -18,6 +18,7 @@ import { recognizeAndroidOtaPayload } from "./firmware/androidOtaPayload.js"; import { recognizeAndroidSparseImage } from "./firmware/androidSparseImage.js"; import { hasUImageMagic } from "./uimageFormat.js"; import { hasBfltMagic } from "./bfltExecutable.js"; +import { hasNroMagic, hasNsoMagic } from "./switchExecutable.js"; import { hasUnityFsHeader } from "./unityfsFormat.js"; import { hasMftFileRecordHeader } from "./windows/ntfsMft.js"; import { hasWindowsShortcutHeader } from "./windows/windowsShortcutHeader.js"; @@ -53,6 +54,8 @@ export type RecognizedArtifactFormat = Extract< | "ktx" | "ktx2" | "uimage" + | "nso" + | "nro" | "android-boot-image" | "android-ota-payload" | "android-sparse-image" @@ -176,6 +179,8 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] = when("ktx", hasKtx1Identifier), when("ktx2", hasKtx2Identifier), when("uimage", hasUImageMagic), + when("nso", hasNsoMagic), + when("nro", hasNroMagic), when("android-boot-image", hasAndroidBootImageMagic), ({ prefix }) => { const ota = recognizeAndroidOtaPayload(prefix); diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index 728152bda9..fe5a26f9ef 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -82,6 +82,8 @@ export const ARTIFACT_FORMAT_IDS = [ "ktx", "ktx2", "uimage", + "nso", + "nro", "android-boot-image", "android-ota-payload", "android-sparse-image", @@ -140,6 +142,8 @@ const artifactContentFormatSchema = artifactFormatSchema.extract([ "ktx", "ktx2", "uimage", + "nso", + "nro", "android-boot-image", "android-ota-payload", "android-sparse-image", diff --git a/src/domain/formatMetadata/packageAndGameMetadata.ts b/src/domain/formatMetadata/packageAndGameMetadata.ts index b009bcf0da..246bf75828 100644 --- a/src/domain/formatMetadata/packageAndGameMetadata.ts +++ b/src/domain/formatMetadata/packageAndGameMetadata.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { jsonRecordSchema } from "../jsonRecord.js"; import { jsonValueSchema } from "../jsonValue.js"; -import { offset, uint32 } from "./primitives.js"; +import { offset, sha256Hex, uint32 } from "./primitives.js"; /** Parsed source fields owned by the PCK adapter, independent of content hashes. */ export const godotPckMetadataSchema = z.strictObject({ @@ -360,3 +360,62 @@ export const tarEntryMetadataSchema = z.strictObject({ gname: z.string().nullable(), link_name: z.string().nullable(), }); + +const switchExtentSchema = z.strictObject({ offset: uint32, size: uint32 }); + +/** + * Nintendo Switch NSO or NRO header facts. Offsets and sizes are the header's + * declarations; `asset_section` is null when an NRO has no `ASET` trailer. + */ +export const switchExecutableMetadataSchema = z.strictObject({ + kind: z.literal("switch-executable"), + format: z.enum(["nso", "nro"]), + version: uint32, + flags: uint32, + /** NSO flag bits outside compression and hash checks; 0 for NRO. */ + unknown_flags: uint32, + /** Build id that pairs the module with crash logs and patches. */ + module_id: z.string().regex(/^[0-9a-f]{64}$/u), + bss_size: uint32, + /** + * MOD0 header offset, when it could be read: for NSO relative to the start + * of text (read at text+4); for NRO the header's file-relative field at 0x4. + */ + mod0_offset: uint32.nullable(), + /** NRO: whether `MOD0` is at that file offset; null for NSO or when unread. */ + mod0_present: z.boolean().nullable(), + embedded: switchExtentSchema, + dynstr: switchExtentSchema, + dynsym: switchExtentSchema, + /** NRO declared image size; null for NSO. */ + image_size: uint32.nullable(), + asset_section: z.strictObject({ offset, version: uint32 }).nullable(), +}); +export type SwitchExecutableMetadata = z.infer< + typeof switchExecutableMetadataSchema +>; + +/** One NSO/NRO segment or NRO asset as the header declares it. */ +export const switchExecutableEntryMetadataSchema = z.strictObject({ + kind: z.literal("switch-executable-entry"), + role: z.enum(["text", "rodata", "data", "icon", "nacp", "romfs"]), + file_offset: offset, + /** Load offset of a segment; null for assets. */ + memory_offset: offset.nullable(), + /** Bytes stored in the file; differs from the entry size when compressed. */ + file_size: offset, + compressed: z.boolean(), + /** Declared SHA-256 of the loaded segment (NSO only). */ + declared_sha256: sha256Hex.nullable(), + /** SHA-256 REA computed over the loaded segment, when it was read. */ + observed_sha256: sha256Hex.nullable(), + /** + * `match`/`mismatch`: the header asked for a hash check and REA compared. + * `not-checked`: the header does not request a check. `unavailable`: the + * segment could not be read or decompressed within budget. + */ + hash_status: z.enum(["match", "mismatch", "not-checked", "unavailable"]), +}); +export type SwitchExecutableEntryMetadata = z.infer< + typeof switchExecutableEntryMetadataSchema +>; diff --git a/src/domain/switchExecutable.fixture.ts b/src/domain/switchExecutable.fixture.ts new file mode 100644 index 0000000000..60fbe77cb5 --- /dev/null +++ b/src/domain/switchExecutable.fixture.ts @@ -0,0 +1,119 @@ +import { createHash } from "node:crypto"; + +import { lz4LiteralBlock } from "../../tests/fixtures/lz4LiteralBlock.js"; + +export const MODULE_ID = Buffer.from( + "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff", + "hex", +); + +export interface NsoFixtureOptions { + /** Loaded bytes for text, rodata, data. */ + readonly segments?: readonly [Buffer, Buffer, Buffer]; + readonly compress?: readonly [boolean, boolean, boolean]; + readonly hashCheck?: readonly [boolean, boolean, boolean]; + /** Store a wrong SHA-256 for this segment index. */ + readonly corruptHash?: number; + readonly extraFlags?: number; + /** Drop this many bytes from the end of the file. */ + readonly truncateBy?: number; +} + +/** Text starts with a branch and the MOD0 offset at text+4. */ +export const defaultText = (): Buffer => { + const text = Buffer.alloc(32, 0x11); + text.writeUInt32LE(0x14000002, 0); + text.writeUInt32LE(0x10, 4); + text.write("MOD0", 0x10, "latin1"); + return text; +}; + +export const buildNso = (options: NsoFixtureOptions = {}): Buffer => { + const segments = options.segments ?? [ + defaultText(), + Buffer.from("read-only data segment"), + Buffer.from("writable data"), + ]; + const compress = options.compress ?? [true, false, true]; + const hashCheck = options.hashCheck ?? [true, true, true]; + const header = Buffer.alloc(0x100); + header.write("NSO0", 0, "latin1"); + let flags = options.extraFlags ?? 0; + const stored: Buffer[] = []; + let fileOffset = 0x100; + let memoryOffset = 0; + segments.forEach((loaded, index) => { + if (compress[index]) flags |= 1 << index; + if (hashCheck[index]) flags |= 1 << (index + 3); + const bytes = compress[index] ? lz4LiteralBlock(loaded) : loaded; + const at = 0x10 + index * 0x10; + header.writeUInt32LE(fileOffset, at); + header.writeUInt32LE(memoryOffset, at + 4); + header.writeUInt32LE(loaded.length, at + 8); + header.writeUInt32LE(bytes.length, 0x60 + index * 4); + const digest = createHash("sha256").update(loaded).digest(); + if (options.corruptHash === index) + digest.writeUInt8(digest.readUInt8(0) ^ 0xff, 0); + digest.copy(header, 0xa0 + index * 0x20); + stored.push(bytes); + fileOffset += bytes.length; + memoryOffset += 0x1000; + }); + header.writeUInt32LE(flags >>> 0, 0x0c); + header.writeUInt32LE(0x40, 0x3c); + MODULE_ID.copy(header, 0x40); + const file = Buffer.concat([header, ...stored]); + return file.subarray(0, file.length - (options.truncateBy ?? 0)); +}; + +export interface NroFixtureOptions { + readonly assets?: { + readonly icon?: Buffer; + readonly nacp?: Buffer; + readonly romfs?: Buffer; + }; + readonly trailing?: Buffer; + readonly truncateBy?: number; +} + +export const buildNro = (options: NroFixtureOptions = {}): Buffer => { + const header = Buffer.alloc(0x80); + const text = Buffer.alloc(0x20, 0x22); + text.write("MOD0", 0, "latin1"); + const rodata = Buffer.from("nro rodata"); + const data = Buffer.from("nro data"); + header.writeUInt32LE(0x80, 0x04); + header.write("NRO0", 0x10, "latin1"); + const textOffset = 0x80; + const rodataOffset = textOffset + text.length; + const dataOffset = rodataOffset + rodata.length; + const size = dataOffset + data.length; + header.writeUInt32LE(size, 0x18); + header.writeUInt32LE(textOffset, 0x20); + header.writeUInt32LE(text.length, 0x24); + header.writeUInt32LE(rodataOffset, 0x28); + header.writeUInt32LE(rodata.length, 0x2c); + header.writeUInt32LE(dataOffset, 0x30); + header.writeUInt32LE(data.length, 0x34); + header.writeUInt32LE(0x100, 0x38); + MODULE_ID.copy(header, 0x40); + const parts: Buffer[] = [header, text, rodata, data]; + if (options.assets !== undefined) { + const aset = Buffer.alloc(0x38); + aset.write("ASET", 0, "latin1"); + let relative = 0x38; + const payloads: Buffer[] = []; + (["icon", "nacp", "romfs"] as const).forEach((name, index) => { + const bytes = options.assets?.[name]; + if (bytes === undefined) return; + aset.writeBigUInt64LE(BigInt(relative), 0x08 + index * 0x10); + aset.writeBigUInt64LE(BigInt(bytes.length), 0x10 + index * 0x10); + payloads.push(bytes); + relative += bytes.length; + }); + parts.push(aset, ...payloads); + } + if (options.trailing !== undefined) parts.push(options.trailing); + const file = Buffer.concat(parts); + return file.subarray(0, file.length - (options.truncateBy ?? 0)); +}; diff --git a/src/domain/switchExecutable.test.ts b/src/domain/switchExecutable.test.ts new file mode 100644 index 0000000000..1f0d3c9fca --- /dev/null +++ b/src/domain/switchExecutable.test.ts @@ -0,0 +1,282 @@ +import { expect, it } from "vitest"; + +import { ParseFailureError } from "./parseFailure.js"; +import { buildNro, buildNso, MODULE_ID } from "./switchExecutable.fixture.js"; +import { + hasMod0Magic, + hasNroMagic, + hasNsoMagic, + NRO_HEADER_SIZE, + nroMod0MagicExtent, + parseNroAssetSection, + parseNroHeader, + parseNsoHeader, + parseTextMod0Offset, +} from "./switchExecutable.js"; + +it("parses NSO segment headers, flags and the module id", () => { + const bytes = buildNso(); + expect(hasNsoMagic(bytes)).toBe(true); + const parsed = parseNsoHeader(bytes, bytes.length); + if (!parsed.ok) throw parsed.error; + expect(parsed.value).toMatchObject({ + format: "nso", + flags: 0b111101, + unknownFlags: 0, + moduleId: MODULE_ID.toString("hex"), + bssSize: 0x40, + }); + expect( + parsed.value.segments.map((segment) => [ + segment.name, + segment.memoryOffset, + segment.size, + segment.compressed, + segment.hashChecked, + segment.truncated, + ]), + ).toEqual([ + ["text", 0, 32, true, true, false], + ["rodata", 0x1000, 22, false, true, false], + ["data", 0x2000, 13, true, true, false], + ]); + // Literal-only LZ4 adds one token byte, so stored sizes exceed loaded ones. + expect(parsed.value.segments[0]?.fileSize).toBe(34); +}); + +it("keeps unknown NSO flag bits and marks a short segment as truncated", () => { + const bytes = buildNso({ extraFlags: 0x100, truncateBy: 4 }); + const parsed = parseNsoHeader(bytes, bytes.length); + expect(parsed).toMatchObject({ + ok: true, + value: { + unknownFlags: 0x100, + segments: [ + { truncated: false }, + { truncated: false }, + { truncated: true }, + ], + }, + }); +}); + +it("refuses a truncated NSO header and a segment overlapping the header", () => { + const truncated = parseNsoHeader(buildNso().subarray(0, 0x80), 0x80); + expect(truncated.ok).toBe(false); + if (!truncated.ok) { + expect(truncated.error).toBeInstanceOf(ParseFailureError); + expect(truncated.error.failure).toEqual({ + kind: "truncated", + format: "nso", + detail: expect.stringContaining("truncated"), + offset: 0, + field: "header", + extent: { availableBytes: 0x80, requiredBytes: 0x100 }, + }); + } + const overlap = buildNso(); + overlap.writeUInt32LE(0x20, 0x10); + const overlapping = parseNsoHeader(overlap, overlap.length); + expect(overlapping.ok).toBe(false); + if (!overlapping.ok) { + expect(overlapping.error).toBeInstanceOf(ParseFailureError); + expect(overlapping.error.failure).toEqual({ + kind: "malformed", + format: "nso", + detail: expect.stringContaining("overlaps the header"), + offset: 0x10, + field: "text_segment.file_offset", + }); + } +}); + +it("parses an NRO header and its ASET section", () => { + const icon = Buffer.from("jpeg"); + const nacp = Buffer.alloc(16, 1); + const bytes = buildNro({ assets: { icon, nacp } }); + expect(hasNroMagic(bytes)).toBe(true); + expect(hasNsoMagic(bytes)).toBe(false); + const parsed = parseNroHeader( + bytes.subarray(0, NRO_HEADER_SIZE), + bytes.length, + ); + if (!parsed.ok) throw parsed.error; + const header = parsed.value; + expect(header).toMatchObject({ + format: "nro", + mod0Offset: 0x80, + moduleId: MODULE_ID.toString("hex"), + segments: [ + { name: "text", fileOffset: 0x80, size: 0x20, truncated: false }, + { name: "rodata", fileOffset: 0xa0, size: 10 }, + { name: "data", fileOffset: 0xaa, size: 8 }, + ], + }); + const assets = parseNroAssetSection( + bytes.subarray(header.size), + header.size, + bytes.length, + ); + expect(assets).toEqual({ + ok: true, + value: { + offset: header.size, + version: 0, + rejected: [], + assets: [ + { + name: "icon", + fileOffset: header.size + 0x38, + size: 4, + truncated: false, + }, + { + name: "nacp", + fileOffset: header.size + 0x3c, + size: 16, + truncated: false, + }, + ], + }, + }); +}); + +it("keeps valid NRO assets when a declared range is unsafe", () => { + const bytes = buildNro({ + assets: { icon: Buffer.from("jpeg"), nacp: Buffer.alloc(16, 1) }, + }); + const offset = bytes.readUInt32LE(0x18); + const aset = bytes.subarray(offset); + aset.writeBigUInt64LE(BigInt(Number.MAX_SAFE_INTEGER) - BigInt(offset), 0x28); + aset.writeBigUInt64LE(1n, 0x30); + + expect(parseNroAssetSection(aset, offset, bytes.length)).toMatchObject({ + ok: true, + value: { + assets: [ + { name: "icon", truncated: false }, + { name: "nacp", truncated: false }, + ], + rejected: ["NRO romfs asset range exceeds a safe file offset"], + }, + }); +}); + +it("returns no asset section when the trailer is not ASET", () => { + expect(parseNroAssetSection(Buffer.from("JUNKJUNK"), 0x100, 0x108)).toEqual({ + ok: true, + value: undefined, + }); +}); + +it("refuses an NRO whose segment ends past the declared image size", () => { + const bytes = buildNro(); + bytes.writeUInt32LE(0x1000, 0x34); + const parsed = parseNroHeader(bytes, bytes.length); + expect(parsed.ok).toBe(false); + if (!parsed.ok) { + expect(parsed.error).toBeInstanceOf(ParseFailureError); + expect(parsed.error.failure).toEqual({ + kind: "malformed", + format: "nro", + detail: expect.stringContaining("past the declared image size"), + offset: 0x30, + field: "data_segment", + }); + } +}); + +it("reports structured parse failure facts for missing magic, small NRO size, and truncated headers", () => { + const missingNsoMagic = parseNsoHeader(Buffer.alloc(0x100), 0x100); + expect(missingNsoMagic.ok).toBe(false); + if (!missingNsoMagic.ok) { + expect(missingNsoMagic.error).toBeInstanceOf(ParseFailureError); + expect(missingNsoMagic.error.failure).toEqual({ + kind: "malformed", + format: "nso", + detail: "NSO magic NSO0 is missing", + offset: 0, + field: "magic", + }); + } + + const missingNroMagic = parseNroHeader(Buffer.alloc(0x80), 0x80); + expect(missingNroMagic.ok).toBe(false); + if (!missingNroMagic.ok) { + expect(missingNroMagic.error).toBeInstanceOf(ParseFailureError); + expect(missingNroMagic.error.failure).toEqual({ + kind: "malformed", + format: "nro", + detail: "NRO magic NRO0 is missing", + offset: 0x10, + field: "magic", + }); + } + + const truncatedNro = parseNroHeader(buildNro().subarray(0, 0x40), 0x40); + expect(truncatedNro.ok).toBe(false); + if (!truncatedNro.ok) { + expect(truncatedNro.error).toBeInstanceOf(ParseFailureError); + expect(truncatedNro.error.failure).toEqual({ + kind: "truncated", + format: "nro", + detail: expect.stringContaining("truncated"), + offset: 0, + field: "header", + extent: { availableBytes: 0x40, requiredBytes: NRO_HEADER_SIZE }, + }); + } + + const smallNro = buildNro(); + smallNro.writeUInt32LE(0x40, 0x18); + const parsedSmallNro = parseNroHeader(smallNro, smallNro.length); + expect(parsedSmallNro.ok).toBe(false); + if (!parsedSmallNro.ok) { + expect(parsedSmallNro.error).toBeInstanceOf(ParseFailureError); + expect(parsedSmallNro.error.failure).toEqual({ + kind: "malformed", + format: "nro", + detail: expect.stringContaining("smaller than"), + offset: 0x18, + field: "size", + }); + } + + const truncatedAset = parseNroAssetSection( + Buffer.from("ASET\0\0\0\0"), + 0x100, + 0x108, + ); + expect(truncatedAset.ok).toBe(false); + if (!truncatedAset.ok) { + expect(truncatedAset.error).toBeInstanceOf(ParseFailureError); + expect(truncatedAset.error.failure).toEqual({ + kind: "truncated", + format: "nro", + detail: expect.stringContaining("truncated"), + offset: 0x100, + field: "asset_header", + extent: { availableBytes: 8, requiredBytes: 0x38 }, + }); + } +}); + +it("reads the MOD0 offset at text+4 only from a full text prefix", () => { + const prefix = Buffer.alloc(8); + prefix.writeUInt32LE(0x1234, 4); + expect(parseTextMod0Offset(prefix)).toBe(0x1234); + expect(parseTextMod0Offset(prefix.subarray(0, 7))).toBeNull(); + expect(hasMod0Magic(Buffer.from("MOD0rest"))).toBe(true); + expect(hasMod0Magic(Buffer.from("MOD"))).toBe(false); +}); + +it("locates the NRO MOD0 magic only when the file holds it", () => { + const bytes = buildNro(); + const parsed = parseNroHeader(bytes, bytes.length); + if (!parsed.ok) throw parsed.error; + expect(nroMod0MagicExtent(parsed.value, bytes.length)).toEqual({ + offset: 0x80, + size: 4, + }); + expect(nroMod0MagicExtent(parsed.value, 0x83)).toBeUndefined(); +}); diff --git a/src/domain/switchExecutable.ts b/src/domain/switchExecutable.ts new file mode 100644 index 0000000000..f7d6ae02c1 --- /dev/null +++ b/src/domain/switchExecutable.ts @@ -0,0 +1,328 @@ +import { BinaryReader } from "./binaryContainer.js"; +import { ParseFailureError, type ParseFailure } from "./parseFailure.js"; +import { err, ok, type Result } from "./result.js"; + +/** + * Nintendo Switch NSO and NRO executable headers (switchbrew "NSO" and "NRO", + * all fields little-endian). Only the fixed headers and the NRO asset header + * are interpreted here; segment bytes are never executed or patched. + */ +export const NSO_HEADER_SIZE = 0x100; +export const NRO_HEADER_SIZE = 0x80; +export const NRO_ASSET_HEADER_SIZE = 0x38; +const NRO_MAGIC_OFFSET = 0x10; + +export const SWITCH_SEGMENT_NAMES = ["text", "rodata", "data"] as const; +export type SwitchSegmentName = (typeof SWITCH_SEGMENT_NAMES)[number]; + +/** NSO flag bits 0-5: per-segment LZ4 compression, then per-segment hash checks. */ +const NSO_KNOWN_FLAGS = 0x3f; + +const fail = (failure: ParseFailure): Result => + err(new ParseFailureError(failure)); + +export interface SwitchExtent { + readonly offset: number; + readonly size: number; +} + +export interface NsoSegment { + readonly name: SwitchSegmentName; + readonly fileOffset: number; + readonly memoryOffset: number; + /** Size of the segment once loaded, after any decompression. */ + readonly size: number; + /** Bytes the segment occupies in the file. */ + readonly fileSize: number; + readonly compressed: boolean; + readonly hashChecked: boolean; + /** SHA-256 the header declares over the loaded segment bytes. */ + readonly sha256: string; + /** The stored range ends past the end of the file. */ + readonly truncated: boolean; +} + +export interface NsoHeader { + readonly format: "nso"; + readonly version: number; + readonly flags: number; + /** Flag bits outside the six that name compression and hash checks. */ + readonly unknownFlags: number; + readonly moduleId: string; + readonly bssSize: number; + readonly embedded: SwitchExtent; + readonly dynstr: SwitchExtent; + readonly dynsym: SwitchExtent; + readonly segments: readonly NsoSegment[]; +} + +export interface NroSegment { + readonly name: SwitchSegmentName; + /** NRO segments are stored uncompressed at their memory offsets. */ + readonly fileOffset: number; + readonly size: number; + readonly truncated: boolean; +} + +export interface NroHeader { + readonly format: "nro"; + readonly version: number; + readonly flags: number; + /** Total NRO image size; an asset section, when present, starts here. */ + readonly size: number; + readonly mod0Offset: number; + readonly moduleId: string; + readonly bssSize: number; + readonly embedded: SwitchExtent; + readonly dynstr: SwitchExtent; + readonly dynsym: SwitchExtent; + readonly segments: readonly NroSegment[]; +} + +export type SwitchAssetName = "icon" | "nacp" | "romfs"; + +export interface NroAsset { + readonly name: SwitchAssetName; + /** Absolute file offset (asset-section offset plus the declared offset). */ + readonly fileOffset: number; + readonly size: number; + readonly truncated: boolean; +} + +export interface NroAssetSection { + readonly offset: number; + readonly version: number; + /** Declared assets with safe ranges and a non-zero size, in icon, NACP, RomFS order. */ + readonly assets: readonly NroAsset[]; + /** Messages for declared ranges that were skipped. */ + readonly rejected: readonly string[]; +} + +const ascii = (bytes: Buffer, offset: number, magic: string): boolean => + bytes.length >= offset + magic.length && + bytes.toString("latin1", offset, offset + magic.length) === magic; + +export const hasNsoMagic = (prefix: Buffer): boolean => + ascii(prefix, 0, "NSO0"); + +export const hasNroMagic = (prefix: Buffer): boolean => + ascii(prefix, NRO_MAGIC_OFFSET, "NRO0"); + +const extent = (reader: BinaryReader, at: number): SwitchExtent => ({ + offset: reader.u32(at), + size: reader.u32(at + 4), +}); + +/** Parse the 0x100-byte NSO header against the measured file size. */ +export const parseNsoHeader = ( + bytes: Buffer, + fileSize: number, +): Result => { + if (!hasNsoMagic(bytes)) + return fail({ + kind: "malformed", + format: "nso", + detail: "NSO magic NSO0 is missing", + offset: 0, + field: "magic", + }); + if (bytes.length < NSO_HEADER_SIZE || fileSize < NSO_HEADER_SIZE) { + const availableBytes = Math.min(bytes.length, fileSize); + return fail({ + kind: "truncated", + format: "nso", + detail: `NSO header is truncated: ${String(availableBytes)} of ${String(NSO_HEADER_SIZE)} bytes`, + offset: 0, + field: "header", + extent: { availableBytes, requiredBytes: NSO_HEADER_SIZE }, + }); + } + const reader = new BinaryReader(bytes, true, "nso"); + const flags = reader.u32(0x0c); + const segments = SWITCH_SEGMENT_NAMES.map((name, index): NsoSegment => { + const at = 0x10 + index * 0x10; + const compressed = (flags & (1 << index)) !== 0; + const size = reader.u32(at + 8); + const fileOffset = reader.u32(at); + const stored = compressed ? reader.u32(0x60 + index * 4) : size; + return { + name, + fileOffset, + memoryOffset: reader.u32(at + 4), + size, + fileSize: stored, + compressed, + hashChecked: (flags & (1 << (index + 3))) !== 0, + sha256: bytes.toString("hex", 0xa0 + index * 0x20, 0xc0 + index * 0x20), + truncated: fileOffset + stored > fileSize, + }; + }); + for (const [index, segment] of segments.entries()) + if (segment.fileOffset < NSO_HEADER_SIZE && segment.fileSize > 0) + return fail({ + kind: "malformed", + format: "nso", + detail: `NSO ${segment.name} segment offset ${String(segment.fileOffset)} overlaps the header`, + offset: 0x10 + index * 0x10, + field: `${segment.name}_segment.file_offset`, + }); + return ok({ + format: "nso", + version: reader.u32(0x04), + flags, + unknownFlags: (flags & ~NSO_KNOWN_FLAGS) >>> 0, + moduleId: bytes.toString("hex", 0x40, 0x60), + bssSize: reader.u32(0x3c), + embedded: extent(reader, 0x88), + dynstr: extent(reader, 0x90), + dynsym: extent(reader, 0x98), + segments, + }); +}; + +/** + * Bytes at the start of a loaded text segment that hold the module's MOD0 + * pointer: a branch word, then the MOD0 header offset relative to text. + */ +export const SWITCH_TEXT_PREFIX_SIZE = 8; +const MOD0_MAGIC = "MOD0"; + +/** The MOD0 offset at text+4, or null when the loaded text is too short. */ +export const parseTextMod0Offset = (textPrefix: Buffer): number | null => + textPrefix.length < SWITCH_TEXT_PREFIX_SIZE + ? null + : new BinaryReader(textPrefix, true, "nso").u32(4); + +/** + * The file range that should hold an NRO's `MOD0` magic. NRO text is stored + * at file offset 0, so the header's MOD0 offset is a file offset. Undefined + * when that range ends past the file. + */ +export const nroMod0MagicExtent = ( + header: NroHeader, + fileSize: number, +): SwitchExtent | undefined => + header.mod0Offset + MOD0_MAGIC.length <= fileSize + ? { offset: header.mod0Offset, size: MOD0_MAGIC.length } + : undefined; + +/** Whether bytes read at a MOD0 offset start with the `MOD0` magic. */ +export const hasMod0Magic = (bytes: Buffer): boolean => + ascii(bytes, 0, MOD0_MAGIC); + +/** Parse the 0x80-byte NRO header against the measured file size. */ +export const parseNroHeader = ( + bytes: Buffer, + fileSize: number, +): Result => { + if (!hasNroMagic(bytes)) + return fail({ + kind: "malformed", + format: "nro", + detail: "NRO magic NRO0 is missing", + offset: NRO_MAGIC_OFFSET, + field: "magic", + }); + if (bytes.length < NRO_HEADER_SIZE || fileSize < NRO_HEADER_SIZE) { + const availableBytes = Math.min(bytes.length, fileSize); + return fail({ + kind: "truncated", + format: "nro", + detail: `NRO header is truncated: ${String(availableBytes)} of ${String(NRO_HEADER_SIZE)} bytes`, + offset: 0, + field: "header", + extent: { availableBytes, requiredBytes: NRO_HEADER_SIZE }, + }); + } + const reader = new BinaryReader(bytes, true, "nro"); + const size = reader.u32(0x18); + if (size < NRO_HEADER_SIZE) + return fail({ + kind: "malformed", + format: "nro", + detail: `NRO declares size ${String(size)}, smaller than its ${String(NRO_HEADER_SIZE)}-byte header`, + offset: 0x18, + field: "size", + }); + const segments = SWITCH_SEGMENT_NAMES.map((name, index): NroSegment => { + const at = 0x20 + index * 8; + const fileOffset = reader.u32(at); + const segmentSize = reader.u32(at + 4); + return { + name, + fileOffset, + size: segmentSize, + truncated: fileOffset + segmentSize > fileSize, + }; + }); + for (const [index, segment] of segments.entries()) + if (segment.fileOffset + segment.size > size) + return fail({ + kind: "malformed", + format: "nro", + detail: `NRO ${segment.name} segment ends at ${String(segment.fileOffset + segment.size)}, past the declared image size ${String(size)}`, + offset: 0x20 + index * 8, + field: `${segment.name}_segment`, + }); + return ok({ + format: "nro", + version: reader.u32(0x14), + flags: reader.u32(0x1c), + size, + mod0Offset: reader.u32(0x04), + moduleId: bytes.toString("hex", 0x40, 0x60), + bssSize: reader.u32(0x38), + embedded: extent(reader, 0x68), + dynstr: extent(reader, 0x70), + dynsym: extent(reader, 0x78), + segments, + }); +}; + +/** + * Parse an NRO `ASET` header read at `offset`. Returns undefined when the + * bytes there do not start with `ASET`, so a plain NRO stays asset-free. + */ +export const parseNroAssetSection = ( + bytes: Buffer, + offset: number, + fileSize: number, +): Result => { + if (!ascii(bytes, 0, "ASET")) return ok(undefined); + if (bytes.length < NRO_ASSET_HEADER_SIZE) + return fail({ + kind: "truncated", + format: "nro", + detail: `NRO asset header is truncated: ${String(bytes.length)} of ${String(NRO_ASSET_HEADER_SIZE)} bytes`, + offset, + field: "asset_header", + extent: { + availableBytes: bytes.length, + requiredBytes: NRO_ASSET_HEADER_SIZE, + }, + }); + const reader = new BinaryReader(bytes, true, "nro"); + const assets: NroAsset[] = []; + const rejected: string[] = []; + const names: readonly SwitchAssetName[] = ["icon", "nacp", "romfs"]; + for (const [index, name] of names.entries()) { + const at = 0x08 + index * 0x10; + const relative = reader.word(at, 64); + const size = reader.word(at + 8, 64); + if (size === 0n) continue; + const absolute = BigInt(offset) + relative; + if (absolute + size > BigInt(Number.MAX_SAFE_INTEGER)) { + rejected.push(`NRO ${name} asset range exceeds a safe file offset`); + continue; + } + const fileOffset = Number(absolute); + const assetSize = Number(size); + assets.push({ + name, + fileOffset, + size: assetSize, + truncated: fileOffset + assetSize > fileSize, + }); + } + return ok({ offset, version: reader.u32(0x04), assets, rejected }); +}; diff --git a/src/domain/targetFormats.ts b/src/domain/targetFormats.ts index 3003d29689..cd25a0a608 100644 --- a/src/domain/targetFormats.ts +++ b/src/domain/targetFormats.ts @@ -29,6 +29,8 @@ export const BINARY_TARGET_FORMAT_KINDS = { ktx: "archive", ktx2: "archive", uimage: "archive", + nso: "archive", + nro: "archive", "android-boot-image": "archive", "android-ota-payload": "archive", "android-sparse-image": "archive", diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index 3d6496f188..7fd324d1e4 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -261,6 +261,8 @@ export interface ArtifactReader { | "ktx" | "ktx2" | "uimage" + | "nso" + | "nro" | "android-boot-image" | "android-ota-payload" | "android-sparse-image"