fix(native): retain failed pwntools process and runtime cleanup (#1708)
* fix(native): retain failed pwntools process and runtime cleanup Keep failed worker/debugger cleanup owners and their private files until verified process shutdown and successful directory removal. Retry cleanup before another inspection and expose shutdown through the shared services, CLI and MCP server. Serialize acquisition without delaying cancellation of queued callers, and preserve primary diagnostics when CLI cleanup fails. The original decoder reproduction left a live owned Node child with its runtime deleted and no retained cleanup owner; the regression now verifies retention, admission blocking, retries and eventual process/file cleanup. Validation: 10 lifecycle/public CLI/MCP tests, 20 service tests, test discovery 814/814, build:cached and full check including architecture guards. Actual POSIX process/filesystem boundaries used injected Node workers on macOS; real Linux pwntools/GDB provider parsing was not exercised. * test(native): verify retained recorded-crash cleanup lifecycle * fix(native): finalize diagnostic cleanup before publishing results * fix(native): retire decoder stages before reading runtime evidence --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -10,6 +10,11 @@ import type { ProviderIdentity } from "../AnalysisProvider.js";
|
||||
/** Replaceable offline binary-layout provider; owns its parser and process protocol. */
|
||||
export interface BinaryLayoutPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
inspectAndClose(
|
||||
input: InspectBinaryLayoutInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<BinaryLayout, AnalysisError>>;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectBinaryLayoutInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -17,6 +17,9 @@ it.each([
|
||||
"rejects malformed selection before starting the provider: %j",
|
||||
async (input) => {
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -32,6 +35,9 @@ it.each([
|
||||
it("records the decoded layout once in its Evidence", async () => {
|
||||
const layout = binaryLayoutFixture();
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(layout)),
|
||||
});
|
||||
@@ -49,6 +55,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
"ELF core belongs to recorded-crash analysis.",
|
||||
);
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(err(failure)),
|
||||
});
|
||||
@@ -58,6 +67,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
it("cancels before invocation and after an acquired observation", async () => {
|
||||
const controller = new AbortController();
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
controller.abort();
|
||||
@@ -77,6 +89,9 @@ it("cancels before invocation and after an acquired observation", async () => {
|
||||
},
|
||||
});
|
||||
const untouched = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -112,6 +127,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
|
||||
permissions: { read: true, write: false, execute: true },
|
||||
});
|
||||
const service = new BinaryLayoutService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: BINARY_LAYOUT_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
|
||||
@@ -21,10 +21,36 @@ const OPERATION = "inspect_binary_layout";
|
||||
export class BinaryLayoutService {
|
||||
constructor(readonly provider: BinaryLayoutPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspect(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
|
||||
inspectAndClose(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspectAndClose(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions | undefined,
|
||||
inspect: (
|
||||
input: Parameters<BinaryLayoutPort["inspect"]>[0],
|
||||
) => ReturnType<BinaryLayoutPort["inspect"]>,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
@@ -45,7 +71,7 @@ export class BinaryLayoutService {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
const inspected = await inspect(input.data);
|
||||
if (!inspected.ok) return inspected;
|
||||
const diagnostics = binaryLayoutSchema.shape.diagnostics.safeParse(
|
||||
inspected.value.diagnostics,
|
||||
|
||||
@@ -12,6 +12,11 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Replaceable decoder of supplied recordings; historical PID is never live authority. */
|
||||
export interface RecordedCrashPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
inspectAndClose(
|
||||
input: InspectRecordedCrashInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<RecordedCrash, AnalysisError>>;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectRecordedCrashInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -13,6 +13,9 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
|
||||
const fixture = recordedCrashFixture();
|
||||
fixture.debugger = recordedCrashDebuggerFixture();
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
@@ -36,6 +39,9 @@ it.each([
|
||||
"rejects malformed selection before starting the provider: %j",
|
||||
async (input) => {
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -55,6 +61,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
"ELF core belongs to recorded-crash analysis.",
|
||||
);
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(err(failure)),
|
||||
});
|
||||
@@ -64,6 +73,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
|
||||
it("cancels before invocation and after an acquired observation", async () => {
|
||||
const controller = new AbortController();
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
controller.abort();
|
||||
@@ -83,6 +95,9 @@ it("cancels before invocation and after an acquired observation", async () => {
|
||||
},
|
||||
});
|
||||
const untouched = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => {
|
||||
throw new Error("must not run");
|
||||
@@ -117,6 +132,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
|
||||
flags: "0x5",
|
||||
});
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
|
||||
@@ -21,10 +21,36 @@ const OPERATION = "inspect_recorded_crash";
|
||||
export class RecordedCrashService {
|
||||
constructor(readonly provider: RecordedCrashPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspect(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
|
||||
inspectAndClose(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return this.#inspect(rawInput, options, (input) =>
|
||||
this.provider.inspectAndClose(input, options),
|
||||
);
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions | undefined,
|
||||
inspect: (
|
||||
input: Parameters<RecordedCrashPort["inspect"]>[0],
|
||||
) => ReturnType<RecordedCrashPort["inspect"]>,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
@@ -45,7 +71,7 @@ export class RecordedCrashService {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
const inspected = await inspect(input.data);
|
||||
if (!inspected.ok) return inspected;
|
||||
const diagnostics = recordedCrashSchema.shape.diagnostics.safeParse(
|
||||
inspected.value.diagnostics,
|
||||
|
||||
@@ -53,7 +53,7 @@ export const registerBinaryDiagnosticsCommands = (
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectBinaryLayout, async () => {
|
||||
const result = await service.inspect(
|
||||
const result = await service.inspectAndClose(
|
||||
{ path: resolve(args.path) },
|
||||
{ signal },
|
||||
);
|
||||
@@ -75,7 +75,7 @@ export const registerBinaryDiagnosticsCommands = (
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectRecordedCrash, async () => {
|
||||
const result = await recorded.inspect(
|
||||
const result = await recorded.inspectAndClose(
|
||||
{
|
||||
path: resolve(args.path),
|
||||
include_debugger_context: options.debuggerContext,
|
||||
|
||||
@@ -109,6 +109,11 @@ import type {
|
||||
AdbPackagePullPartialObservation,
|
||||
} from "./adb/adbDeviceAnalysis.js";
|
||||
import type { NativeUiObservationResult } from "./native/nativeUiObservation.js";
|
||||
import type { BinaryLayout } from "./native/binaryLayout.js";
|
||||
import type {
|
||||
RecordedCrash,
|
||||
RecordedCrashPartialObservation,
|
||||
} from "./native/recordedCrash.js";
|
||||
|
||||
/** Provider-neutral evidence collected before a typed analysis failure. */
|
||||
export type AnalysisPartialObservation =
|
||||
@@ -123,6 +128,9 @@ export type AnalysisPartialObservation =
|
||||
| WebScriptExportPartialObservation
|
||||
| JavaScriptRecoveryPartialObservation
|
||||
| Evidence
|
||||
| BinaryLayout
|
||||
| RecordedCrash
|
||||
| RecordedCrashPartialObservation
|
||||
| AndroidPartialObservation
|
||||
| FirmwarePartialObservation
|
||||
| NativeUiObservationResult
|
||||
|
||||
@@ -358,3 +358,14 @@ export type InspectRecordedCrashInput = z.output<
|
||||
typeof inspectRecordedCrashInputSchema
|
||||
>;
|
||||
export type RecordedCrash = z.output<typeof recordedCrashSchema>;
|
||||
|
||||
/** Validated basic core evidence retained when requested debugger enrichment fails. */
|
||||
export type RecordedCrashPartialObservation = Omit<
|
||||
RecordedCrash,
|
||||
"debugger"
|
||||
> & {
|
||||
readonly debugger: {
|
||||
readonly status: "unavailable";
|
||||
readonly requested: true;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -17,14 +17,14 @@ import {
|
||||
type RecordedCrash,
|
||||
} from "../../domain/native/recordedCrash.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { runOwnedCommand } from "../../process/OwnedCommand.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
capturedPwntoolsOutput,
|
||||
pwntoolsDecoderFailure,
|
||||
} from "../pwntools/PwntoolsFailures.js";
|
||||
import { PWNTOOLS_LIMITS } from "../pwntools/PwntoolsRelease.js";
|
||||
import { readPwntoolsFailureEvidence } from "../pwntools/PwntoolsResourceLimits.js";
|
||||
import type { PwntoolsLauncher } from "../pwntools/PwntoolsDecoder.js";
|
||||
import type { PwntoolsCommand } from "../pwntools/PwntoolsDecoder.js";
|
||||
|
||||
const OPERATION = "inspect_recorded_crash";
|
||||
const replySchema = z.discriminatedUnion("ok", [
|
||||
@@ -48,14 +48,14 @@ export const inspectPwndbgCore = async ({
|
||||
rootPath,
|
||||
diagnostics,
|
||||
options,
|
||||
launcher,
|
||||
runCommand,
|
||||
probePath,
|
||||
}: {
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly rootPath: string;
|
||||
readonly diagnostics: AnalysisCapturedOutput;
|
||||
readonly options: ExecutionOptions | undefined;
|
||||
readonly launcher?: PwntoolsLauncher;
|
||||
readonly runCommand: PwntoolsCommand;
|
||||
readonly probePath?: (
|
||||
path: string,
|
||||
kind: "file" | "directory",
|
||||
@@ -126,9 +126,23 @@ export const inspectPwndbgCore = async ({
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
let output: AnalysisCapturedOutput | undefined;
|
||||
const failureContext = {
|
||||
operation: OPERATION,
|
||||
providerId: "pwndbg-core",
|
||||
precedingOutput: diagnostics,
|
||||
};
|
||||
const failure = (cause: unknown) =>
|
||||
pwntoolsDecoderFailure(
|
||||
cause,
|
||||
"debugger",
|
||||
gdb,
|
||||
environment.REA_PWNTOOLS_PYTHON ?? "",
|
||||
{},
|
||||
failureContext,
|
||||
);
|
||||
try {
|
||||
options?.signal?.throwIfAborted();
|
||||
const execution = await runOwnedCommand(
|
||||
const execution = await runCommand(
|
||||
{
|
||||
command: environment.REA_PWNTOOLS_PYTHON ?? "",
|
||||
arguments: [
|
||||
@@ -155,14 +169,7 @@ export const inspectPwndbgCore = async ({
|
||||
OMP_NUM_THREADS: "1",
|
||||
},
|
||||
},
|
||||
{
|
||||
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
|
||||
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(launcher === undefined ? {} : { launcher }),
|
||||
},
|
||||
failure,
|
||||
);
|
||||
output = capturedPwntoolsOutput(execution);
|
||||
let reply: z.output<typeof replySchema>;
|
||||
@@ -218,6 +225,7 @@ export const inspectPwndbgCore = async ({
|
||||
);
|
||||
return { ...reply.value, diagnostics: output };
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisError && cause.cleanupIncomplete) throw cause;
|
||||
if (
|
||||
options?.signal?.aborted &&
|
||||
(cause === options.signal.reason ||
|
||||
@@ -232,11 +240,7 @@ export const inspectPwndbgCore = async ({
|
||||
gdb,
|
||||
environment.REA_PWNTOOLS_PYTHON ?? "",
|
||||
await readPwntoolsFailureEvidence(cause, stage),
|
||||
{
|
||||
operation: OPERATION,
|
||||
providerId: "pwndbg-core",
|
||||
precedingOutput: diagnostics,
|
||||
},
|
||||
failureContext,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,9 +11,12 @@ import { fileURLToPath } from "node:url";
|
||||
import { z } from "zod";
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import type { ProviderIdentity } from "../../application/AnalysisProvider.js";
|
||||
import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js";
|
||||
import type {
|
||||
AnalysisCapturedOutput,
|
||||
AnalysisPartialObservation,
|
||||
} from "../../domain/analysisErrorBase.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
@@ -23,10 +26,17 @@ import {
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { runOwnedCommand } from "../../process/OwnedCommand.js";
|
||||
import type {
|
||||
ProviderProcessSupervisor,
|
||||
OwnedProviderProcessSpawnOptions,
|
||||
ProviderProcessSnapshot,
|
||||
} from "../../process/ProviderProcess.js";
|
||||
import { PendingOperations } from "../../process/PendingOperations.js";
|
||||
import {
|
||||
pwntoolsResourceLimitsSchema,
|
||||
readPwntoolsFailureEvidence,
|
||||
@@ -44,9 +54,15 @@ const HOST_REQUIREMENT =
|
||||
export type PwntoolsLauncher = NonNullable<
|
||||
Parameters<typeof runOwnedCommand>[2]
|
||||
>["launcher"];
|
||||
interface DecoderReport {
|
||||
/** Owner-bound execution; replies and failure files are stable only after this settles without cleanup uncertainty. */
|
||||
export type PwntoolsCommand = (
|
||||
spawn: OwnedProviderProcessSpawnOptions,
|
||||
/** Project the original failure without reading files an unresolved worker may change. */
|
||||
failure: (cause: unknown) => AnalysisError,
|
||||
) => Promise<ProviderProcessSnapshot>;
|
||||
type DecoderReport = AnalysisPartialObservation & {
|
||||
readonly diagnostics: AnalysisCapturedOutput;
|
||||
}
|
||||
};
|
||||
/** Adapter-selected semantics around a shared owned pwntools process boundary. */
|
||||
export interface PwntoolsDecoderProfile<
|
||||
Input extends { readonly path: string },
|
||||
@@ -64,6 +80,7 @@ export interface PwntoolsDecoderProfile<
|
||||
readonly rootPath: string;
|
||||
readonly diagnostics: AnalysisCapturedOutput;
|
||||
readonly options: ExecutionOptions | undefined;
|
||||
readonly runCommand: PwntoolsCommand;
|
||||
}) => Report | Promise<Report>;
|
||||
}
|
||||
|
||||
@@ -74,6 +91,22 @@ export class PwntoolsDecoder<
|
||||
Report extends DecoderReport,
|
||||
> {
|
||||
readonly identity: ProviderIdentity;
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
readonly #admissions = new PendingOperations<
|
||||
symbol,
|
||||
"admitted" | "cancelled"
|
||||
>();
|
||||
#closing = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#pendingCleanup:
|
||||
| {
|
||||
root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
process: ProviderProcessSupervisor | undefined;
|
||||
failure: AnalysisError | undefined;
|
||||
diagnostics: AnalysisCapturedOutput | undefined;
|
||||
observation: AnalysisPartialObservation | undefined;
|
||||
}
|
||||
| undefined;
|
||||
constructor(
|
||||
readonly profile: PwntoolsDecoderProfile<Input, Payload, Report>,
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>,
|
||||
@@ -86,10 +119,61 @@ export class PwntoolsDecoder<
|
||||
}
|
||||
|
||||
/** Snapshot one explicit artifact and return complete static observations without launching the selected object as a host process. */
|
||||
async inspect(
|
||||
inspect(
|
||||
input: Input,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Report, AnalysisError>> {
|
||||
return this.#enqueue(() => this.#inspect(input, options), options);
|
||||
}
|
||||
|
||||
/** Finalize an admitted inspection before publishing its outcome; rejected admission acquires nothing and does not close the provider. */
|
||||
inspectAndClose(
|
||||
input: Input,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Report, AnalysisError>> {
|
||||
return this.#enqueue(() => {
|
||||
this.#closing = true;
|
||||
return this.#inspect(input, options);
|
||||
}, options);
|
||||
}
|
||||
|
||||
#enqueue(
|
||||
inspect: () => Promise<Result<Report, AnalysisError>>,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Report, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return Promise.resolve(
|
||||
err(new AnalysisCancelledError(this.profile.operation)),
|
||||
);
|
||||
if (this.#closing) return Promise.resolve(err(this.#closedError()));
|
||||
const key = Symbol();
|
||||
const admission = this.#admissions.wait(key, {
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
cancelledValue: () => "cancelled",
|
||||
});
|
||||
const operation = this.#tail.then(() => {
|
||||
this.#admissions.settle(key, "admitted");
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(this.profile.operation));
|
||||
return this.#closing ? err(this.#closedError()) : inspect();
|
||||
});
|
||||
this.#tail = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return admission.then((state) =>
|
||||
state === "cancelled"
|
||||
? err(new AnalysisCancelledError(this.profile.operation))
|
||||
: operation,
|
||||
);
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
input: Input,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Report, AnalysisError>> {
|
||||
const pending = await this.#retire();
|
||||
if (pending !== undefined) return err(pending);
|
||||
const OPERATION = this.profile.operation;
|
||||
const context = { operation: OPERATION, providerId: this.identity.id };
|
||||
const replySchema = z.discriminatedUnion("ok", [
|
||||
@@ -118,6 +202,15 @@ export class PwntoolsDecoder<
|
||||
let phase: "configuration" | "artifact-read" | "decoder" = "configuration";
|
||||
const executablePath = this.environment.REA_PWNTOOLS_PYTHON ?? "";
|
||||
let selectedPath = executablePath;
|
||||
const failure = (cause: unknown) =>
|
||||
pwntoolsDecoderFailure(
|
||||
cause,
|
||||
phase,
|
||||
selectedPath,
|
||||
executablePath,
|
||||
{},
|
||||
context,
|
||||
);
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
if (process.platform !== "linux" || process.arch !== "x64")
|
||||
@@ -154,6 +247,13 @@ export class PwntoolsDecoder<
|
||||
);
|
||||
phase = "decoder";
|
||||
root = await this.createRuntime();
|
||||
this.#pendingCleanup = {
|
||||
root,
|
||||
process: undefined,
|
||||
failure: undefined,
|
||||
diagnostics: undefined,
|
||||
observation: undefined,
|
||||
};
|
||||
const requestPath = join(root.path, "request.json");
|
||||
const snapshotPath = join(root.path, "object.snapshot");
|
||||
const replyPath = join(root.path, "reply.json");
|
||||
@@ -167,7 +267,7 @@ export class PwntoolsDecoder<
|
||||
JSON.stringify({ snapshot_path: snapshotPath, reply_path: replyPath }),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const execution = await runOwnedCommand(
|
||||
const execution = await this.#runCommand(
|
||||
{
|
||||
command: this.environment.REA_PWNTOOLS_PYTHON ?? "",
|
||||
arguments: [
|
||||
@@ -188,14 +288,8 @@ export class PwntoolsDecoder<
|
||||
OMP_NUM_THREADS: "1",
|
||||
},
|
||||
},
|
||||
{
|
||||
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
|
||||
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
},
|
||||
options,
|
||||
failure,
|
||||
);
|
||||
const capturedOutput = capturedPwntoolsOutput(execution);
|
||||
let reply: z.output<typeof replySchema>;
|
||||
@@ -277,9 +371,20 @@ export class PwntoolsDecoder<
|
||||
rootPath: root.path,
|
||||
diagnostics: capturedOutput,
|
||||
options,
|
||||
runCommand: (spawn, classifyFailure) =>
|
||||
this.#runCommand(spawn, options, classifyFailure),
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
// The command owner has exhausted this operation's cleanup attempts.
|
||||
// Keep its resources and do not consume files an unresolved worker may change.
|
||||
if (cause instanceof AnalysisError && cause.cleanupIncomplete) {
|
||||
if (this.#pendingCleanup !== undefined) {
|
||||
this.#pendingCleanup.failure = cause;
|
||||
this.#pendingCleanup.observation = cause.partialObservation;
|
||||
}
|
||||
return err(cause);
|
||||
}
|
||||
const evidence = await readPwntoolsFailureEvidence(cause, root?.path);
|
||||
result = err(
|
||||
options?.signal?.aborted &&
|
||||
@@ -296,37 +401,26 @@ export class PwntoolsDecoder<
|
||||
),
|
||||
);
|
||||
}
|
||||
if (root !== undefined) {
|
||||
try {
|
||||
await root.close();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
this.identity.id,
|
||||
[root.path],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
...(result.ok
|
||||
? {
|
||||
captured_output: {
|
||||
stdout: result.value.diagnostics.stdout,
|
||||
stderr: result.value.diagnostics.stderr,
|
||||
truncated: result.value.diagnostics.truncated,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
{ operation: OPERATION },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (this.#pendingCleanup !== undefined) {
|
||||
this.#pendingCleanup.failure = result.ok ? undefined : result.error;
|
||||
this.#pendingCleanup.observation = result.ok
|
||||
? result.value
|
||||
: result.error.partialObservation;
|
||||
this.#pendingCleanup.diagnostics = result.ok
|
||||
? result.value.diagnostics
|
||||
: result.error.capturedOutput;
|
||||
}
|
||||
const cleanup = await this.#completeCleanup(() => this.#retire());
|
||||
if (cleanup !== undefined)
|
||||
return err(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(result.error, cleanup, OPERATION),
|
||||
);
|
||||
return result.ok && options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(OPERATION, {
|
||||
partialObservation: result.value,
|
||||
capturedOutput: {
|
||||
stdout: result.value.diagnostics.stdout,
|
||||
stderr: result.value.diagnostics.stderr,
|
||||
@@ -336,4 +430,152 @@ export class PwntoolsDecoder<
|
||||
)
|
||||
: result;
|
||||
}
|
||||
|
||||
async #runCommand(
|
||||
spawn: OwnedProviderProcessSpawnOptions,
|
||||
options: ExecutionOptions | undefined,
|
||||
failure: (cause: unknown) => AnalysisError,
|
||||
): Promise<ProviderProcessSnapshot> {
|
||||
// A runtime is registered before either decoder stage may acquire a process.
|
||||
const pending = this.#pendingCleanup;
|
||||
if (pending === undefined)
|
||||
throw new Error("Decoder command requires an owned runtime.");
|
||||
let outcome: Result<ProviderProcessSnapshot, unknown>;
|
||||
try {
|
||||
outcome = ok(
|
||||
await runOwnedCommand(
|
||||
spawn,
|
||||
{
|
||||
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
|
||||
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined
|
||||
? {}
|
||||
: { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
retainCleanup: (owner) => {
|
||||
pending.process = owner;
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
outcome = err(cause);
|
||||
}
|
||||
const cleanup = await this.#completeCleanup(() => this.#retireProcess());
|
||||
if (cleanup !== undefined) {
|
||||
if (outcome.ok) throw cleanup;
|
||||
// Until retirement succeeds, resource-limit markers remain unverified.
|
||||
const primary = failure(outcome.error);
|
||||
throw analysisErrorWithCleanupFailure(
|
||||
primary,
|
||||
cleanup,
|
||||
this.profile.operation,
|
||||
);
|
||||
}
|
||||
if (!outcome.ok) throw outcome.error;
|
||||
return outcome.value;
|
||||
}
|
||||
|
||||
/** Drain the running inspection, reject queued acquisition, and retry retained processes before deleting their files. */
|
||||
close(): Promise<void> {
|
||||
this.#closing = true;
|
||||
this.#closePromise ??= this.#tail
|
||||
.then(async () => {
|
||||
const failure = await this.#retire();
|
||||
if (failure !== undefined) throw failure;
|
||||
})
|
||||
.catch((cause: unknown) => {
|
||||
this.#closePromise = undefined;
|
||||
throw cause;
|
||||
});
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
#closedError(): AnalysisCapabilityUnavailableError {
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
this.identity.id,
|
||||
this.profile.operation,
|
||||
"Provider is closing; create a new inspection service.",
|
||||
);
|
||||
}
|
||||
|
||||
async #completeCleanup(
|
||||
retire: () => Promise<ProviderCleanupError | undefined>,
|
||||
): Promise<ProviderCleanupError | undefined> {
|
||||
const failure = await retire();
|
||||
return failure !== undefined && this.#closing ? retire() : failure;
|
||||
}
|
||||
|
||||
async #retireProcess(): Promise<ProviderCleanupError | undefined> {
|
||||
const pending = this.#pendingCleanup;
|
||||
if (pending?.process === undefined) return undefined;
|
||||
const stopped = await pending.process.stop();
|
||||
if (stopped.status === "incomplete")
|
||||
return new ProviderCleanupError(
|
||||
this.identity.id,
|
||||
[
|
||||
pending.process.launch.ownership?.runId ?? "owned-decoder",
|
||||
...(pending.root === undefined ? [] : [pending.root.path]),
|
||||
],
|
||||
{
|
||||
reason: stopped.reason,
|
||||
captured_output: {
|
||||
...(pending.diagnostics ??
|
||||
capturedPwntoolsOutput(pending.process.snapshot())),
|
||||
},
|
||||
previous_error:
|
||||
pending.failure === undefined
|
||||
? null
|
||||
: projectAnalysisError(pending.failure),
|
||||
},
|
||||
{
|
||||
operation: this.profile.operation,
|
||||
...(pending.observation === undefined
|
||||
? {}
|
||||
: { partialObservation: pending.observation }),
|
||||
},
|
||||
);
|
||||
pending.process = undefined;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async #retire(): Promise<ProviderCleanupError | undefined> {
|
||||
const failure = await this.#retireProcess();
|
||||
if (failure !== undefined) return failure;
|
||||
const pending = this.#pendingCleanup;
|
||||
if (pending === undefined) return undefined;
|
||||
if (pending.root !== undefined) {
|
||||
const root = pending.root;
|
||||
try {
|
||||
await root.close();
|
||||
pending.root = undefined;
|
||||
} catch (cause: unknown) {
|
||||
return new ProviderCleanupError(
|
||||
this.identity.id,
|
||||
[root.path],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
...(pending.diagnostics === undefined
|
||||
? {}
|
||||
: { captured_output: { ...pending.diagnostics } }),
|
||||
previous_error:
|
||||
pending.failure === undefined
|
||||
? null
|
||||
: projectAnalysisError(pending.failure),
|
||||
},
|
||||
{
|
||||
operation: this.profile.operation,
|
||||
cause,
|
||||
...(pending.observation === undefined
|
||||
? {}
|
||||
: { partialObservation: pending.observation }),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
this.#pendingCleanup = undefined;
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
recordedCrashPayloadSchema,
|
||||
recordedCrashSchema,
|
||||
@@ -49,6 +50,7 @@ export class PwntoolsRecordedCrashProvider
|
||||
rootPath,
|
||||
diagnostics,
|
||||
options,
|
||||
runCommand,
|
||||
}) => {
|
||||
const validate = (debuggerContext: RecordedCrash["debugger"]) =>
|
||||
recordedCrashSchema.safeParse({
|
||||
@@ -114,26 +116,38 @@ export class PwntoolsRecordedCrashProvider
|
||||
);
|
||||
}
|
||||
if (!input.include_debugger_context) return value;
|
||||
const context = await inspectPwndbgCore({
|
||||
environment,
|
||||
rootPath,
|
||||
diagnostics,
|
||||
options,
|
||||
...(launcher === undefined ? {} : { launcher }),
|
||||
});
|
||||
const enriched = validate(context);
|
||||
if (!enriched.success)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_recorded_crash",
|
||||
`Recorded debugger context is invalid: ${enriched.error.issues[0]?.message ?? "schema mismatch"}`,
|
||||
{
|
||||
capturedOutput:
|
||||
context.status === "available"
|
||||
? recordedCrashStageOutput(diagnostics, context.diagnostics)
|
||||
: diagnostics,
|
||||
},
|
||||
);
|
||||
return enriched.data;
|
||||
try {
|
||||
const context = await inspectPwndbgCore({
|
||||
environment,
|
||||
rootPath,
|
||||
diagnostics,
|
||||
options,
|
||||
runCommand,
|
||||
});
|
||||
const enriched = validate(context);
|
||||
if (!enriched.success)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_recorded_crash",
|
||||
`Recorded debugger context is invalid: ${enriched.error.issues[0]?.message ?? "schema mismatch"}`,
|
||||
{
|
||||
capturedOutput:
|
||||
context.status === "available"
|
||||
? recordedCrashStageOutput(
|
||||
diagnostics,
|
||||
context.diagnostics,
|
||||
)
|
||||
: diagnostics,
|
||||
},
|
||||
);
|
||||
return enriched.data;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisError)
|
||||
cause.retainPartialObservation({
|
||||
...value,
|
||||
debugger: { status: "unavailable", requested: true },
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
},
|
||||
environment,
|
||||
|
||||
@@ -45,6 +45,8 @@ export const runOwnedCommand = async (
|
||||
},
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
/** Synchronously accept unresolved cleanup ownership; execution still returns its original outcome. Must not throw. */
|
||||
readonly retainCleanup?: (owner: ProviderProcessSupervisor) => void;
|
||||
readonly launcher?: (
|
||||
input: OwnedProviderProcessSpawnOptions,
|
||||
) => Promise<SpawnedOwnedProviderProcess>;
|
||||
@@ -64,6 +66,7 @@ export const runOwnedCommand = async (
|
||||
options.launcher ?? spawnOwnedProviderProcess,
|
||||
deadline,
|
||||
callerSignal,
|
||||
options.retainCleanup,
|
||||
);
|
||||
} finally {
|
||||
deadline.dispose();
|
||||
@@ -82,6 +85,7 @@ const collectOwnedCommand = async (
|
||||
) => Promise<SpawnedOwnedProviderProcess>,
|
||||
deadline: ProviderStartupDeadline,
|
||||
callerSignal?: AbortSignal,
|
||||
retainCleanup?: (owner: ProviderProcessSupervisor) => void,
|
||||
): Promise<ProviderProcessSnapshot> => {
|
||||
const signal = deadline.signal;
|
||||
let launched: SpawnedOwnedProviderProcess;
|
||||
@@ -190,7 +194,9 @@ const collectOwnedCommand = async (
|
||||
}
|
||||
const stopped = await supervisor.stop();
|
||||
const snapshot = supervisor.snapshot();
|
||||
if (stopped.status === "incomplete")
|
||||
if (stopped.status === "incomplete" && retainCleanup !== undefined)
|
||||
retainCleanup(supervisor);
|
||||
else if (stopped.status === "incomplete")
|
||||
throw new OwnedCommandFailure(
|
||||
failure?.reason ?? "process",
|
||||
failure?.message ?? "Command cleanup failed.",
|
||||
|
||||
@@ -243,6 +243,10 @@ export const createServer = (
|
||||
const delivery = selectToolResultDelivery(environment, options.delivery);
|
||||
const evmInterface =
|
||||
options.evmInterface ?? evmInterfaceModule.create(environment);
|
||||
const binaryLayout =
|
||||
options.binaryLayout ?? createBinaryLayoutService(environment);
|
||||
const recordedCrash =
|
||||
options.recordedCrash ?? createRecordedCrashService(environment);
|
||||
const webSourceLocation =
|
||||
options.webSourceLocation ?? createWebSourceLocationService(environment);
|
||||
const webModuleTrace =
|
||||
@@ -258,6 +262,8 @@ export const createServer = (
|
||||
environment,
|
||||
delivery,
|
||||
evmInterface,
|
||||
binaryLayout,
|
||||
recordedCrash,
|
||||
webSourceLocation,
|
||||
webModuleTrace,
|
||||
javascriptRecovery,
|
||||
@@ -296,6 +302,8 @@ export const createServer = (
|
||||
adbDevice.close(),
|
||||
flutter.close(),
|
||||
evmInterface.close(),
|
||||
binaryLayout.close(),
|
||||
recordedCrash.close(),
|
||||
webSourceLocation.close(),
|
||||
webModuleTrace.close(),
|
||||
javascriptRecovery.close?.() ?? Promise.resolve(),
|
||||
|
||||
Reference in New Issue
Block a user