Skip to content

Commit 4481f86

Browse files
rohitg00morlutokaoru0822-kitaujiclaudedakjdakd
authored
fix(frida): drain admitted operations and honor queued cancellation (#2305)
* fix(frida): drain admitted operations and honor queued cancellation * fix(frida): settle cancelled loads before queued resume * test(frida): share lifecycle fixtures without duplicating assertions * fix(frida): preserve operation admission before session close * test(apple): bound cold archive fixture compilation * fix(frida): retain cancelled script creation evidence * test(release): scope preflight schema to selected jobs * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(comparison): recheck historical calls-only changes (#2223) * fix(comparison): preserve incomplete function call evidence Keep missing, unknown, partial and unresolved call relationships unknown in function comparisons and reconstruction claims. Aggregate IDA caller and callee coverage without overwriting uncertainty. Validate with 144 focused tests, typecheck/lint, docs checks and test discovery. Real providers were not verified; the full headless IDA session suite requires unavailable Windows native controls. * fix(comparison): recheck historical calls-only changes --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> (cherry picked from commit 688defc) * fix(ci): isolate Linux Hopper process fixture inventory (cherry picked from commit 8cac51e) * fix(android): make DEX descriptor pattern portable (cherry picked from commit 1335bcd) * fix: repair the static-check failures on the default branch (#2895) * fix: repair the static-check failures on the default branch The default branch fails its own required `Static checks` job three ways, so every pull request reports that job as failed regardless of its own change. - `npm run format:check` reports `src/domain/functionComparison.test.ts` and `src/ida/IdaOperationRunner.ts`. - `npm run lint` reports a duplicate `import { join } from "node:path"` in `tests/boundary/mcp/ghidraInventoryMcp.test.ts` (lines 4 and 17). - `npm run typecheck` reports `format: "devin"` missing from the client format union in `src/application/SupportedClients.ts`, and an unchecked index in `tests/boundary/cli/clientProfileLifecycle.test.ts`, whose pair array is inferred as `string[][]`. Apply the pinned formatter, drop the duplicate import, list the `"devin"` format that its own definition already uses, and mark the pair array `as const`. Validation: `npm run check:fast` and `npm run format:check` pass. * fix(setup): keep Devin on the JSON configuration dialect --------- Co-authored-by: 吴佳浩 <wujiahao@supremind.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> (cherry picked from commit df3d96d) --------- Co-authored-by: morluto <morluto@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Lucien <164857476+dakjdakd@users.noreply.github.com> Co-authored-by: 吴佳浩Alben <35291372+XiaoBinGan@users.noreply.github.com> Co-authored-by: 吴佳浩 <wujiahao@supremind.com> Co-authored-by: OpenAI Codex <codex@openai.com>
1 parent 72d5bbc commit 4481f86

8 files changed

Lines changed: 1013 additions & 44 deletions

‎docs/frida-instrumentation.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ For remote devices, pass a host with an optional port (`host[:port]`; bracket IP
66

77
MCP exposes `list_frida_devices`, `list_frida_processes`, `start_frida_session`, `load_frida_script`, `resume_frida_session`, `unload_frida_script`, `frida_session_status`, and `close_frida_session`. A spawned process starts paused so scripts can load first. Closing unloads session scripts and detaches. If a spawn remains paused, REA resumes it only after script cleanup or session detach confirms the instrumentation is released; if both cleanup paths fail, the target stays paused and the cleanup error is retained. REA never kills the target. MCP sessions end with the server process. The one-shot CLI command `instrument-with-frida` accepts one inline script or script file, observes messages for a bounded duration, and returns Evidence with the source hash and captured messages.
88

9-
Failed startup cleanup retains acquired Frida handles, including a paused spawn that has not attached, for later cleanup retries. Its remote connection stays leased until session detach and target resume complete. CLI commands await provider cleanup before returning; MCP retains these resources for cleanup when its server closes. A failed cleanup remains reported rather than treating an unregistered session as fully released.
9+
Failed startup cleanup retains acquired Frida handles, including a paused spawn that has not attached, for later cleanup retries. Its remote connection stays leased until session detach and target resume complete. CLI commands await provider cleanup before returning; MCP retains these resources for cleanup when its server closes. Server shutdown stops admitting new Frida operations and waits for admitted startup, discovery, and queued work before releasing their resources. A failed cleanup remains reported and can be retried by closing the server again, rather than treating an unregistered session as fully released.
1010

11-
Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.
11+
Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. A cancelled script load on an existing session releases only its new script before queued operations can run; the session and previously loaded scripts remain available. Once the provider commits a successful load, later request cancellation does not unload that script; use `unload_frida_script` to release it. If script cleanup fails, the script remains owned and a paused target cannot resume until the pending instrumentation is released. Queued script loads, resumes, and unloads check cancellation before dispatching native effects. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.
1212

1313
The [Frida Core API](https://frida.re/docs/frida-core-api/) documents device management, sessions, and script loading; the [JavaScript API](https://frida.re/docs/javascript-api/) documents target-side instrumentation. [Luma](https://luma.frida.re/) is Frida's standalone GUI; REA does not automate or control it. `npm run verify:frida` requires a Linux host with the optional Frida binding and uses a short-lived local Node.js fixture created by the verifier. Add `-- --address HOST:PORT --pid PID` to run the separate remote attach lane against a caller-selected target. Mock tests do not establish real device/server compatibility.

‎src/application/frida/FridaInstrumentationManager.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1023,6 +1023,28 @@ it("serializes script loading against concurrent close and unloads the loaded sc
10231023
expect(bindings.device.session.isDetached()).toBe(true);
10241024
});
10251025

1026+
it("drains startup when the provider loader initiates shutdown", async () => {
1027+
const bindings = new FakeDeviceManager();
1028+
let closing: Promise<void> | undefined;
1029+
const manager = new FridaInstrumentationManager({
1030+
deviceManagerLoader: async () => {
1031+
closing = manager.closeAll();
1032+
return bindings;
1033+
},
1034+
});
1035+
const started = await manager.startSession({
1036+
mode: "spawn",
1037+
deviceId: "local",
1038+
program: "/tmp/fixture",
1039+
});
1040+
if (!started.ok) throw started.error;
1041+
expect(closing).toBeDefined();
1042+
await closing;
1043+
expect(bindings.device.session.isDetached()).toBe(true);
1044+
expect(bindings.device.resumed).toEqual([512]);
1045+
expect(manager.status(started.value.sessionId)).toBeUndefined();
1046+
});
1047+
10261048
it("names the unknown session or script ID it rejects", async () => {
10271049
const { manager, started } = await startLocalAttachedSession();
10281050
if (!started.ok) throw started.error;

‎src/application/frida/FridaInstrumentationPort.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
1+
import type {
2+
AnalysisError,
3+
AnalysisErrorOptions,
4+
} from "../../domain/analysisErrorBase.js";
5+
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
26
import type { OptionalProviderLoadFailure } from "../OptionalObservationProviders.js";
37
import type { JsonValue } from "../../domain/jsonValue.js";
48
import type { Result } from "../../domain/result.js";
@@ -60,6 +64,15 @@ export interface FridaScriptObservation {
6064
readonly messagesTruncated: boolean;
6165
}
6266

67+
export class FridaScriptLoadCancelledError extends AnalysisCancelledError {
68+
constructor(
69+
readonly script: FridaScriptObservation,
70+
options?: AnalysisErrorOptions,
71+
) {
72+
super("load_frida_script", options);
73+
}
74+
}
75+
6376
export interface FridaSessionStatus extends FridaSessionObservation {
6477
/** True only after REA has successfully resumed this spawned target. */
6578
readonly targetResumeObserved: boolean;
@@ -100,14 +113,20 @@ export interface FridaInstrumentationPort {
100113
startSession(
101114
input: StartFridaSessionInput,
102115
): Promise<Result<FridaSessionObservation, AnalysisError>>;
116+
/** Own cancellation and new-script cleanup before returning a final load outcome. */
103117
loadScript(
104118
sessionId: string,
105119
source: FridaScriptSource,
120+
signal?: AbortSignal,
106121
): Promise<Result<FridaScriptObservation, AnalysisError>>;
107-
resumeSession(sessionId: string): Promise<Result<null, AnalysisError>>;
122+
resumeSession(
123+
sessionId: string,
124+
signal?: AbortSignal,
125+
): Promise<Result<null, AnalysisError>>;
108126
unloadScript(
109127
sessionId: string,
110128
scriptId: string,
129+
signal?: AbortSignal,
111130
): Promise<Result<null, AnalysisError>>;
112131
status(sessionId: string): FridaSessionStatus | undefined;
113132
closeSession(

‎src/application/frida/FridaInstrumentationService.test.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { join } from "node:path";
33

44
import { expect, it } from "vitest";
55

6+
import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";
67
import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";
78
import { FridaInstrumentationService } from "./FridaInstrumentationService.js";
89
import {
@@ -569,3 +570,74 @@ it("cleans up a session and returns typed cancellation after a pending start", a
569570
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
570571
expect(closed).toEqual(["00000000-0000-4000-8000-000000000001"]);
571572
});
573+
574+
it("retains a cancelled provider load's source and messages in one-shot Evidence", async () => {
575+
const controller = new AbortController();
576+
const script = {
577+
...createScriptObservation(),
578+
messages: [{ type: "send", payload: "cancelled-load" }],
579+
};
580+
const service = new FridaInstrumentationService(
581+
createProvider({
582+
async loadScript() {
583+
controller.abort(new Error("cancel during native load"));
584+
return {
585+
ok: false,
586+
error: new FridaScriptLoadCancelledError(script, {
587+
cause: controller.signal.reason,
588+
}),
589+
};
590+
},
591+
}),
592+
);
593+
const result = await service.instrument(
594+
{
595+
mode: "spawn",
596+
program: "/fixture",
597+
source: { sourceKind: "inline", source: "send('cancelled-load')" },
598+
durationMs: 0,
599+
},
600+
controller.signal,
601+
);
602+
if (result.ok) throw new Error("Cancelled instrumentation succeeded");
603+
expect(result.error.partialObservation).toMatchObject({
604+
normalized_result: {
605+
source_kind: "inline",
606+
source_sha256: script.sourceSha256,
607+
messages: script.messages,
608+
instrumentation_cleanup: "released",
609+
},
610+
});
611+
});
612+
613+
it("preserves a provider-committed load when cancellation arrives during result delivery", async () => {
614+
const controller = new AbortController();
615+
let unloads = 0;
616+
const script = createScriptObservation();
617+
const service = new FridaInstrumentationService(
618+
createProvider({
619+
loadScript() {
620+
const completed = Promise.resolve({ ok: true as const, value: script });
621+
void completed.then(() =>
622+
controller.abort(new Error("late cancellation")),
623+
);
624+
return completed;
625+
},
626+
async unloadScript() {
627+
unloads += 1;
628+
return { ok: true, value: null };
629+
},
630+
}),
631+
);
632+
const loaded = await service.loadScript(
633+
createSession().sessionId,
634+
{ sourceKind: "inline", source: "send('ready')" },
635+
controller.signal,
636+
);
637+
expect(controller.signal.aborted).toBe(true);
638+
if (!loaded.ok) throw loaded.error;
639+
expect(loaded.value.normalized_result).toMatchObject({
640+
script_id: script.scriptId,
641+
});
642+
expect(unloads).toBe(0);
643+
});

‎src/application/frida/FridaInstrumentationService.ts‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
AnalysisInputError,
1313
} from "../../domain/analysisErrorCore.js";
1414
import { err, ok, type Result } from "../../domain/result.js";
15+
import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";
1516
import type {
1617
FridaDeviceSelector,
1718
FridaInstrumentationPort,
@@ -181,8 +182,17 @@ export class FridaInstrumentationService {
181182
async loadScript(
182183
sessionId: string,
183184
source: FridaScriptSource,
185+
signal?: AbortSignal,
184186
): Promise<Result<Evidence, AnalysisError>> {
185-
const loaded = await this.#provider.loadScript(sessionId, source);
187+
if (signal?.aborted)
188+
return err(
189+
new AnalysisCancelledError("load_frida_script", {
190+
cause: signal.reason,
191+
}),
192+
);
193+
const loaded = await this.#provider.loadScript(sessionId, source, signal);
194+
if (!loaded.ok && loaded.error instanceof FridaScriptLoadCancelledError)
195+
return err(cancelledScriptEvidence(sessionId, loaded.error));
186196
return loaded.ok
187197
? ok(
188198
fridaEvidence("load_frida_script", scriptOutput(loaded.value), {
@@ -192,12 +202,12 @@ export class FridaInstrumentationService {
192202
: loaded;
193203
}
194204

195-
resumeSession(sessionId: string) {
196-
return this.#provider.resumeSession(sessionId);
205+
resumeSession(sessionId: string, signal?: AbortSignal) {
206+
return this.#provider.resumeSession(sessionId, signal);
197207
}
198208

199-
unloadScript(sessionId: string, scriptId: string) {
200-
return this.#provider.unloadScript(sessionId, scriptId);
209+
unloadScript(sessionId: string, scriptId: string, signal?: AbortSignal) {
210+
return this.#provider.unloadScript(sessionId, scriptId, signal);
201211
}
202212

203213
status(sessionId: string): FridaSessionStatus | undefined {
@@ -243,14 +253,19 @@ export class FridaInstrumentationService {
243253
const loaded = await this.#provider.loadScript(
244254
started.value.sessionId,
245255
input.source,
256+
signal,
246257
);
258+
let scriptObservation: FridaScriptObservation | undefined;
259+
if (loaded.ok) scriptObservation = loaded.value;
260+
else if (loaded.error instanceof FridaScriptLoadCancelledError)
261+
scriptObservation = loaded.error.script;
247262
if (signal?.aborted)
248263
return this.#cancelSession(
249264
"instrument_with_frida",
250265
started.value,
251266
input,
252267
signal.reason,
253-
loaded.ok ? loaded.value : undefined,
268+
scriptObservation,
254269
);
255270
if (!loaded.ok) {
256271
const closed = await this.#provider.closeSession(started.value.sessionId);
@@ -267,6 +282,7 @@ export class FridaInstrumentationService {
267282
if (started.value.mode === "spawn") {
268283
const resumed = await this.#provider.resumeSession(
269284
started.value.sessionId,
285+
signal,
270286
);
271287
if (signal?.aborted)
272288
return this.#cancelSession(
@@ -462,3 +478,23 @@ const sessionStatusOutput = (status: FridaSessionStatus) => ({
462478
messages: status.messages,
463479
messages_truncated: status.messagesTruncated,
464480
});
481+
482+
const cancelledScriptEvidence = (
483+
sessionId: string,
484+
error: FridaScriptLoadCancelledError,
485+
): AnalysisCancelledError =>
486+
new AnalysisCancelledError(error.operation, {
487+
cause: error.cause,
488+
cleanup: error.cleanup,
489+
partialObservation: fridaEvidence(
490+
error.operation,
491+
{
492+
...scriptOutput(error.script),
493+
cleanup_error: error.cleanup?.reason ?? null,
494+
script_cleanup: error.cleanupIncomplete
495+
? "incomplete_or_unknown"
496+
: "released",
497+
},
498+
{ session_id: sessionId },
499+
),
500+
});

0 commit comments

Comments
 (0)