fix(javascript): integrate current provider timeout recovery
Include the main-branch Hopper startup timeout normalization already merged in #1866 so combined CI retains launcher diagnostics when either timer fires. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
47f8156efe
@@ -10,6 +10,7 @@ describe("runtime configuration", () => {
|
||||
if (empty.ok) {
|
||||
expect(empty.value.hopperTargetPath).toBeUndefined();
|
||||
expect(empty.value.analysisProvider).toBe("auto");
|
||||
expect(empty.value.hopperStartupTimeoutMs).toBe(120_000);
|
||||
}
|
||||
const result = parseConfig({ HOPPER_TARGET_PATH: "/usr/bin/true" });
|
||||
expect(result.ok).toBe(true);
|
||||
@@ -170,6 +171,40 @@ describe("runtime collection configuration", () => {
|
||||
});
|
||||
|
||||
describe("configuration failure diagnostics", () => {
|
||||
it.each(["1", "900000", "2147483647"])(
|
||||
"accepts Hopper startup deadline %s without changing Ghidra's deadline",
|
||||
(value) => {
|
||||
expect(
|
||||
parseConfig({ REA_HOPPER_STARTUP_TIMEOUT_MS: value }),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
hopperStartupTimeoutMs: Number(value),
|
||||
ghidraStartupTimeoutMs: 330_000,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["", "0", "-1", "1.5", "1e3", "invalid", "2147483648"])(
|
||||
"rejects malformed Hopper startup deadline %j with its setting",
|
||||
(value) => {
|
||||
const result = parseConfig({ REA_HOPPER_STARTUP_TIMEOUT_MS: value });
|
||||
if (result.ok) throw new Error("Expected invalid startup deadline");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "configuration_invalid",
|
||||
details: {
|
||||
settings: [
|
||||
{
|
||||
setting: "REA_HOPPER_STARTUP_TIMEOUT_MS",
|
||||
constraint: expect.any(String),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"",
|
||||
" ",
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
ghidraCompilerSpecIdSchema,
|
||||
ghidraLanguageIdSchema,
|
||||
} from "./ghidraLanguageOverride.js";
|
||||
import { ghidraStartupTimeoutSchema } from "./ghidraStartupTimeout.js";
|
||||
import {
|
||||
DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
|
||||
providerStartupTimeoutSchema,
|
||||
} from "./providerStartupTimeout.js";
|
||||
import { mcpInputSchemaProfileSchema } from "./mcpInputSchemaProfile.js";
|
||||
import { mcpResponseBudgetSchema } from "./mcpResponseBudget.js";
|
||||
|
||||
@@ -36,7 +40,12 @@ const environmentSchema = z.object({
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_GHIDRA_NATIVEAOT_JAR must be absolute")
|
||||
.optional(),
|
||||
REA_GHIDRA_STARTUP_TIMEOUT_MS: ghidraStartupTimeoutSchema,
|
||||
REA_GHIDRA_STARTUP_TIMEOUT_MS: providerStartupTimeoutSchema.default(
|
||||
DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
),
|
||||
REA_HOPPER_STARTUP_TIMEOUT_MS: providerStartupTimeoutSchema.default(
|
||||
DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
|
||||
),
|
||||
REA_GHIDRA_LANGUAGE_ID: ghidraLanguageIdSchema.optional(),
|
||||
REA_GHIDRA_COMPILER_SPEC_ID: ghidraCompilerSpecIdSchema.optional(),
|
||||
REA_GHIDRA_SEED_FILE: z
|
||||
|
||||
@@ -98,6 +98,7 @@ export const parseConfig = (
|
||||
process.platform,
|
||||
homeDirectoryFromEnvironment(environment, process.platform),
|
||||
),
|
||||
hopperStartupTimeoutMs: env.REA_HOPPER_STARTUP_TIMEOUT_MS,
|
||||
hopperTargetPath: env.HOPPER_TARGET_PATH,
|
||||
hopperTargetKind: env.HOPPER_TARGET_KIND,
|
||||
hopperLoaderArgs: loaderArgs.value,
|
||||
|
||||
@@ -3,13 +3,15 @@ import { z } from "zod";
|
||||
/** Default absolute deadline for Ghidra import, analysis, bridge, and readiness. */
|
||||
export const DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS = 330_000;
|
||||
|
||||
/** Default absolute deadline for Hopper launch, analysis, bridge, and readiness. */
|
||||
export const DEFAULT_HOPPER_STARTUP_TIMEOUT_MS = 120_000;
|
||||
|
||||
// Node schedules delays above this signed 32-bit boundary as a 1 ms timer.
|
||||
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
||||
|
||||
/** Parse the optional setting without reading the ambient process environment. */
|
||||
export const ghidraStartupTimeoutSchema = z
|
||||
export const providerStartupTimeoutSchema = z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u, "must be a positive decimal integer")
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().min(1).max(MAX_TIMER_DELAY_MS))
|
||||
.default(DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS);
|
||||
.pipe(z.number().int().min(1).max(MAX_TIMER_DELAY_MS));
|
||||
@@ -18,6 +18,7 @@ export interface AppConfig {
|
||||
readonly ghidraNativeAotJar?: string;
|
||||
readonly ilspyCmdPath: string | undefined;
|
||||
readonly hopperLauncherPath: string;
|
||||
readonly hopperStartupTimeoutMs: number;
|
||||
readonly hopperTargetPath: string | undefined;
|
||||
readonly hopperTargetKind: "executable" | "database";
|
||||
readonly hopperLoaderArgs: readonly string[];
|
||||
|
||||
@@ -123,11 +123,10 @@ export const compareArtifacts = (
|
||||
],
|
||||
leftCovered && rightCovered,
|
||||
);
|
||||
const rootChange = rootHashChange(left.inventory, right.inventory, changes, [
|
||||
applyRootHashChange(left.inventory, right.inventory, changes, [
|
||||
...left.evidence.map(({ evidence_id: id }) => id),
|
||||
...right.evidence.map(({ evidence_id: id }) => id),
|
||||
]);
|
||||
if (rootChange !== null) changes.push(rootChange);
|
||||
const summary = summarize(
|
||||
left.inventory,
|
||||
right.inventory,
|
||||
@@ -441,27 +440,45 @@ const hasCoverageLimitation = (limitations: readonly string[]): boolean =>
|
||||
!/integrity contradiction\(s\) were recorded/u.test(limitation),
|
||||
);
|
||||
|
||||
const rootHashChange = (
|
||||
// Differing manifest root digests prove a root content change even when node
|
||||
// details are unavailable. Fold that fact into an existing root row so one
|
||||
// logical path keeps one classification.
|
||||
const applyRootHashChange = (
|
||||
left: InventorySet,
|
||||
right: InventorySet,
|
||||
changes: readonly ArtifactChange[],
|
||||
changes: ArtifactChange[],
|
||||
evidenceLinks: readonly string[],
|
||||
): ArtifactChange | null => {
|
||||
if (left.manifest.root_sha256 === right.manifest.root_sha256) return null;
|
||||
if (
|
||||
changes.some(
|
||||
(change) =>
|
||||
change.logical_path === "." && change.dimensions.includes("content"),
|
||||
): void => {
|
||||
if (left.manifest.root_sha256 === right.manifest.root_sha256) return;
|
||||
const index = changes.findIndex((change) => change.logical_path === ".");
|
||||
const existing = changes[index];
|
||||
if (existing !== undefined) {
|
||||
if (
|
||||
existing.dimensions.includes("content") ||
|
||||
(existing.classification !== "unknown" &&
|
||||
existing.classification !== "changed")
|
||||
)
|
||||
)
|
||||
return null;
|
||||
return;
|
||||
changes[index] = {
|
||||
...existing,
|
||||
classification: "changed",
|
||||
dimensions: comparisonDimensionSchema.options.filter(
|
||||
(dimension) =>
|
||||
dimension === "content" || existing.dimensions.includes(dimension),
|
||||
),
|
||||
evidence_links: [
|
||||
...new Set([...existing.evidence_links, ...evidenceLinks]),
|
||||
],
|
||||
};
|
||||
return;
|
||||
}
|
||||
const leftRoot = left.occurrences.find(
|
||||
(occurrence) => occurrence.logical_path === ".",
|
||||
);
|
||||
const rightRoot = right.occurrences.find(
|
||||
(occurrence) => occurrence.logical_path === ".",
|
||||
);
|
||||
return {
|
||||
changes.push({
|
||||
classification: "changed",
|
||||
logical_path: ".",
|
||||
dimensions: ["content"],
|
||||
@@ -470,5 +487,5 @@ const rootHashChange = (
|
||||
left_artifact_id: leftRoot?.artifact_id ?? null,
|
||||
right_artifact_id: rightRoot?.artifact_id ?? null,
|
||||
evidence_links: [...evidenceLinks],
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
@@ -304,14 +304,22 @@ const collectNamedExports = (
|
||||
node,
|
||||
);
|
||||
for (const specifier of node.specifiers)
|
||||
if (t.isExportSpecifier(specifier))
|
||||
if (
|
||||
t.isExportSpecifier(specifier) ||
|
||||
(t.isExportNamespaceSpecifier(specifier) && node.exportKind !== "type")
|
||||
)
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: node.source == null ? "export" : "re-export",
|
||||
specifier: node.source?.value ?? null,
|
||||
importedName: propertyName(specifier.local),
|
||||
localName: node.source == null ? propertyName(specifier.local) : null,
|
||||
importedName: t.isExportNamespaceSpecifier(specifier)
|
||||
? "*"
|
||||
: propertyName(specifier.local),
|
||||
localName:
|
||||
node.source == null && t.isExportSpecifier(specifier)
|
||||
? propertyName(specifier.local)
|
||||
: null,
|
||||
exportedName: propertyName(specifier.exported),
|
||||
location: range(specifier),
|
||||
},
|
||||
|
||||
@@ -142,4 +142,20 @@ describe("captured module candidates", () => {
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
it("retains exact non-URL identities without matching response fragments", () => {
|
||||
const scripts = [
|
||||
script("relative/module.js#part", "page-script"),
|
||||
script("relative/module.js#part", "scenario-response"),
|
||||
script("relative/module.js", "scenario-response"),
|
||||
];
|
||||
expect(
|
||||
matchCapturedModules("relative/module.js#part", scripts).map((item) => [
|
||||
item.script_index,
|
||||
item.match,
|
||||
]),
|
||||
).toEqual([
|
||||
[0, "exact-reported-url"],
|
||||
[1, "exact-reported-url"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -108,6 +108,8 @@ export const matchCapturedModules = (
|
||||
url: string,
|
||||
scripts: readonly ExportedWebScript[],
|
||||
) => {
|
||||
const transport = URL.parse(url);
|
||||
if (transport !== null) transport.hash = "";
|
||||
const candidates: {
|
||||
script_index: number;
|
||||
match: "exact-reported-url" | "response-url-without-fragment";
|
||||
@@ -116,20 +118,15 @@ export const matchCapturedModules = (
|
||||
scripts.forEach((script, script_index) => {
|
||||
if (script.url === url)
|
||||
candidates.push({ script_index, match: "exact-reported-url", script });
|
||||
else if (script.source.kind === "scenario-response") {
|
||||
try {
|
||||
const transport = new URL(url);
|
||||
transport.hash = "";
|
||||
if (transport.href === script.url)
|
||||
candidates.push({
|
||||
script_index,
|
||||
match: "response-url-without-fragment",
|
||||
script,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
}
|
||||
}
|
||||
else if (
|
||||
script.source.kind === "scenario-response" &&
|
||||
transport?.href === script.url
|
||||
)
|
||||
candidates.push({
|
||||
script_index,
|
||||
match: "response-url-without-fragment",
|
||||
script,
|
||||
});
|
||||
});
|
||||
return candidates;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import { ManagedDecodeBudget } from "./ManagedDecodeBudget.js";
|
||||
import { edges } from "./ManagedMemberRows.js";
|
||||
import type { ManagedMethod } from "./ManagedMemberInspectorCore.js";
|
||||
import { signature, type ManagedMethod } from "./ManagedMemberInspectorCore.js";
|
||||
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
|
||||
import { managedMemberInspectionSchema } from "../domain/managed/managedArtifact.js";
|
||||
import { comparisonLimitations } from "../domain/managed/managedMemberComparisonCoverage.js";
|
||||
@@ -248,6 +248,63 @@ describe("managed exported types", () => {
|
||||
});
|
||||
|
||||
describe("managed member decoding budget", () => {
|
||||
it("admits a wide-instruction method whose actual records fit the budget", () => {
|
||||
// Five-byte branches all target the next instruction. A final ret leaves
|
||||
// the method stack-neutral, despite over 256 KiB of valid IL bytes.
|
||||
const il = Buffer.alloc(270_001);
|
||||
for (let offset = 0; offset < il.length - 1; offset += 5) {
|
||||
il[offset] = 0x38;
|
||||
}
|
||||
il[il.length - 1] = 0x2a;
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt16LE(0x3003, 0);
|
||||
header.writeUInt16LE(8, 2);
|
||||
header.writeUInt32LE(il.length, 4);
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([header, il]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
);
|
||||
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
expect(result.types).toHaveLength(1);
|
||||
expect(result.methods[0]?.body).toMatchObject({
|
||||
status: "present",
|
||||
il_size: il.length,
|
||||
decoded_instruction_count: 54_001,
|
||||
opcode_counts: { br: 54_000, ret: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("still rejects dense one-byte instructions before exceeding capacity", () => {
|
||||
// All NOPs: unlike wide instructions, each IL byte adds a decoded record.
|
||||
// A true oversized transient must remain an actionable resource limit.
|
||||
const il = Buffer.alloc(270_001);
|
||||
il[il.length - 1] = 0x2a;
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt16LE(0x3003, 0);
|
||||
header.writeUInt16LE(8, 2);
|
||||
header.writeUInt32LE(il.length, 4);
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([header, il]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
);
|
||||
|
||||
expect(result.coverage).toMatchObject({
|
||||
state: "unavailable",
|
||||
issues: [{ code: "resource-limit", scope: "metadata.representation" }],
|
||||
});
|
||||
// Report the originating IL coordinate, not a generic decoding error.
|
||||
expect(result.coverage.issues[0]?.offset).toBeGreaterThan(0);
|
||||
expect(result.types).toEqual([]);
|
||||
expect(result.methods).toEqual([]);
|
||||
});
|
||||
|
||||
it("charges decoded output rather than accumulated decoding bounds", () => {
|
||||
// Each bound fits alone, but 256 bytes per IL and signature byte together
|
||||
// exceed the 64 MiB budget although the retained members are small.
|
||||
@@ -499,18 +556,197 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an admitted but unimplemented element type unsupported", () => {
|
||||
// ECMA-335 ELEMENT_TYPE_ARRAY is valid, but multidimensional arrays are not decoded here.
|
||||
it("decodes generic instantiation member signatures as complete coverage", () => {
|
||||
// System.Runtime.Caching 0x06000001: instance void (Dictionary<string, object>)
|
||||
// shape, with TypeRef/TypeSpec coded tokens kept as encoded.
|
||||
const bytes = buildManagedPeFixture({
|
||||
fieldSignature: Buffer.from([6, 0x14, 8, 1, 0, 0]),
|
||||
methodSignature: Buffer.from([
|
||||
0x00, 0x01, 0x01, 0x15, 0x12, 0x71, 0x01, 0x0e,
|
||||
]),
|
||||
fieldSignature: Buffer.from([
|
||||
0x06, 0x15, 0x11, 0x0a, 0x02, 0x13, 0x00, 0x1e, 0x01,
|
||||
]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
);
|
||||
|
||||
expect(result.methods[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
return_type: "void",
|
||||
parameter_types: ["class:113<string>"],
|
||||
issue: null,
|
||||
});
|
||||
expect(result.fields[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: "valuetype:10<var:0,mvar:1>",
|
||||
});
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["single-dimension general array", [0x14, 0x08, 0x01, 0x00, 0x00], "i4[...]"],
|
||||
[
|
||||
"sized array with signed lower bounds",
|
||||
[0x14, 0x08, 0x02, 0x02, 0x04, 0x03, 0x02, 0x02, 0x7f],
|
||||
"i4[1...4,-1...1]",
|
||||
],
|
||||
[
|
||||
"partially bounded array",
|
||||
[0x14, 0x0e, 0x03, 0x01, 0x05, 0x00],
|
||||
"string[5,,]",
|
||||
],
|
||||
[
|
||||
"function pointer",
|
||||
[0x1b, 0x00, 0x02, 0x08, 0x0e, 0x1c],
|
||||
"fnptr[default](string,object)->i4",
|
||||
],
|
||||
["required modifier", [0x1f, 0x09, 0x08], "i4 modreq:9"],
|
||||
[
|
||||
"optional modifier under a pointer",
|
||||
[0x0f, 0x20, 0x0d, 0x08],
|
||||
"i4 modopt:13*",
|
||||
],
|
||||
[
|
||||
"adjacent modifiers in source order",
|
||||
[0x1f, 0x05, 0x20, 0x09, 0x08],
|
||||
"i4 modreq:5 modopt:9",
|
||||
],
|
||||
[
|
||||
"modifier runs separated by a pointer",
|
||||
[0x1f, 0x05, 0x0f, 0x20, 0x09, 0x08],
|
||||
"i4 modopt:9* modreq:5",
|
||||
],
|
||||
[
|
||||
"unmanaged cdecl function pointer",
|
||||
[0x1b, 0x01, 0x01, 0x01, 0x18],
|
||||
"fnptr[c](native-int)->void",
|
||||
],
|
||||
[
|
||||
"array of generic instantiations",
|
||||
[0x1d, 0x15, 0x12, 0x05, 0x01, 0x14, 0x08, 0x01, 0x01, 0x03, 0x00],
|
||||
"class:5<i4[3]>[]",
|
||||
],
|
||||
])("decodes a %s field signature", (_name, type, expected) => {
|
||||
expect(signature(Buffer.from([0x06, ...type]))).toMatchObject({
|
||||
kind: "field",
|
||||
parse_status: "decoded",
|
||||
field_type: expected,
|
||||
issue: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["generic instantiation without arguments", [0x15, 0x12, 0x05, 0x00]],
|
||||
["generic instantiation of a primitive", [0x15, 0x08, 0x05, 0x01, 0x08]],
|
||||
["zero-rank array", [0x14, 0x08, 0x00, 0x00, 0x00]],
|
||||
[
|
||||
"array with more sizes than dimensions",
|
||||
[0x14, 0x08, 0x01, 0x02, 0x01, 0x01, 0x00],
|
||||
],
|
||||
["truncated generic argument list", [0x15, 0x12, 0x05, 0x02, 0x08]],
|
||||
["truncated function pointer", [0x1b, 0x00, 0x01, 0x08]],
|
||||
["function pointer with a field header", [0x1b, 0x06, 0x00, 0x01]],
|
||||
["function pointer with a reserved flag", [0x1b, 0x80, 0x00, 0x01]],
|
||||
[
|
||||
"function pointer with explicit-this but no has-this",
|
||||
[0x1b, 0x40, 0x00, 0x01],
|
||||
],
|
||||
["typed reference field", [0x16]],
|
||||
["modified typed reference field", [0x20, 0x09, 0x16]],
|
||||
["typed reference generic argument", [0x15, 0x12, 0x05, 0x01, 0x16]],
|
||||
["typed reference array element", [0x1d, 0x16]],
|
||||
["by-reference generic argument", [0x15, 0x12, 0x05, 0x01, 0x10, 0x08]],
|
||||
["void generic argument", [0x15, 0x12, 0x05, 0x01, 0x01]],
|
||||
["void function pointer parameter", [0x1b, 0x00, 0x01, 0x01, 0x01]],
|
||||
["by-reference pointee", [0x0f, 0x10, 0x08]],
|
||||
["nested by-reference", [0x10, 0x10, 0x08]],
|
||||
["void field", [0x01]],
|
||||
["void array element", [0x1d, 0x01]],
|
||||
])("reports a %s as malformed", (_name, type) => {
|
||||
expect(signature(Buffer.from([0x06, ...type]))).toMatchObject({
|
||||
kind: "unknown",
|
||||
parse_status: "malformed",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects array ranks beyond the CLR limit before rendering dimensions", () => {
|
||||
expect(
|
||||
signature(
|
||||
Buffer.from([0x06, 0x14, 0x08, 0xdf, 0xff, 0xff, 0xff, 0x00, 0x00]),
|
||||
),
|
||||
).toMatchObject({
|
||||
parse_status: "unsupported",
|
||||
issue: "unsupported element type 0x14",
|
||||
issue: "array rank 536870911 exceeds the 32 dimensions the CLR supports",
|
||||
});
|
||||
expect(
|
||||
signature(Buffer.from([0x06, 0x14, 0x08, 0x20, 0x00, 0x00])),
|
||||
).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: `i4[${",".repeat(31)}]`,
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes typed references in parameter and return positions", () => {
|
||||
expect(
|
||||
signature(Buffer.from([0x00, 0x02, 0x16, 0x20, 0x09, 0x16, 0x08])),
|
||||
).toMatchObject({
|
||||
kind: "method",
|
||||
parse_status: "decoded",
|
||||
return_type: "typedbyref",
|
||||
parameter_types: ["typedbyref modopt:9", "i4"],
|
||||
});
|
||||
expect(
|
||||
signature(Buffer.from([0x06, 0x1b, 0x20, 0x01, 0x01, 0x16])),
|
||||
).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: "fnptr[default has-this](typedbyref)->void",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["by-reference field", [0x06, 0x10, 0x08], { field_type: "i4&" }],
|
||||
["void pointer field", [0x06, 0x0f, 0x01], { field_type: "void*" }],
|
||||
[
|
||||
"by-reference function pointer return and parameter",
|
||||
[0x06, 0x1b, 0x00, 0x01, 0x10, 0x08, 0x10, 0x0e],
|
||||
{ field_type: "fnptr[default](string&)->i4&" },
|
||||
],
|
||||
[
|
||||
"by-reference method return and parameter",
|
||||
[0x00, 0x01, 0x10, 0x08, 0x10, 0x15, 0x12, 0x05, 0x01, 0x0f, 0x01],
|
||||
{ return_type: "i4&", parameter_types: ["class:5<void*>&"] },
|
||||
],
|
||||
])("decodes a %s in its grammar position", (_name, blob, expected) => {
|
||||
expect(signature(Buffer.from(blob))).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
...expected,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps element types that member signatures do not assign unsupported", () => {
|
||||
expect(signature(Buffer.from([0x06, 0x45, 0x08]))).toMatchObject({
|
||||
parse_status: "unsupported",
|
||||
issue: "unsupported element type 0x45",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes deeply nested generic instantiations without recursion", () => {
|
||||
const depth = 4_000;
|
||||
const decoded = signature(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x06]),
|
||||
Buffer.from(
|
||||
Array.from({ length: depth }, () => [0x15, 0x12, 0x05, 0x01]).flat(),
|
||||
),
|
||||
Buffer.from([0x08]),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(decoded).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: `${"class:5<".repeat(depth)}i4${">".repeat(depth)}`,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -186,7 +186,7 @@ export const inspectManagedMembersBytes = (
|
||||
"Metadata tokens are build-local coordinates and are only meaningful with the reported artifact SHA-256 and MVID.",
|
||||
"CIL instruction anchors are decoded from file-backed method bodies only; no target assembly is loaded or executed.",
|
||||
"Exported types are reported from ExportedType rows as declared; forwarded types are not resolved in their implementing assemblies.",
|
||||
"Signatures are decoded for common ECMA-335 primitive, class, valuetype, pointer, byref, array, and generic variable forms; unsupported forms retain raw signature hashes.",
|
||||
"Member signatures decode ECMA-335 primitive, class, valuetype, generic instantiation, generic variable, pointer, byref, single-dimension and general array, function pointer, custom modifier, and typed reference forms; class and valuetype operands keep their encoded TypeDefOrRefOrSpec values, and unsupported forms such as vararg sentinels retain raw signature hashes.",
|
||||
],
|
||||
},
|
||||
managedDecodeBudget(layout),
|
||||
|
||||
@@ -346,50 +346,297 @@ const ELEMENT_TYPES = new Map<number, string>([
|
||||
[0x1c, "object"],
|
||||
]);
|
||||
|
||||
const readTypeSignature = (
|
||||
const readSignedCompressed = (
|
||||
bytes: Buffer,
|
||||
offset: number,
|
||||
): { readonly value: number; readonly next: number } => {
|
||||
const encoded = readCompressed(bytes, offset);
|
||||
const width =
|
||||
encoded.next - offset === 1 ? 7 : encoded.next - offset === 2 ? 14 : 29;
|
||||
const magnitude = Math.floor(encoded.value / 2);
|
||||
return {
|
||||
value: encoded.value % 2 === 0 ? magnitude : magnitude - 2 ** (width - 1),
|
||||
next: encoded.next,
|
||||
};
|
||||
};
|
||||
|
||||
const malformedSignature = (detail: string, offset: number): never => {
|
||||
throw managedFailure("invalid-blob", "signature", detail, offset);
|
||||
};
|
||||
|
||||
// Pending work while decoding one Type. Signatures nest arbitrarily deep, so
|
||||
// decoding keeps an explicit stack instead of recursing.
|
||||
type TypeContinuation =
|
||||
| { readonly kind: "suffix"; readonly suffix: "*" | "&" | "[]" }
|
||||
| { readonly kind: "modifiers"; readonly modifiers: string[] }
|
||||
| { readonly kind: "array" }
|
||||
| {
|
||||
readonly kind: "list";
|
||||
remaining: number;
|
||||
readonly items: string[];
|
||||
// Function pointer items are a RetType then Params; generic
|
||||
// arguments are Types.
|
||||
readonly signatureItems: boolean;
|
||||
readonly render: (items: readonly string[]) => string;
|
||||
};
|
||||
|
||||
interface MethodSignatureHeader {
|
||||
readonly first: number;
|
||||
readonly genericParameterCount: number | null;
|
||||
readonly parameterCount: number;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
const readMethodSignatureHeader = (
|
||||
blob: Buffer,
|
||||
offset: number,
|
||||
): MethodSignatureHeader => {
|
||||
const first = blob[offset];
|
||||
if (first === undefined)
|
||||
return malformedSignature("truncated method signature", offset);
|
||||
let next = offset + 1;
|
||||
let genericParameterCount: number | null = null;
|
||||
if ((first & 0x10) !== 0) {
|
||||
const generic = readCompressed(blob, next);
|
||||
genericParameterCount = generic.value;
|
||||
next = generic.next;
|
||||
}
|
||||
const parameterCount = readCompressed(blob, next);
|
||||
return {
|
||||
first,
|
||||
genericParameterCount,
|
||||
parameterCount: parameterCount.value,
|
||||
next: parameterCount.next,
|
||||
};
|
||||
};
|
||||
|
||||
const MAX_ARRAY_RANK = 32;
|
||||
|
||||
// FNPTR carries a method signature: managed DEFAULT/VARARG, or the unmanaged
|
||||
// C, STDCALL, THISCALL, FASTCALL, and UNMANAGED conventions that compilers
|
||||
// emit for unmanaged function pointers. FIELD, LOCAL_SIG, PROPERTY, and
|
||||
// GENERICINST headers are not method signatures.
|
||||
const FUNCTION_POINTER_CONVENTIONS = new Set([0, 1, 2, 3, 4, 5, 9]);
|
||||
|
||||
const arrayShape = (
|
||||
blob: Buffer,
|
||||
offset: number,
|
||||
): { readonly value: string; readonly next: number } => {
|
||||
const suffixes: string[] = [];
|
||||
let cursor = offset;
|
||||
let kind = blob[cursor];
|
||||
while (kind === 0x0f || kind === 0x10 || kind === 0x1d) {
|
||||
suffixes.push(kind === 0x0f ? "*" : kind === 0x10 ? "&" : "[]");
|
||||
cursor += 1;
|
||||
kind = blob[cursor];
|
||||
}
|
||||
if (kind === undefined)
|
||||
throw managedFailure(
|
||||
"invalid-blob",
|
||||
"signature",
|
||||
"truncated type signature",
|
||||
cursor,
|
||||
);
|
||||
const named = ELEMENT_TYPES.get(kind);
|
||||
let value: string;
|
||||
let next: number;
|
||||
if (named !== undefined) {
|
||||
value = named;
|
||||
next = cursor + 1;
|
||||
} else if (kind === 0x11 || kind === 0x12) {
|
||||
const token = readCompressed(blob, cursor + 1);
|
||||
value = `${kind === 0x11 ? "valuetype" : "class"}:${String(token.value)}`;
|
||||
next = token.next;
|
||||
} else if (kind === 0x1e || kind === 0x13) {
|
||||
const variable = readCompressed(blob, cursor + 1);
|
||||
value = `${kind === 0x1e ? "mvar" : "var"}:${String(variable.value)}`;
|
||||
next = variable.next;
|
||||
} else {
|
||||
const rank = readCompressed(blob, offset);
|
||||
if (rank.value === 0) return malformedSignature("array rank is zero", offset);
|
||||
// ECMA-335 leaves rank unbounded, but the CLR loads at most 32 dimensions;
|
||||
// larger ranks would expand a few bytes into an unbounded rendering.
|
||||
if (rank.value > MAX_ARRAY_RANK)
|
||||
throw managedFailure(
|
||||
"unsupported-signature",
|
||||
"signature",
|
||||
`unsupported element type 0x${kind.toString(16)}`,
|
||||
cursor,
|
||||
`array rank ${String(rank.value)} exceeds the ${String(MAX_ARRAY_RANK)} dimensions the CLR supports`,
|
||||
offset,
|
||||
);
|
||||
const sizeCount = readCompressed(blob, rank.next);
|
||||
if (sizeCount.value > rank.value)
|
||||
return malformedSignature("array has more sizes than dimensions", offset);
|
||||
const sizes: number[] = [];
|
||||
let next = sizeCount.next;
|
||||
for (let index = 0; index < sizeCount.value; index += 1) {
|
||||
const size = readCompressed(blob, next);
|
||||
sizes.push(size.value);
|
||||
next = size.next;
|
||||
}
|
||||
return { value: value + suffixes.reverse().join(""), next };
|
||||
const boundCount = readCompressed(blob, next);
|
||||
if (boundCount.value > rank.value)
|
||||
return malformedSignature(
|
||||
"array has more lower bounds than dimensions",
|
||||
offset,
|
||||
);
|
||||
const lowerBounds: number[] = [];
|
||||
next = boundCount.next;
|
||||
for (let index = 0; index < boundCount.value; index += 1) {
|
||||
const bound = readSignedCompressed(blob, next);
|
||||
lowerBounds.push(bound.value);
|
||||
next = bound.next;
|
||||
}
|
||||
const dimensions = Array.from({ length: rank.value }, (_, index) => {
|
||||
const size = sizes[index];
|
||||
const lower = lowerBounds[index];
|
||||
if (lower !== undefined)
|
||||
return size === undefined
|
||||
? `${String(lower)}...`
|
||||
: `${String(lower)}...${String(lower + size - 1)}`;
|
||||
if (size !== undefined) return String(size);
|
||||
// ILAsm spelling: a bare rank-1 `[]` is reserved for SZARRAY.
|
||||
return rank.value === 1 ? "..." : "";
|
||||
});
|
||||
return { value: `[${dimensions.join(",")}]`, next };
|
||||
};
|
||||
|
||||
/** Grammar position of the element being decoded (ECMA-335 II.23.2). */
|
||||
type SignaturePosition = "field" | "return" | "parameter" | "type" | "pointee";
|
||||
|
||||
// Custom modifiers do not change the position they precede.
|
||||
const currentPosition = (
|
||||
stack: readonly TypeContinuation[],
|
||||
base: SignaturePosition,
|
||||
): SignaturePosition => {
|
||||
const frame = stack.findLast(({ kind }) => kind !== "modifiers");
|
||||
if (frame === undefined) return base;
|
||||
if (frame.kind === "suffix") return frame.suffix === "*" ? "pointee" : "type";
|
||||
if (frame.kind === "list" && frame.signatureItems)
|
||||
return frame.items.length === 0 ? "return" : "parameter";
|
||||
return "type";
|
||||
};
|
||||
|
||||
// VOID is a RetType or a pointee; TYPEDBYREF is a RetType or Param; BYREF
|
||||
// prefixes a RetType, Param, or (since ref fields) a field type.
|
||||
const POSITION_ELEMENTS: ReadonlyMap<number, readonly SignaturePosition[]> =
|
||||
new Map([
|
||||
[0x01, ["return", "pointee"]],
|
||||
[0x16, ["return", "parameter"]],
|
||||
[0x10, ["return", "parameter", "field"]],
|
||||
]);
|
||||
|
||||
const readTypeSignature = (
|
||||
blob: Buffer,
|
||||
offset: number,
|
||||
base: SignaturePosition,
|
||||
): { readonly value: string; readonly next: number } => {
|
||||
const stack: TypeContinuation[] = [];
|
||||
let cursor = offset;
|
||||
for (;;) {
|
||||
let value: string | undefined;
|
||||
const kind = blob[cursor];
|
||||
if (kind === undefined)
|
||||
return malformedSignature("truncated type signature", cursor);
|
||||
const positions = POSITION_ELEMENTS.get(kind);
|
||||
if (
|
||||
positions !== undefined &&
|
||||
!positions.includes(currentPosition(stack, base))
|
||||
)
|
||||
return malformedSignature(
|
||||
`element type 0x${kind.toString(16)} is not valid in a ${currentPosition(stack, base)} position`,
|
||||
cursor,
|
||||
);
|
||||
const named = ELEMENT_TYPES.get(kind);
|
||||
if (named !== undefined) {
|
||||
value = named;
|
||||
cursor += 1;
|
||||
} else if (kind === 0x0f || kind === 0x10 || kind === 0x1d) {
|
||||
const suffix = kind === 0x0f ? "*" : kind === 0x10 ? "&" : "[]";
|
||||
stack.push({ kind: "suffix", suffix });
|
||||
cursor += 1;
|
||||
} else if (kind === 0x1f || kind === 0x20) {
|
||||
const token = readCompressed(blob, cursor + 1);
|
||||
const modifier = `${kind === 0x1f ? "modreq" : "modopt"}:${String(token.value)}`;
|
||||
// A modifier frame on top was pushed by the directly preceding byte;
|
||||
// keep an adjacent run together and in source order.
|
||||
const top = stack.at(-1);
|
||||
if (top?.kind === "modifiers") top.modifiers.push(modifier);
|
||||
else stack.push({ kind: "modifiers", modifiers: [modifier] });
|
||||
cursor = token.next;
|
||||
} else if (kind === 0x11 || kind === 0x12) {
|
||||
const token = readCompressed(blob, cursor + 1);
|
||||
value = `${kind === 0x11 ? "valuetype" : "class"}:${String(token.value)}`;
|
||||
cursor = token.next;
|
||||
} else if (kind === 0x1e || kind === 0x13) {
|
||||
const variable = readCompressed(blob, cursor + 1);
|
||||
value = `${kind === 0x1e ? "mvar" : "var"}:${String(variable.value)}`;
|
||||
cursor = variable.next;
|
||||
} else if (kind === 0x16) {
|
||||
value = "typedbyref";
|
||||
cursor += 1;
|
||||
} else if (kind === 0x14) {
|
||||
stack.push({ kind: "array" });
|
||||
cursor += 1;
|
||||
} else if (kind === 0x15) {
|
||||
const generic = blob[cursor + 1];
|
||||
if (generic !== 0x11 && generic !== 0x12)
|
||||
return malformedSignature(
|
||||
"generic instantiation does not name a class or value type",
|
||||
cursor + 1,
|
||||
);
|
||||
const token = readCompressed(blob, cursor + 2);
|
||||
const argumentCount = readCompressed(blob, token.next);
|
||||
if (argumentCount.value === 0)
|
||||
return malformedSignature(
|
||||
"generic instantiation has no type arguments",
|
||||
token.next,
|
||||
);
|
||||
const head = `${generic === 0x11 ? "valuetype" : "class"}:${String(token.value)}`;
|
||||
stack.push({
|
||||
kind: "list",
|
||||
remaining: argumentCount.value,
|
||||
items: [],
|
||||
signatureItems: false,
|
||||
render: (items) => `${head}<${items.join(",")}>`,
|
||||
});
|
||||
cursor = argumentCount.next;
|
||||
} else if (kind === 0x1b) {
|
||||
const header = readMethodSignatureHeader(blob, cursor + 1);
|
||||
if (
|
||||
!FUNCTION_POINTER_CONVENTIONS.has(header.first & 0x0f) ||
|
||||
(header.first & 0x80) !== 0 ||
|
||||
((header.first & 0x40) !== 0 && (header.first & 0x20) === 0)
|
||||
)
|
||||
return malformedSignature(
|
||||
`function pointer calling convention 0x${header.first.toString(16)} does not head a method signature`,
|
||||
cursor + 1,
|
||||
);
|
||||
const convention = callingConvention(header.first);
|
||||
const head =
|
||||
header.genericParameterCount === null
|
||||
? convention
|
||||
: `${convention};${String(header.genericParameterCount)}`;
|
||||
stack.push({
|
||||
kind: "list",
|
||||
remaining: header.parameterCount + 1,
|
||||
items: [],
|
||||
signatureItems: true,
|
||||
render: ([returnType, ...parameters]) =>
|
||||
`fnptr[${head}](${parameters.join(",")})->${returnType ?? ""}`,
|
||||
});
|
||||
cursor = header.next;
|
||||
} else {
|
||||
throw managedFailure(
|
||||
"unsupported-signature",
|
||||
"signature",
|
||||
`unsupported element type 0x${kind.toString(16)}`,
|
||||
cursor,
|
||||
);
|
||||
}
|
||||
while (value !== undefined) {
|
||||
const top = stack.pop();
|
||||
if (top === undefined) return { value, next: cursor };
|
||||
if (top.kind === "suffix") value += top.suffix;
|
||||
else if (top.kind === "modifiers")
|
||||
value = `${value} ${top.modifiers.join(" ")}`;
|
||||
else if (top.kind === "array") {
|
||||
const shape = arrayShape(blob, cursor);
|
||||
value += shape.value;
|
||||
cursor = shape.next;
|
||||
} else {
|
||||
top.items.push(value);
|
||||
top.remaining -= 1;
|
||||
if (top.remaining === 0) value = top.render(top.items);
|
||||
else {
|
||||
value = undefined;
|
||||
stack.push(top);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const CALLING_CONVENTION_NAMES = new Map([
|
||||
[0, "default"],
|
||||
[1, "c"],
|
||||
[2, "stdcall"],
|
||||
[3, "thiscall"],
|
||||
[4, "fastcall"],
|
||||
[5, "vararg"],
|
||||
[6, "field"],
|
||||
[9, "unmanaged"],
|
||||
]);
|
||||
|
||||
const callingConvention = (value: number): string => {
|
||||
const base = value & 0x0f;
|
||||
const flags = [
|
||||
@@ -397,14 +644,7 @@ const callingConvention = (value: number): string => {
|
||||
(value & 0x40) === 0 ? null : "explicit-this",
|
||||
(value & 0x10) === 0 ? null : "generic",
|
||||
].filter((flag) => flag !== null);
|
||||
const name =
|
||||
base === 0
|
||||
? "default"
|
||||
: base === 5
|
||||
? "vararg"
|
||||
: base === 6
|
||||
? "field"
|
||||
: `unknown:${String(base)}`;
|
||||
const name = CALLING_CONVENTION_NAMES.get(base) ?? `unknown:${String(base)}`;
|
||||
return flags.length === 0 ? name : `${name} ${flags.join(" ")}`;
|
||||
};
|
||||
|
||||
@@ -421,7 +661,7 @@ export const signature = (
|
||||
throw managedFailure("invalid-blob", "signature", "empty signature", 0);
|
||||
const first = blob[0] ?? 0;
|
||||
if ((first & 0x0f) === 6) {
|
||||
const fieldType = readTypeSignature(blob, 1);
|
||||
const fieldType = readTypeSignature(blob, 1, "field");
|
||||
return {
|
||||
...raw,
|
||||
kind: "field",
|
||||
@@ -436,20 +676,12 @@ export const signature = (
|
||||
fieldType.next === blob.length ? null : "Trailing signature data",
|
||||
};
|
||||
}
|
||||
let offset = 1;
|
||||
let genericParameterCount: number | null = null;
|
||||
if ((first & 0x10) !== 0) {
|
||||
const generic = readCompressed(blob, offset);
|
||||
genericParameterCount = generic.value;
|
||||
offset = generic.next;
|
||||
}
|
||||
const parameterCount = readCompressed(blob, offset);
|
||||
offset = parameterCount.next;
|
||||
const returnType = readTypeSignature(blob, offset);
|
||||
offset = returnType.next;
|
||||
const header = readMethodSignatureHeader(blob, 0);
|
||||
const returnType = readTypeSignature(blob, header.next, "return");
|
||||
let offset = returnType.next;
|
||||
const parameters: string[] = [];
|
||||
for (let index = 0; index < parameterCount.value; index += 1) {
|
||||
const parameter = readTypeSignature(blob, offset);
|
||||
for (let index = 0; index < header.parameterCount; index += 1) {
|
||||
const parameter = readTypeSignature(blob, offset, "parameter");
|
||||
parameters.push(parameter.value);
|
||||
offset = parameter.next;
|
||||
}
|
||||
@@ -458,8 +690,8 @@ export const signature = (
|
||||
kind: "method",
|
||||
parse_status: offset === blob.length ? "decoded" : "partial",
|
||||
calling_convention: callingConvention(first),
|
||||
generic_parameter_count: genericParameterCount,
|
||||
parameter_count: parameterCount.value,
|
||||
generic_parameter_count: header.genericParameterCount,
|
||||
parameter_count: header.parameterCount,
|
||||
return_type: returnType.value,
|
||||
parameter_types: parameters,
|
||||
field_type: null,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ManagedDecodeBudget } from "./ManagedDecodeBudget.js";
|
||||
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
|
||||
import type {
|
||||
ManagedExceptionRegion,
|
||||
ManagedInstructionAnchor,
|
||||
@@ -381,6 +382,7 @@ const readOperand = (
|
||||
|
||||
export const decodeInstructions = (
|
||||
il: Buffer,
|
||||
admitInstruction?: (offset: number) => void,
|
||||
): {
|
||||
readonly parsed: readonly ParsedInstruction[];
|
||||
readonly instructionStarts: readonly number[];
|
||||
@@ -409,6 +411,9 @@ export const decodeInstructions = (
|
||||
issue = `Instruction ${descriptor.name} at IL offset ${String(start)} leaves method body`;
|
||||
break;
|
||||
}
|
||||
// Charge each actual instruction before growing the decoded arrays.
|
||||
// A multi-byte operand must not consume a full record per raw IL byte.
|
||||
admitInstruction?.(start);
|
||||
offset = operand.next;
|
||||
if (PREFIX_OPCODES.has(descriptor.name)) {
|
||||
prefixStart ??= start;
|
||||
@@ -424,6 +429,7 @@ export const decodeInstructions = (
|
||||
});
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ManagedReaderFailure) throw cause;
|
||||
issue =
|
||||
cause instanceof Error ? cause.message : "Instruction decode failed";
|
||||
}
|
||||
|
||||
@@ -100,11 +100,15 @@ export const methodBody = (
|
||||
if (ilOffset > bytes.length - header.ilSize)
|
||||
throw new RangeError("Method IL bytes leave artifact");
|
||||
const il = bytes.subarray(ilOffset, ilOffset + header.ilSize);
|
||||
// One byte can produce an instruction record, start index, normalized tuple,
|
||||
// and anchor. Bound that bookkeeping before decoding; the retained body is
|
||||
// reserved once it is known.
|
||||
budget?.admitTransient(il.length * 256, ilOffset);
|
||||
const decoded = decodeInstructions(il);
|
||||
// Bound the actual instruction records before allocating them. One raw
|
||||
// byte is only an upper bound on count; wide operands do not create a
|
||||
// separate instruction for every byte. Retained output is charged below.
|
||||
const decoded = decodeInstructions(
|
||||
il,
|
||||
budget === undefined
|
||||
? undefined
|
||||
: (start) => budget.admitTransient(256, ilOffset + start),
|
||||
);
|
||||
const opcodeCounts: Record<string, number> = {};
|
||||
for (const instruction of decoded.parsed)
|
||||
opcodeCounts[instruction.opcode] =
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type ProviderProcessSnapshot,
|
||||
ProviderProcessSupervisor,
|
||||
} from "../process/ProviderProcess.js";
|
||||
import { DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS } from "../config/ghidraStartupTimeout.js";
|
||||
import { DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS } from "../config/providerStartupTimeout.js";
|
||||
import type {
|
||||
GhidraClientOptions,
|
||||
GhidraRequestOptions,
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
acquireLinuxHopperApplicationLease,
|
||||
} from "./HopperTargetLease.js";
|
||||
import type { HopperTargetLease } from "./HopperTargetLease.js";
|
||||
import { HOPPER_SHUTDOWN_TIMEOUT_MS } from "./HopperSessionValues.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const HOPPER_BACKGROUND_STARTUP_MS = 5_000;
|
||||
@@ -46,6 +47,8 @@ export interface BridgeSession {
|
||||
|
||||
/** Process handle returned by a bridge launcher. */
|
||||
export type BridgeLaunch = {
|
||||
/** Only literal native-helper arguments support a pre-handoff denial conclusion. */
|
||||
readonly authorizationDenialBeforeHandoff?: true;
|
||||
/** Release application/target exclusivity only after verified document and process cleanup. */
|
||||
readonly releaseLease?: () => Promise<void>;
|
||||
/** Exact launch command retained in local ownership metadata. */
|
||||
@@ -254,6 +257,15 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
...ownedLauncher,
|
||||
providerLifetime: "external-application",
|
||||
shutdownMode: "bridge-request",
|
||||
// The vendor helper interpolates these values into AppleScript
|
||||
// literals without escaping. Preserve them, but withhold the
|
||||
// pre-handoff conclusion when they can alter that script.
|
||||
...((this.dependencies.platform ?? process.platform) === "darwin" &&
|
||||
![this.options.launcherPath, ...argumentsForTarget].some((value) =>
|
||||
/["\\\r\n]/u.test(value),
|
||||
)
|
||||
? { authorizationDenialBeforeHandoff: true as const }
|
||||
: {}),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(hopperLaunchFailure(cause, signal));
|
||||
@@ -370,6 +382,7 @@ const bridgeBootstrapSource = (
|
||||
`REA_RUN_ID = ${JSON.stringify(session.runId)}`,
|
||||
`REA_TARGET_PATH = ${JSON.stringify(loadedPath)}`,
|
||||
`REA_OWNS_PROCESS_LIFETIME = ${ownsProcessLifetime ? "True" : "False"}`,
|
||||
`REA_RECONNECT_TIMEOUT_SECONDS = ${HOPPER_SHUTDOWN_TIMEOUT_MS / 1_000}`,
|
||||
`exec(compile(open(${JSON.stringify(options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(options.bridgeScriptPath)}, 'exec'))`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
+125
-36
@@ -34,7 +34,10 @@ import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
import type { Logger } from "pino";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import {
|
||||
ProviderStartupDeadline,
|
||||
waitForAbortableDelay,
|
||||
} from "../process/ProviderDeadline.js";
|
||||
import { redactCapturedTransportCredential } from "../process/ProviderDiagnosticRedaction.js";
|
||||
import { ProviderRunLineage } from "../process/ProviderRunLineage.js";
|
||||
import {
|
||||
@@ -50,10 +53,15 @@ import {
|
||||
} from "./HopperCleanup.js";
|
||||
import {
|
||||
parseHopperServerInfo,
|
||||
HOPPER_SHUTDOWN_TIMEOUT_MS,
|
||||
type HopperServerInfo,
|
||||
} from "./HopperSessionValues.js";
|
||||
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
|
||||
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
|
||||
import {
|
||||
hopperLauncherFailureDiagnostic,
|
||||
nativeHopperLaunchWasDenied,
|
||||
} from "./HopperProcessDiagnostic.js";
|
||||
import { DEFAULT_HOPPER_STARTUP_TIMEOUT_MS } from "../config/providerStartupTimeout.js";
|
||||
import {
|
||||
HopperRequestQueue,
|
||||
type HopperRequestActivity,
|
||||
@@ -68,7 +76,6 @@ import {
|
||||
/** Aggregate in-memory retention budget for this provider's launcher output. */
|
||||
export const HOPPER_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
const SHUTDOWN_TIMEOUT_MS = 30_000;
|
||||
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
|
||||
|
||||
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
|
||||
@@ -114,6 +121,8 @@ export class HopperClient {
|
||||
#launcherFailureDiagnostic: HopperStartupFailureDiagnostic | undefined;
|
||||
#operationFailure: OperationFailureRecord | undefined;
|
||||
#startupController: AbortController | undefined;
|
||||
#startupFailureResult: AnalysisError | undefined;
|
||||
#runId: string | undefined;
|
||||
#startPromise: Promise<Result<HopperServerInfo, AnalysisError>> | undefined;
|
||||
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
|
||||
readonly #onSocketData = (chunk: string): void => {
|
||||
@@ -169,7 +178,8 @@ export class HopperClient {
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
this.#options = {
|
||||
...options,
|
||||
startupTimeoutMs: options.startupTimeoutMs ?? 120_000,
|
||||
startupTimeoutMs:
|
||||
options.startupTimeoutMs ?? DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
|
||||
};
|
||||
this.#requests = new HopperRequestQueue(
|
||||
({ id, method, params }, failed) => {
|
||||
@@ -311,14 +321,18 @@ export class HopperClient {
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<HopperServerInfo, AnalysisError>> {
|
||||
if (isAborted(signal)) return err(new HopperCancelledError());
|
||||
this.#operationFailure = undefined;
|
||||
if (
|
||||
this.#socket !== undefined ||
|
||||
this.#resources.launch !== undefined ||
|
||||
this.#resources.runtimeRoot !== undefined
|
||||
) {
|
||||
return err(new HopperProtocolError("Hopper client is already started"));
|
||||
return err(
|
||||
this.#startupFailureResult ??
|
||||
new HopperProtocolError("Hopper client is already started"),
|
||||
);
|
||||
}
|
||||
this.#operationFailure = undefined;
|
||||
this.#startupFailureResult = undefined;
|
||||
this.#resources.shutdownConfirmed = false;
|
||||
const deadline = new ProviderStartupDeadline(
|
||||
this.#options.startupTimeoutMs,
|
||||
@@ -343,7 +357,7 @@ export class HopperClient {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
if (deadline.signal.aborted) {
|
||||
return this.#startupFailure(startupInterruption(deadline));
|
||||
return this.#startupFailure(await this.#startupInterruption(deadline));
|
||||
}
|
||||
const socketPath = join(this.#resources.runtimeRoot.path, "bridge.sock");
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
@@ -351,6 +365,7 @@ export class HopperClient {
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
const runId = this.#options.runId ?? randomUUID();
|
||||
this.#runId = runId;
|
||||
const launched: Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
@@ -368,7 +383,7 @@ export class HopperClient {
|
||||
if (!launched.ok) {
|
||||
return this.#startupFailure(
|
||||
deadline.signal.aborted
|
||||
? startupInterruption(deadline)
|
||||
? await this.#startupInterruption(deadline)
|
||||
: launched.error,
|
||||
);
|
||||
}
|
||||
@@ -399,9 +414,7 @@ export class HopperClient {
|
||||
}
|
||||
const remainingMs = deadline.remainingMs();
|
||||
if (remainingMs <= 0) {
|
||||
return this.#startupFailure(
|
||||
new HopperTimeoutError(this.#options.startupTimeoutMs),
|
||||
);
|
||||
return this.#startupFailure(await this.#startupInterruption(deadline));
|
||||
}
|
||||
const health = await this.#request(
|
||||
"health",
|
||||
@@ -413,7 +426,9 @@ export class HopperClient {
|
||||
);
|
||||
if (!health.ok) {
|
||||
return this.#startupFailure(
|
||||
deadline.signal.aborted ? startupInterruption(deadline) : health.error,
|
||||
deadline.signal.aborted || health.error instanceof HopperTimeoutError
|
||||
? await this.#startupInterruption(deadline)
|
||||
: health.error,
|
||||
);
|
||||
}
|
||||
const parsed = parseHopperServerInfo(health.value, runId);
|
||||
@@ -426,22 +441,20 @@ export class HopperClient {
|
||||
primary: AnalysisError,
|
||||
): Promise<Result<never, AnalysisError>> {
|
||||
this.#rememberStartupFailure(primary);
|
||||
// Failed readiness never authorized this connection to mutate a document.
|
||||
this.#releaseTransport();
|
||||
const closed = await this.#cleanup();
|
||||
return err(
|
||||
closed.ok
|
||||
? primary
|
||||
: analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"),
|
||||
);
|
||||
const failure = closed.ok
|
||||
? primary
|
||||
: analysisErrorWithCleanupFailure(primary, closed.error, "open_binary");
|
||||
this.#startupFailureResult = failure;
|
||||
return err(failure);
|
||||
}
|
||||
|
||||
#rememberStartupFailure(failure: AnalysisError): void {
|
||||
if (failure instanceof HopperProcessError)
|
||||
this.#rememberProcessFailure(failure, []);
|
||||
else if (
|
||||
this.#operationFailure === undefined &&
|
||||
(failure instanceof HopperTimeoutError ||
|
||||
failure instanceof HopperStartError)
|
||||
)
|
||||
else if (this.#operationFailure === undefined)
|
||||
this.#operationFailure = {
|
||||
state:
|
||||
failure instanceof HopperTimeoutError ? "not_started" : "unknown",
|
||||
@@ -500,6 +513,7 @@ export class HopperClient {
|
||||
// best-effort cleanup: a rejected startup must not mask close/cleanup;
|
||||
// #cleanup reports the authoritative close result.
|
||||
await starting?.catch(() => undefined);
|
||||
await this.#reconnectForCleanup();
|
||||
return await this.#cleanup(options);
|
||||
} finally {
|
||||
if (this.#startPromise === starting) this.#startPromise = undefined;
|
||||
@@ -510,6 +524,68 @@ export class HopperClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Reauthenticate this run after late readiness or a lost transport. */
|
||||
async #reconnectForCleanup(): Promise<void> {
|
||||
if (this.#socket?.destroyed === true) this.#releaseTransport();
|
||||
const root = this.#resources.runtimeRoot;
|
||||
const runId = this.#runId;
|
||||
if (
|
||||
this.#socket !== undefined ||
|
||||
root === undefined ||
|
||||
runId === undefined ||
|
||||
this.#token === undefined ||
|
||||
this.#resources.shutdownConfirmed ||
|
||||
this.#resources.launch?.providerLifetime !== "external-application"
|
||||
)
|
||||
return;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(
|
||||
() => controller.abort(),
|
||||
HOPPER_SHUTDOWN_TIMEOUT_MS,
|
||||
);
|
||||
this.#closing = true;
|
||||
try {
|
||||
const socketPath = join(root.path, "bridge.sock");
|
||||
let connected = await connectHopperSocketOnce(
|
||||
socketPath,
|
||||
controller.signal,
|
||||
);
|
||||
while (!connected.ok) {
|
||||
const cause = connected.error.cause;
|
||||
if (
|
||||
!(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" || cause.code === "ECONNREFUSED")
|
||||
)
|
||||
)
|
||||
return;
|
||||
if ((await waitForAbortableDelay(50, controller.signal)) === "aborted")
|
||||
return;
|
||||
connected = await connectHopperSocketOnce(
|
||||
socketPath,
|
||||
controller.signal,
|
||||
);
|
||||
}
|
||||
const socket = connected.value;
|
||||
this.#socket = socket;
|
||||
this.#attachSocket(socket);
|
||||
const health = await this.#request(
|
||||
"health",
|
||||
{},
|
||||
{
|
||||
signal: controller.signal,
|
||||
timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
if (health.ok && parseHopperServerInfo(health.value, runId).ok) return;
|
||||
this.#releaseTransport();
|
||||
} finally {
|
||||
this.#closing = false;
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async #cleanup(
|
||||
options: HopperClientCloseOptions = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
@@ -523,18 +599,18 @@ export class HopperClient {
|
||||
logger: this.#logger,
|
||||
onDiagnostic: this.#options.onDiagnostic,
|
||||
request: (method) =>
|
||||
this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }),
|
||||
this.#request(method, {}, { timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS }),
|
||||
retainDocument: options.retainDocument === true,
|
||||
releaseTransport: (socket) => {
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
if (socket !== undefined) this.#detachSocket(socket);
|
||||
socket?.destroy();
|
||||
},
|
||||
releaseTransport: () => this.#releaseTransport(),
|
||||
});
|
||||
} finally {
|
||||
if (this.#socket?.destroyed === true) this.#socket = undefined;
|
||||
|
||||
if (this.#socket === undefined) this.#token = undefined;
|
||||
// Retained external launches may publish their authenticated socket later.
|
||||
if (this.#resources.runtimeRoot === undefined) {
|
||||
this.#token = undefined;
|
||||
this.#runId = undefined;
|
||||
}
|
||||
if (this.#socket === undefined) this.#responses.reset();
|
||||
if (this.#resources.processSupervisor === undefined) {
|
||||
this.#launcherExitCode = undefined;
|
||||
@@ -662,6 +738,17 @@ export class HopperClient {
|
||||
"launch",
|
||||
launcherFailure,
|
||||
);
|
||||
if (
|
||||
this.#resources.launch?.authorizationDenialBeforeHandoff === true &&
|
||||
nativeHopperLaunchWasDenied(launcherFailure)
|
||||
) {
|
||||
this.#resources.shutdownConfirmed = true;
|
||||
return new HopperStartError({
|
||||
userMessage:
|
||||
"macOS denied permission to send Apple Events to Hopper. Allow the application that starts REA under System Settings > Privacy & Security > Automation, then retry opening the target.",
|
||||
launcherFailure,
|
||||
});
|
||||
}
|
||||
return new HopperStartError({
|
||||
userMessage:
|
||||
"Hopper's launcher helper failed before bridge readiness. Review details.launcher and complete Hopper setup before retrying.",
|
||||
@@ -757,6 +844,15 @@ export class HopperClient {
|
||||
socket.off("close", this.#onSocketClose);
|
||||
}
|
||||
|
||||
#releaseTransport(): void {
|
||||
const socket = this.#socket;
|
||||
this.#socket = undefined;
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
if (socket !== undefined) this.#detachSocket(socket);
|
||||
socket?.destroy();
|
||||
this.#responses.reset();
|
||||
}
|
||||
|
||||
#attachLauncher(launch: BridgeLaunch): void {
|
||||
this.#resources.processSupervisor = new ProviderProcessSupervisor(launch, {
|
||||
maxDiagnosticBytes: HOPPER_PROCESS_DIAGNOSTIC_BYTES,
|
||||
@@ -927,10 +1023,3 @@ const mergeFailedRequests = (
|
||||
};
|
||||
|
||||
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
|
||||
|
||||
const startupInterruption = (
|
||||
deadline: ProviderStartupDeadline,
|
||||
): HopperCancelledError | HopperTimeoutError =>
|
||||
deadline.interruption === "cancelled"
|
||||
? new HopperCancelledError()
|
||||
: new HopperTimeoutError(deadline.timeoutMs);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import type { HopperLauncherOutcome } from "../domain/hopperErrors.js";
|
||||
import { nativeHopperLaunchWasDenied } from "./HopperProcessDiagnostic.js";
|
||||
|
||||
// Captured from Hopper 6.1.0-demo and 6.6.0-demo's unmodified helpers with native
|
||||
// AppleScript error -1743 before open dispatch. The target script never ran.
|
||||
const denied: HopperLauncherOutcome = {
|
||||
exit_code: 2,
|
||||
signal: null,
|
||||
stdout: { text: "", bytes: 0, retained_bytes: 0 },
|
||||
stderr: {
|
||||
text: "Cannot launch Hopper!\nNot authorized to send Apple events to current application.\n",
|
||||
bytes: 82,
|
||||
retained_bytes: 82,
|
||||
},
|
||||
output_closed: true,
|
||||
diagnostic_truncated: false,
|
||||
};
|
||||
|
||||
it("recognizes the native helper's complete authorization rejection", () => {
|
||||
expect(nativeHopperLaunchWasDenied(denied)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ output_closed: false },
|
||||
{ diagnostic_truncated: true },
|
||||
{ signal: "SIGTERM", exit_code: null },
|
||||
{ signal: "SIGTERM", exit_code: 2 },
|
||||
{ exit_code: 0 },
|
||||
{
|
||||
stderr: {
|
||||
...denied.stderr,
|
||||
text: "Cannot launch Hopper!\nExpected end of line, etc. but found identifier.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
stderr: {
|
||||
...denied.stderr,
|
||||
text: `${denied.stderr.text}another failure\n`,
|
||||
},
|
||||
},
|
||||
{
|
||||
stderr: {
|
||||
...denied.stderr,
|
||||
text: "Not authorized to send Apple events to current application.\n",
|
||||
},
|
||||
},
|
||||
])(
|
||||
"preserves unknown document ownership for incomplete or different failures: %j",
|
||||
(change) => {
|
||||
expect(nativeHopperLaunchWasDenied({ ...denied, ...change })).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -4,6 +4,25 @@ import {
|
||||
} from "../domain/hopperStartupFailure.js";
|
||||
import type { ProviderProcessDiagnostic } from "../process/ProviderProcess.js";
|
||||
import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js";
|
||||
import type { HopperLauncherOutcome } from "../domain/hopperErrors.js";
|
||||
|
||||
/**
|
||||
* Hopper's native helper sends activate before its open-document Apple event.
|
||||
* Recognize its explicit authorization rejection. The launcher must separately
|
||||
* establish that caller arguments could not alter the generated AppleScript.
|
||||
* Other script errors, signals, and incomplete output leave ownership unknown.
|
||||
*/
|
||||
export const nativeHopperLaunchWasDenied = (
|
||||
outcome: HopperLauncherOutcome | undefined,
|
||||
): outcome is HopperLauncherOutcome =>
|
||||
outcome !== undefined &&
|
||||
outcome.exit_code === 2 &&
|
||||
outcome.signal === null &&
|
||||
outcome.output_closed &&
|
||||
!outcome.diagnostic_truncated &&
|
||||
/^Cannot launch Hopper!\r?\nNot authorized to send Apple events to [^\r\n]+\.\r?\n?$/u.test(
|
||||
outcome.stderr.text,
|
||||
);
|
||||
|
||||
/** Extract only a matching Linux adapter failure record. */
|
||||
export const hopperLauncherFailureDiagnostic = (
|
||||
|
||||
@@ -237,6 +237,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
: { launchMode: "native" as const }),
|
||||
}),
|
||||
...(context === undefined ? {} : { runId: context.runId }),
|
||||
startupTimeoutMs: this.config.hopperStartupTimeoutMs,
|
||||
logger: this.logger.child({ layer: "bridge" }),
|
||||
onDiagnostic: (diagnostic) =>
|
||||
this.logger.info(diagnostic, "Hopper bridge reported a diagnostic"),
|
||||
|
||||
@@ -2,6 +2,9 @@ import { HopperProtocolError } from "../domain/hopperErrors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Bound cleanup handshakes and the bridge's idle reconnection wait. */
|
||||
export const HOPPER_SHUTDOWN_TIMEOUT_MS = 30_000;
|
||||
|
||||
/** Authenticated identity returned by the Hopper bridge health handshake. */
|
||||
export interface HopperServerInfo {
|
||||
readonly name: string;
|
||||
|
||||
Reference in New Issue
Block a user