refactor(process): give POSIX PATH search order one owner (#10891)

* refactor(process): give POSIX PATH search order one owner

Program lookup, the packet-tool locator and Jadx's Java lookup each split
PATH and resolved empty and relative entries themselves. They now take the
candidates from posixPathCandidates in src/process/executableSearch and keep
only their own probe and failure reporting. A counted architecture guard
keeps new PATH splits from returning; the remaining Windows and Ghidra
searches are baselined.

* refactor(process): move the colon-split PATH searches onto the search owner

REA's launcher-alias lookup and Ghidra's macOS Java lookup split PATH on
":" and skipped relative entries themselves; they now use
posixPathCandidates with relativeEntries: "skip", and the guard counts
colon splits of PATH as well.

* fix(process): produce PATH candidates lazily so an unused entry cannot fail an earlier match

* refactor(process): give Windows PATH/PATHEXT search order the executable search owner (#10916)

* refactor(process): give Windows PATH/PATHEXT search order the executable search owner

* fix(process): keep later PATH entries searchable after a stray quote or a removed working directory

* fix(reverse): refuse a Windows objdump or Rizin command that PATH does not find (#10953)

* fix(reverse): refuse an objdump or Rizin command Windows PATH does not find instead of launching the bare name

* fix(reverse): report a Windows lookup refusal after cancellation and to capability discovery

* fix(desktop): search a Windows host's PATH as Windows does when doctor looks up a program

programOnPath sent every host through the POSIX PATH search, so on Windows a
relative PATH entry reached absoluteCallerPath with platform linux and the
Windows working directory, which resolved against itself until the stack
overflowed. programOnPath now searches PATH and PATHEXT through
windowsPathCandidates on a Windows host, and absoluteCallerPath refuses a
non-POSIX working directory with a TypeError instead of recursing.
This commit is contained in:
morluto authored and GitHub committed 2026-11-15 18:24:04 +08:00
1 parent 659772952d
commit 422cff00ab
23 files changed
+912 -330

No files matched your search

+24 -73
View File
@@ -1,30 +1,8 @@
import { stat } from "node:fs/promises";
import { win32 } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
import { AbortedWait, waitForAbortable } from "./AbortablePromise.js";
import { snapshotEnvironment } from "./snapshotEnvironment.js";
/** Parse PATH once, preserving quoted semicolons and explicit relative entries. */
export 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 = !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];
});
};
import { windowsPathCandidates } from "./executableSearch.js";
export type WindowsExecutableFailure =
| { readonly kind: "missing" }
@@ -38,7 +16,8 @@ export type WindowsExecutableFailure =
};
/**
* Resolve a default bare command against PATH/PATHEXT only. Never return a bare
* Resolve a default bare command against PATH/PATHEXT only, probing the
* search owner's candidates (src/process/executableSearch) in order. Never return a bare
* name on failure: handing it to Windows would restart implicit CWD lookup.
* Callers own the lookup deadline and translation to their operation errors.
*/
@@ -52,56 +31,28 @@ export const findWindowsExecutable = async (
},
): Promise<Result<string, WindowsExecutableFailure>> => {
if (options.signal.aborted) return err({ kind: "interrupted" });
const selected = snapshotEnvironment(environment, "win32");
const extensions = (selected.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.filter((extension) => extension !== "");
for (const extension of extensions)
if (!extension.startsWith(".") || /[\\/:\0]/u.test(extension))
return err({ kind: "invalid_extension", extension });
const explicitExtension = win32.extname(executable);
const allowed =
explicitExtension !== ""
? options.allowBatch === true ||
[".exe", ".com"].includes(explicitExtension.toLowerCase())
? [""]
: []
: options.allowBatch === true
? extensions
: extensions.filter((extension) =>
[".exe", ".com"].includes(extension.toLowerCase()),
);
const cwd = options.cwd ?? process.cwd();
for (const directory of windowsPathEntries(selected.PATH ?? "")) {
for (const extension of allowed) {
const candidates = windowsPathCandidates(executable, environment, options);
if (!candidates.ok) return candidates;
for (const { path: candidate } of candidates.value) {
if (options.signal.aborted) return err({ kind: "interrupted" });
try {
const metadata = await waitForAbortable(stat(candidate), options.signal);
if (metadata instanceof AbortedWait || options.signal.aborted)
return err({ kind: "interrupted" });
if (metadata.isFile()) return ok(candidate);
} catch (cause: unknown) {
if (options.signal.aborted) return err({ kind: "interrupted" });
const candidate = win32.resolve(
cwd,
directory,
`${executable}${extension}`,
);
try {
const metadata = await waitForAbortable(
stat(candidate),
options.signal,
);
if (metadata instanceof AbortedWait || options.signal.aborted)
return err({ kind: "interrupted" });
if (metadata.isFile()) return ok(candidate);
} catch (cause: unknown) {
if (options.signal.aborted) return err({ kind: "interrupted" });
const code =
typeof cause === "object" && cause !== null
? Reflect.get(cause, "code")
: undefined;
if (code === "ENOENT" || code === "ENOTDIR") continue;
return err({
kind: "inspection",
path: candidate,
code: typeof code === "string" ? code : null,
cause,
});
}
const code =
typeof cause === "object" && cause !== null
? Reflect.get(cause, "code")
: undefined;
if (code === "ENOENT" || code === "ENOTDIR") continue;
return err({
kind: "inspection",
path: candidate,
code: typeof code === "string" ? code : null,
cause,
});
}
}
return err({ kind: "missing" });
+170
View File
@@ -0,0 +1,170 @@
import { describe, expect, it, vi } from "vitest";
import {
posixPathCandidates,
windowsPathCandidates,
} from "./executableSearch.js";
describe("posixPathCandidates", () => {
it("searches PATH in order, resolving empty and relative entries against the working directory", () => {
expect([
...posixPathCandidates("tool", "/usr/bin::bin:/opt/./x/../y/", {
relativeEntries: "resolve",
workingDirectory: "/work",
}),
]).toEqual([
{ path: "/usr/bin/tool", relativeEntry: false },
{ path: "/work/tool", relativeEntry: true },
{ path: "/work/bin/tool", relativeEntry: true },
// `..` stays for the filesystem to resolve after a symbolic link.
{ path: "/opt/x/../y/tool", relativeEntry: false },
]);
});
it("leaves out entries that depend on the working directory when asked", () => {
expect([
...posixPathCandidates("tool", ":bin:/usr/bin", {
relativeEntries: "skip",
}),
]).toEqual([{ path: "/usr/bin/tool", relativeEntry: false }]);
// An empty PATH is one empty entry: the working directory.
expect([
...posixPathCandidates("tool", "", { relativeEntries: "skip" }),
]).toEqual([]);
expect([
...posixPathCandidates("tool", "", {
relativeEntries: "resolve",
workingDirectory: "/work",
}),
]).toEqual([{ path: "/work/tool", relativeEntry: true }]);
});
it("resolves no entry after the one the caller stops at", () => {
// Resolving `.` without a working directory reads this process's
// directory, which may have been removed; an earlier match must not
// depend on it.
const cwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("ENOENT: uv_cwd");
});
try {
const [first] = posixPathCandidates("java", "/jdk/bin:.", {
relativeEntries: "resolve",
});
expect(first).toEqual({ path: "/jdk/bin/java", relativeEntry: false });
expect(cwd).not.toHaveBeenCalled();
} finally {
cwd.mockRestore();
}
});
it("skips relative entries once the working directory is removed and searches later ones", () => {
const cwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("ENOENT: uv_cwd");
});
try {
expect([
...posixPathCandidates("java", ".::/jdk/bin", {
relativeEntries: "resolve",
}),
]).toEqual([{ path: "/jdk/bin/java", relativeEntry: false }]);
const windows = windowsPathCandidates("java", {
PATH: "bin;C:\\jdk\\bin",
PATHEXT: ".EXE",
});
if (!windows.ok) throw new Error(windows.error.extension);
expect([...windows.value]).toEqual([
{ path: "C:\\jdk\\bin\\java.EXE", relativeEntry: false },
]);
} finally {
cwd.mockRestore();
}
});
it("tries every name in an entry before the next entry", () => {
expect([
...posixPathCandidates(["ghidra", "ghidraRun"], "/a:/b", {
relativeEntries: "skip",
}),
]).toEqual([
{ path: "/a/ghidra", relativeEntry: false },
{ path: "/a/ghidraRun", relativeEntry: false },
{ path: "/b/ghidra", relativeEntry: false },
{ path: "/b/ghidraRun", relativeEntry: false },
]);
});
});
describe("windowsPathCandidates", () => {
const paths = (
...input: Parameters<typeof windowsPathCandidates>
): readonly string[] => {
const search = windowsPathCandidates(...input);
if (!search.ok) throw new Error(search.error.extension);
return [...search.value].map(({ path }) => path);
};
it("searches quoted, relative and case-insensitive PATH entries with image PATHEXT extensions", () => {
expect(
paths(
"rizin",
{
Path: '"C:\\Program Files\\a;b";.\\bin;;"";bad"quote',
PathExt: ".CMD;.EXE;.COM",
},
{ cwd: "D:\\work" },
),
).toEqual([
"C:\\Program Files\\a;b\\rizin.EXE",
"C:\\Program Files\\a;b\\rizin.COM",
"D:\\work\\bin\\rizin.EXE",
"D:\\work\\bin\\rizin.COM",
]);
});
it("opens a quote only at the start of an entry, so a stray quote cannot hide later entries", () => {
expect(
paths(
["ghidra.bat"],
{ PATH: 'bad"quote;C:\\ghidra;"C:\\a;b"' },
{ allowBatch: true, cwd: "C:\\" },
),
).toEqual(["C:\\ghidra\\ghidra.bat", "C:\\a;b\\ghidra.bat"]);
});
it("includes batch launchers only when the caller can start them through cmd.exe", () => {
const environment = { PATH: "C:\\tools", PATHEXT: ".BAT;.EXE" };
expect(paths("apktool", environment, { cwd: "C:\\" })).toEqual([
"C:\\tools\\apktool.EXE",
]);
expect(
paths("apktool", environment, { cwd: "C:\\", allowBatch: true }),
).toEqual(["C:\\tools\\apktool.BAT", "C:\\tools\\apktool.EXE"]);
expect(paths("npm.cmd", environment, { cwd: "C:\\" })).toEqual([]);
});
it("tries every launcher name in an entry before the next entry", () => {
expect(
paths(
["ghidra.bat", "ghidra.exe"],
{ PATH: "C:\\a;C:\\b" },
{ allowBatch: true, cwd: "C:\\" },
),
).toEqual([
"C:\\a\\ghidra.bat",
"C:\\a\\ghidra.exe",
"C:\\b\\ghidra.bat",
"C:\\b\\ghidra.exe",
]);
});
it("fails a search that would append an invalid PATHEXT entry, but not one with a named extension", () => {
const environment = { PATH: "C:\\jdk\\bin", PATHEXT: ".EXE;C:\\bad" };
expect(windowsPathCandidates("java", environment)).toEqual({
ok: false,
error: { kind: "invalid_extension", extension: "C:\\bad" },
});
expect(paths("java.exe", environment, { cwd: "C:\\" })).toEqual([
"C:\\jdk\\bin\\java.exe",
]);
});
});
+175
View File
@@ -0,0 +1,175 @@
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 bare commands, in order:
* 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 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 names = listed.flatMap((command) => {
const explicit = win32.extname(command);
if (explicit !== "") return runnable(explicit) ? [command] : [];
return extensions
.filter(runnable)
.map((extension) => `${command}${extension}`);
});
const entries = windowsPathEntries(selected.PATH ?? "");
return ok({
*[Symbol.iterator]() {
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),
};
}
},
});
};