Files
reverse-engineering-anything/src/gpu/GpuCodeObjectsProvider.ts
T
morluto 1badb6a8ae fix(native)!: report details.limit for remaining native reader budgets and make BEAM table rows adjustable (#14631)
* fix(native)!: report details.limit for native reader per-call budgets

Devicetree, Windows shortcut, kernel build config, firmware staging and
byte-entropy refusals of caller-selected budgets named their control only
in remediation prose. Each now sets details.limit from a domain-owned
budget object that also builds the schema (src/domain/parameterBudget.ts),
so the reported range is the one the next call accepts.

inspect_devicetree's fixed 32 MiB decoded representation allowance becomes
the per-call max_decoded_bytes (default 32 MiB, 1 KiB to 256 MiB); its
refusal reports boundary max_decoded_bytes instead of decoded_bytes.

The pwntools allocation failure declares measuredExhaustion, the firmware
inherited RLIMIT_FSIZE refusal declares measuredExhaustion, and the LLDB
combined-result ceiling is a registered representation bound.

Part of #14234 and #14235.

BREAKING CHANGE: inspect_devicetree's decoded-representation refusal reports
reported_limits.boundary "max_decoded_bytes" with details.limit, instead of
"decoded_bytes".

* fix(native): keep FIT decoded-budget boundary, LLDB narrowing and entropy length range exact

The FIT reader compared the renamed devicetree limit against decoded_bytes, so a decoded-budget refusal became capacity; it now checks max_decoded_bytes, with a test. The LLDB representation ceiling keeps a short name and carries its recovery as narrowing. The byte-entropy length maximum is the window the selected block_size admits.

* fix(cli): describe inspect-devicetree --max-decoded-bytes

* refactor(native): let the generated adjustable-budget recovery name the native reader controls

With #14625 the refusal owns per-call recovery, so the devicetree, Windows shortcut, kernel build config, firmware staging and byte-entropy refusals drop their authored sentences. inspect_byte_entropy reports the smallest admitting block_size as required_value.

* fix(native)!: report details.limit for remaining native reader budgets and make BEAM table rows adjustable

inspect_elf_dependencies, inspect_elf_unwind_ranges, inspect_apple_ips,
inspect_dwarf_units, inspect_native_initializers and inspect_pe_resources
named their per-call budgets only in remediation prose. Each now reports
details.limit from a domain-owned budget object that also builds the
schema. The unwind per-page symbol-name text refusal names the page size
`limit`, the control that admits it.

The fixed 65,536-row BEAM table ceiling becomes the per-call
max_table_rows (default 65,536, at most 1,048,576).

The plist nesting allowance is reclassified as a representation bound
(MAX_JSON_DEPTH less the report envelope). GPU and APK input refusals that
named their fixed allowances only in prose now declare them, registered
as pending #14235.

Part of #14234 and #14235.

BREAKING CHANGE: a BEAM table-row refusal reports details.limit for
max_table_rows instead of a fixed_ceiling refusal.

* fix(native): keep naming the dependency and BEAM row controls in recovery

* refactor(native): let the generated adjustable-budget recovery name the remaining native controls

With #14625 the refusal owns per-call recovery, so the ELF dependency, ELF unwind, Apple IPS, DWARF, initializer, PE resource and BEAM refusals drop their authored sentences. BEAM reports the complete row and atom counts as required_value. The unwind per-page text allowance is a registered fixed allowance whose narrowing names a smaller limit, because a larger page would not admit it.

* style: format the PE resources provider test

* refactor(native): keep one owner of the IPS budget bounds and document the unwind text allowance
2026-11-26 04:31:33 +00:00

348 lines
12 KiB
TypeScript

import {
readerIntegrityFailure,
ArtifactResourceScope,
ArtifactReaderFailure,
withArtifactRegularFile,
bindArtifactFileCleanup,
artifactFilePrimaryFacts,
artifactFileCancellationError,
artifactFileCompletion,
selectedFileTargetError,
} from "../resources/index.js";
import { GPU_CODE_OBJECTS_PROVIDER_IDENTITY } from "./GpuCodeObjectsProviderIdentity.js";
import { lstat, type FileHandle } from "node:fs/promises";
import type { GpuCodeObjectsPort } from "../ports/gpu/GpuCodeObjectsPort.js";
import {
createGpuCodeObjectsEvidence,
createGpuCodeObjectsPartialEvidence,
} from "../domain/gpu/gpuCodeObjectsEvidence.js";
import type { ExecutionOptions } from "../ports/AnalysisProvider.js";
import type {
GpuCodeObjects,
GpuCodeObjectsInput,
} from "../domain/gpu/gpuCodeObjects.js";
import {
gpuCodeObjectsSchema,
gpuCodeObjectsPartialSchema,
} from "../domain/gpu/gpuCodeObjects.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisArtifactChangedError,
AnalysisAccessDeniedError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import {
parseFailureAnalysisError,
parseLimitConstraint,
} from "../domain/parseFailureAnalysisError.js";
import {
projectZstandardFrameAllowance,
ZstandardFrameAllowanceError,
} from "../domain/compression/zstandardFrameAllowance.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../domain/binaryContainer.js";
import {
fixedAllowanceOptions,
fixedProducerInputAllowance,
} from "../domain/fixedAllowanceRemediation.js";
import {
GpuFileSource,
gpuCount,
GPU_OBJECT_BYTES,
GPU_REPORT_BYTES,
} from "./GpuSource.js";
import { GpuInventory } from "./GpuInventory.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import {
isSelectedRegularFileError,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import { errorMessage } from "../kernel/errorMessage.js";
const OPERATION = "inspect_gpu_code_objects";
/** One admitted descriptor and bounded report at a time; retained cleanup blocks new work. */
export class GpuCodeObjectsProvider implements GpuCodeObjectsPort {
readonly identity = GPU_CODE_OBJECTS_PROVIDER_IDENTITY;
readonly #resources = new ArtifactResourceScope();
#busy = false;
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause) {
const error = new ProviderCleanupError(
this.identity.id,
this.#resources.cleanupResources,
{},
{ cause, operation: OPERATION },
);
bindArtifactFileCleanup(cause, error);
throw error;
}
}
async inspect(
input: GpuCodeObjectsInput,
options?: ExecutionOptions,
): Promise<Result<GpuCodeObjects, AnalysisError>> {
if (this.#busy)
return err(
new AnalysisResourceConstraintError(
OPERATION,
"capacity",
"One GPU inspection is already active",
{ concurrent_inspections: 1 },
{ retryable: true, measuredExhaustion: true },
),
);
this.#busy = true;
let progress: { inventory: GpuInventory; size: number } | undefined;
try {
return ok(
await this.#resources.run(() =>
withArtifactRegularFile(
input.path,
this.#resources,
options?.signal,
({ handle: file }) =>
this.#read(file, input, options?.signal, (value) => {
progress = value;
}),
),
),
);
} catch (cause) {
const { cause: primary, origin } = artifactFilePrimaryFacts(cause);
// Malformed and truncated bytes are a malformed target; unsupported
// bytes are an unsupported target, as for every other format parser.
const formatFailure = parseFailureAnalysisError(
OPERATION,
input.path,
primary,
);
const frameAllowance =
primary instanceof ZstandardFrameAllowanceError
? primary
: cause instanceof ZstandardFrameAllowanceError
? cause
: undefined;
let error: AnalysisError;
if (frameAllowance !== undefined)
error = projectZstandardFrameAllowance(OPERATION, frameAllowance);
else if (
origin === "owned-or-classified" &&
primary instanceof AnalysisError
)
error = primary;
else if (primary instanceof BinaryResourceFailure)
error = parseLimitConstraint(OPERATION, "memory", primary, {
reportedLimitContext: {
maximum_object_bytes: GPU_OBJECT_BYTES,
maximum_report_bytes: GPU_REPORT_BYTES,
},
...fixedAllowanceOptions(
"The GPU parser allowance",
"parser",
binaryResourceCeiling(primary),
),
});
else if (formatFailure !== undefined) error = formatFailure;
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "cancelled"
)
error = artifactFileCancellationError(OPERATION, primary);
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "integrity"
)
error = readerIntegrityFailure(OPERATION, input.path, primary, {
cause,
});
else if (
primary instanceof Error &&
"code" in primary &&
(primary.code === "EACCES" || primary.code === "EPERM")
)
error = new AnalysisAccessDeniedError(
OPERATION,
input.path,
primary.code,
{ cause: primary },
);
else if (isSelectedRegularFileError(primary))
error = selectedFileTargetError(input.path, primary, cause);
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "limit"
)
error = new AnalysisResourceConstraintError(
OPERATION,
"memory",
primary.message,
{ maximum_object_bytes: GPU_OBJECT_BYTES },
{
cause: primary,
...fixedProducerInputAllowance(
GPU_OBJECT_BYTES,
"The GPU object allowance",
),
},
);
// Other coded I/O failures remain host failures (for example, EMFILE).
else
error = new ProviderAdapterError(this.identity.id, OPERATION, {
cause,
diagnostics: {
path: input.path,
reason: errorMessage(primary),
},
});
if (
cause instanceof ArtifactReaderFailure &&
cause.cleanup !== undefined
) {
const cleanup = new ProviderCleanupError(
this.identity.id,
cause.cleanup.resources,
{ reason: cause.cleanup.reason },
{ cause, operation: OPERATION },
);
error = analysisErrorWithCleanupFailure(error, cleanup, OPERATION);
}
const completed = artifactFileCompletion(cause);
if (completed !== undefined) {
// The descriptor owner retains observations even when its final close fails.
const report = gpuCodeObjectsSchema.safeParse(completed.value);
if (report.success)
error.retainPartialObservation(
createGpuCodeObjectsEvidence(report.data, this.identity, input),
);
}
if (
error.partialObservation === undefined &&
progress !== undefined &&
progress.inventory.objects.length > 0
) {
const partial = gpuCodeObjectsPartialSchema.parse({
kind: "gpu-code-objects-partial",
artifact: {
path: input.path,
observed_file_size: progress.size,
sha256: null,
file_identity: "unverified",
},
analysis: input.analysis,
objects: progress.inventory.objects,
kernels: progress.inventory.kernels,
ptx_artifacts: progress.inventory.ptx_artifacts,
coverage: { discovery: "partial", payloads: "partial" },
limitations: [
...progress.inventory.limitations,
"Only completed declarations observed before interruption are retained. Root file identity and completeness were not verified; positional IDs are scoped to this interrupted observation.",
],
});
error.retainPartialObservation(
createGpuCodeObjectsPartialEvidence(partial, this.identity, input),
);
}
bindArtifactFileCleanup(cause, error);
return err(error);
} finally {
this.#busy = false;
}
}
async #read(
file: FileHandle,
input: GpuCodeObjectsInput,
signal: AbortSignal | undefined,
retainProgress: (progress: {
inventory: GpuInventory;
size: number;
}) => void,
): Promise<GpuCodeObjects> {
const initial = await file.stat({ bigint: true });
const size = gpuCount(initial.size);
const source = new GpuFileSource(file, size, signal);
const sha256 = await source.digest();
if (input.expected_sha256 !== undefined && sha256 !== input.expected_sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
input.path,
"GPU source does not match the inventory's selected SHA-256",
);
const inventory = new GpuInventory(input, signal);
retainProgress({ inventory, size });
const format = await inventory.inspect(source);
const after = await file.stat({ bigint: true });
const named = await lstat(input.path, { bigint: true }).catch(
(cause: unknown) => {
if (
cause instanceof Error &&
"code" in cause &&
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
)
throw new ArtifactReaderFailure(
"integrity",
"Selected GPU path changed during inspection",
{ cause, integrityCheck: "container-identity" },
);
throw cause;
},
);
if ([after, named].some((state) => !sameRegularFileState(initial, state)))
throw new ArtifactReaderFailure(
"integrity",
"GPU source changed during inspection",
{ integrityCheck: "container-identity" },
);
const leaves = inventory.objects.filter(
(row) =>
row.kind !== "cuda-fatbin" &&
row.kind !== "hip-bundle" &&
row.kind !== "native-section" &&
row.kind !== "host",
);
return gpuCodeObjectsSchema.parse({
artifact: {
path: input.path,
file_size: size,
sha256,
bytes_read: source.bytesRead,
},
format,
analysis: input.analysis,
objects: inventory.objects,
kernels: inventory.kernels,
ptx_artifacts: inventory.ptx_artifacts,
coverage: {
discovery_scope: "supported-section-names-and-standalone-formats",
discovery: inventory.discovery,
payloads:
input.analysis === "inventory"
? "not-requested"
: leaves.every((row) => row.inspection === "complete") &&
inventory.discovery === "complete"
? "complete"
: "partial",
examined_sections: inventory.examined_sections,
unknown_section_names: inventory.unknown_section_names,
},
limitations: [
...inventory.limitations,
"Full-file SHA-256 streams every file byte; section and selected payload reads add to artifact.bytes_read. Retained Evidence is historical and never reopens the target.",
],
});
}
}