Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions src/adb/AdbProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ it("reads a bounded logcat dump with the caller count and buffer", async () => {
const { binary } = await writeAdbStub(
shellStub({
logcat:
"08-10 13:00:00.000 I/Tag( 123): first\\n08-10 13:00:01.000 I/Tag( 123): second\\n",
"08-10 13:00:00.000 I/Tag( 123): first\n08-10 13:00:01.000 I/Tag( 123): second\n",
}),
);
const result = await evidenceResult(providerOver(binary), {
Expand Down Expand Up @@ -903,7 +903,7 @@ it("resolves packages by case-insensitive substring", async () => {
const { binary } = await writeAdbStub(
shellStub({
"pm:list":
"package:/data/app/x/base.apk=com.whatsapp\\npackage:/data/app/y/base.apk=com.whatsapp.w4b\\npackage:/data/app/z/base.apk=com.example\\n",
"package:/data/app/x/base.apk=com.whatsapp\npackage:/data/app/y/base.apk=com.whatsapp.w4b\npackage:/data/app/z/base.apk=com.example\n",
}),
);
const result = await evidenceResult(providerOver(binary), {
Expand Down Expand Up @@ -1109,20 +1109,23 @@ exit 1`,

it("quotes caller text before adb joins the remote shell command", async () => {
const { binary, root } = await writeAdbStub(
(root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
shift 3
# Model adb's remote command joining, then execute the resulting shell string.
printf '#!/bin/sh\nprintf "%%s" "$@" > "${join(root, "observed")}"\n' > "${join(root, "ls")}"
chmod +x "${join(root, "ls")}"
PATH="${root}:$PATH" sh -c "$*"
sh -c "$*"
`,
);
const value = `/sdcard/a 'quoted'; touch ${join(root, "injected")}`;
await providerOver(binary).execute({
const value = join(root, `device 'quoted'; touch ${join(root, "injected")}`);
await mkdir(value, { recursive: true });
const result = await evidenceResult(providerOver(binary), {
operation: "list_adb_directory",
input: { serial: "device", device_path: value },
});
expect(await readFile(join(root, "observed"), "utf8")).toContain(value);
expect(result).toMatchObject({
device_path: value,
entries: [],
coverage: "complete",
});
await expect(readFile(join(root, "injected"))).rejects.toThrow();
});

Expand Down
8 changes: 4 additions & 4 deletions src/cli/webModuleCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ export const registerWebModuleCommands = (
options: z.object({
importerUrl: webModuleTraceInputSchema.shape.importer_url,
importMapPath: importMapInputSchema.shape.path
.optional()
.describe(
"Absolute local import-map JSON path; requires --import-map-base-url",
)
.optional(),
),
importMapBaseUrl: importMapInputSchema.shape.base_url
.describe("HTTP(S) import-map base URL; requires --import-map-path")
.optional(),
.optional()
.describe("HTTP(S) import-map base URL; requires --import-map-path"),
}),
run: ({ args, options }) =>
withCommandCancellation(async (signal) => {
Expand Down
32 changes: 31 additions & 1 deletion src/ghidra/GhidraClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import type { ProgressReporter } from "../application/ProgressReporter.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import {
providerRetryAction,
type ProviderOperationHealth,
} from "../domain/providerOperationHealth.js";
import { err, ok, type Result } from "../domain/result.js";
import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
Expand Down Expand Up @@ -477,6 +481,32 @@ export class GhidraClient {
});
}

/** Observed failures that prevent a retained session from being reused. */
operationHealthSnapshot(): ProviderOperationHealth | undefined {
const exit = this.#process?.observedExit();
const state =
exit !== undefined
? "exited"
: this.#socket?.destroyed === true
? "unreachable"
: this.#startPromise === undefined &&
(this.#process !== undefined ||
this.#socket !== undefined ||
this.#runtimeRoot !== undefined ||
this.#socketRoot !== undefined ||
this.#snapshotOwners.size > 0)
? "unknown"
: undefined;
if (state === undefined) return undefined;
return {
state,
stage: null,
retryAction: providerRetryAction(state),
exitCode: exit?.code ?? null,
requests: [],
};
}

/** Latest bounded local diagnostics, with bearer material redacted. */
diagnostics(): Readonly<Record<string, JsonValue>> {
return structuredClone(this.#diagnostics());
Expand Down Expand Up @@ -633,7 +663,7 @@ export class GhidraClient {
deadline,
failure: this.#failure,
isClosed: () => this.#closing,
processExited: () => this.#process?.snapshot().exitCode !== undefined,
processExited: () => this.#process?.observedExit() !== undefined,
startupTimeoutMs: this.#options.startupTimeoutMs,
handlers: {
data: this.#onSocketData,
Expand Down
6 changes: 5 additions & 1 deletion src/ghidra/GhidraProviderClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,10 @@ export type GhidraProviderClientFactory = (
Partial<
Pick<
GhidraClient,
"runtimeLineage" | "readTargetSnapshot" | "hashTargetSnapshot"
| "operationHealthSnapshot"
| "runtimeLineage"
| "readTargetSnapshot"
| "hashTargetSnapshot"
>
>;

Expand Down Expand Up @@ -840,6 +843,7 @@ export const createGhidraProviderClient = (input: {
}),
);
},
operationHealthSnapshot: () => client.operationHealthSnapshot?.(),
runtimeLineageSnapshots: () => {
const observation = client.runtimeLineage?.() ?? null;
return observation === null
Expand Down
28 changes: 21 additions & 7 deletions src/process/ProviderProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ export type ProviderProcessLaunch =
readonly cleanup?: () => Promise<ProcessCleanupResult>;
};

/**
* Process exit recorded by the supervisor.
* Independent of retained stream diagnostics.
*/
export interface ProviderProcessExitObservation {
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
}

/** Detached diagnostics captured for one supervised provider process. */
export interface ProviderProcessSnapshot {
/** True only when a configured diagnostic budget excluded output bytes. */
Expand Down Expand Up @@ -233,10 +242,7 @@ export class ProviderProcessSupervisor {
readonly #options: ProviderProcessSupervisorOptions;
readonly #stdout = new ProcessOutputCapture();
readonly #stderr = new ProcessOutputCapture();
readonly #exit = deferred<{
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
}>();
readonly #exit = deferred<ProviderProcessExitObservation>();
readonly #outputClose = deferred<void>();
#outputClosed = false;
#stdoutObservedBytes = 0;
Expand Down Expand Up @@ -271,9 +277,7 @@ export class ProviderProcessSupervisor {
readonly #onError = (cause: Error): void => {
this.#options.onDiagnostic?.({ type: "error", message: cause.message });
};
#exitObservation:
| { readonly code: number | null; readonly signal: NodeJS.Signals | null }
| undefined;
#exitObservation: ProviderProcessExitObservation | undefined;
#stopPromise: Promise<ProviderProcessStopResult> | undefined;
#disposed = false;

Expand All @@ -292,6 +296,16 @@ export class ProviderProcessSupervisor {
this.#recordExit(launch.process.exitCode, launch.process.signalCode);
}

/**
* Recorded process exit without concatenating retained stream diagnostics.
* Undefined until exit or close is observed.
*/
observedExit(): ProviderProcessExitObservation | undefined {
const exit = this.#exitObservation;
if (exit === undefined) return undefined;
return { code: exit.code, signal: exit.signal };
}

/** Latest retained output and exit observation, with explicit configured truncation. */
snapshot(): ProviderProcessSnapshot {
return {
Expand Down
53 changes: 52 additions & 1 deletion src/process/ProviderProcessOutput.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { ProviderProcessSupervisor } from "./ProviderProcess.js";

it("exit does not establish complete output when a producer closes its streams later", async () => {
Expand Down Expand Up @@ -34,6 +34,57 @@ it("exit does not establish complete output when a producer closes its streams l
}
});

it("reads an observed exit without materializing stream diagnostics", () => {
const producer = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null,
signalCode: null,
kill: () => false,
});
const supervisor = new ProviderProcessSupervisor({
process: producer,
ownsProcessLifetime: false,
});
try {
producer.stdout.write("retained-diagnostic");
const snapshot = vi.spyOn(supervisor, "snapshot");
expect(supervisor.observedExit()).toBeUndefined();
producer.emit("exit", null, "SIGKILL");
expect(supervisor.observedExit()).toEqual({
code: null,
signal: "SIGKILL",
});
expect(snapshot).not.toHaveBeenCalled();
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "retained-diagnostic" },
exitCode: null,
signal: "SIGKILL",
});
} finally {
supervisor.dispose();
}
});

it("observes an exit that completed before supervision", () => {
const producer = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: 2,
signalCode: null,
kill: () => false,
});
const supervisor = new ProviderProcessSupervisor({
process: producer,
ownsProcessLifetime: false,
});
try {
expect(supervisor.observedExit()).toEqual({ code: 2, signal: null });
} finally {
supervisor.dispose();
}
});

it("reports a reached process memory limit only when the handle observed one", () => {
let reached = false;
const producer = Object.assign(new EventEmitter(), {
Expand Down
Loading
Loading