Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
4d3b7a1
feat(ghidra): admit caller-selected matching dSYM companions
jimpablo Oct 12, 2026
f0eb9c4
fix(targets): partition dSYM identity and match the selected slice
jimpablo Oct 12, 2026
104601e
fix(targets): keep legacy query ids and bound companion admission
jimpablo Oct 12, 2026
c219cb9
fix(targets): bound uuid walking and carry companion provenance
jimpablo Oct 12, 2026
ab3bf42
fix(contracts): budget command spans and partition companions by path
jimpablo Oct 12, 2026
11e1002
fix(ghidra): commit companion identity in the analysis profile
jimpablo Oct 12, 2026
731f243
fix(targets): carry companion identity through split mach-o variants
jimpablo Oct 12, 2026
03f9058
fix(targets): charge traversal reads and bound staged member copies
jimpablo Oct 13, 2026
d3fe4a0
fix(ghidra): document and enforce dSYM admission resource budgets
morluto Oct 13, 2026
dbf8d2c
fix(ghidra): preserve dSYM resource refusals and staging coverage
morluto Oct 13, 2026
dea1571
fix(ghidra): stream dSYM UUID commands through their format owner
morluto Oct 13, 2026
437eb2d
fix(ghidra): retain dSYM input ownership and shared format semantics
morluto Oct 13, 2026
26effd7
fix(ghidra): preserve dSYM companion admission facts
morluto Oct 13, 2026
0ab02a0
fix(ghidra): retain failed source copy owners
morluto Oct 13, 2026
58af2fb
fix(targets): settle merged companion types and heap stub props
jimpablo Oct 14, 2026
7bafafc
fix(macho): retain dSYM admission resources
morluto Oct 13, 2026
71cee08
fix(ghidra): preserve dSYM identity and cleanup failures
morluto Oct 13, 2026
7e7d3d2
fix(targets): settle merged types, heap stub props, and split oversiz…
jimpablo Oct 14, 2026
b735fd3
fix(ghidra): rebase onto main, drop hanging copy helper, restore staging
jimpablo Oct 27, 2026
529d444
fix(targets): settle second rebase: weave dsym admission into new res…
jimpablo Oct 28, 2026
07da6f1
fix(targets): restore upstream code dropped during rebase
jimpablo Oct 28, 2026
1a2fa6a
fix(contracts): omit debug_companion from bare Mach-O summaries
jimpablo Oct 28, 2026
0b4ae16
fix(targets): address companion admission review findings
jimpablo Oct 28, 2026
aa20d1d
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
6b32456
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
4483d21
fix(ghidra): harden dSYM companion admission, staging ownership, and …
jimpablo Nov 5, 2026
a7e17e6
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
d90dcca
fix(ghidra): preserve dSYM cleanup primary causes and reuse Mach-O lo…
jimpablo Nov 5, 2026
8bec33a
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
c50d6f5
fix(ghidra): reject dsym_path in existing-project mode and enforce de…
jimpablo Nov 5, 2026
636d664
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
30e21fa
fix(macho): separate companion EOF truncation from traversal budget a…
jimpablo Nov 5, 2026
97a2e09
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 5, 2026
fbef489
fix(cli): reuse absoluteLocalPathStringSchema for --dsym-path option
jimpablo Nov 5, 2026
f51fb61
fix(macho): clamp initial UUID prefix reads to remaining traversal bu…
jimpablo Nov 5, 2026
2c150cb
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 8, 2026
417b628
fix(dsym): enforce .dSYM bundle directory naming and pin companion di…
jimpablo Nov 8, 2026
0988275
fix(dsym): preserve close cancellation, reject ambiguous FAT slices, …
jimpablo Nov 8, 2026
390918f
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 8, 2026
a0cac2a
fix(dsym): preserve close cancellation during directory and staging c…
jimpablo Nov 8, 2026
a84c8a8
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 8, 2026
6a32f35
fix(dsym): preserve member and directory refusals over final-close ca…
jimpablo Nov 8, 2026
c72fb30
docs(specs): add Mach-O dSYM companion feature specification
jimpablo Nov 8, 2026
dd33451
docs(specs): align module and checkpoint test paths in dsym plan
jimpablo Nov 8, 2026
a6f3b94
docs(specs): match symlink policy and saved-project error contract
jimpablo Nov 8, 2026
ca7d919
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 8, 2026
c50bf0d
fix(dsym): skip checkpoint restaging and harden companion identity
jimpablo Nov 8, 2026
2152709
test(mcp): validate session dsym_path outputs via toolContract
jimpablo Nov 8, 2026
4d3ad8f
fix(dsym): retain both companion and target cleanup owners on dual cl…
jimpablo Nov 8, 2026
57f2edc
fix(dsym): reject duplicate FAT target CPU identities before slice na…
jimpablo Nov 8, 2026
9560a44
fix(dsym): keep post-admission member read faults fatal across close …
jimpablo Nov 9, 2026
9f36e1f
fix(dsym): use tagged member failure union and guard opaque abort rea…
jimpablo Nov 9, 2026
bdd456e
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 10, 2026
616d5dc
chore(dsym): merge upstream/main and remove unused imports
jimpablo Nov 10, 2026
3f8c9ce
chore(dsym): restore upstream files modified by lint-staged during merge
jimpablo Nov 10, 2026
92d9d79
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 11, 2026
b244242
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 15, 2026
ea7612b
fix(contracts): preserve headerless issues alongside dsym_path and ex…
jimpablo Nov 15, 2026
03b3ff8
chore(dsym): restore upstream javascriptStaticAnalysis modified by li…
jimpablo Nov 15, 2026
4d761f9
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 16, 2026
858d124
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 16, 2026
65d40a3
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 17, 2026
b32d1bf
Merge remote-tracking branch 'upstream/main' into feat/dsym-companion…
jimpablo Nov 21, 2026
cbddb9d
test(target): verify dsym_path rejection on Hopper and IDA databases
jimpablo Nov 21, 2026
336d28c
fix(ghidra): preserve dSYM parse failures, refusals, and staging owne…
jimpablo Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(targets): partition dSYM identity and match the selected slice
  • Loading branch information
