Files
reverse-engineering-anything/src/resources/ArtifactFileOperation.ts
T
7fd50eb361 fix(zstd): share exact-frame Zstandard decoding across ELF and OTA (#12416)
* fix(zstd): share exact-frame Zstandard decoding across ELF and OTA

Walk RFC 8878 frames once so ELF sections, Android OTA REPLACE_ZSTD, and GPU payloads reject truncated headers, blocks, checksums, and trailing bytes on every supported Node runtime. Bound that walk with the runtime zstd.max_frames setting.

* fix(zstd): keep frame output tight and report GPU frame-cap refusals

Copy each Node 22 frame off its decoder chunk before the next frame is decoded. Map a GPU zstd.max_frames refusal through the resource-limit contract instead of a provider failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): keep frame-cap refusals and bad seeds out of malformed results

Project zstd.max_frames through one resource-limit helper for ELF notes, DWARF, GPU, and artifact reads. An invalid REA_ZSTD_MAX_FRAMES seed stays a configuration failure, and frame-header tests cover content size, window, dictionary id, and RLE blocks.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield GPU frame decoding so cancellation can land

The frame-by-frame fallback awaits a caller pause before each data frame. GPU yields and checks the read signal there, so a many-frame payload does not finish before a disconnect is observed.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): advertise the frame cap and keep strict GPU decode cancellable

List every operation that enforces zstd.max_frames, including GPU, DWARF, and ELF notes. The strict sequence uses the async decoder and checks the caller signal again after it returns, and a single output buffer is not copied a second time.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): refresh analysis-setting schemas and GPU frame-cap projection

Regenerate the advertised input summaries for inspect_analysis_settings and update_analysis_settings. GPU inventory now throws the projected zstd.max_frames resource limit from payload decode and #retainFailure, so the adjustable setting survives the public failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style(gpu): format the frame-cap projection throw

oxfmt keeps the zstd.max_frames throw in #retainFailure on one line so CI format:check matches the local formatter.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield after the last frame-by-frame GPU decode

The fallback returned success in the same turn as the final synchronous frame, so a queued abort was still invisible to the caller's signal check. Pause once more before that success, matching the strict sequence.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield ELF, OTA, and DWARF frame decoding on the caller signal

The synchronous frame loop ignored abort signals owned by inspect_elf_notes, inspect_dwarf_units, and Android OTA partition reads. Those callers now use the cooperative decoder and yield before Zstandard work, and 32-frame cancellations cover each path.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): observe cancellation during structural parsing

* fix(zstd): project section-name frame caps at the ELF directory boundary

readElfDirectoryFromBuffer now requires the caller's operation and throws the adjustable zstd.max_frames resource limit. Hardening, unwind, and the other directory consumers keep that typed refusal instead of an adapter or I/O error.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): preserve optional ELF evidence when frames are capped

* fix(zip): validate Zstandard members through frame completion (#12461)

fix(zip): require complete Zstandard member frames

* fix(elf): yield hardening section name decoding

* fix(elf): yield section names for unwind and export reads

* fix(zstd): yield ELF directory reads that already own a cancellation signal

Hardening, unwind, initializers, exports, kernel modules, debug link, and Android JNI now read section names through the cooperative directory when their caller has a signal. Readers with no signal stay synchronous.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): share one initializer directory and retain its snapshot

* fix(android): reuse the admitted JNI ELF directory

* fix(elf): retain optional debug candidate evidence through cooperative decoding

* fix(zstd): yield ELF section names for Go, Rust, and IL2CPP

These inspections already own an abort signal. Their ELF directory read now uses the cooperative container decoder so a queued cancellation can land during a many-frame section-name table.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): recognize compressed kernel modules before ELF decoding

The cooperative module reader decoded the bytes as ELF before the container check, so gzip, xz, and zstd modules became malformed images. The compression check now returns the unsupported-container report first.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* refactor(elf): classify each container once before reading it

* fix(il2cpp): preserve admission order during cooperative linking

