fix: bind identity and coverage to the producing rule (#1513)

* fix: bind identity and coverage to the producing rule

Logical paths, container families, examined bytes, path-segment conventions, destination collisions, file-id leases, Mach-O CPU selection, and firmware cleanup now follow the observation that owns each rule.

* fix: fail unmatched Mach-O slices and keep firmware roots independent

A fat target whose architecture lipo did not list now stops before slice tools run. Chained fixups still count unread LC_DYLD_INFO rebase bytes, and a firmware cleanup failure no longer blocks the next workspace.

* test: cover path identity and runtime families at the projection boundary

NFC joins and segment conventions are now asserted by the path resolver, the Apple projection, and a real APK inventory instead of helper unit tests.

* test: expect unread dyld rebase bytes in the Apple dispatch fixture

The legacy LC_DYLD_INFO fixture keeps a rebase range this reader does not decode, so the public CLI and MCP check now requires that partial coverage beside the bind opcodes.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
morluto
2026-10-10 17:14:47 +08:00
committed by GitHub
co-authored by Cursor Agent
parent 7a56fe6260
commit b4db35f092
48 changed files with 1251 additions and 266 deletions
+31 -15
View File
@@ -4,11 +4,19 @@ import type { DecodeIssue } from "./AppleDispatchDecodeFacts.js";
import type { FacetDecodeFacts } from "./AppleDispatchDecodeFacts.js";
const describeFixups = (fixups: PointerFixups): string => {
if (fixups.kind === "chained")
return `chained fixups: ${fixups.formats.join(", ") || "no fixup segments"}`;
return fixups.kind === "dyld-info"
? "LC_DYLD_INFO bind opcodes"
: "no fixup load commands";
const unread =
fixups.unreadRebaseBytes > 0
? `LC_DYLD_INFO rebase opcodes were not decoded (${fixups.unreadRebaseBytes} bytes)`
: undefined;
const kind =
fixups.kind === "chained"
? `chained fixups: ${fixups.formats.join(", ") || "no fixup segments"}`
: fixups.kind === "dyld-info"
? "LC_DYLD_INFO bind opcodes"
: unread === undefined
? "no fixup load commands"
: undefined;
return [unread, kind].filter((line) => line !== undefined).join("; ");
};
/** Append the per-facet coverage of one Apple dispatch metadata decode. */
@@ -83,18 +91,26 @@ export const pushDispatchCoverage = (input: {
({ decode }) => decode.status === "decoded",
).length,
});
const fixupReason = [
describeFixups(fixups),
...fixups.issues.map(
({ code, location, message }) =>
`${code}${location === undefined ? "" : ` at ${location}`}: ${message}`,
),
]
.filter((line) => line.length > 0)
.join("; ");
result.coverage.push({
facet: "pointer_fixups",
status: fixups.issues.length > 0 ? "partial" : "complete",
reason: [
describeFixups(fixups),
...fixups.issues.map(
({ code, location, message }) =>
`${code}${location === undefined ? "" : ` at ${location}`}: ${message}`,
),
].join("; "),
examined: 0,
decoded: 0,
status:
fixups.issues.length > 0 || fixups.unreadRebaseBytes > 0
? "partial"
: fixups.examined === 0
? "unsupported"
: "complete",
reason: fixupReason.length > 0 ? fixupReason : null,
examined: fixups.examined,
decoded: fixups.issues.length > 0 ? 0 : fixups.examined,
});
result.coverage.push({
facet: "swift_generic_resilient_witnesses_overrides_async_coroutines",
+1 -1
View File
@@ -354,7 +354,7 @@ describe("byte-swapped universal Apple dispatch metadata", () => {
const bytes = wrapped(false);
bytes.writeUInt32BE(0xfeedface, 256);
expect(() => decodeAppleDispatchMetadata(bytes, 100, provenance)).toThrow(
"Only little-endian 64-bit Mach-O metadata is supported",
"Unsupported 32-bit Mach-O metadata for requested CPU type arm64 (FAT header byte order: little-endian)",
);
});
+33 -2
View File
@@ -149,13 +149,37 @@ describe("pointer fixup tables", () => {
data.writeUInt16LE(99, 46);
const fixups = parsePointerFixups(
data,
{ chained: { offset: 0, size: data.length }, binds: [], dylibs: [] },
{
chained: { offset: 0, size: data.length },
binds: [],
rebases: [],
dylibs: [],
},
SEGMENTS,
BASE,
);
expect(fixups.failures).toContain("Unsupported chained pointer format 99");
});
it("keeps unread LC_DYLD_INFO rebase bytes when chained fixups are present", () => {
const data = chainedData(1);
const fixups = parsePointerFixups(
data,
{
chained: { offset: 0, size: data.length },
binds: [],
rebases: [{ offset: 8, size: 12 }],
dylibs: [],
},
SEGMENTS,
BASE,
);
expect(fixups).toMatchObject({
kind: "chained",
unreadRebaseBytes: 12,
});
});
it("does not decode unreferenced imports while constructing fixup facts", () => {
const data = chainedData(1);
// The second import is outside the table bytes; only the first is needed
@@ -164,7 +188,12 @@ describe("pointer fixup tables", () => {
expect(() =>
parsePointerFixups(
data,
{ chained: { offset: 0, size: data.length }, binds: [], dylibs: [] },
{
chained: { offset: 0, size: data.length },
binds: [],
rebases: [],
dylibs: [],
},
SEGMENTS,
BASE,
),
@@ -179,6 +208,7 @@ describe("pointer fixup tables", () => {
{
chained: { offset: 0, size: data.length },
binds: [],
rebases: [],
dylibs: ["/usr/lib/libobjc.A.dylib", "/usr/lib/libSystem.B.dylib"],
},
SEGMENTS,
@@ -241,6 +271,7 @@ describe("pointer fixup tables", () => {
{ offset: 0, size: opcodes.length, stream: "bind" },
{ offset: opcodes.length, size: lazy.length, stream: "lazy" },
],
rebases: [],
dylibs: ["/usr/lib/libobjc.A.dylib", "/usr/lib/libSystem.B.dylib"],
},
SEGMENTS,
+25 -1
View File
@@ -6,6 +6,11 @@ import type { DecodeIssue } from "./AppleDispatchDecodeFacts.js";
export interface FixupCommands {
/** Absolute file range of `LC_DYLD_CHAINED_FIXUPS` data. */
readonly chained: { readonly offset: number; readonly size: number } | null;
/** Absolute file ranges of `LC_DYLD_INFO(_ONLY)` rebase streams. */
readonly rebases: readonly {
readonly offset: number;
readonly size: number;
}[];
/** Absolute file ranges of `LC_DYLD_INFO(_ONLY)` bind streams. */
readonly binds: readonly {
readonly offset: number;
@@ -35,6 +40,10 @@ export interface PointerFixups {
readonly formats: readonly string[];
readonly failures: readonly string[];
readonly issues: readonly DecodeIssue[];
/** Fixup segments or bind streams this reader walked. */
readonly examined: number;
/** Rebase opcode bytes present in the load command and not decoded. */
readonly unreadRebaseBytes: number;
/** Decode the pointer stored at `address` whose raw 64-bit value is `raw`. */
decode(address: bigint, raw: bigint): DecodedPointer;
}
@@ -250,6 +259,8 @@ const chainedFixups = (
formats,
failures: issues.map(({ message }) => message),
issues,
examined: Math.max(ranges.length, 1),
unreadRebaseBytes: 0,
decode(address, raw) {
const segment = ranges.find(
({ from, to }) => address >= from && address < to,
@@ -420,13 +431,24 @@ export const parsePointerFixups = (
baseAddress: bigint,
): PointerFixups => {
const image = { bytes, segments, dylibs: commands.dylibs, baseAddress };
if (commands.chained !== null) return chainedFixups(image, commands.chained);
const unreadRebaseBytes = commands.rebases.reduce(
(total, rebase) => total + rebase.size,
0,
);
if (commands.chained !== null) {
const chained = chainedFixups(image, commands.chained);
return unreadRebaseBytes === 0
? chained
: { ...chained, unreadRebaseBytes };
}
if (commands.binds.length === 0)
return {
kind: "none",
formats: [],
failures: [],
issues: [],
examined: 0,
unreadRebaseBytes,
decode: (_address, raw) => ({ kind: "rebase", target: raw }),
};
const binds = new Map<bigint, Import>();
@@ -446,6 +468,8 @@ export const parsePointerFixups = (
issues: failures.map((message) =>
issue("pointer_fixups", "bind_stream_decode_failed", message),
),
examined: commands.binds.length,
unreadRebaseBytes,
decode(address, raw) {
const bound = binds.get(address);
return bound === undefined
+21
View File
@@ -16,6 +16,27 @@ describe("native Mach-O slice selection", () => {
expect(parseMachoLayout(Buffer.from(fat), "arm64").segments).toEqual([]);
});
it("selects only the admitted CPU type and rejects a 32-bit slice", () => {
const sixtyFour = fatImage([
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
]);
expect(() => parseMachoLayout(Buffer.from(sixtyFour), "x86")).toThrow(
/Requested FAT architecture is absent/u,
);
expect(() => parseMachoLayout(Buffer.from(sixtyFour), "arm")).toThrow(
/Requested FAT architecture is absent/u,
);
const thirtyTwo = fatImage([
{
cpu: CPU.i386,
bytes: machoImage({ cpu: CPU.i386, wide: false }),
},
]);
expect(() => parseMachoLayout(Buffer.from(thirtyTwo), "x86")).toThrow(
/Unsupported 32-bit Mach-O metadata for requested CPU type x86/u,
);
});
it("rejects FAT subtype disagreement and unaligned slice offsets", () => {
const original = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
const mismatched = original.slice();
+25 -3
View File
@@ -90,7 +90,8 @@ export const selectMachoSlice = (
const headerEnd = 8 + count * stride;
if (count > 128 || headerEnd > bytes.length)
throw malformed("Malformed FAT architecture table");
const cpu = architecture === "arm64" ? 0x0100000c : 0x01000007;
const cpu = MACHO_CPU_TYPE[architecture];
if (cpu === undefined) throw invalid("Requested FAT architecture is absent");
const declarations = readFatSliceDeclarations(bytes.subarray(8, headerEnd), {
count,
wide: fat64,
@@ -115,9 +116,26 @@ export const selectMachoSlice = (
}
if (selected === undefined)
throw invalid("Requested FAT architecture is absent");
if (selected.slice + 4 > bytes.length)
throw malformed("Truncated Mach-O header");
const sliceMagic = bytes.readUInt32LE(selected.slice);
if (sliceMagic === MH_MAGIC || sliceMagic === MH_CIGAM)
throw invalid(
`Unsupported 32-bit Mach-O metadata for requested CPU type ${architecture}`,
);
return selected;
};
/** CPU types admitted by `machArchitecture` in the domain binary target parser. */
const MACHO_CPU_TYPE: Readonly<Record<string, number>> = {
x86: 7,
x86_64: 0x01000007,
arm: 12,
arm64: 0x0100000c,
};
const MH_MAGIC = 0xfeedface;
const MH_CIGAM = 0xcefaedfe;
/** Parse segments/sections for a little-endian 64-bit Mach-O architecture slice. */
export const parseMachoLayout = (
bytes: Buffer,
@@ -151,6 +169,7 @@ export const parseMachoLayout = (
sections: [],
dylibs: [],
binds: [],
rebases: [],
chained: null,
baseAddress: undefined,
};
@@ -168,7 +187,7 @@ export const parseMachoLayout = (
else collectFixupCommand(bytes, command, state);
cursor += command.size;
}
const { segments, sections, chained, binds, dylibs } = state;
const { segments, sections, chained, binds, rebases, dylibs } = state;
const offset = (address: bigint, size = 1): number => {
const matches = segments.filter(
(segment) =>
@@ -187,7 +206,7 @@ export const parseMachoLayout = (
segments,
sections,
offset,
fixups: { chained, binds, dylibs },
fixups: { chained, binds, rebases, dylibs },
baseAddress: state.baseAddress ?? 0n,
};
};
@@ -200,6 +219,7 @@ interface LayoutState {
readonly sections: Section[];
readonly dylibs: string[];
readonly binds: FixupCommands["binds"][number][];
readonly rebases: FixupCommands["rebases"][number][];
chained: FixupCommands["chained"];
baseAddress: bigint | undefined;
}
@@ -273,6 +293,8 @@ const collectFixupCommand = (
state.chained = range(cursor + 8);
} else if (kind === LC_DYLD_INFO || kind === LC_DYLD_INFO_ONLY) {
if (size < 48) throw new RangeError("Truncated dyld-info command");
const rebase = range(cursor + 8);
if (rebase.size > 0) state.rebases.push(rebase);
for (const [at, stream] of [
[cursor + 16, "bind"],
[cursor + 24, "weak"],
+4
View File
@@ -66,6 +66,8 @@ describe("Swift vtable coverage facts: unresolved Swift dispatch slots", () => {
failures: [],
issues: [],
decode: (_address, raw) => ({ kind: "rebase", target: raw }),
examined: 0,
unreadRebaseBytes: 0,
},
swift: {
facet: "swift_conformances_static_witness_slots",
@@ -178,6 +180,8 @@ describe("Swift vtable coverage facts: unsupported pointer fixup coverage", () =
kind: "unsupported",
reason: "Unsupported chained pointer format 99",
}),
examined: 0,
unreadRebaseBytes: 0,
},
swift: {
facet: "swift_conformances_static_witness_slots",
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { inspectNativeMacho } from "./NativeMachoInspection.js";
const capture = (tool: string, stdout: string): NativeCommandCapture => ({
tool,
executable: tool,
executableSha256: "a".repeat(64),
toolVersion: null,
versionReason: null,
arguments: [],
stdout,
stderr: "",
stdoutBytes: stdout.length,
stderrBytes: 0,
exitCode: 0,
signal: null,
});
const inspect = async (lipo: string, architecture: "x86" | "arm64") => {
const commands: {
readonly tool: string;
readonly args: readonly string[];
}[] = [];
const result = await inspectNativeMacho({
target: {
kind: "executable",
format: "mach-o",
path: "/fixture/app",
sha256: "b".repeat(64),
architecture,
availableArchitectures: ["x86", "arm64"],
},
run: (tool, args) => {
commands.push({ tool, args });
if (tool === "lipo") return Promise.resolve(ok(capture(tool, lipo)));
if (tool === "file") return Promise.resolve(ok(capture(tool, "Mach-O")));
return Promise.resolve(err(new AnalysisCancelledError("inspect_native")));
},
invocation: () => {
throw new Error("invocation is not reached");
},
});
return { result, commands };
};
describe("Mach-O tool architecture selection", () => {
it("rejects a CPU lipo did not list instead of reading another slice", async () => {
const { result, commands } = await inspect("architecture arm64\n", "x86");
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
_tag: "AnalysisOutputError",
reason: "lipo did not list i386; refusing to read another slice",
});
expect(commands.map(({ tool }) => tool)).toEqual(["file", "lipo"]);
});
it("passes the arm64e slice lipo listed for an arm64 target", async () => {
const { commands } = await inspect("architecture arm64e\n", "arm64");
const otool = commands.find(({ tool }) => tool === "otool");
expect(otool?.args).toEqual([
"-h",
"-l",
"-arch",
"arm64e",
"/fixture/app",
]);
});
});
+27 -9
View File
@@ -1,6 +1,7 @@
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import {
inspectMachoSchema,
type NativeCommandInvocation,
@@ -65,10 +66,19 @@ export const inspectNativeMacho = async (
}
const lipo = captures.find(({ tool }) => tool === "lipo");
if (lipo === undefined) throw new TypeError("Missing lipo capture");
const selectedArchitecture = selectArchitecture(
context.target,
parseLipoArchitectures(lipo.stdout).map(({ name }) => name),
const availableArchitectures = parseLipoArchitectures(lipo.stdout).map(
({ name }) => name,
);
const selection = selectArchitecture(context.target, availableArchitectures);
if (selection.status === "absent")
return err(
new AnalysisOutputError(
"inspect_macho",
`lipo did not list ${selection.architecture}; refusing to read another slice`,
),
);
const selectedArchitecture =
selection.status === "selected" ? selection.architecture : null;
for (const [tool, prefix] of REQUIRED_SLICE_COMMANDS) {
const captured = await context.run(
tool,
@@ -339,24 +349,32 @@ const selectedArchitectureArguments = (
: ["-arch", toolArchitecture];
};
type ArchitectureSelection =
| { readonly status: "unfiltered" }
| { readonly status: "selected"; readonly architecture: string }
| { readonly status: "absent"; readonly architecture: string };
const selectArchitecture = (
target: BinaryTarget,
available: readonly string[],
): string | null => {
): ArchitectureSelection => {
if (target.kind !== "executable" || target.availableArchitectures.length < 2)
return null;
return { status: "unfiltered" };
const normalized =
target.architecture === "x86" ? "i386" : target.architecture;
if (available.includes(normalized)) return normalized;
if (available.includes(normalized))
return { status: "selected", architecture: normalized };
// BinaryTarget intentionally normalizes ARM64 CPU subtypes. Recover the
// concrete arm64e slice name from lipo before invoking slice-aware tools.
if (normalized === "arm64") {
const arm64e = available.find((architecture) => architecture === "arm64e");
if (arm64e !== undefined) return arm64e;
if (arm64e !== undefined)
return { status: "selected", architecture: arm64e };
const variant = available.find((architecture) =>
/^arm64e\.[A-Za-z0-9_]+$/u.test(architecture),
);
if (variant !== undefined) return variant;
if (variant !== undefined)
return { status: "selected", architecture: variant };
}
return normalized;
return { status: "absent", architecture: normalized };
};