mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 11:43:20 +00:00
* refactor(errors): require a reason for every analysis cancellation Add cancelledBy, the one constructor for AnalysisCancelledError. Its reason argument is required: an aborted signal, an earlier cancellation, a reason carried from an inner failure, or an OwnerCancellation when REA closed the work's owner itself. Closed adb, apktool, firmware, sqlite, gdb, web-bundle analyzer and binary-session record owners now report OwnerCancellation.ownerClosed instead of an absent reason. Firmware's predecessor wait returns its cancellation as a Result, removing an unreachable reason-less fallback. An architecture guard rejects new direct constructions, with a counted per-file baseline that can only shrink. * refactor(errors): share one aborted-signal predicate with cancelledBy * refactor(process): return a departing caller's reason from a shared startup wait * refactor(android): build mobile-provider cancellations with a required reason Migrate every remaining AnalysisCancelledError construction under src/adb, src/android, src/apktool, src/apkSignature, src/flutter, src/il2cpp, src/dotnet and src/frida to cancelledBy and lower the guard baseline from 671 to 608. A closed adb provider reports OwnerCancellation.ownerClosed for later probes, and JADX and apktool shutdown abort with that typed reason. * refactor(providers): build decompiler-provider cancellations with a required reason (#10587) Migrate every AnalysisCancelledError construction under src/ghidra, src/ida, src/cutter, src/jeb and src/kuna to cancelledBy and lower the guard baseline from 671 to 572. Closed Kuna target commands report OwnerCancellation.ownerClosed instead of an absent reason, and Kuna and JEB close abort their lifetimes with that typed reason. * fix(errors): read the reason of any signal-shaped cancellation source * test(ci): cover the counted-baseline comparison behind the architecture guard
421 lines
14 KiB
TypeScript
421 lines
14 KiB
TypeScript
import {
|
|
AnalysisProtocolError,
|
|
AnalysisResourceConstraintError,
|
|
AnalysisTimeoutError,
|
|
AnalysisUnsupportedTargetError,
|
|
cancelledBy,
|
|
carriedReason,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
|
|
import type { JsonValue } from "../domain/jsonValue.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import {
|
|
execFileBytes,
|
|
execFileFailureCapturedOutput,
|
|
ExecFileOutputCancelledError,
|
|
execFileOutputFailure,
|
|
type ExecFileOutputFailure,
|
|
spawnCapacityExhausted,
|
|
} from "../process/ExecFileOutput.js";
|
|
import { packageChangeFailureReason } from "./AdbShellOutput.js";
|
|
import {
|
|
isSuccessfulDaemonStartNotice,
|
|
isDaemonStartingNotice,
|
|
hasOnlySuccessfulAdbStartupNotices,
|
|
} from "./AdbDeviceOutput.js";
|
|
import {
|
|
adbHostCapacityRemediation,
|
|
type AdbBinarySelection,
|
|
} from "./AdbConfiguration.js";
|
|
|
|
const STDERR_EXCERPT_CHARACTERS = 512;
|
|
|
|
// Match the known host operand in adb's local-file diagnostics. The suffix is
|
|
// part of the format: opening/reading identify local failures explicitly.
|
|
const LOCAL_FILE_DIAGNOSTICS = [
|
|
["cannot create", ":"],
|
|
["cannot create file/directory", ":"],
|
|
["cannot stat", ":"],
|
|
["cannot open", ":"],
|
|
["cannot write", ":"],
|
|
["failed to stat local file", ":"],
|
|
["failed to read all of", ":"],
|
|
["failed to access", ":"],
|
|
["failed to stat", ":"],
|
|
["failed to open", ":"],
|
|
["opening", " locally failed:"],
|
|
["reading", " locally failed:"],
|
|
] as const;
|
|
|
|
/** Parsed command failure owned by this adapter, separate from its public tag. */
|
|
class AdbProtocolError extends AnalysisProtocolError {
|
|
constructor(
|
|
message: string,
|
|
readonly commandFailure: ExecFileOutputFailure,
|
|
cause: unknown,
|
|
) {
|
|
super(message, {
|
|
cause,
|
|
capturedOutput: execFileFailureCapturedOutput(commandFailure),
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Return the retained process result only for command failures owned here. */
|
|
export const adbCommandOutputFailure = (
|
|
error: AnalysisError,
|
|
): ExecFileOutputFailure | undefined =>
|
|
error instanceof AdbProtocolError ? error.commandFailure : undefined;
|
|
|
|
/** adb joins shell operands into a remote POSIX command; quote at that boundary. */
|
|
const quoteShellOperand = (value: string): string =>
|
|
/^[A-Za-z0-9_./:=@+,-]+$/u.test(value)
|
|
? value
|
|
: "'" + value.replaceAll("'", "'\\''") + "'";
|
|
|
|
export const adbArguments = (
|
|
serial: string | undefined,
|
|
arguments_: readonly string[],
|
|
): readonly string[] => {
|
|
const operands =
|
|
arguments_[0] === "shell"
|
|
? ["shell", ...arguments_.slice(1).map(quoteShellOperand)]
|
|
: [...arguments_];
|
|
return serial === undefined ? operands : ["-s", serial, ...operands];
|
|
};
|
|
|
|
export interface AdbRunLimits {
|
|
readonly timeoutMs: number;
|
|
readonly maxOutputBytes: number;
|
|
/**
|
|
* Live device observations can shrink between calls. Mutation commands omit
|
|
* this so a truncated result stays non-retryable.
|
|
*/
|
|
readonly volatileOutput?: boolean;
|
|
}
|
|
|
|
/** Keep the selected device separate from the file addressed by the command. */
|
|
export interface AdbCommandTarget {
|
|
readonly device: string;
|
|
/** Caller-addressed file, such as a remote path or the original APK input. */
|
|
readonly path?: string;
|
|
/** Exact host operand adb consumes, including an owned input snapshot. */
|
|
readonly localPath?: string;
|
|
}
|
|
|
|
/** The host, not adb, lacked process, memory or descriptor capacity to start it. */
|
|
export const adbSpawnCapacityError = (
|
|
operation: string,
|
|
spawnError: string,
|
|
cause: unknown,
|
|
diagnostics?: Readonly<Record<string, JsonValue>>,
|
|
): AnalysisResourceConstraintError =>
|
|
new AnalysisResourceConstraintError(
|
|
operation,
|
|
"capacity",
|
|
`The host could not start adb (${spawnError}) for ${operation}`,
|
|
{ spawn_error: spawnError },
|
|
{
|
|
cause,
|
|
diagnostics,
|
|
retryable: true,
|
|
remediationAction: adbHostCapacityRemediation(spawnError),
|
|
},
|
|
);
|
|
|
|
/** Run one bounded adb invocation and keep its exact failure shape. */
|
|
export const runAdbCapture = async (
|
|
operation: string,
|
|
target: AdbCommandTarget,
|
|
selection: AdbBinarySelection,
|
|
arguments_: readonly string[],
|
|
limits: AdbRunLimits,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<Result<{ stdout: Buffer; stderr: Buffer }, AnalysisError>> => {
|
|
if (signal?.aborted === true) return err(cancelledBy(operation, signal));
|
|
try {
|
|
return ok(
|
|
await execFileBytes(selection.binary, arguments_, {
|
|
env: selection.environment,
|
|
timeout: limits.timeoutMs,
|
|
maxBuffer: limits.maxOutputBytes,
|
|
stopSignal: "SIGTERM",
|
|
...(signal === undefined ? {} : { signal }),
|
|
}),
|
|
);
|
|
} catch (cause) {
|
|
const failure = execFileOutputFailure(cause);
|
|
if (cause instanceof ExecFileOutputCancelledError)
|
|
return err(
|
|
cancelledBy(
|
|
operation,
|
|
carriedReason(cause.cause),
|
|
failure === undefined
|
|
? {}
|
|
: { capturedOutput: execFileFailureCapturedOutput(failure) },
|
|
),
|
|
);
|
|
if (failure === undefined)
|
|
return err(
|
|
new AnalysisProtocolError(`adb failed for ${operation}`, { cause }),
|
|
);
|
|
const detail = {
|
|
cause,
|
|
capturedOutput: execFileFailureCapturedOutput(failure),
|
|
};
|
|
if (failure.outputTruncated) {
|
|
const name = `The adb output capture allowance of ${String(limits.maxOutputBytes)} bytes (this release has no runtime override)`;
|
|
const allowance =
|
|
limits.volatileOutput === true
|
|
? {
|
|
fixedAllowance: { name, kind: "live" as const },
|
|
retryable: true as const,
|
|
}
|
|
: fixedAllowanceOptions(name, "capture");
|
|
return err(
|
|
new AnalysisResourceConstraintError(
|
|
operation,
|
|
"memory",
|
|
`adb output exceeded the ${String(limits.maxOutputBytes)}-byte capture budget`,
|
|
{ max_output_bytes: limits.maxOutputBytes },
|
|
{ ...detail, ...allowance },
|
|
),
|
|
);
|
|
}
|
|
const stderr = failure.stderr.trim();
|
|
const excerpt = stderr.slice(0, STDERR_EXCERPT_CHARACTERS);
|
|
// Device-state words inside a reported file name are not device verdicts.
|
|
// Only leading notices need line parsing. Do not expand a capture-sized
|
|
// stderr into an array whose entries can exceed the byte capture budget.
|
|
let diagnosticStart = 0;
|
|
while (diagnosticStart < stderr.length) {
|
|
const newline = stderr.indexOf("\n", diagnosticStart);
|
|
const line = stderr
|
|
.slice(diagnosticStart, newline === -1 ? stderr.length : newline)
|
|
.trimEnd();
|
|
if (!isSuccessfulDaemonStartNotice(line) && !isDaemonStartingNotice(line))
|
|
break;
|
|
diagnosticStart = newline === -1 ? stderr.length : newline + 1;
|
|
}
|
|
const diagnostic = stderr
|
|
.slice(diagnosticStart)
|
|
.replace(
|
|
/^(?:adb:\s*)?(?:error:\s*)?(?:(?:failed to get feature set|connect failed):\s*)?/iu,
|
|
"",
|
|
);
|
|
if (
|
|
/^(?:unauthorized\b|device(?: '[^'\n]*')? (?:unauthorized\b|offline\b|not found\b|still authorizing\b)|still authorizing\b|more than one device\b)/iu.test(
|
|
diagnostic,
|
|
)
|
|
)
|
|
return err(
|
|
new AnalysisUnsupportedTargetError(
|
|
operation,
|
|
target.device,
|
|
excerpt,
|
|
detail,
|
|
),
|
|
);
|
|
if (
|
|
/No such file or directory|Permission denied|read: Permission denied/iu.test(
|
|
diagnostic,
|
|
)
|
|
) {
|
|
const localPath = target.localPath;
|
|
const path =
|
|
localPath !== undefined &&
|
|
LOCAL_FILE_DIAGNOSTICS.some(([verb, suffix]) =>
|
|
[localPath, `'${localPath}'`, `"${localPath}"`].some((operand) =>
|
|
diagnostic.startsWith(`${verb} ${operand}${suffix}`),
|
|
),
|
|
)
|
|
? localPath
|
|
: (target.path ?? target.device);
|
|
return err(
|
|
new AnalysisUnsupportedTargetError(operation, path, excerpt, detail),
|
|
);
|
|
}
|
|
if (failure.killed)
|
|
return err(
|
|
new AnalysisTimeoutError(operation, limits.timeoutMs, {
|
|
...detail,
|
|
userMessage: `adb ${operation} reached its ${String(limits.timeoutMs)} ms deadline (deadlineExpired). This release has no runtime override.`,
|
|
remediationAction: `This ${String(limits.timeoutMs)} ms adb deadline has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
|
|
}),
|
|
);
|
|
// The host, not adb, lacked capacity to start it.
|
|
if (spawnCapacityExhausted(failure))
|
|
return err(adbSpawnCapacityError(operation, String(failure.code), cause));
|
|
return err(
|
|
new AdbProtocolError(
|
|
failure.spawnFailed === true
|
|
? `adb could not be started (${String(failure.code)}) for ${operation}`
|
|
: excerpt === ""
|
|
? `adb exited with code ${String(failure.code)} for ${operation}`
|
|
: excerpt,
|
|
failure,
|
|
cause,
|
|
),
|
|
);
|
|
}
|
|
};
|
|
|
|
/** Decode textual adb protocols after the shared byte capture and error boundary. */
|
|
export const runAdb = async (
|
|
...arguments_: Parameters<typeof runAdbCapture>
|
|
): Promise<
|
|
Result<{ stdout: string; stderr: string; stdoutBytes: number }, AnalysisError>
|
|
> => {
|
|
const captured = await runAdbCapture(...arguments_);
|
|
if (!captured.ok) return captured;
|
|
return ok({
|
|
stdout: captured.value.stdout.toString("utf8"),
|
|
stderr: captured.value.stderr.toString("utf8"),
|
|
// Byte count of the captured output before UTF-8 decoding, so malformed
|
|
// sequences replaced by U+FFFD still report their true captured size.
|
|
stdoutBytes: captured.value.stdout.byteLength,
|
|
});
|
|
};
|
|
|
|
/**
|
|
* adb exits nonzero when the device refuses a package change, printing the
|
|
* `Failure [...]` verdict to stderr (install) or stdout (uninstall). Read the
|
|
* refusal from that failed run so it is not reported as unreadable output.
|
|
*/
|
|
export const packageChangeRefusal = (
|
|
operation: string,
|
|
serial: string,
|
|
error: AnalysisError,
|
|
): Result<never, AnalysisError> | undefined => {
|
|
if (!(error instanceof AdbProtocolError)) return undefined;
|
|
const failure = error.commandFailure;
|
|
const reason = packageChangeFailureReason(
|
|
`${failure.stdout}\n${failure.stderr}`,
|
|
);
|
|
return reason === null
|
|
? undefined
|
|
: err(
|
|
new AnalysisUnsupportedTargetError(operation, serial, reason, {
|
|
cause: error,
|
|
}),
|
|
);
|
|
};
|
|
|
|
/** Parsed predicate and the complete output that supports it. */
|
|
export interface AdbPathProbe {
|
|
readonly matches: boolean;
|
|
readonly capturedOutput: {
|
|
readonly stdout: string;
|
|
readonly stderr: string;
|
|
readonly stdout_bytes: number;
|
|
readonly stderr_bytes: number;
|
|
readonly exit_code: 0 | 1;
|
|
readonly signal: null;
|
|
readonly truncated: false;
|
|
};
|
|
}
|
|
const completedAdbPathProbe = (
|
|
matches: boolean,
|
|
stderr: string,
|
|
): AdbPathProbe => ({
|
|
matches,
|
|
capturedOutput: {
|
|
stdout: "",
|
|
stderr,
|
|
stdout_bytes: 0,
|
|
stderr_bytes: Buffer.byteLength(stderr),
|
|
exit_code: matches ? 0 : 1,
|
|
signal: null,
|
|
truncated: false,
|
|
},
|
|
});
|
|
const recognizedProbeStderr = (stderr: string): boolean =>
|
|
stderr === "" || hasOnlySuccessfulAdbStartupNotices(stderr);
|
|
|
|
/** Only a complete false predicate, with no device diagnostics, establishes absence. */
|
|
export const probeAdbPathExistence = async (
|
|
operation: string,
|
|
serial: string,
|
|
path: string,
|
|
selection: AdbBinarySelection,
|
|
limits: AdbRunLimits,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<Result<AdbPathProbe, AnalysisError>> => {
|
|
return probeAdbPath(operation, serial, path, selection, limits, signal, "-e");
|
|
};
|
|
|
|
/** Completed predicate status is independent of recognized host startup notices. */
|
|
export const probeAdbPathDirectory = async (
|
|
operation: string,
|
|
serial: string,
|
|
path: string,
|
|
selection: AdbBinarySelection,
|
|
limits: AdbRunLimits,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<Result<AdbPathProbe, AnalysisError>> =>
|
|
probeAdbPath(operation, serial, path, selection, limits, signal, "-d");
|
|
|
|
const probeAdbPath = async (
|
|
operation: string,
|
|
serial: string,
|
|
path: string,
|
|
selection: AdbBinarySelection,
|
|
limits: AdbRunLimits,
|
|
signal: AbortSignal | undefined,
|
|
predicate: "-d" | "-e",
|
|
): Promise<Result<AdbPathProbe, AnalysisError>> => {
|
|
const fact =
|
|
predicate === "-d" ? "destination_directory" : "destination_existence";
|
|
const probed = await runAdbCapture(
|
|
operation,
|
|
{ device: serial, path },
|
|
selection,
|
|
adbArguments(serial, ["shell", "test", predicate, path]),
|
|
{ ...limits, volatileOutput: true },
|
|
signal,
|
|
);
|
|
if (probed.ok) {
|
|
const stderr = probed.value.stderr.toString("utf8");
|
|
if (probed.value.stdout.length === 0 && recognizedProbeStderr(stderr))
|
|
return ok(completedAdbPathProbe(true, stderr));
|
|
return err(
|
|
new AnalysisProtocolError(
|
|
`The ADB path ${predicate === "-d" ? "directory" : "existence"} probe returned unexpected output; destination status is unknown`,
|
|
{
|
|
diagnostics: { [fact]: "unknown" },
|
|
capturedOutput: {
|
|
stdout: probed.value.stdout.toString("utf8"),
|
|
stderr: probed.value.stderr.toString("utf8"),
|
|
stdout_bytes: probed.value.stdout.length,
|
|
stderr_bytes: probed.value.stderr.length,
|
|
exit_code: 0,
|
|
signal: null,
|
|
truncated: false,
|
|
},
|
|
},
|
|
),
|
|
);
|
|
}
|
|
const error = probed.error;
|
|
if (!(error instanceof AdbProtocolError)) return probed;
|
|
const failure = error.commandFailure;
|
|
if (
|
|
failure.code === 1 &&
|
|
failure.signal === null &&
|
|
!failure.killed &&
|
|
!failure.outputTruncated &&
|
|
failure.collectionFailure !== true &&
|
|
failure.stdout === "" &&
|
|
recognizedProbeStderr(failure.stderr)
|
|
)
|
|
return ok(completedAdbPathProbe(false, failure.stderr));
|
|
return err(
|
|
new AnalysisProtocolError(error.message, {
|
|
cause: error.cause,
|
|
diagnostics: { [fact]: "unknown" },
|
|
capturedOutput: execFileFailureCapturedOutput(failure),
|
|
}),
|
|
);
|
|
};
|