jimpablo committed Oct 28, 2026
commit f0eb9c484761461148c5f6b54d9be065eceee46f
182 changes: 115 additions & 67 deletions src/application/DebugCompanionAdmission.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { constants, type Stats } from "node:fs";
import { open, readdir, stat } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import type { FileHandle } from "node:fs/promises";

import { err, ok, type Result } from "../domain/result.js";
import type { MachODebugCompanion } from "../domain/binaryTargetTypes.js";
import type {
BinaryArchitecture,
MachODebugCompanion,
} from "../domain/binaryTargetTypes.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
debugCompanionMatches,
readMachoUuids,
readMachoUuidEntries,
type MachOUuidEntry,
} from "../domain/machoDebugCompanion.js";

/** Bound on the bytes read to walk Mach-O headers and load commands. */
const HEADER_READ_LIMIT = 64 * 1024;

const DSYM_DWARF_DIRECTORY = join("Contents", "Resources", "DWARF");

/**
* Mach-O cputypes for the provider-neutral CPU families REA admits, including
* the 64-bit flag the ABI sets on x86_64 and arm64. MIPS has no Mach-O
* cputype; a companion can never match it.
*/
const CPU_TYPES: Readonly<Record<BinaryArchitecture, readonly number[]>> = {
x86: [0x00000007],
x86_64: [0x01000007],
arm: [0x0000000c],
arm64: [0x0100000c],
mips: [],
};

/** Admitted identity of a caller-selected dSYM companion. */
export type DebugCompanionAdmission = Result<
MachODebugCompanion,
Expand All @@ -27,6 +45,11 @@ export interface DebugCompanionRejection {
readonly reason: string;
}

const throwIfCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true)
throw new AnalysisCancelledError("resolve_binary_target");
};
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

