Files
reverse-engineering-anything/src/artifacts/InesArtifactReader.ts
T
David Muñoz Reyandmorluto cd3590c8ee feat(artifacts): inspect NES 2.0 container headers and regions (#10674)
* feat(artifacts): inspect NES 2.0 container headers and regions

Problem: the iNES lane refused every header whose byte 7 bits 2-3 select
NES 2.0, so NES 2.0 cartridges could not be inventoried, extracted or
reconstructed even though their file layout extends classic iNES.

Fix: the single iNES-family header parser now reads NES 2.0 alongside
classic iNES. It reports the 12-bit mapper, submapper, 12-bit and
exponent-multiplier PRG/CHR sizes, declared PRG/CHR RAM and NVRAM sizes,
CPU/PPU timing, console type with Vs. System and extended console codes,
miscellaneous ROM count and default expansion device in a "nes-2.0"
header variant; classic headers keep their exact serialization. Regions
add one prg.bin/chr.bin for exponent sizes and misc-rom.bin for the bytes
after CHR-ROM when miscellaneous ROMs are declared. Oversized
declarations (with exact totals, including exponent sizes beyond safe
integers), nonzero unused header bits, empty PRG-ROM and declared but
absent miscellaneous ROM bytes are refused through the existing format
error. Nested byte classification now admits NES 2.0 through the same
parser. The reader limitation, tool description, guide and skill
reference now state that UNIF remains unsupported and that RAM, timing
and console values are declarations.

Validation: new synthetic NES 2.0 unit cases fail on the base (15 of 24)
and pass after the change; focused boundary and acceptance iNES suites
(75 tests) pass, including NES 2.0 inventory, extraction, reconstruction
and compiled CLI inspection; npm run check:fast passes.

Refs morluto/rea#2072

* test(artifacts): extract an exponent-sized NES 2.0 ROM area

Review follow-up for NES 2.0 headers.

The exponent-multiplier case stopped at parseInesLayout, and the
extraction test used counted ROM units, so prg.bin and chr.bin from
an exponent-sized area never went through the reader or extraction.
A boundary case now builds a NES 2.0 file with a 2^10 * 3 byte PRG-ROM
area beside one counted 8 KiB CHR-ROM unit. It checks the header omits
the PRG unit count, the source offsets of prg.bin and chr/000.bin,
the verified reconstruction order, and that the extracted regions
match the original bytes exactly.

Tests: tests/boundary/filesystem/inesArtifact.test.ts passes (38).

* refactor(artifacts): read NES header bytes through one helper

The NES 2.0 declaration added a sixth raw Buffer read to
inesContainer.ts. On current main the architecture guard allows five
there, so the merged tree failed Static checks. iNES and NES 2.0
declarations and the format probe now read header bytes through one
headerByte helper. The file has one raw read, and its counted baseline
drops from 5 to 1 through --shrink-baselines.

Tests: inesContainer domain tests (24) and the NES boundary and
acceptance tests (76) pass. architecture-guards, format:check and
check:ci:fast pass on the branch merged with main.

* refactor(artifacts): report iNES header failures through ParseFailure

Review follow-up: the NES 2.0 declaration added plain-string failures.
The iNES-family parser now returns Result<_, ParseFailure> with its
kind and where it was found:
- malformed: a missing signature, a dirty legacy header, an empty
  PRG-ROM area, reserved NES 2.0 bits or an invalid file extent;
- truncated: a short header, a short payload, or declared
  miscellaneous ROM with no bytes;
- unsupported: UNIF or another header variant, with undecoded content.
The detail text is unchanged.

The format registry refuses with the detail, and the iNES reader and
root classifier translate the failure at their boundary into the
existing format ArtifactReaderFailure, with the ParseFailureError as
its cause.

Tests: the refusal table now asserts each failure's kind and format
as well as its detail. iNES domain and recognition tests, NES boundary
and acceptance tests (76), architecture-guards, format:check and
check:ci:fast pass on the branch merged with main.

* fix(artifacts): preserve NES header declarations and iNES evidence

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-19 20:49:33 +00:00

320 lines
11 KiB
TypeScript

import { ParseFailureError } from "../domain/parseFailure.js";
import {
artifactOperationCause,
ArtifactReaderFailure,
copyArtifactEntry,
assertProducedEntry,
type ArtifactEntry,
type ArtifactReader,
type ArtifactTraversalOptions,
streamChunkToBuffer,
abortIfNeeded,
ArtifactResourceScope,
} from "../resources/index.js";
import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js";
import { Transform, pipeline, type Readable } from "node:stream";
import {
parseInesLayout,
type InesInventory,
type InesLayout,
} from "../domain/inesContainer.js";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
import {
RegularFileChangedError,
RegularFileOperationCancelled,
assertStableRegularFileIdentity,
type StableRegularFileDescriptor,
} from "../filesystem/RegularFile.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
const CLASSIC_INES_LIMITATION =
"Classic iNES file regions are observed; mapper execution, CPU bank mappings, CHR-RAM contents, 6502 analysis and emulator behavior are not observed. Trailing bytes are retained without interpretation. NES 2.0 and UNIF are unsupported.";
const NES_2_LIMITATION =
"NES 2.0 file regions are observed; header mapper, nametable layout flags, RAM/NVRAM, timing, console and expansion-device values are declarations. Effective nametable wiring, mapper execution, CPU bank mappings, CHR-RAM contents, miscellaneous ROM boundaries, 6502 analysis and emulator behavior are not observed. Trailing bytes are retained without interpretation. UNIF is unsupported.";
/** Keep the classic inventory's existing semantic limitation and Evidence identity. */
export const inesInventoryLimitation = (
header: InesInventory["header"],
): string =>
header.format === "ines" ? CLASSIC_INES_LIMITATION : NES_2_LIMITATION;
/** Actual concatenated bytes observed by the inventory's ordered region scan. */
export type InesRegionScan = Omit<InesInventory["reconstruction"], "verified">;
const regionReadFailure = (cause: unknown): ArtifactReaderFailure =>
cause instanceof ArtifactReaderFailure
? cause
: new ArtifactReaderFailure("io", "Could not read iNES region", { cause });
/** Read positional regions from a descriptor retained by the artifact resource scope. */
export class InesArtifactReader implements ArtifactReader {
readonly format = "ines" as const;
readonly #entries = new Map<string, ArtifactEntry>();
readonly #scope = new ArtifactResourceScope();
readonly #lifecycle = new AbortController();
readonly #closedFailure = new ArtifactReaderFailure(
"unavailable",
"iNES reader is closed",
);
#layout: InesLayout | undefined;
#closed = false;
constructor(
private readonly path: string,
private readonly source: StableRegularFileDescriptor,
private readonly ownedSource?: OwnedFileHandle,
) {}
async *entries(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncIterable<ArtifactEntry> {
const layout = await this.#scope.run(async () => {
await this.#verifySource(signal);
const prefix = await readFileHandlePrefix(this.source.handle, 16, () =>
abortIfNeeded(signal),
);
abortIfNeeded(signal);
// Concurrent source changes take precedence over malformed header diagnostics.
await this.#verifySource(signal);
const parsed = parseInesLayout(prefix, this.source.initial.size);
if (!parsed.ok)
throw new ArtifactReaderFailure("format", parsed.error.detail, {
cause: new ParseFailureError(parsed.error),
});
this.#layout = parsed.value;
this.#entries.clear();
return parsed.value;
});
for (const region of layout.regions) {
this.#assertOpen(signal);
const entry: ArtifactEntry = {
path: region.path,
kind: "file",
declaredSize: region.length,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset: region.offset,
declaredIntegrity: null,
unpacked: false,
limitations: [],
adapterKey: region.path,
};
this.#entries.set(entry.adapterKey, copyArtifactEntry(entry));
yield entry;
}
this.#assertOpen(signal);
// The regions tile the file: header, trainer, units and any trailing bytes.
options?.onCoverage?.({ status: "complete", limitations: [] });
}
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
return this.#scope.run(() => this.#openRegion(entry, signal));
}
async #openRegion(
entry: ArtifactEntry,
signal?: AbortSignal,
): Promise<Readable> {
this.#assertOpen(signal);
const produced = this.#entries.get(entry.adapterKey);
assertProducedEntry(
entry,
produced,
"iNES region does not match this reader's inventory",
);
await this.#verifySource(signal);
this.#assertOpen(signal);
const offset = produced.byteOffset;
const size = produced.declaredSize;
if (offset === null || size === null || size <= 0)
throw new ArtifactReaderFailure(
"integrity",
"Invalid iNES region range",
{ integrityCheck: "layout-consistency" },
);
const active = AbortSignal.any([
this.#lifecycle.signal,
...(signal === undefined ? [] : [signal]),
]);
const failure = (): ArtifactReaderFailure =>
this.#lifecycle.signal.aborted && active.reason === this.#closedFailure
? this.#closedFailure
: new ArtifactReaderFailure("cancelled", "iNES region read cancelled", {
cause: active.reason,
});
const source = readFileHandleChunks(this.source.handle, {
start: offset,
end: offset + size - 1,
signal: active,
cancellationFailure: failure,
});
// Transform destruction can precede an asynchronous final callback. Keep
// that descriptor validation admitted independently of stream retirement.
const verify = () =>
this.#scope.run(() => this.#verifySource(active, failure));
const assertActive = () => this.#assertOpen(active, failure);
let bytes = 0;
const output = new Transform({
destroy(cause, callback) {
callback(cause === null ? null : regionReadFailure(cause));
},
transform(raw: unknown, _encoding, callback) {
try {
assertActive();
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
callback(null, chunk);
} catch (cause: unknown) {
callback(regionReadFailure(cause));
}
},
final(callback) {
void (async () => {
if (bytes !== size)
throw new ArtifactReaderFailure(
"integrity",
"Truncated iNES region",
{ integrityCheck: "read-coverage" },
);
await verify();
})().then(
() => callback(),
(cause: unknown) => callback(regionReadFailure(cause)),
);
},
});
output.on("error", () => undefined);
let producerComplete = false;
const onAbort = (): void => {
if (producerComplete && !output.destroyed) output.destroy(failure());
};
const retired = new Promise<void>((resolve) => {
output.once("close", () => {
active.removeEventListener("abort", onAbort);
resolve();
});
});
active.addEventListener("abort", onAbort, { once: true });
void this.#scope
.run(async () => {
await Promise.all([
new Promise<void>((resolve) => {
pipeline(source, output, () => {
producerComplete = true;
if (active.aborted) onAbort();
resolve();
});
}),
retired,
]);
})
.catch((cause: unknown) => output.destroy(regionReadFailure(cause)));
return output;
}
/** Validate the completed region scan without rereading its payload. */
async verifyReconstruction(
expectedSha256: string,
observed: InesRegionScan,
signal?: AbortSignal,
): Promise<InesInventory> {
return this.#scope.run(() =>
this.#verifyReconstruction(expectedSha256, observed, signal),
);
}
async #verifyReconstruction(
expectedSha256: string,
observed: InesRegionScan,
signal?: AbortSignal,
): Promise<InesInventory> {
this.#assertOpen(signal);
const layout = this.#layout;
if (layout === undefined || this.#entries.size !== layout.regions.length)
throw new ArtifactReaderFailure(
"integrity",
"Incomplete iNES inventory",
{
integrityCheck: "reconstruction",
},
);
await this.#verifySource(signal);
if (
observed.region_order.length !== layout.regions.length ||
layout.regions.some(
(region, index) => observed.region_order[index] !== region.path,
) ||
observed.bytes !== this.source.initial.size ||
observed.sha256 !== expectedSha256
)
throw new ArtifactReaderFailure(
"integrity",
"iNES reconstruction differs from the source",
{ integrityCheck: "reconstruction" },
);
return {
header: layout.header,
reconstruction: {
...observed,
verified: true,
},
};
}
provenance(): readonly ArtifactCommand[] {
return [];
}
async close(): Promise<void> {
// Inventory borrows its admitting scope's descriptor. Extraction owns its
// separately opened descriptor and retains this reader if close fails.
this.#closed = true;
this.#lifecycle.abort(this.#closedFailure);
await this.#scope.close();
await this.ownedSource?.close();
}
async #verifySource(
signal?: AbortSignal,
interruption?: () => ArtifactReaderFailure,
): Promise<void> {
this.#assertOpen(signal, interruption);
try {
await assertStableRegularFileIdentity(
this.source.handle,
this.path,
this.source.initial,
{ symlinks: "reject", ...(signal === undefined ? {} : { signal }) },
);
} catch (cause: unknown) {
if (
interruption !== undefined &&
cause instanceof RegularFileOperationCancelled
)
throw interruption();
if (cause instanceof RegularFileChangedError)
throw new ArtifactReaderFailure(
"integrity",
"iNES source changed during reading",
{ cause: cause.cause ?? cause, integrityCheck: "container-identity" },
);
throw artifactOperationCause(cause);
}
// State validation is asynchronous even after the final byte was consumed.
this.#assertOpen(signal, interruption);
}
#assertOpen(
signal?: AbortSignal,
interruption?: () => ArtifactReaderFailure,
): void {
if (signal?.aborted === true && interruption !== undefined)
throw interruption();
abortIfNeeded(signal);
if (this.#closed) throw this.#closedFailure;
}
}