fix(native): supervise LLDB and preserve bounded capture uncertainty

This commit is contained in:
morluto
2026-10-09 00:49:30 +08:00
parent 488f448ae2
commit 915855e75c
20 changed files with 1690 additions and 237 deletions
+13 -2
View File
@@ -39,26 +39,37 @@ export interface AnalysisCapturedOutput {
readonly truncated: boolean;
}
/** Cleanup uncertainty attached to the original typed analysis failure. */
export interface AnalysisCleanupObservation {
readonly reason: string;
readonly resources: readonly string[];
}
/** Optional provider-neutral context that must survive typed error projection. */
export interface AnalysisErrorOptions extends ErrorOptions {
readonly capturedOutput?: AnalysisCapturedOutput;
readonly cleanup?: AnalysisCleanupObservation;
}
/** Base class for expected analysis, provider, and session failures. */
export abstract class AnalysisError extends Error {
readonly capturedOutput: AnalysisCapturedOutput | undefined;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupIncomplete: boolean;
readonly cleanupResources: readonly string[];
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
this.capturedOutput =
options?.capturedOutput === undefined
? undefined
: { ...options.capturedOutput };
this.cleanup = options?.cleanup;
this.cleanupIncomplete = options?.cleanup !== undefined;
this.cleanupResources = options?.cleanup?.resources ?? [];
}
abstract readonly _tag: AnalysisErrorTag;
readonly userMessage: string | undefined = undefined;
readonly userCategory: "cancelled" | undefined = undefined;
readonly cleanupIncomplete: boolean = false;
readonly cleanupResources: readonly string[] = [];
readonly executionFailure: string | undefined = undefined;
readonly partialObservation: PartialProcessCaptureObservation | undefined =
undefined;
@@ -11,6 +11,7 @@ import {
import { ArtifactOperationError } from "./artifactOperationError.js";
import { BinaryTargetError } from "./configurationErrors.js";
import { BrowserObservationError } from "./browserObservationError.js";
import { EvidenceIntegrityError } from "./evidenceErrors.js";
import {
HopperProcessError,
HopperRemoteError,
@@ -131,6 +132,53 @@ it.each([
},
);
it.each([
new AnalysisCancelledError("observe_native_calls", {
cleanup: {
reason: "target process termination could not be verified",
resources: ["native-target:4242"],
},
}),
new AnalysisTimeoutError("observe_native_calls", 65_000, {
cleanup: {
reason: "target process identity was unavailable",
resources: ["native-target:4242"],
},
}),
])("retains incomplete cleanup for lifecycle failures: $._tag", (failure) => {
expect(projectAnalysisError(failure)).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
cleanup_reason: expect.any(String),
resources: ["native-target:4242"],
},
});
});
it("retains the original failure tag and code when cleanup is incomplete", () => {
const error = new EvidenceIntegrityError(
"The launched native target did not match its selected digest",
{
cleanup: {
reason: "target survivor identity could not be verified",
resources: ["native-target:4242"],
},
},
);
expect(error._tag).toBe("EvidenceIntegrityError");
expect(projectAnalysisError(error)).toMatchObject({
code: "cleanup_incomplete",
category: "integrity_mismatch",
details: {
cleanup: "incomplete",
cleanup_reason: "target survivor identity could not be verified",
resources: ["native-target:4242"],
execution_failure: "evidence_integrity_mismatch",
},
});
});
describe("analysis error projection: provider failures", () => {
it("projects the primary browser failure alongside incomplete cleanup", () => {
const projected = projectAnalysisError(
+45 -10
View File
@@ -42,12 +42,26 @@ export const projectAnalysisError = (
error: AnalysisError,
): AnalysisErrorProjection => {
assertKnownAnalysisErrorTag(error._tag);
const code = errorCode(error);
const underlyingCode = underlyingErrorCode(error);
const code = error.cleanupIncomplete ? "cleanup_incomplete" : underlyingCode;
const primaryDetails = errorDetails(error);
const details =
error.capturedOutput === undefined
? primaryDetails
: { ...primaryDetails, captured_output: { ...error.capturedOutput } };
const details = {
...primaryDetails,
...(error.cleanupIncomplete
? {
cleanup: "incomplete",
resources: [...error.cleanupResources],
...(error.cleanup === undefined
? {}
: { cleanup_reason: error.cleanup.reason }),
execution_failure:
primaryDetails?.execution_failure ?? underlyingCode,
}
: {}),
...(error.capturedOutput === undefined
? {}
: { captured_output: { ...error.capturedOutput } }),
};
return {
code,
category: analysisErrorCategory(error),
@@ -56,12 +70,13 @@ export const projectAnalysisError = (
remediation: {
action: analysisErrorRemediationAction(error),
},
...(details === undefined ? {} : { details }),
...(Object.keys(details).length === 0 ? {} : { details }),
};
};
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
if (error.cleanupIncomplete) return "cleanup_incomplete";
const underlyingErrorCode = (
error: AnalysisError,
): AnalysisErrorProjection["code"] => {
if (error instanceof ProviderSelectionError)
return error.reason === "provider_unavailable"
? "provider_unavailable"
@@ -380,11 +395,31 @@ const lifecycleErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisCancelledError)
return { operation: error.operation, cleanup: "complete" };
return {
operation: error.operation,
cleanup: error.cleanup === undefined ? "complete" : "incomplete",
...(error.cleanup === undefined
? {}
: {
cleanup_reason: error.cleanup.reason,
resources: [...error.cleanup.resources],
execution_failure: "cancelled",
}),
};
if (error instanceof HopperCancelledError)
return { operation: "hopper", cleanup: "complete" };
if (error instanceof AnalysisTimeoutError)
return { operation: error.operation, timeout_ms: error.timeoutMs };
return {
operation: error.operation,
timeout_ms: error.timeoutMs,
...(error.cleanup === undefined
? {}
: {
cleanup: "incomplete",
cleanup_reason: error.cleanup.reason,
resources: [...error.cleanup.resources],
}),
};
if (error instanceof HopperTimeoutError)
return {
stage: error.operation === undefined ? "startup" : error.stage,
@@ -129,8 +129,10 @@ export const nativeCallEventSchema = z.strictObject({
const capturedOutputSchema = z.strictObject({
text: z.string(),
/** Bytes observed by the bridge, not a total when complete is false. */
bytes: z.number().int().nonnegative(),
truncated: z.boolean(),
complete: z.boolean(),
});
/** Observed calls, the process lifecycle, and breakpoint resolution. */
@@ -140,7 +142,21 @@ export const nativeCallObservationResultSchema = z.strictObject({
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
architecture: z.string(),
arguments: z.array(z.string()),
environment: z.record(z.string(), z.string()),
working_directory: z.string().nullable(),
launch_identity: z.strictObject({
/** A pathname hash does not verify the bytes mapped into the process. */
loaded_image_sha256: z.null(),
file_device: z.string().nullable(),
file_inode: z.string().nullable(),
selected_file_sha256: z
.string()
.regex(/^[0-9a-f]{64}$/u)
.nullable(),
module_path: z.string().nullable(),
module_uuid: z.string().nullable(),
stable: z.boolean(),
}),
}),
debugger: z.strictObject({
path: z.string(),
@@ -154,6 +170,7 @@ export const nativeCallObservationResultSchema = z.strictObject({
"duration-elapsed",
"event-limit",
"stop-limit",
"resource-limit",
]),
exit_status: z.number().int().nullable(),
exit_description: z.string().nullable(),
@@ -187,6 +204,7 @@ export const nativeCallObservationResultSchema = z.strictObject({
coverage: z.strictObject({
status: z.enum(["complete", "partial"]),
event_limit_reached: z.boolean(),
resource_limit_reached: z.boolean(),
/** Requests that matched no code in any image loaded while observing. */
unresolved_breakpoints: z.array(z.number().int().nonnegative()),
}),
+5 -2
View File
@@ -1,8 +1,11 @@
import type { JsonValue } from "./jsonValue.js";
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** A provider adapter failed outside its more precise typed variants. */
export interface ProviderAdapterErrorOptions extends ErrorOptions {
export interface ProviderAdapterErrorOptions extends AnalysisErrorOptions {
readonly diagnostics?: Readonly<Record<string, JsonValue>>;
}
+394 -109
View File
@@ -1,4 +1,4 @@
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { open, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -10,7 +10,11 @@ import {
AnalysisCapabilityUnavailableError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import type {
AnalysisCleanupObservation,
AnalysisError,
} from "../domain/analysisErrorBase.js";
import {
nativeCallEventSchema,
nativeCodeLocationSchema,
@@ -19,7 +23,21 @@ import {
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
observeProcessStartIdentity,
prepareProcessOwnershipInspection,
signalProcessWithStartIdentity,
} from "../process/ProcessOwnershipObservation.js";
import type { ProcessIdentityObservation } from "../process/ProcessOwnership.js";
import {
ProviderStartupDeadline,
waitForAbortableDelay,
} from "../process/ProviderDeadline.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { resolveXcrunTool, type ResolvedTool } from "./CommandRunner.js";
@@ -40,11 +58,38 @@ const tracedSchema = z.strictObject({
status: z.literal("traced"),
version: z.string(),
pid: z.number().int().positive(),
outcome: z.enum(["exited", "duration-elapsed", "event-limit", "stop-limit"]),
outcome: z.enum([
"exited",
"duration-elapsed",
"event-limit",
"stop-limit",
"resource-limit",
]),
exit_status: z.number().int().nullable(),
exit_description: z.string().nullable(),
killed: z.boolean(),
terminated: z.boolean(),
target_identity: z.strictObject({
loaded_image_sha256: z.null(),
selected_file_sha256: z
.string()
.regex(/^[0-9a-f]{64}$/u)
.nullable(),
file_device: z.string().nullable(),
file_inode: z.string().nullable(),
module_path: z.string().nullable(),
module_uuid: z.string().nullable(),
stable: z.boolean(),
}),
resource_limit_reached: z.boolean(),
target_output: z.strictObject({
stdout_bytes: z.number().int().nonnegative(),
stderr_bytes: z.number().int().nonnegative(),
stdout_truncated: z.boolean(),
stderr_truncated: z.boolean(),
stdout_complete: z.boolean(),
stderr_complete: z.boolean(),
}),
elapsed_ms: z.number().nonnegative(),
breakpoints: z.array(
z.strictObject({
@@ -60,7 +105,13 @@ const tracedSchema = z.strictObject({
const tracerOutputSchema = z.discriminatedUnion("status", [
tracedSchema,
z.strictObject({
status: z.enum(["target-error", "launch-error", "tracer-error"]),
status: z.enum([
"target-error",
"target-integrity-error",
"target-identity-unavailable",
"launch-error",
"tracer-error",
]),
error: z.string().nullable(),
}),
]);
@@ -68,8 +119,11 @@ const tracerOutputSchema = z.discriminatedUnion("status", [
/** Bounded text of one target output stream. */
export interface CapturedOutput {
readonly text: string;
/** Bytes drained from the target, which may exceed the retained prefix. */
readonly bytes: number;
readonly truncated: boolean;
/** Whether the bridge confirms it drained the stream through EOF. */
readonly complete: boolean;
}
/** One completed LLDB observation, before projection into the result contract. */
@@ -88,6 +142,7 @@ export interface NativeCallTracer {
request: {
readonly executable: string;
readonly architecture: string;
readonly expectedSha256: string;
readonly input: NativeCallObservationInput;
},
signal?: AbortSignal,
@@ -133,8 +188,11 @@ export class LldbCallTracer implements NativeCallTracer {
config: join(directory, "config.json"),
result: join(directory, "result.json"),
pid: join(directory, "pid"),
identityAck: join(directory, "identity.ack"),
stdout: join(directory, "stdout"),
stderr: join(directory, "stderr"),
stdoutCapture: join(directory, "stdout.capture"),
stderrCapture: join(directory, "stderr.capture"),
};
const { input } = request;
await writeFile(
@@ -142,6 +200,7 @@ export class LldbCallTracer implements NativeCallTracer {
JSON.stringify({
executable: request.executable,
architecture: request.architecture,
expected_sha256: request.expectedSha256,
arguments: input.arguments,
environment: input.environment,
working_directory: input.working_directory ?? null,
@@ -154,13 +213,18 @@ export class LldbCallTracer implements NativeCallTracer {
max_events: input.max_events,
argument_registers: input.argument_registers,
backtrace_frames: input.backtrace_frames,
max_output_bytes: MAX_OUTPUT_BYTES,
stdout_path: paths.stdout,
stderr_path: paths.stderr,
stdout_capture_path: paths.stdoutCapture,
stderr_capture_path: paths.stderrCapture,
result_path: paths.result,
pid_path: paths.pid,
identity_ack_path: paths.identityAck,
}),
{ mode: 0o600 },
);
await prepareProcessOwnershipInspection(signal);
const exited = await runLldb(
lldb.path,
[
@@ -174,20 +238,77 @@ export class LldbCallTracer implements NativeCallTracer {
],
{
deadlineMs: input.duration_ms + DEADLINE_GRACE_MS,
pidPath: paths.pid,
identityAckPath: paths.identityAck,
...(signal === undefined ? {} : { signal }),
},
);
const terminated = await ensureTerminated(paths.pid, request.executable);
const output =
exited.kind === "exited"
? await readTracerOutput(paths.result)
: undefined;
let targetTermination = await ensureTerminated(
paths.pid,
exited.targetIdentity,
true,
);
// These two bridge outcomes are emitted before a target process exists.
// Other missing-PID cases, including a missing result, remain unknown.
if (
output !== undefined &&
(output.status === "target-error" || output.status === "launch-error") &&
(await readTargetPid(paths.pid)) === undefined
)
targetTermination = "terminated";
const terminated = targetTermination === "terminated";
const cleanupDetails = [
exited.cleanupFailure,
...(terminated ? [] : [targetTerminationReason(targetTermination)]),
].filter((detail): detail is string => detail !== undefined);
const lifecycleCleanup =
cleanupDetails.length === 0
? undefined
: {
reason: cleanupDetails.join("; "),
resources: [
`native-target:${String((await readTargetPid(paths.pid)) ?? "unknown")}`,
],
};
if (exited.kind === "cancelled")
return err(new AnalysisCancelledError(OPERATION));
return err(
new AnalysisCancelledError(
OPERATION,
lifecycleCleanup === undefined
? undefined
: { cleanup: lifecycleCleanup },
),
);
if (exited.kind === "timeout")
return err(
new AnalysisTimeoutError(
OPERATION,
input.duration_ms + DEADLINE_GRACE_MS,
lifecycleCleanup === undefined
? undefined
: { cleanup: lifecycleCleanup },
),
);
const output = await readTracerOutput(paths.result);
if (exited.cleanupFailure !== undefined)
return err(
new ProviderAdapterError(PROVIDER, OPERATION, {
cleanup: lifecycleCleanup ?? {
reason: exited.cleanupFailure,
resources: ["lldb-process-group"],
},
diagnostics: {
reason: "LLDB process-group cleanup could not be verified",
cleanup_failure: exited.cleanupFailure,
...(lifecycleCleanup === undefined
? {}
: { target_cleanup: lifecycleCleanup }),
},
}),
);
if (output === undefined)
return err(
new ProviderAdapterError(PROVIDER, OPERATION, {
@@ -195,15 +316,48 @@ export class LldbCallTracer implements NativeCallTracer {
reason: "LLDB exited without a tracer result",
exit_code: exited.exitCode,
lldb_output: exited.output,
...(lifecycleCleanup === undefined
? {}
: { target_cleanup: lifecycleCleanup }),
},
...(lifecycleCleanup === undefined
? {}
: { cleanup: lifecycleCleanup }),
}),
);
if (output.status !== "traced") {
return err(tracerFailure(output, lifecycleCleanup));
}
const stdout = await capturedOutput(
paths.stdoutCapture,
output.target_output.stdout_bytes,
output.target_output.stdout_truncated,
output.target_output.stdout_complete,
);
const stderr = await capturedOutput(
paths.stderrCapture,
output.target_output.stderr_bytes,
output.target_output.stderr_truncated,
output.target_output.stderr_complete,
);
if (!stdout.ok || !stderr.ok)
return err(
new ProviderAdapterError(PROVIDER, OPERATION, {
diagnostics: {
reason: "LLDB target output capture could not be read",
...(stdout.ok ? {} : { stdout_capture_error: stdout.error }),
...(stderr.ok ? {} : { stderr_capture_error: stderr.error }),
...(lifecycleCleanup === undefined
? {}
: { target_cleanup: lifecycleCleanup }),
},
}),
);
if (output.status !== "traced") return err(tracerFailure(output));
return ok({
debugger: { ...lldb, version: output.version },
run: output,
stdout: await capturedOutput(paths.stdout),
stderr: await capturedOutput(paths.stderr),
stdout: stdout.value,
stderr: stderr.value,
terminated,
});
}
@@ -213,13 +367,36 @@ export class LldbCallTracer implements NativeCallTracer {
const quote = (value: string): string =>
`"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
const tracerFailure = (output: {
readonly status: "target-error" | "launch-error" | "tracer-error";
readonly error: string | null;
}): AnalysisError => {
const tracerFailure = (
output: {
readonly status:
| "target-error"
| "target-integrity-error"
| "target-identity-unavailable"
| "launch-error"
| "tracer-error";
readonly error: string | null;
},
cleanup?: AnalysisCleanupObservation,
): AnalysisError => {
const options = cleanup === undefined ? undefined : { cleanup };
const message = output.error ?? "no LLDB error text";
if (output.status === "target-integrity-error")
return new EvidenceIntegrityError(
message || "The launched native target did not match its session digest",
options,
);
if (output.status === "target-identity-unavailable")
return new ProviderAdapterError(PROVIDER, OPERATION, {
...options,
diagnostics: {
reason: message,
constraint: "target process start identity could not be verified",
},
});
if (output.status === "tracer-error")
return new ProviderAdapterError(PROVIDER, OPERATION, {
...options,
diagnostics: { reason: `LLDB bridge failed: ${message}` },
});
if (output.status === "target-error")
@@ -227,6 +404,7 @@ const tracerFailure = (output: {
PROVIDER,
OPERATION,
`lldb-target-unloadable: ${message}`,
options,
);
// debugserver reports denied task access as an attach failure.
return /attach|not allowed|permission|denied|debugserver/iu.test(message)
@@ -234,12 +412,13 @@ const tracerFailure = (output: {
PROVIDER,
OPERATION,
`debugger-attach-denied: ${message}`,
{ userMessage: ATTACH_REMEDIATION },
{ userMessage: ATTACH_REMEDIATION, ...options },
)
: new AnalysisCapabilityUnavailableError(
PROVIDER,
OPERATION,
`launch-failed: ${message}`,
options,
);
};
@@ -258,24 +437,40 @@ const readTracerOutput = async (
return output.success ? output.data : undefined;
};
const capturedOutput = async (path: string): Promise<CapturedOutput> => {
let handle;
const capturedOutput = async (
path: string,
observedBytes: number,
truncated: boolean,
complete: boolean,
): Promise<Result<CapturedOutput, string>> => {
let handle: Awaited<ReturnType<typeof open>> | undefined;
try {
handle = await open(path, "r");
} catch {
return { text: "", bytes: 0, truncated: false };
}
try {
const { size } = await handle.stat();
const buffer = Buffer.alloc(Math.min(size, MAX_OUTPUT_BYTES));
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
return {
const captured = {
text: buffer.subarray(0, bytesRead).toString("utf8"),
bytes: size,
truncated: size > MAX_OUTPUT_BYTES,
};
} finally {
bytes: observedBytes,
truncated: truncated || size > MAX_OUTPUT_BYTES,
complete:
complete && bytesRead >= Math.min(observedBytes, MAX_OUTPUT_BYTES),
} satisfies CapturedOutput;
await handle.close();
handle = undefined;
return ok(captured);
} catch (cause: unknown) {
const failure = cause instanceof Error ? cause.message : String(cause);
if (handle !== undefined) {
try {
await handle.close();
} catch (closeCause: unknown) {
return err(
`${failure}; closing capture file failed: ${closeCause instanceof Error ? closeCause.message : String(closeCause)}`,
);
}
}
return err(failure);
}
};
@@ -284,93 +479,196 @@ type LldbExit =
readonly kind: "exited";
readonly exitCode: number | null;
readonly output: string;
readonly targetIdentity: string | undefined;
readonly cleanupFailure: string | undefined;
}
| { readonly kind: "cancelled" }
| { readonly kind: "timeout" };
| {
readonly kind: "cancelled";
readonly targetIdentity: string | undefined;
readonly cleanupFailure: string | undefined;
}
| {
readonly kind: "timeout";
readonly targetIdentity: string | undefined;
readonly cleanupFailure: string | undefined;
};
/** Run LLDB in its own process group so cancellation can stop it and debugserver. */
const runLldb = (
/** Supervise LLDB as an owned process group while observing its target PID identity. */
const runLldb = async (
executable: string,
arguments_: readonly string[],
options: { readonly signal?: AbortSignal; readonly deadlineMs: number },
): Promise<LldbExit> =>
new Promise((resolve) => {
if (options.signal?.aborted === true) {
resolve({ kind: "cancelled" });
return;
}
const child = spawn(executable, [...arguments_], {
shell: false,
detached: true,
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
let stopped: "cancelled" | "timeout" | undefined;
const keep = (chunk: Buffer): void => {
output = (output + chunk.toString("utf8")).slice(-DIAGNOSTIC_BYTES);
options: {
readonly signal?: AbortSignal;
readonly deadlineMs: number;
readonly pidPath: string;
readonly identityAckPath: string;
},
): Promise<LldbExit> => {
if (options.signal?.aborted === true)
return {
kind: "cancelled",
targetIdentity: undefined,
cleanupFailure: undefined,
};
child.stdout.on("data", keep);
child.stderr.on("data", keep);
const kill = (reason: "cancelled" | "timeout"): void => {
stopped ??= reason;
if (child.pid !== undefined)
const deadline = new ProviderStartupDeadline(
options.deadlineMs,
options.signal,
);
let targetIdentity: string | undefined;
let supervisor: ProviderProcessSupervisor | undefined;
try {
const launched = await spawnOwnedProviderProcess({
command: executable,
arguments: arguments_,
runId: randomUUID(),
expectedCommand: executable,
signal: deadline.signal,
});
supervisor = new ProviderProcessSupervisor(
{
...launched,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(launched.ownership),
},
{ maxDiagnosticBytes: DIAGNOSTIC_BYTES },
);
let identityAckWritten = false;
while (!(await supervisor.waitForOutputClose(20))) {
const pid = await readTargetPid(options.pidPath);
if (pid !== undefined && !identityAckWritten) {
let observation: ProcessIdentityObservation | undefined;
try {
process.kill(-child.pid, "SIGKILL");
observation = await observeProcessStartIdentity(pid);
} catch {
// The group already exited.
observation = undefined;
}
if (observation?.state === "readable")
targetIdentity = observation.identity;
await writeFile(
options.identityAckPath,
observation?.state === "readable" ? "readable" : "unavailable",
{ mode: 0o600 },
);
identityAckWritten = true;
}
const interruption = deadline.interruption;
if (interruption !== undefined) {
const stopped = await supervisor.stop();
const cleanupFailure =
stopped.status === "incomplete" ? stopped.reason : undefined;
return interruption === "cancelled"
? { kind: "cancelled", targetIdentity, cleanupFailure }
: { kind: "timeout", targetIdentity, cleanupFailure };
}
await waitForAbortableDelay(20, deadline.signal);
}
const snapshot = supervisor.snapshot();
const stopped = await supervisor.stop();
const cleanupFailure =
stopped.status === "incomplete" ? stopped.reason : undefined;
const interruption = deadline.interruption;
if (interruption === "cancelled")
return { kind: "cancelled", targetIdentity, cleanupFailure };
if (interruption === "timeout")
return { kind: "timeout", targetIdentity, cleanupFailure };
return {
kind: "exited",
exitCode: snapshot.exitCode ?? null,
output: `${snapshot.stdout.text}${snapshot.stderr.text}`.slice(
-DIAGNOSTIC_BYTES,
),
targetIdentity,
cleanupFailure,
};
const timer = setTimeout(() => {
kill("timeout");
}, options.deadlineMs);
const onAbort = (): void => {
kill("cancelled");
};
options.signal?.addEventListener("abort", onAbort, { once: true });
const finish = (exitCode: number | null): void => {
clearTimeout(timer);
options.signal?.removeEventListener("abort", onAbort);
resolve(
stopped === undefined
? { kind: "exited", exitCode, output }
: { kind: stopped },
);
};
child.on("error", () => {
finish(null);
});
child.on("close", (code) => {
finish(code);
});
});
} catch (cause: unknown) {
const interruption = deadline.interruption;
const stopped = await supervisor?.stop();
const cleanupFailure =
stopped?.status === "incomplete" ? stopped.reason : undefined;
return interruption === "timeout"
? { kind: "timeout", targetIdentity, cleanupFailure }
: interruption === "cancelled"
? { kind: "cancelled", targetIdentity, cleanupFailure }
: {
kind: "exited",
exitCode: null,
output: cause instanceof Error ? cause.message : String(cause),
targetIdentity,
cleanupFailure,
};
} finally {
supervisor?.dispose();
deadline.dispose();
}
};
/**
* debugserver kills the traced process when LLDB exits. Confirm it, and kill a
* survivor only when its executable is still the traced one.
* Confirm target exit, and signal a survivor only when its OS start identity
* still matches the one captured while it was stopped at entry.
*/
const readTargetPid = async (pidPath: string): Promise<number | undefined> => {
try {
const pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);
return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
} catch {
return undefined;
}
};
type TargetTermination =
| "terminated"
| "identity-unavailable"
| "identity-changed"
| "signal-did-not-stop";
/** Only signal a surviving target when its captured OS start identity still matches. */
const ensureTerminated = async (
pidPath: string,
executable: string,
): Promise<boolean> => {
let pid: number;
try {
pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);
} catch {
// LLDB never launched the target.
return true;
}
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
identity: string | undefined,
missingPidIsUnknown: boolean,
): Promise<TargetTermination> => {
const pid = await readTargetPid(pidPath);
if (pid === undefined)
return missingPidIsUnknown ? "identity-unavailable" : "terminated";
if (!Number.isSafeInteger(pid) || pid <= 0) return "identity-unavailable";
let signalDisposition: Exclude<TargetTermination, "terminated"> | undefined;
for (let attempt = 0; attempt < 20; attempt++) {
if (!alive(pid)) return true;
if (attempt === 10 && (await commandOf(pid)) === executable)
try {
process.kill(pid, "SIGKILL");
} catch {
// It exited between the checks.
if (!alive(pid)) return "terminated";
if (attempt === 10) {
if (identity === undefined) signalDisposition = "identity-unavailable";
else {
const result = await signalProcessWithStartIdentity(
pid,
identity,
"SIGKILL",
);
if (result === "gone") return "terminated";
if (result === "identity-changed")
signalDisposition = "identity-changed";
else if (result === "unverified")
signalDisposition = "identity-unavailable";
else if (result === "signaled")
signalDisposition = "signal-did-not-stop";
}
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
return !alive(pid);
return !alive(pid)
? "terminated"
: (signalDisposition ?? "identity-unavailable");
};
const targetTerminationReason = (termination: TargetTermination): string => {
switch (termination) {
case "terminated":
return "target process terminated";
case "identity-unavailable":
return "target process start identity was unavailable; survivor was left untouched";
case "identity-changed":
return "target PID start identity changed; replacement process was left untouched";
case "signal-did-not-stop":
return "verified target did not exit after SIGKILL";
}
};
const alive = (pid: number): boolean => {
@@ -385,16 +683,3 @@ const alive = (pid: number): boolean => {
);
}
};
const commandOf = async (pid: number): Promise<string | undefined> => {
try {
const { stdout } = await execFileOutput(
"/bin/ps",
["-o", "comm=", "-p", String(pid)],
{ timeout: 5_000 },
);
return stdout.trim();
} catch {
return undefined;
}
};
+57
View File
@@ -0,0 +1,57 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, type Result } from "../domain/result.js";
import type { NativeCallTrace, NativeCallTracer } from "./LldbCallTracer.js";
import { observeNativeCalls } from "./NativeCallObservation.js";
import { nativeMachoTarget } from "../../tests/fixtures/nativeCommands.js";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
class NeverStartedTracer implements NativeCallTracer {
calls = 0;
trace(): Promise<Result<NativeCallTrace, AnalysisError>> {
this.calls += 1;
throw new Error("tracer must not run after hash cancellation");
}
}
describe("native call target digest cancellation", () => {
it("returns tagged cancellation when hashing aborts after a chunk", async () => {
const directory = await createTestTempDirectory("rea-native-digest-");
const path = join(directory, "fixture");
const bytes = "selected executable";
await writeFile(path, bytes);
const target = {
...nativeMachoTarget(path),
sha256: createHash("sha256").update(bytes).digest("hex"),
};
const signal = new AbortController();
const tracer = new NeverStartedTracer();
const observed = await observeNativeCalls(
target,
{ breakpoints: [{ kind: "function", name: "main" }] } satisfies Record<
string,
JsonValue
>,
tracer,
signal.signal,
async () => {
signal.abort();
throw new DOMException("read aborted", "AbortError");
},
);
expect(!observed.ok && observed.error).toBeInstanceOf(
AnalysisCancelledError,
);
expect(tracer.calls).toBe(0);
});
});
+55 -2
View File
@@ -9,6 +9,7 @@ import {
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
nativeCallObservationInputSchema,
@@ -37,6 +38,7 @@ export const observeNativeCalls = async (
parameters: Readonly<Record<string, JsonValue>>,
tracer: NativeCallTracer,
signal?: AbortSignal,
readTargetDigest: typeof fileSha256 = fileSha256,
): Promise<Result<NativeCallObservationResult, AnalysisError>> => {
if (target.kind !== "executable" || target.format !== "mach-o")
return err(
@@ -50,7 +52,22 @@ export const observeNativeCalls = async (
if (!parsed.success)
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
// Observe the bytes the session's other Evidence describes.
if ((await fileSha256(target.path, signal)) !== target.sha256)
let digest: string;
try {
digest = await readTargetDigest(target.path, signal);
} catch (cause: unknown) {
if (signal?.aborted === true || isAbortError(cause))
return err(new AnalysisCancelledError(OPERATION));
return err(
new ProviderAdapterError("native-macos", OPERATION, {
diagnostics: {
reason: "Unable to verify the selected target digest",
detail: cause instanceof Error ? cause.message : String(cause),
},
}),
);
}
if (digest !== target.sha256)
return err(
new EvidenceIntegrityError(
"Native call observation target digest changed after session binding",
@@ -62,6 +79,7 @@ export const observeNativeCalls = async (
{
executable: target.path,
architecture: target.architecture,
expectedSha256: target.sha256,
input: parsed.data,
},
signal,
@@ -70,6 +88,9 @@ export const observeNativeCalls = async (
return ok(projectNativeCalls(target, parsed.data, traced.value));
};
const isAbortError = (cause: unknown): boolean =>
cause instanceof Error && cause.name === "AbortError";
/** Join the request, the tracer's run and REA's own checks into the result contract. */
export const projectNativeCalls = (
target: Pick<BinaryTarget, "path" | "sha256"> & {
@@ -83,15 +104,30 @@ export const projectNativeCalls = (
.filter(({ location_count: count }) => count === 0)
.map(({ index }) => index);
const eventLimit = run.outcome === "event-limit";
const resourceLimit = run.outcome === "resource-limit";
const partial =
eventLimit || run.outcome === "stop-limit" || unresolved.length > 0;
eventLimit ||
resourceLimit ||
run.outcome === "duration-elapsed" ||
run.outcome === "stop-limit" ||
unresolved.length > 0;
return nativeCallObservationResultSchema.parse({
target: {
path: target.path,
sha256: target.sha256,
architecture: target.architecture,
arguments: input.arguments,
environment: input.environment,
working_directory: input.working_directory ?? null,
launch_identity: {
loaded_image_sha256: run.target_identity.loaded_image_sha256,
file_device: run.target_identity.file_device,
file_inode: run.target_identity.file_inode,
selected_file_sha256: run.target_identity.selected_file_sha256,
module_path: run.target_identity.module_path,
module_uuid: run.target_identity.module_uuid,
stable: run.target_identity.stable,
},
},
debugger: trace.debugger,
process: {
@@ -118,20 +154,32 @@ export const projectNativeCalls = (
coverage: {
status: partial ? "partial" : "complete",
event_limit_reached: eventLimit,
resource_limit_reached: resourceLimit,
unresolved_breakpoints: unresolved,
},
limitations: [
...NATIVE_CALL_OBSERVATION_LIMITATIONS,
"The selected pathname digest and LLDB module identity are checked around launch. No immutable executable snapshot is used; concurrent in-place mutation or replacement and restoration cannot be ruled out, so the loaded-image digest remains unknown.",
...(eventLimit
? [
`Observation stopped at max_events (${input.max_events}); later calls were not recorded and the process was killed.`,
]
: []),
...(resourceLimit
? [
"Observation stopped before retaining the next complete event because the estimated 8 MiB trace-payload or 65,536-frame aggregate budget was reached; the process was killed.",
]
: []),
...(run.outcome === "duration-elapsed"
? [
`The process was still running after duration_ms (${input.duration_ms}) and was killed.`,
]
: []),
...(run.target_identity.stable
? []
: [
"LLDB did not provide enough module identity evidence to confirm pathname and module continuity around launch.",
]),
...(run.outcome === "stop-limit"
? [
"Observation stopped after repeated signal or exception stops; the process was killed.",
@@ -152,6 +200,11 @@ export const projectNativeCalls = (
...(trace.stdout.truncated || trace.stderr.truncated
? ["Target output beyond 1 MiB per stream is counted but not kept."]
: []),
...(!trace.stdout.complete || !trace.stderr.complete
? [
"Target output draining did not complete; reported byte counts are observed lower bounds, not stream totals.",
]
: []),
...(run.terminated && trace.terminated
? []
: [
@@ -367,6 +367,49 @@ export const createSystemProcessOwnershipHost = (
export const systemProcessOwnershipHost = createSystemProcessOwnershipHost();
/** Observe the current OS start identity for one live PID, when supported. */
export const observeProcessStartIdentity = async (
pid: number,
host: ProcessOwnershipHost = systemProcessOwnershipHost,
): Promise<ProcessIdentityObservation | undefined> => {
const process = (await host.listProcesses()).find(
(entry) => entry.pid === pid,
);
if (process === undefined || liveProcesses([process]).length === 0)
return undefined;
if (host.processIdentities === undefined)
return { state: "unavailable", reason: "process identity is unsupported" };
return (
(await host.processIdentities([process])).get(pid) ?? {
state: "unavailable",
reason: "process identity was not returned",
}
);
};
/** Revalidate a launch-time start identity immediately before signaling a PID. */
export const signalProcessWithStartIdentity = async (
pid: number,
expectedIdentity: string,
signal: NodeJS.Signals,
options: {
readonly host?: ProcessOwnershipHost;
readonly sendSignal?: (pid: number, signal: NodeJS.Signals) => void;
} = {},
): Promise<"signaled" | "gone" | "identity-changed" | "unverified"> => {
const host = options.host ?? systemProcessOwnershipHost;
try {
const observed = await observeProcessStartIdentity(pid, host);
if (observed === undefined) return "gone";
if (observed.state !== "readable") return "unverified";
if (observed.identity !== expectedIdentity) return "identity-changed";
(options.sendSignal ?? process.kill)(pid, signal);
return "signaled";
} catch {
return "unverified";
}
};
/** Prepare native token inspection before REA launches a captured child. */
export const prepareProcessOwnershipInspection = async (
signal?: AbortSignal,
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from "vitest";
import type { ProcessOwnershipHost } from "./ProcessOwnership.js";
import {
observeProcessStartIdentity,
signalProcessWithStartIdentity,
} from "./ProcessOwnershipObservation.js";
const host = (identity: string | undefined): ProcessOwnershipHost => ({
platform: "linux",
listProcesses: async () =>
identity === undefined
? []
: [
{
pid: 42,
parentPid: 1,
processGroupId: 42,
uid: 1000,
state: "S",
command: "/bin/fixture",
},
],
environment: async () => ({}),
processIdentities: async () =>
new Map([[42, { state: "readable", identity: identity ?? "" }]]),
signalGroup: () => undefined,
});
describe("process start identity lease", () => {
it("captures a readable identity for a live PID", async () => {
await expect(
observeProcessStartIdentity(42, host("start-1")),
).resolves.toEqual({
state: "readable",
identity: "start-1",
});
});
it("signals the PID when its launch identity still matches", async () => {
const sendSignal = vi.fn();
await expect(
signalProcessWithStartIdentity(42, "start-1", "SIGKILL", {
host: host("start-1"),
sendSignal,
}),
).resolves.toBe("signaled");
expect(sendSignal).toHaveBeenCalledWith(42, "SIGKILL");
});
it("does not signal a reused PID even when its command is unchanged", async () => {
const sendSignal = vi.fn();
await expect(
signalProcessWithStartIdentity(42, "start-1", "SIGKILL", {
host: host("start-2"),
sendSignal,
}),
).resolves.toBe("identity-changed");
expect(sendSignal).not.toHaveBeenCalled();
});
it("does not signal when the PID identity is unavailable", async () => {
const unavailable: ProcessOwnershipHost = {
...host("start-1"),
processIdentities: async () =>
new Map([[42, { state: "unavailable", reason: "reader unavailable" }]]),
};
const sendSignal = vi.fn();
await expect(
signalProcessWithStartIdentity(42, "start-1", "SIGKILL", {
host: unavailable,
sendSignal,
}),
).resolves.toBe("unverified");
expect(sendSignal).not.toHaveBeenCalled();
});
it("reports an already-gone PID without signaling", async () => {
const sendSignal = vi.fn();
await expect(
signalProcessWithStartIdentity(42, "start-1", "SIGKILL", {
host: host(undefined),
sendSignal,
}),
).resolves.toBe("gone");
expect(sendSignal).not.toHaveBeenCalled();
});
});