const readUuidWindow = async (
handle: FileHandle,
offset: number,
Expand All @@ -38,34 +61,29 @@ const readUuidWindow = async (
};

/**
* Read every LC_UUID of a Mach-O file: a thin image from its start, or each
* slice of a universal container from its table.
* Read every LC_UUID of a Mach-O file with its declaring cputype: a thin
* image from its start, or each slice of a universal container from its table.
*/
export const readMachoFileUuids = async (
export const readMachoFileUuidEntries = async (
handle: FileHandle,
fileSize: number,
): Promise<Result<string[], string>> => {
): Promise<Result<MachOUuidEntry[], string>> => {
const prefix = await readUuidWindow(handle, 0, fileSize);
if (!prefix.ok) return prefix;
const magic = prefix.value.length >= 4 ? prefix.value.readUInt32BE(0) : 0;
if (magic !== 0xcafebabe && magic !== 0xcafebabf) {
const thin = readMachoUuids(prefix.value);
return thin.ok && thin.value.length > 0
? thin
: thin.ok
? err("the Mach-O target declares no LC_UUID")
: thin;
}
if (magic !== 0xcafebabe && magic !== 0xcafebabf)
return readMachoUuidEntries(prefix.value);
Comment thread
morluto marked this conversation as resolved.
Resolved
const wide = magic === 0xcafebabf;
if (prefix.value.length < 8)
return err("the universal Mach-O container header is truncated");
const count = prefix.value.readUInt32BE(4);
const entrySize = wide ? 32 : 20;
if (count > 128 || 8 + count * entrySize > prefix.value.length)
return err("the universal Mach-O container table is truncated");
const uuids: string[] = [];
const entries: MachOUuidEntry[] = [];
for (let index = 0; index < count; index += 1) {
Comment thread
morluto marked this conversation as resolved.
Resolved
const entry = 8 + index * entrySize;
const cpuType = prefix.value.readInt32BE(entry);
const sliceOffset = wide
? Number(prefix.value.readBigUInt64BE(entry + 8))
: prefix.value.readUInt32BE(entry + 8);
Expand All @@ -76,54 +94,71 @@ export const readMachoFileUuids = async (
return err("a universal Mach-O slice is out of file bounds");
const slice = await readUuidWindow(handle, sliceOffset, sliceSize);
if (!slice.ok) return slice;
const read = readMachoUuids(slice.value);
const read = readMachoUuidEntries(slice.value);
if (!read.ok) return read;
uuids.push(...read.value);
for (const item of read.value) entries.push({ cpuType, uuid: item.uuid });
}
return ok(uuids);
return ok(entries);
};

const digestFile = async (path: string): Promise<string> => {
const handle = await open(path, constants.O_RDONLY);
try {
const hash = createHash("sha256");
const chunk = Buffer.allocUnsafe(64 * 1024);
let position = 0;
for (;;) {
const observed = await handle.read(chunk, 0, chunk.length, position);
if (observed.bytesRead === 0) break;
hash.update(chunk.subarray(0, observed.bytesRead));
position += observed.bytesRead;
}
return hash.digest("hex");
} finally {
await handle.close();
const sameFile = (initial: Stats, observed: Stats): boolean =>
initial.dev === observed.dev &&
initial.ino === observed.ino &&
initial.size === observed.size &&
initial.mtimeMs === observed.mtimeMs;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

/**
* Digest a DWARF member through the same handle its UUID was read from, so a
* member atomically replaced on disk cannot pair another file's digest with
* the validated UUID. The read loop honors cancellation between chunks.
*/
const digestOpenHandle = async (
handle: FileHandle,
initial: Stats,
signal: AbortSignal | undefined,
): Promise<Result<string, string>> => {
const hash = createHash("sha256");
const chunk = Buffer.allocUnsafe(64 * 1024);
let position = 0;
while (position < initial.size) {
throwIfCancelled(signal);
const observed = await handle.read(chunk, 0, chunk.length, position);
if (observed.bytesRead === 0) break;
hash.update(chunk.subarray(0, observed.bytesRead));
position += observed.bytesRead;
}
const opened = await handle.stat();
if (!sameFile(initial, opened))
return err("the dSYM DWARF member changed while being read");
return ok(hash.digest("hex"));
};

/**
* Admit a caller-selected dSYM bundle for a detected Mach-O target: the
* bundle must contain a DWARF member whose LC_UUID matches a UUID of the
* target image. Only the matched member is retained for staging.
* bundle must contain a DWARF member whose LC_UUID matches the UUID of the
* target image slice REA selected for the requested architecture. Only the
* matched member is retained for staging; a non-Mach-O or unreadable member
* candidate (for example `.DS_Store`) is skipped, not fatal.
*/
export const admitDebugCompanion = async (input: {
readonly dsymPath: string;
readonly targetHandle: FileHandle;
readonly targetSize: number;
readonly architecture: BinaryArchitecture;
readonly signal?: AbortSignal;
}): Promise<DebugCompanionAdmission> => {
const { dsymPath } = input;
const { dsymPath, signal } = input;
throwIfCancelled(signal);
if (!isAbsolute(dsymPath))
return err({
reason:
"dsym_path must be an absolute local filesystem path to a .dSYM bundle",
});
let bundle: Awaited<ReturnType<typeof stat>>;
let bundle: Stats;
try {
bundle = await stat(dsymPath);
} catch {
return err({
reason: `dsym_path is not readable: ${dsymPath}`,
});
return err({ reason: `dsym_path is not readable: ${dsymPath}` });
}
if (!bundle.isDirectory())
return err({
Expand All @@ -138,53 +173,66 @@ export const admitDebugCompanion = async (input: {
reason: `dsym_path has no Contents/Resources/DWARF member directory: ${dsymPath}`,
});
Comment thread
morluto marked this conversation as resolved.
Resolved
}
const members: string[] = [];
const memberPaths: string[] = [];
for (const name of names) {
const memberPath = join(dwarfDirectory, name);
const memberStat = await stat(memberPath).catch(() => undefined);
Comment thread
morluto marked this conversation as resolved.
Resolved
if (memberStat?.isFile() === true) members.push(memberPath);
if (memberStat?.isFile() === true) memberPaths.push(memberPath);
}
if (members.length === 0)
if (memberPaths.length === 0)
return err({
reason: `dsym_path contains no DWARF member file: ${dsymPath}`,
});
const targetUuids = await readMachoFileUuids(
const targetEntries = await readMachoFileUuidEntries(
input.targetHandle,
input.targetSize,
);
if (!targetUuids.ok) return err({ reason: targetUuids.error });
for (const memberPath of members) {
if (!targetEntries.ok) return err({ reason: targetEntries.error });
const selectedCpuTypes = CPU_TYPES[input.architecture];
const selectedUuids = targetEntries.value
.filter(({ cpuType }) => selectedCpuTypes.includes(cpuType))
.map(({ uuid }) => uuid);
Comment thread
morluto marked this conversation as resolved.
Resolved
if (selectedUuids.length === 0)
return err({
reason: `the target image declares no LC_UUID for the selected ${input.architecture} slice`,
});
for (const memberPath of memberPaths) {
throwIfCancelled(signal);
const memberHandle = await open(memberPath, constants.O_RDONLY).catch(
() => undefined,
);
if (memberHandle === undefined)
return err({
reason: `dsym DWARF member is not readable: ${memberPath}`,
});
if (memberHandle === undefined) continue;
try {
const size = (await memberHandle.stat()).size;
const memberUuids = await readMachoFileUuids(memberHandle, size);
if (!memberUuids.ok)
return err({
reason: `dsym DWARF member could not be read as Mach-O: ${memberPath} (${memberUuids.error})`,
});
const initial = await memberHandle.stat();
if (!initial.isFile()) continue;
const memberEntries = await readMachoFileUuidEntries(
memberHandle,
initial.size,
);
if (!memberEntries.ok) continue;
const matched = debugCompanionMatches({
executableUuids: targetUuids.value,
companionUuids: memberUuids.value,
executableUuids: selectedUuids,
companionUuids: memberEntries.value.map(({ uuid }) => uuid),
});
if (!matched.ok) continue;
const memberSha256 = await digestOpenHandle(
memberHandle,
initial,
signal,
);
if (!memberSha256.ok) return err({ reason: memberSha256.error });
return ok({
sourcePath: dsymPath,
memberPath,
memberSha256: memberSha256.value,
uuid: matched.value.uuid,
});
if (matched.ok)
return ok({
sourcePath: dsymPath,
memberPath,
memberSha256: await digestFile(memberPath),
uuid: matched.value.uuid,
});
} finally {
await memberHandle.close();
}
}
return err({
reason:
"dsym_path contains no DWARF member whose LC_UUID matches the target image",
"dsym_path contains no Mach-O DWARF member whose LC_UUID matches the selected target slice",
});
};
46 changes: 46 additions & 0 deletions src/domain/analysisSnapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,52 @@ describe("analysis snapshot target identity", () => {
"entry_point",
);
});

it("partitions session and snapshot identity by the selected dSYM", () => {
const base: BinaryTarget = {
path: "/fixture/pair",
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["arm64"],
};
const companion = {
sourcePath: "/fixture/pair.dSYM",
memberPath: "/fixture/pair.dSYM/Contents/Resources/DWARF/pair",
memberSha256: "a".repeat(64),
uuid: "A1B2C3D4-E5F6-0789-ABCD-EF0123456789",
};
const withCompanion = { ...base, debugCompanion: companion };
expect(snapshotMatchesTarget(snapshotTarget(base), base)).toBe(true);
expect(
snapshotMatchesTarget(snapshotTarget(withCompanion), withCompanion),
).toBe(true);
// Omitting the companion after using one, or adding one after a bare open,
// is a different analysis input and must not reuse the retained session.
expect(snapshotMatchesTarget(snapshotTarget(withCompanion), base)).toBe(
false,
);
expect(snapshotMatchesTarget(snapshotTarget(base), withCompanion)).toBe(
false,
);
// A different companion is a different identity too.
expect(
snapshotMatchesTarget(snapshotTarget(withCompanion), {
...base,
debugCompanion: {
...companion,
uuid: "99999999-9999-9999-9999-999999999999",
},
}),
).toBe(false);
// Snapshots persisted before companion admission carry no field and match
// only a bare target.
const legacy = snapshotTarget(base);
delete (legacy as Record<string, unknown>).debug_companion;
expect(snapshotMatchesTarget(legacy, base)).toBe(true);
expect(snapshotMatchesTarget(legacy, withCompanion)).toBe(false);
});
});

describe("analysis snapshot nested subject contract", () => {
Expand Down
Loading