Files
reverse-engineering-anything/src/process/executableSearch.ts
T
morluto 998faa4118 refactor(ida): launch stdio registrations through the owned MCP transport (#10739)
* refactor(ida): launch stdio registrations through the owned MCP transport

IDA stdio servers now run as an owned process group (POSIX) or job (Windows) through OwnedMcpStdioTransport instead of the SDK's unowned child. Windows bare commands resolve against the registration PATH/PATHEXT and .cmd/.bat launchers run through the shared WindowsBatchCommand cmd.exe invocation. The frame limit is classified from the transport's typed OwnedMcpOutputLimitError instead of parsing SDK error text, detach no longer reaches into the SDK's private _process, and the per-operation byte budget is optional.

* fix(ida): keep owned stdio cleanup observable and resolve Windows interpreter paths

- StructuredContentMcpClient observes SDK-initiated closes like OwnedMcpClient,
  so a failed handshake with incomplete owned cleanup cannot reject unhandled.
- OwnedMcpStdioTransport attaches an owner-redacted captured output to cleanup
  failures; IDA passes its retained stderr tail.
- findWindowsExecutable resolves path-qualified commands at their own location
  with PATHEXT; IDA routes every Windows registration through it and refuses
  non-drive paths with an actionable remedy before the owned launcher.

* fix(process): end a stalled stdio launch when the owned MCP transport closes

OwnedMcpStdioTransport passes the launcher a signal it aborts with OwnerCancellation.ownerClosed when it stops, so IDA's Windows PATH/PATHEXT lookup stalled on an unreachable directory no longer holds close() open; IDA reports the interrupted lookup by its abort reason. The IDA environment tests use createTestTempDirectory for owned temporary roots.

* fix(ida): bound the Windows command lookup by the registration timeout

The PATH/PATHEXT search for a stdio registration now runs under a ProviderStartupDeadline of the registration's timeoutMs that also follows the transport's close signal. A lookup stalled on an unreachable PATH directory ends as an AnalysisTimeoutError (phase windows_path_lookup) instead of leaving connect() pending, matching Apktool's Windows lookup.

* test(ida): stub REA's PATH again now that process inspection runs ps from fixed locations

* test(ida): pass the required registration protocol in owned-stdio fixtures

* fix(ida): report an uninspectable Windows command candidate with its path and code

* refactor(ida): take the host platform from composition, not an ambient read

* fix(verify): pass the host platform to the real IDA upstream check

* fix(process): keep a failed launch's preparation cleanup owned by the stdio transport's close

OwnedMcpStdioTransport discarded the launch rejection before a supervisor
existed, so an ownership-helper preparation that transferred a cleanup owner
(or reported a cleanup failure without one) was dropped and close() reported
success. The transport's close now closes each transferred owner from
processInspectionCleanupFailures, and reports a ProviderCleanupError naming the
preparation resource until it does; a later close retries it.
2026-11-15 19:38:13 +08:00

195 lines
7.7 KiB
TypeScript

import { posix, win32 } from "node:path";
import {
absoluteCallerPath,
appendCallerPath,
} from "../filesystem/callerPath.js";
import { err, ok, type Result } from "../domain/result.js";
import { snapshotEnvironment } from "./snapshotEnvironment.js";
/** One file a launcher tries for a bare command, in search order. */
export interface PathSearchCandidate {
/** The absolute file the launch would execute from this entry. */
readonly path: string;
/** An empty or relative PATH entry, which depends on the working directory. */
readonly relativeEntry: boolean;
}
/**
* How entries that depend on the working directory are searched: `skip` leaves
* them out; otherwise they resolve against `workingDirectory`, or against this
* process's directory when omitted (read only when such an entry exists).
*/
export type RelativePathEntries =
| { readonly relativeEntries: "skip" }
| { readonly relativeEntries: "resolve"; readonly workingDirectory?: string };
/**
* The files `execvp` tries for a bare command (one without `/`), in PATH
* order: an empty entry names the working directory and a relative entry
* resolves against it. `..` is kept for the filesystem to resolve after any
* symbolic link. Each caller decides how a candidate is probed and how a
* failed probe is reported; this owner fixes only the search order.
* Candidates are produced on demand: stop iterating at the first match.
* Several names are tried in each entry before the next entry.
*/
export function* posixPathCandidates(
commands: string | readonly string[],
searchPath: string,
selection: RelativePathEntries,
): Generator<PathSearchCandidate, void, undefined> {
// Lazy, so an entry after the first match is never resolved: resolving a
// relative entry reads the working directory, which may no longer exist.
for (const directory of searchPath.split(posix.delimiter)) {
const relativeEntry = !posix.isAbsolute(directory);
if (relativeEntry && selection.relativeEntries === "skip") continue;
const workingDirectory =
relativeEntry && selection.relativeEntries === "resolve"
? (selection.workingDirectory ?? currentDirectory())
: undefined;
// A removed working directory holds nothing; later entries still count.
if (relativeEntry && workingDirectory === undefined) continue;
for (const command of typeof commands === "string" ? [commands] : commands)
yield {
path: absoluteCallerPath(
appendCallerPath(directory, command, "linux"),
{
...(workingDirectory === undefined
? {}
: { cwd: workingDirectory }),
platform: "linux",
},
),
relativeEntry,
};
}
}
/**
* This process's directory, or `undefined` once it has been removed: a
* launcher then finds nothing under a relative entry and moves on.
*/
const currentDirectory = (): string | undefined => {
try {
return process.cwd();
} catch (cause: unknown) {
// A removed directory has no path; the entry names nothing.
void cause;
return undefined;
}
};
/**
* Windows PATH entries in order. A quote opens only at the start of an entry,
* and a quoted entry may contain `;`; elsewhere a quote is an ordinary
* character, so it cannot join later entries. Empty entries, `""` and
* entries with a stray quote name nothing and are skipped.
*/
const windowsPathEntries = (value: string): readonly string[] => {
const entries: string[] = [];
let start = 0;
let quoted = false;
for (let index = 0; index < value.length; index += 1) {
if (value[index] === '"' && (quoted || index === start)) quoted = !quoted;
else if (value[index] === ";" && !quoted) {
entries.push(value.slice(start, index));
start = index + 1;
}
}
entries.push(value.slice(start));
return entries.flatMap((entry) => {
if (entry === "") return [];
if (entry.startsWith('"') && entry.endsWith('"') && entry.length >= 2)
return entry.length === 2 ? [] : [entry.slice(1, -1)];
return entry.includes('"') ? [] : [entry];
});
};
/** Image extensions Windows starts directly; anything else needs a host such as cmd.exe. */
const WINDOWS_IMAGE_EXTENSIONS: ReadonlySet<string> = new Set([".com", ".exe"]);
/** A PATHEXT entry that is not a filename extension, so the search is unknown. */
export interface WindowsPathSearchFailure {
readonly kind: "invalid_extension";
readonly extension: string;
}
/**
* The files Windows' PATH/PATHEXT search tries for commands, in order: a
* path-qualified command (`C:\Python\python`, `.venv\Scripts\python`) only at
* its own location, resolved against `cwd`, and never on PATH; then for each
* PATH entry (relative ones resolve against `cwd`, or against this process's
* directory, read only when such an entry is reached and skipped once
* removed), each bare command with every PATHEXT extension,
* or as written when it already names an extension. Only `.com` and `.exe`
* images are searched unless `allowBatch`; a `.bat` or `.cmd` launcher must
* then be started through src/process/WindowsBatchCommand. An invalid
* PATHEXT entry fails a search that would append extensions; a command that
* names its extension never consults PATHEXT. Environment names match without
* case.
*/
export const windowsPathCandidates = (
commands: string | readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
search: { readonly cwd?: string; readonly allowBatch?: boolean } = {},
): Result<Iterable<PathSearchCandidate>, WindowsPathSearchFailure> => {
const selected = snapshotEnvironment(environment, "win32");
const listed = typeof commands === "string" ? [commands] : commands;
const extensions = (selected.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.filter((extension) => extension !== "");
const invalid = listed.every((command) => win32.extname(command) !== "")
? undefined
: extensions.find(
(extension) =>
!extension.startsWith(".") || /[\\/:\0]/u.test(extension),
);
if (invalid !== undefined)
return err({ kind: "invalid_extension", extension: invalid });
const runnable = (extension: string) =>
search.allowBatch === true ||
WINDOWS_IMAGE_EXTENSIONS.has(extension.toLowerCase());
const spelled = (command: string): string[] => {
const explicit = win32.extname(command);
if (explicit !== "") return runnable(explicit) ? [command] : [];
return extensions
.filter(runnable)
.map((extension) => `${command}${extension}`);
};
const qualified = (command: string): boolean =>
/[\\/]/u.test(command) || win32.parse(command).root !== "";
const located = listed.filter(qualified).flatMap(spelled);
const names = listed
.filter((command) => !qualified(command))
.flatMap(spelled);
const entries = windowsPathEntries(selected.PATH ?? "");
return ok({
*[Symbol.iterator]() {
for (const name of located) {
const workingDirectory = win32.isAbsolute(name)
? name
: (search.cwd ?? currentDirectory());
if (workingDirectory === undefined) continue;
yield {
path: win32.resolve(workingDirectory, name),
relativeEntry: false,
};
}
if (names.length === 0) return;
for (const directory of entries) {
// Only an entry without a drive or UNC root reads the working
// directory; a removed one holds nothing, and later entries count.
const workingDirectory = /^(?:[A-Za-z]:[\\/]|[\\/]{2})/u.test(directory)
? directory
: (search.cwd ?? currentDirectory());
if (workingDirectory === undefined) continue;
for (const name of names)
yield {
path: win32.resolve(workingDirectory, directory, name),
relativeEntry: !win32.isAbsolute(directory),
};
}
},
});
};