* fix(elf): reuse section-name decoding in debug-link comparison (#12472)

* style(elf): format updated section-reader test calls

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-19 19:45:26 +00:00

392 lines
13 KiB
TypeScript

import type { FileHandle } from "node:fs/promises";
import { scheduler } from "node:timers/promises";
import {
RegularFileOperationCancelled,
type StableRegularFileDescriptor,
} from "../filesystem/RegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
withOwnedFileHandle,
withOwnedRegularFile,
RegularFileCancelled,
RegularFileCleanupFailure,
} from "../filesystem/OwnedRegularFile.js";
import {
ArtifactReaderFailure,
artifactPrimaryCleanupLeases,
} from "./ArtifactReader.js";
import type {
ArtifactResourceOwner,
ArtifactResourceScope,
} from "./ArtifactResourceScope.js";
import {
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
} from "./AnalysisCleanupLease.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { ArtifactLimitBoundary } from "../domain/artifactOperationError.js";
import { ParseFailureError, type LimitRef } from "../domain/parseFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** Artifact projection plus the exact descriptor owner and physical operation outcome. */
export class ArtifactFileCleanupFailure<
Value = unknown,
> extends ArtifactReaderFailure {
override readonly cleanupLeases: readonly AnalysisCleanupLease[] | undefined;
readonly fileCleanupFailure: RegularFileCleanupFailure<Value>;
constructor(
fileCleanupFailure: RegularFileCleanupFailure<Value>,
readonly cleanupLease: AnalysisCleanupLease,
) {
const outcome = fileCleanupFailure.outcome;
if (
fileCleanupFailure.operationFailure === undefined &&
outcome.kind === "failed" &&
outcome.cause instanceof RegularFileOperationCancelled
)
fileCleanupFailure = new RegularFileCleanupFailure({
...fileCleanupFailure,
outcome: {
kind: "failed",
cause: artifactOperationCause(outcome.cause),
},
});
const completionCancellation = fileCleanupFailure.completionCancellation;
const primary =
fileCleanupFailure.outcome.kind === "failed"
? fileCleanupFailure.outcome.cause
: completionCancellation === undefined
? fileCleanupFailure.cleanupCause
: new ArtifactReaderFailure(
"cancelled",
"Artifact read cancelled during close",
{
cause: completionCancellation.reason,
},
);
const projected = ArtifactReaderFailure.withCleanup(
fileCleanupFailure.operationFailure !== undefined &&
fileCleanupFailure.outcome.kind === "failed" &&
Object.is(primary, fileCleanupFailure.operationFailure.operationCause)
? new ArtifactReaderFailure("io", errorMessage(primary), {
cause: primary,
})
: primary,
ArtifactReaderFailure.cleanupObservation(
fileCleanupFailure.cleanupCause,
fileCleanupFailure.path,
),
);
super(
projected.reason,
projected.message,
{
cause: fileCleanupFailure,
cleanup: projected.cleanup,
partialObservation: projected.partialObservation,
cancellation: projected.cancellation,
...projected.primaryFacts(),
},
projected.details,
);
this.fileCleanupFailure = fileCleanupFailure;
const inherited =
fileCleanupFailure.operationFailure === undefined &&
fileCleanupFailure.outcome.kind === "failed"
? artifactPrimaryCleanupLeases(fileCleanupFailure.outcome.cause)
: [];
this.cleanupLeases =
inherited === undefined
? undefined
: [...new Set([cleanupLease, ...inherited])];
}
}
/** Errnos raised while the caller-selected artifact path is being resolved. */
export type ArtifactSelectedPathErrno =
| "ENOENT"
| "ENOTDIR"
| "ELOOP"
| "ENAMETOOLONG";
/** Return only known path-resolution errnos; permissions and I/O remain distinct. */
export const artifactSelectedPathErrno = (
cause: unknown,
): ArtifactSelectedPathErrno | undefined => {
if (!(cause instanceof Error) || !("code" in cause)) return undefined;
switch (String(cause.code)) {
case "ENOENT":
return "ENOENT";
case "ENOTDIR":
return "ENOTDIR";
case "ELOOP":
return "ELOOP";
case "ENAMETOOLONG":
return "ENAMETOOLONG";
default:
return undefined;
}
};
/** Normalize the physical primary failure without replacing its exact cleanup owner. */
export const mapArtifactFileFailure = (
cause: unknown,
classify: (cause: unknown) => unknown,
): unknown => {
if (!(cause instanceof ArtifactFileCleanupFailure)) return classify(cause);
const physical = cause.fileCleanupFailure;
if (physical.outcome.kind !== "failed") return cause;
const primary =
physical.operationFailure === undefined &&
physical.outcome.cause instanceof ArtifactFileCleanupFailure
? mapArtifactFileFailure(physical.outcome.cause, classify)
: classify(physical.outcome.cause);
if (Object.is(primary, physical.outcome.cause)) return cause;
return new ArtifactFileCleanupFailure(
new RegularFileCleanupFailure({
...physical,
outcome: { kind: "failed", cause: primary },
}),
cause.cleanupLease,
);
};
export interface ArtifactFilePrimaryFacts {
readonly cause: unknown;
readonly origin: "opaque-operation" | "owned-or-classified";
}
/** Preserve physical origin while inspecting only explicit nested operation owners. */
export const artifactFilePrimaryFacts = (
cause: unknown,
): ArtifactFilePrimaryFacts => {
while (cause instanceof ArtifactFileCleanupFailure) {
const physical = cause.fileCleanupFailure;
if (physical.outcome.kind !== "failed") break;
cause = physical.outcome.cause;
if (physical.operationFailure !== undefined)
return {
cause,
origin: Object.is(cause, physical.operationFailure.operationCause)
? "opaque-operation"
: "owned-or-classified",
};
}
return { cause, origin: "owned-or-classified" };
};
/** Cancellation after confirmed close retains the completed physical operation. */
export class ArtifactFileCancelled<
Value = unknown,
> extends ArtifactReaderFailure {
constructor(
readonly fileCancellation: Pick<
RegularFileCancelled<Value>,
"reason" | "outcome"
>,
) {
super("cancelled", "Artifact read cancelled", {
cause: fileCancellation.reason,
});
}
}
/** Completion facts recorded by the file owner, independent of later caller state. */
export const artifactFileCompletion = (
cause: unknown,
):
| {
readonly kind: "completed";
readonly value: unknown;
readonly cancellation: { readonly reason: unknown } | undefined;
}
| undefined => {
if (cause instanceof ArtifactFileCancelled)
return {
...cause.fileCancellation.outcome,
cancellation: { reason: cause.fileCancellation.reason },
};
if (
cause instanceof ArtifactFileCleanupFailure &&
cause.fileCleanupFailure.outcome.kind === "completed"
)
return {
...cause.fileCleanupFailure.outcome,
cancellation: cause.fileCleanupFailure.completionCancellation,
};
return undefined;
};
/** Bind a translated failure to its exact descriptor leases, including failed retries. */
export const bindArtifactFileCleanup = (
cause: unknown,
error: AnalysisError,
): void => {
const leases =
cause instanceof ArtifactReaderFailure ? cause.cleanupLeases : undefined;
if (leases !== undefined) new AnalysisCleanupLeaseGroup(error, leases);
};
/** Interpret this owner's typed cancellation, preserving an undefined reason. */
export const artifactFileCancellationCause = (
cause: ArtifactReaderFailure,
): unknown => {
return cause.cancellation === undefined
? cause.cause
: cause.cancellation.reason;
};
/** Report cancellation at the read stage that actually observed the caller signal. */
export const assertArtifactReadActive = (
signal: AbortSignal | undefined,
): void => {
if (signal?.aborted)
throw new ArtifactReaderFailure("cancelled", "Artifact read cancelled", {
cause: signal.reason,
});
};
/**
* Let a queued abort land, then report it. Synchronous multi-frame decoding
* cannot observe the signal until the caller yields.
*/
export const yieldArtifactRead = async (
signal: AbortSignal | undefined,
): Promise<void> => {
await scheduler.yield();
assertArtifactReadActive(signal);
};
/**
* Project a failure raised by a domain byte parser over artifact bytes onto the
* reader's reasons: the caller's cancellation (`signal.reason`) becomes
* `cancelled`, parser failure kinds and limit facts survive, and
* `limitBoundary` describes what a decode budget constrains. Every other cause
* passes through unchanged.
*/
export const artifactParseFailure = (
cause: unknown,
signal: AbortSignal | undefined,
limitBoundary?: (limit: LimitRef) => ArtifactLimitBoundary | undefined,
): unknown => {
if (signal?.aborted === true && Object.is(cause, signal.reason))
return new ArtifactReaderFailure("cancelled", "Artifact read cancelled", {
cause,
});
if (!(cause instanceof ParseFailureError)) return cause;
const { failure } = cause;
if (failure.kind === "limit") {
const boundary = limitBoundary?.(failure.limit);
return new ArtifactReaderFailure("limit", cause.message, {
cause,
parserLimit: failure.limit,
...(boundary === undefined ? {} : { boundary }),
});
}
return new ArtifactReaderFailure(failure.kind, cause.message, { cause });
};
/** Recognize only the originating caller's cancellation without discarding cleanup ownership. */
export const artifactReadCancelledBy = (
cause: unknown,
signal: AbortSignal | undefined,
): boolean =>
signal?.aborted === true &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled" &&
cause.cleanup === undefined &&
Object.is(cause.cancellation?.reason, signal.reason);
/** Admit a regular file without blocking on pipes, retaining failed admission closes. */
export const withArtifactRegularFile = async <Value>(
path: string,
resources: {
retain(
owner: Extract<ArtifactResourceOwner, { readonly kind: "lease" }>,
): void;
},
signal: AbortSignal | undefined,
operation: (source: StableRegularFileDescriptor) => Promise<Value>,
symlinks: "follow" | "reject" = "reject",
): Promise<Value> => {
let cleanupLease: AnalysisCleanupLease | undefined;
assertArtifactReadActive(signal);
try {
const value = await withOwnedRegularFile(
path,
{
symlinks,
...(signal === undefined ? {} : { signal }),
retainFailedClose: (owner) => {
cleanupLease = new AnalysisCleanupLease(() => owner.close(), [path]);
resources.retain({
kind: "lease",
resource: path,
lease: cleanupLease,
});
},
},
async (source) => {
assertArtifactReadActive(signal);
return await operation(source);
},
);
return value;
} catch (cause: unknown) {
if (
cause instanceof RegularFileCleanupFailure &&
cleanupLease !== undefined
)
throw new ArtifactFileCleanupFailure(cause, cleanupLease);
if (cause instanceof RegularFileCancelled)
throw new ArtifactFileCancelled(cause);
throw artifactOperationCause(cause);
}
};
/** Keep admission, operation outcome, final close and failed-owner transfer together. */
export const withArtifactFileHandle = async <Value>(
path: string,
file: FileHandle | OwnedFileHandle,
resources: ArtifactResourceScope | undefined,
signal: AbortSignal | undefined,
operation: (file: FileHandle) => Promise<Value>,
): Promise<Value> => {
const owner: OwnedFileHandle & {
readonly cleanupResources?: readonly string[];
} = file instanceof OwnedFileHandle ? file : new OwnedFileHandle(file);
const cleanupLease = AnalysisCleanupLease.forCloseOwner(owner, path);
try {
return await withOwnedFileHandle(
path,
owner,
{
...(signal === undefined ? {} : { signal }),
retainFailedClose: () =>
resources?.retain({
kind: "lease",
resource: path,
lease: cleanupLease,
}),
},
operation,
);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure)
throw new ArtifactFileCleanupFailure(cause, cleanupLease);
if (cause instanceof RegularFileCancelled)
throw new ArtifactFileCancelled(cause);
throw artifactOperationCause(cause);
}
};
/** Convert only cancellation produced by the regular-file owner. */
export const artifactOperationCause = (cause: unknown): unknown =>
cause instanceof RegularFileOperationCancelled
? new ArtifactReaderFailure(
"cancelled",
"Artifact file operation cancelled",
{ cause: cause.reason },
)
: cause;