Skip to content

Commit 2b263a7

Browse files
committed
fix(native): retain Mach-O facts when dyld rejects missing UUID
Admit only the corroborated missing-UUID validation diagnostic from header-stripped dyld stdout. Preserve readable load commands and nm exports with unknown dyld coverage, and keep unrelated process and tool failures typed. Closes #5606
1 parent d0eca05 commit 2b263a7

5 files changed

Lines changed: 532 additions & 16 deletions

File tree

‎src/native/NativeMacOSProvider.ts‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -917,9 +917,10 @@ class NativeMacOSClient implements AnalysisClient {
917917
return inspectNativeMacho({
918918
target: this.target,
919919
...(signal === undefined ? {} : { signal }),
920-
run: (tool, arguments_, commandSignal) =>
920+
run: (tool, arguments_, commandSignal, acceptNonZeroIf) =>
921921
this.#run("inspect_macho", tool, arguments_, {
922922
signal: commandSignal,
923+
...(acceptNonZeroIf === undefined ? {} : { acceptNonZeroIf }),
923924
}),
924925
invocation: (capture) => invocation(capture, this.target.path),
925926
});
@@ -932,6 +933,9 @@ class NativeMacOSClient implements AnalysisClient {
932933
options: {
933934
readonly signal?: AbortSignal | undefined;
934935
readonly acceptNonZero?: boolean;
936+
readonly acceptNonZeroIf?:
937+
| ((capture: NativeCommandCapture) => boolean)
938+
| undefined;
935939
} = {},
936940
): Promise<Result<NativeCommandCapture, AnalysisError>> {
937941
if (this.#closed)
@@ -944,7 +948,8 @@ class NativeMacOSClient implements AnalysisClient {
944948
);
945949
const command = this.runner.run(tool, arguments_, {
946950
...(options.signal === undefined ? {} : { signal: options.signal }),
947-
acceptNonZero: options.acceptNonZero ?? false,
951+
acceptNonZero:
952+
options.acceptNonZero ?? options.acceptNonZeroIf !== undefined,
948953
});
949954
this.#pendingCommands.add(command);
950955
let captured: Awaited<typeof command>;
@@ -953,7 +958,40 @@ class NativeMacOSClient implements AnalysisClient {
953958
} finally {
954959
this.#pendingCommands.delete(command);
955960
}
956-
if (captured.ok) return captured;
961+
if (captured.ok) {
962+
const hasFailedExit =
963+
captured.value.exitCode !== 0 || captured.value.signal !== null;
964+
if (
965+
hasFailedExit &&
966+
options.acceptNonZeroIf !== undefined &&
967+
!options.acceptNonZeroIf(captured.value)
968+
)
969+
return err(
970+
translateCommandFailure(
971+
operation,
972+
new NativeCommandFailure(
973+
tool,
974+
captured.value.signal !== null ||
975+
(captured.value.exitCode !== null &&
976+
captured.value.exitCode !== 0)
977+
? "nonzero-exit"
978+
: "io",
979+
captured.value.exitCode,
980+
undefined,
981+
{
982+
stdout: captured.value.stdout,
983+
stderr: captured.value.stderr,
984+
stdoutBytes: captured.value.stdoutBytes,
985+
stderrBytes: captured.value.stderrBytes,
986+
exitCode: captured.value.exitCode,
987+
signal: captured.value.signal,
988+
truncated: false,
989+
},
990+
),
991+
),
992+
);
993+
return captured;
994+
}
957995
return err(translateCommandFailure(operation, captured.error));
958996
}
959997
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
2+
import type { NativeCommandCapture } from "./CommandRunner.js";
3+
import { withoutEchoedPathHeader } from "./parsers/echoedPath.js";
4+
5+
const MISSING_UUID_DIAGNOSTIC = "missing LC_UUID load command";
6+
7+
/** Recognize only dyld_info's target-specific missing-UUID refusal. */
8+
export const isMissingUuidDyldFailure = (
9+
capture: NativeCommandCapture,
10+
): boolean =>
11+
capture.tool === "dyld_info" &&
12+
capture.exitCode !== null &&
13+
capture.exitCode !== 0 &&
14+
capture.signal === null &&
15+
withoutEchoedPathHeader(capture.stdout, capture.arguments.at(-1))
16+
.split(/\r?\n/u)
17+
.some(
18+
(line) =>
19+
line.trim().replace(/^(?:dyld_info:\s*)/u, "") ===
20+
MISSING_UUID_DIAGNOSTIC,
21+
);
22+
23+
/** Keep the exact target diagnostic beside the incomplete collection. */
24+
export const missingUuidLimitation = (mode: "imports" | "exports"): string =>
25+
mode === "imports"
26+
? "dyld_info -imports reported 'missing LC_UUID load command'; import observations are unavailable."
27+
: "dyld_info -exports reported 'missing LC_UUID load command'; exports include nm symbol-table observations only.";
28+
29+
/** Preserve unrecognized nonzero command output as an inspection failure. */
30+
export const unusableNativeCommandOutput = (
31+
capture: NativeCommandCapture,
32+
): AnalysisOutputError =>
33+
new AnalysisOutputError(
34+
"inspect_macho",
35+
`${capture.tool} did not produce a usable inspection result`,
36+
{
37+
capturedOutput: {
38+
stdout: capture.stdout,
39+
stderr: capture.stderr,
40+
truncated: false,
41+
stdout_bytes: capture.stdoutBytes,
42+
stderr_bytes: capture.stderrBytes,
43+
exit_code: capture.exitCode,
44+
signal: capture.signal,
45+
},
46+
},
47+
);
48+
49+
/** Refuse a recognized error when the independently parsed load table contradicts it. */
50+
export const conflictingUuidCommandEvidence = (
51+
command: NativeCommandCapture,
52+
): AnalysisOutputError =>
53+
new AnalysisOutputError(
54+
"inspect_macho",
55+
"dyld_info reported a missing LC_UUID despite an observed LC_UUID load command",
56+
{
57+
capturedOutput: {
58+
stdout: command.stdout,
59+
stderr: command.stderr,
60+
truncated: false,
61+
stdout_bytes: command.stdoutBytes,
62+
stderr_bytes: command.stderrBytes,
63+
exit_code: command.exitCode,
64+
signal: command.signal,
65+
},
66+
},
67+
);

‎src/native/NativeMachoInspection.ts‎

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ import { withoutEchoedPathHeader } from "./parsers/echoedPath.js";
1919
import { parseOtoolLoadCommands } from "./parsers/otool.js";
2020
import { reconcileMachoUuid } from "./parsers/machoUuid.js";
2121
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
22+
import {
23+
conflictingUuidCommandEvidence,
24+
isMissingUuidDyldFailure,
25+
missingUuidLimitation,
26+
unusableNativeCommandOutput,
27+
} from "./NativeMachoCommandDiagnostics.js";
2228

2329
interface NativeMachoObservation {
2430
readonly result: JsonValue;
@@ -33,6 +39,7 @@ interface NativeMachoInspectionContext {
3339
tool: string,
3440
arguments_: readonly string[],
3541
signal?: AbortSignal,
42+
acceptNonZeroIf?: (capture: NativeCommandCapture) => boolean,
3643
) => Promise<Result<NativeCommandCapture, AnalysisError>>;
3744
readonly invocation: (
3845
capture: NativeCommandCapture,
@@ -100,6 +107,7 @@ export const inspectNativeMacho = async (
100107
context.target.path,
101108
],
102109
context.signal,
110+
tool === "dyld_info" ? isMissingUuidDyldFailure : undefined,
103111
);
104112
// vtool knows no variant subtypes, so no spelling selects an arm64e.x1 slice.
105113
const vtoolSelectsSlice =
@@ -109,11 +117,18 @@ export const inspectNativeMacho = async (
109117
// Every launch settles before return; declared order fixes provenance and
110118
// which failure is reported.
111119
const [required, optional] = await Promise.all([
112-
Promise.all(REQUIRED_SLICE_COMMANDS.map(runSliceCommand)),
120+
Promise.all(
121+
REQUIRED_SLICE_COMMANDS.map((command) => runSliceCommand(command)),
122+
),
113123
vtoolSelectsSlice ? runSliceCommand(OPTIONAL_VTOOL_COMMAND) : null,
114124
]);
115125
for (const captured of required) {
116126
if (!captured.ok) return err(captured.error);
127+
if (
128+
(captured.value.exitCode !== 0 || captured.value.signal !== null) &&
129+
!isMissingUuidDyldFailure(captured.value)
130+
)
131+
return err(unusableNativeCommandOutput(captured.value));
117132
captures.push(captured.value);
118133
}
119134
const limitations: string[] = [];
@@ -132,7 +147,10 @@ export const inspectNativeMacho = async (
132147
// A stripped symbol table (strip -T) can omit names the export trie keeps.
133148
// Only then does llvm-nm's dyld-info pass add names, and its exact names
134149
// disambiguate dyld_info rows, so rerun it rather than lose them.
135-
if (!namesEveryExport(captures[nmIndex]!.stdout, dyldExports)) {
150+
if (
151+
!isMissingUuidDyldFailure(dyldExports) &&
152+
!namesEveryExport(captures[nmIndex]!.stdout, dyldExports)
153+
) {
136154
const withDyldInfo = await runSliceCommand(DYLD_INFO_EXPORTS);
137155
if (!withDyldInfo.ok) return err(withDyldInfo.error);
138156
captures[nmIndex] = withDyldInfo.value;
@@ -162,6 +180,12 @@ export const inspectNativeMacho = async (
162180
),
163181
);
164182
}
183+
const uuidlessDyldFailure = captures.find(isMissingUuidDyldFailure);
184+
if (
185+
uuidlessDyldFailure !== undefined &&
186+
load.commands.some(({ kind }) => kind === "LC_UUID")
187+
)
188+
return err(conflictingUuidCommandEvidence(uuidlessDyldFailure));
165189
const selectedArchitectureName =
166190
selectedArchitecture ??
167191
(architectures.length === 1 ? (architectures[0]?.name ?? null) : null);
@@ -218,21 +242,26 @@ const normalizeMacho = (
218242
},
219243
) => {
220244
const byTool = captureLookup(captures);
221-
const imports = parseDyldSymbols(
222-
sliceOutput(byTool("dyld_info", 0)),
223-
"imports",
224-
);
245+
const dyldImportsCapture = byTool("dyld_info", 0);
246+
const dyldExportsCapture = byTool("dyld_info", 1);
247+
const missingImportsUuid = isMissingUuidDyldFailure(dyldImportsCapture);
248+
const missingExportsUuid = isMissingUuidDyldFailure(dyldExportsCapture);
249+
const imports = missingImportsUuid
250+
? []
251+
: parseDyldSymbols(sliceOutput(dyldImportsCapture), "imports");
225252
const imageBase =
226253
load.segments.find(
227254
(segment) => segment.file_offset === 0 && (segment.file_size ?? 0) > 0,
228255
)?.vm_address ?? null;
229256
const nmExports = parseNmExports(byTool("nm").stdout);
230-
const dyldExports = parseDyldSymbols(
231-
sliceOutput(byTool("dyld_info", 1)),
232-
"exports",
233-
imageBase,
234-
new Set(nmExports.map(({ name }) => name)),
235-
);
257+
const dyldExports = missingExportsUuid
258+
? []
259+
: parseDyldSymbols(
260+
sliceOutput(dyldExportsCapture),
261+
"exports",
262+
imageBase,
263+
new Set(nmExports.map(({ name }) => name)),
264+
);
236265
const exports = uniqueSymbols([...dyldExports, ...nmExports]);
237266
const dwarfdump = byTool("dwarfdump");
238267
const uuid = reconcileMachoUuid(
@@ -268,6 +297,8 @@ const normalizeMacho = (
268297
]
269298
: []),
270299
...additionalLimitations,
300+
...(missingImportsUuid ? [missingUuidLimitation("imports")] : []),
301+
...(missingExportsUuid ? [missingUuidLimitation("exports")] : []),
271302
...uuid.limitations,
272303
...(threadEntrypoint ? [threadEntrypointLimitation] : []),
273304
...(imageBase === null &&
@@ -296,9 +327,14 @@ const normalizeMacho = (
296327
dependencies: covered(load.dependencies, true),
297328
imports: covered(imports, false, [
298329
"dyld_info textual imports may omit chained or toolchain-unsupported metadata.",
330+
...(missingImportsUuid ? [missingUuidLimitation("imports")] : []),
299331
]),
300332
exports: covered(exports, false, [
301-
"Merged nm/dyld_info results may be incomplete for stripped binaries.",
333+
...(missingExportsUuid
334+
? [missingUuidLimitation("exports")]
335+
: [
336+
"Merged nm/dyld_info results may be incomplete for stripped binaries.",
337+
]),
302338
...(dyldExports.some(({ sourceSymbol }) => sourceSymbol !== undefined)
303339
? [
304340
"Renamed re-exports are listed under their exported name; the source library's symbol name is not reported.",
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { join } from "node:path";
2+
import { writeFile } from "node:fs/promises";
3+
4+
import { describe, expect } from "vitest";
5+
6+
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
7+
import { parseEvidence } from "../../../src/domain/evidence.js";
8+
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
9+
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
10+
import { cliTest } from "../../support/cli/cliFixture.js";
11+
12+
describe.skipIf(process.platform !== "darwin")(
13+
"native Mach-O CLI without LC_UUID",
14+
() => {
15+
cliTest(
16+
"returns readable facts with partial dyld coverage and preserves controls",
17+
async ({ cli, processes }) => {
18+
const directory = await createTestTempDirectory("rea-macho-no-uuid-");
19+
const source = join(directory, "probe.c");
20+
const probe = join(directory, "probe");
21+
const control = join(directory, "control");
22+
const object = join(directory, "probe.o");
23+
await writeFile(
24+
source,
25+
"int exported_add(int a, int b) { return a + b; }\nint main(void) { return exported_add(1, 2); }\n",
26+
);
27+
for (const arguments_ of [
28+
["clang", "-Wl,-no_uuid", "-o", probe, source],
29+
["clang", "-o", control, source],
30+
["clang", "-c", source, "-o", object],
31+
]) {
32+
const compiled = await processes.run("/usr/bin/xcrun", arguments_, {
33+
timeoutMs: 30_000,
34+
});
35+
expect(compiled.exitCode, compiled.stderr).toBe(0);
36+
}
37+
38+
const inspect = async (path: string) => {
39+
const result = await cli.run({
40+
arguments: ["inspect-macho", path, "--json"],
41+
environment: { REA_LOG_LEVEL: "silent" },
42+
});
43+
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
44+
return inspectMachoSchema.parse(
45+
(result.json as { normalized_result?: unknown }).normalized_result,
46+
);
47+
};
48+
49+
const missingUuid = await inspect(probe);
50+
expect(missingUuid).toMatchObject({
51+
uuid: null,
52+
load_commands: { exhaustive: true },
53+
imports: {
54+
items: [],
55+
total: null,
56+
exhaustive: false,
57+
limitations: expect.arrayContaining([
58+
expect.stringContaining(
59+
"dyld_info -imports reported 'missing LC_UUID load command'",
60+
),
61+
]),
62+
},
63+
exports: {
64+
items: expect.arrayContaining([
65+
expect.objectContaining({ name: "_exported_add", source: "nm" }),
66+
expect.objectContaining({ name: "_main", source: "nm" }),
67+
]),
68+
total: null,
69+
exhaustive: false,
70+
},
71+
provenance: expect.arrayContaining([
72+
expect.objectContaining({
73+
tool: "dyld_info",
74+
exit: { code: 1, signal: null },
75+
}),
76+
]),
77+
});
78+
expect(missingUuid.limitations).toContain(
79+
"dyld_info -exports reported 'missing LC_UUID load command'; exports include nm symbol-table observations only.",
80+
);
81+
82+
const normalControl = await inspect(control);
83+
expect(normalControl.uuid).not.toBeNull();
84+
expect(normalControl.load_commands.exhaustive).toBe(true);
85+
86+
const objectControl = await inspect(object);
87+
expect(objectControl.uuid).toBeNull();
88+
expect(objectControl.load_commands.exhaustive).toBe(true);
89+
90+
const { call } = await connectLocalToolsMcp({ HOME: directory });
91+
const opened = await call("open_binary", { path: probe });
92+
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
93+
const mcp = await call("inspect_macho", { detail: "complete" });
94+
expect(mcp.isError, JSON.stringify(mcp)).not.toBe(true);
95+
const report = inspectMachoSchema.parse(
96+
parseEvidence(mcp.structuredContent).normalized_result,
97+
);
98+
expect(report.uuid).toBeNull();
99+
expect(report.imports).toEqual(missingUuid.imports);
100+
expect(report.exports).toEqual(missingUuid.exports);
101+
expect(report.load_commands).toEqual(missingUuid.load_commands);
102+
expect((await call("close_binary", {})).isError).not.toBe(true);
103+
},
104+
);
105+
},
106+
);

0 commit comments

Comments
 (0)