Files
reverse-engineering-anything/src/native/NativeMachoInspection.ts
T
Akshat GuptaandAkshat 2a1a5e903f fix(macho): separate chained bind addends from import names (#14900)
* fix(macho): separate chained bind addends from import names

dyld_info prints a nonzero chained bind addend as a +0x suffix on the
import name, so rows such as __ZTVN10__cxxabiv117__class_type_infoE+0x10
were reported with name null and name_status "ambiguous". When the slice's
chained-fixup import table names the row's ordinal, a row that is that
name plus a hex suffix now reports the exact name and the suffix as
addend. A row equal to the table name keeps a literal suffix, and rows the
table does not settle stay ambiguous with the full expression in raw_name.

* fix(macho): take only dyld's 0x addend prefix and either ordinal spacing

An addend after the import-table name is accepted only with the lowercase
0x prefix dyld_info prints, so a +0X suffix stays ambiguous instead of
yielding an addend that fails the hex address schema. The arm64e CLI test
accepts one or two spaces after the ordinal, as the parser does.

---------

Co-authored-by: Akshat <akshatg9536@gmail.com>
2026-11-29 13:07:40 -05:00

912 lines
32 KiB
TypeScript

import { parseFailureFromCause } from "../domain/parseFailure.js";
import { LC } from "../domain/apple/machoLoadCommandCodes.js";
import type { BundleExecutableProvenance } from "../domain/apple/bundleExecutableProvenance.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisOutputError,
unsupportedTarget,
} from "../domain/analysisErrorCore.js";
import {
inspectMachoSchema,
type NativeCommandInvocation,
} from "../domain/native/nativeInspection.js";
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { machoRuntimeSymbolName } from "../domain/native/machoSymbolName.js";
import { keyedBy, uniqueKeyed } from "../domain/keyedCollection.js";
import { err, ok, type Result } from "../domain/result.js";
import type { MachoSliceSelectionRefusal } from "../domain/apple/machoSliceSelection.js";
import type { NativeCommandCapture } from "../providers/NativeCommandRunner.js";
import { chainedImportNames } from "../domain/apple/appleMachoFixups.js";
import {
architectureBaseName,
selectLipoArchitecture,
type SelectedLipoArchitecture,
} from "../domain/apple/machoArchitectureSelection.js";
import {
parseDyldExportAddressRow,
parseDyldExportLine,
parseDyldExports,
parseDyldImports,
} from "./parsers/dyldInfo.js";
import { parseLipoCapture } from "./parsers/lipo.js";
import { withoutEchoedPathHeader } from "./parsers/echoedPath.js";
import {
projectMachoBinary,
type BinaryMachoProjection,
} from "./MachoBinaryProjection.js";
import type { MachoCommandNames } from "../domain/apple/machoCommandNames.js";
import type { ResolvedMachoSlice } from "./NativeMachoSelectedSlice.js";
import { reconcileMachoUuid } from "./parsers/machoUuid.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import type {
MachoEncryptionFacts,
MachoSliceEncryption,
} from "../domain/apple/machoEncryption.js";
import {
conflictingUuidCommandEvidence,
isMissingUuidDyldFailure,
isUnbackedTextDyldFailure,
isVtoolContainerRefusal,
nativeCommandOperand,
nativeMachoCapturedOutput,
dyldRefusalLimitation,
dyldSliceRefusal,
parseDyldFileTypeRefusal,
unusableNativeCommandOutput,
} from "./NativeMachoCommandDiagnostics.js";
import { invariantViolation } from "../domain/internalInvariant.js";
import { NATIVE_COMMAND_OUTPUT_BUDGET_BYTES } from "../domain/native/nativeCommandOutput.js";
import {
lipoDescribesCpu,
type LipoArchitecture,
} from "../domain/apple/lipo.js";
type ParsedDyldExport = ReturnType<typeof parseDyldExports>[number];
interface CoveredDyldExports {
readonly nmNames: ReadonlySet<string>;
readonly dyldExports: ParsedDyldExport[];
}
interface NativeMachoObservation {
readonly result: JsonValue;
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
/** Structural encryption facts, or why the target bytes were not read. */
export type MachoEncryptionRead =
| MachoEncryptionFacts
| { readonly status: "unread"; readonly reason: string };
interface NativeMachoInspectionContext {
readonly target: BinaryTarget;
readonly bundleProvenance?: BundleExecutableProvenance;
readonly signal?: AbortSignal;
/** Read load-command encryption facts from the bytes the tools inspect. */
readonly readEncryption: (
signal?: AbortSignal,
) => Promise<MachoEncryptionRead>;
readonly run: (
tool: string,
arguments_: readonly string[],
signal?: AbortSignal,
acceptNonZeroIf?: (capture: NativeCommandCapture) => boolean,
) => Promise<Result<NativeCommandCapture, AnalysisError>>;
readonly invocation: (
capture: NativeCommandCapture,
) => NativeCommandInvocation;
readonly resolveSlice: (
selected: LipoArchitecture,
) => Promise<ResolvedMachoSlice>;
/** Read an exact selected-slice range from the same bytes as the tools. */
readonly readSliceRange?: (
offset: number,
size: number | null,
at: number,
length: number,
) => Promise<Uint8Array>;
/** Borrow binary framing from the same identity-bound target as the tools. */
readonly readCommandNames: (
offset: number,
size: number | null,
selected: ResolvedMachoSlice | undefined,
) => Promise<MachoCommandNames>;
}
/**
* Exact names from the selected slice's chained-fixup import table by import
* ordinal, or why that table cannot stand in for the symbol-table inventory.
* Undefined when the context has no slice reader.
*/
const readChainedImportNames = async (
context: NativeMachoInspectionContext,
binary: MachoCommandNames,
offset: number,
size: number | null,
): Promise<Result<readonly (string | null)[], string> | undefined> => {
if (context.readSliceRange === undefined) return undefined;
const chainedFixups = uniqueKeyed(
keyedBy(binary.commands, ({ command }) => command),
LC.DYLD_CHAINED_FIXUPS,
);
if (!chainedFixups.ok)
return err(
`the slice declares ${String(chainedFixups.error.ordinals.length)} LC_DYLD_CHAINED_FIXUPS commands`,
);
const fields = chainedFixups.value?.fixedFields;
const at = fields?.dataoff;
const length = fields?.datasize;
if (at === undefined || length === undefined)
return err("its load command fields are not decoded");
if (length > NATIVE_COMMAND_OUTPUT_BUDGET_BYTES)
return err(
`its ${length}-byte payload exceeds the ${NATIVE_COMMAND_OUTPUT_BUDGET_BYTES}-byte native read budget`,
);
const bytes = await context.readSliceRange(offset, size, at, length);
try {
return ok(
chainedImportNames(
Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
),
);
} catch (cause) {
const failure = parseFailureFromCause(cause);
if (failure !== undefined) return err(failure.message);
throw cause;
}
};
const MH_DSYM = 10;
const DISCOVERY_COMMANDS = [["lipo", ["-detailed_info"]]] as const;
// llvm-nm's default dyld-info pass fakes up symbols the symbol table lacks
// from dyld metadata. It takes seconds on large apps (Keynote arm64: 5.8 s
// versus 0.01 s without it), and under -gU it can only add export-trie names.
const SYMBOL_TABLE_EXPORTS = ["nm", ["-gjU", "--no-dyldinfo"]] as const;
const SYMBOL_TABLE_IMPORTS = ["nm", ["-gju", "--no-dyldinfo"]] as const;
const DYLD_INFO_EXPORTS = ["nm", ["-gjU"]] as const;
const REQUIRED_SLICE_COMMANDS = [
SYMBOL_TABLE_EXPORTS,
["dyld_info", ["-imports"]],
["dyld_info", ["-exports"]],
["dwarfdump", ["--uuid"]],
] as const;
const OPTIONAL_VTOOL_COMMAND = ["vtool", ["-show-build"]] as const;
const VTOOL_UNAVAILABLE_LIMITATION =
"vtool is unavailable; build metadata is normalized from binary load commands.";
/** Recorded when vtool refuses the universal container and slice facts remain. */
const VTOOL_CONTAINER_REFUSAL_LIMITATION =
"vtool declined the universal container as not Mach-O; build metadata is normalized from binary load commands.";
/** Inspect one Mach-O with the required native commands and normalized output. */
export const inspectNativeMacho = async (
context: NativeMachoInspectionContext,
): Promise<Result<NativeMachoObservation, AnalysisError>> => {
const captures: NativeCommandCapture[] = [];
for (const [tool, prefix] of DISCOVERY_COMMANDS) {
const captured = await context.run(
tool,
[...prefix, context.target.path],
context.signal,
);
if (!captured.ok) return captured;
captures.push(captured.value);
}
const lipo = captures.find(({ tool }) => tool === "lipo");
if (lipo === undefined) throw invariantViolation("Missing lipo capture");
const parsedLipo = parseLipoCapture(
lipo,
"inspect_macho",
nativeCommandOperand(lipo) ?? context.target.path,
);
if (!parsedLipo.ok) return parsedLipo;
const { format, architectures } = parsedLipo.value;
const lipoSelection = selectArchitecture(context.target, architectures);
if (!lipoSelection.ok)
return err(
new AnalysisOutputError("inspect_macho", lipoSelection.error.message),
);
const selection = lipoSelection.value;
const selectedArchitecture = selection?.toolName ?? null;
const runSliceCommand = ([tool, prefix]: readonly [
string,
readonly string[],
]) =>
context.run(
tool,
[
...prefix,
...selectedArchitectureArguments(tool, selectedArchitecture),
context.target.path,
],
context.signal,
tool === "dyld_info"
? (capture) =>
dyldSliceRefusal(capture) !== null ||
isUnbackedTextDyldFailure(capture) ||
parseDyldFileTypeRefusal(capture) !== null
: tool === "vtool" && format === "fat"
? (capture) => isVtoolContainerRefusal(capture)
: undefined,
);
// vtool knows no variant subtypes, so no spelling selects an arm64e.x1 slice.
const vtoolSelectsSlice =
selectedArchitecture === null ||
!toolArchitectureName("vtool", selectedArchitecture).includes(".");
// Slice commands only read the selected artifact, so launch them together.
// Every launch settles before return; declared order fixes provenance and
// which failure is reported.
const [required, optional] = await Promise.all([
Promise.all(
REQUIRED_SLICE_COMMANDS.map((command) => runSliceCommand(command)),
),
vtoolSelectsSlice ? runSliceCommand(OPTIONAL_VTOOL_COMMAND) : null,
]);
for (const captured of required) {
if (!captured.ok) return captured;
if (
(captured.value.exitCode !== 0 || captured.value.signal !== null) &&
dyldSliceRefusal(captured.value) === null &&
!isUnbackedTextDyldFailure(captured.value) &&
parseDyldFileTypeRefusal(captured.value) === null
)
return err(unusableNativeCommandOutput(captured.value));
captures.push(captured.value);
}
const limitations = architectures.flatMap(
(architecture) => architecture.limitations,
);
if (optional === null)
limitations.push(
`vtool cannot select the ${selectedArchitecture} slice; build metadata is normalized from binary load commands.`,
);
else if (optional.ok) {
captures.push(optional.value);
if (isVtoolContainerRefusal(optional.value))
limitations.push(VTOOL_CONTAINER_REFUSAL_LIMITATION);
} else if (optional.error._tag === "AnalysisCapabilityUnavailableError")
limitations.push(VTOOL_UNAVAILABLE_LIMITATION);
else return err(optional.error);
const nmIndex = captures.findIndex(({ tool }) => tool === "nm");
const dyldExports = captures.filter(({ tool }) => tool === "dyld_info")[1];
if (nmIndex < 0 || dyldExports === undefined)
throw invariantViolation("Missing nm or dyld_info export capture");
const selected =
selection !== null
? selection.architecture
: architectures.length === 1
? architectures[0]
: undefined;
if (format === "fat" && selected === undefined)
return err(
new AnalysisOutputError(
"inspect_macho",
"The selected binary slice is unavailable",
),
);
const range =
format === "thin"
? { offset: 0, size: null }
: await context.resolveSlice(selected!);
if (
format === "fat" &&
(selected!.file_offset === null || selected!.size === null)
)
limitations.push(
"Selected slice range was derived from the Mach-O FAT table because lipo did not provide an interpretable complete range.",
);
const { offset, size } = range;
const binary = await context.readCommandNames(
offset,
size,
"declaration" in range ? range : undefined,
);
const unbackedTextFailure = captures.find(isUnbackedTextDyldFailure);
if (unbackedTextFailure !== undefined) {
if (binary.header.fileType !== MH_DSYM)
return err(unusableNativeCommandOutput(unbackedTextFailure));
return err(
unsupportedTarget(
"inspect_macho",
context.target.path,
"macho",
"The selected Mach-O is a dSYM companion whose unbacked text sections are unsupported by dyld_info inspection; select the matching linked executable",
{
field: "filetype",
capturedOutput: nativeMachoCapturedOutput(unbackedTextFailure),
},
),
);
}
for (const fileTypeFailure of captures) {
const refusal = parseDyldFileTypeRefusal(fileTypeFailure);
if (refusal === null) continue;
const { fileType, diagnostic } = refusal;
if (binary.header.fileType !== fileType)
return err(unusableNativeCommandOutput(fileTypeFailure));
const typeName = fileType === 4 ? "CORE" : "FVMLIB";
return err(
unsupportedTarget(
"inspect_macho",
context.target.path,
"macho",
`dyld_info refused the selected Mach-O file type MH_${typeName} (${fileType}); it reads linked executables and relocatable objects: ${diagnostic}`,
{
field: "filetype",
capturedOutput: nativeMachoCapturedOutput(fileTypeFailure),
},
),
);
}
const uuidlessDyldFailure = captures.find(isMissingUuidDyldFailure);
if (
uuidlessDyldFailure !== undefined &&
binary.commands.some(({ command }) => command === LC.UUID)
)
return err(conflictingUuidCommandEvidence(uuidlessDyldFailure));
const load = projectMachoBinary(binary);
const imageBase =
load.segments.find(
(segment) =>
segment.file_offset === 0 &&
segment.file_size !== null &&
segment.file_size > 0 &&
segment.file_size <= binary.sliceSize,
)?.vm_address ?? null;
// A stripped symbol table (strip -T) can omit names the export trie keeps.
// Only then does llvm-nm's dyld-info pass add names, and its exact names
// disambiguate dyld_info rows. Refusals above are not export rows.
let precomputedExports: CoveredDyldExports | undefined;
if (dyldSliceRefusal(dyldExports) === null) {
const coverage = analyzeExportCoverage(
captures[nmIndex]!.stdout,
dyldExports,
imageBase,
);
if (coverage.covered) precomputedExports = coverage;
else {
const withDyldInfo = await runSliceCommand(DYLD_INFO_EXPORTS);
if (!withDyldInfo.ok) return withDyldInfo;
captures[nmIndex] = withDyldInfo.value;
}
}
const dyldImports = captures.find(
({ tool, arguments: arguments_ }) =>
tool === "dyld_info" && arguments_[0] === "-imports",
);
if (dyldImports === undefined)
throw invariantViolation("Missing dyld_info import capture");
const hasChainedFixups = load.commands.some(
({ kind }) => kind === "LC_DYLD_CHAINED_FIXUPS",
);
let parsedImports = parseDyldImports(
sliceOutput(dyldImports),
hasChainedFixups,
);
if (parsedImports.needsNameInventory || parsedImports.needsImportTable) {
// Chained rows print entries of the binary's own import table by ordinal.
// Its exact names settle the ordinal spacing even for imports that the
// symbol table omits or lists as defined, such as weak-def coalescing,
// and separate a printed bind addend from the name it follows.
const chainedTable = hasChainedFixups
? await readChainedImportNames(context, binary, offset, size)
: undefined;
if (chainedTable?.ok === true)
parsedImports = parseDyldImports(
sliceOutput(dyldImports),
hasChainedFixups,
undefined,
chainedTable.value,
);
else if (!parsedImports.needsNameInventory) {
// Symbol-table names cannot tell an addend from a literal name suffix.
if (chainedTable !== undefined)
limitations.push(
`The chained-fixup import table is unusable (${chainedTable.error}); chained import names ending in a +0x suffix stay ambiguous.`,
);
} else {
if (chainedTable !== undefined)
limitations.push(
`The chained-fixup import table is unusable (${chainedTable.error}); chained import names are matched against the undefined symbol table instead.`,
);
const importNames = await runSliceCommand(SYMBOL_TABLE_IMPORTS);
if (!importNames.ok) return importNames;
captures.push(importNames.value);
parsedImports = parseDyldImports(
sliceOutput(dyldImports),
hasChainedFixups,
parseNmSymbolNames(importNames.value.stdout),
);
}
}
const encryption = await context.readEncryption(context.signal);
const selectedArchitectureName =
selection?.architecture.name ??
(architectures.length === 1 ? (architectures[0]?.name ?? null) : null);
const containerOffset =
selectedArchitectureName === null ? undefined : offset;
const outsideEntrypoint = load.entrypoints.some(
({ file_offset }) => file_offset >= binary.sliceSize,
);
const locationLimitations =
containerOffset === undefined
? [
selectedArchitectureName === null
? "The selected Mach-O slice is unknown; slice-based evidence locations are unavailable."
: "The selected Mach-O slice's container file offset was not observed; slice-based evidence locations are unavailable.",
]
: [
...(load.entrypoints.some(
({ file_offset }) =>
file_offset >= binary.sliceSize ||
!Number.isSafeInteger(containerOffset + file_offset),
)
? [
"Some entrypoint file locations are outside the selected slice or exceed the supported integer range.",
]
: []),
...(load.segments.some(
({ file_offset, file_size }) =>
file_offset === null ||
file_size === null ||
file_offset + file_size > binary.sliceSize ||
!Number.isSafeInteger(containerOffset + file_offset + file_size),
)
? [
"Some segment file locations are unavailable, outside the selected slice, or exceed the supported integer range.",
]
: []),
];
const result = normalizeMacho(
captures,
format,
context.invocation,
[...limitations, ...locationLimitations],
load,
imageBase,
parsedImports.items,
captures[nmIndex]!,
{ format, architectures, encryption },
{
name: selectedArchitectureName,
container_file_offset: containerOffset ?? null,
},
outsideEntrypoint,
precomputedExports,
);
return ok({
result: {
...result,
...(context.bundleProvenance === undefined
? {}
: {
bundle_provenance: ownedJsonValueSchema.parse(
context.bundleProvenance,
),
}),
} as JsonValue,
limitations: result.limitations,
locations: fileOffsetLocations(result, containerOffset, binary.sliceSize),
});
};
const normalizeMacho = (
captures: readonly NativeCommandCapture[],
containerFormat: "thin" | "fat",
toInvocation: (capture: NativeCommandCapture) => NativeCommandInvocation,
additionalLimitations: readonly string[],
load: BinaryMachoProjection,
imageBase: string | null,
parsedImports: ReturnType<typeof parseDyldImports>["items"],
exportNames: NativeCommandCapture,
slices: {
readonly format: "thin" | "fat";
readonly architectures: readonly LipoArchitecture[];
readonly encryption: MachoEncryptionRead;
},
selectedArchitecture: {
readonly name: string | null;
readonly container_file_offset: number | null;
},
outsideEntrypoint: boolean,
precomputedExports?: CoveredDyldExports,
) => {
const { architectures } = slices;
const encryption = encryptionCoverage(slices);
const byTool = captureLookup(captures);
const dyldImportsCapture = byTool("dyld_info", 0);
const dyldExportsCapture = byTool("dyld_info", 1);
const importsRefusal = dyldSliceRefusal(dyldImportsCapture);
const exportsRefusal = dyldSliceRefusal(dyldExportsCapture);
const imports =
importsRefusal === null ? parsedImports.map(withRuntimeName) : [];
const nmNames =
precomputedExports?.nmNames ?? parseNmSymbolNames(exportNames.stdout);
const dyldExports =
precomputedExports?.dyldExports ??
parseDyldExports(sliceOutput(dyldExportsCapture), imageBase, nmNames);
const exports = mergeMachoExports(dyldExports, nmNames).map(withRuntimeName);
const dwarfdump = byTool("dwarfdump");
const uuid = reconcileMachoUuid(
load.commands,
dwarfdump.stdout,
nativeCommandOperand(dwarfdump) ?? "",
selectedArchitecture.name === null
? null
: {
name: selectedArchitecture.name,
dwarfdumpName: toolArchitectureName(
"dwarfdump",
selectedArchitecture.name,
),
},
);
const provenance = captures.map(toInvocation);
const limitations = [
"Imports and exports combine dyld_info and nm; stripped or toolchain-hidden symbols may be absent.",
...(captures.some(
({ tool, exitCode, signal }) =>
tool === "vtool" && exitCode === 0 && signal === null,
)
? [
"vtool output is retained as provenance; build metadata is normalized from binary load commands.",
]
: []),
...additionalLimitations,
...(importsRefusal === null
? []
: [dyldRefusalLimitation("imports", importsRefusal)]),
...(exportsRefusal === null
? []
: [dyldRefusalLimitation("exports", exportsRefusal)]),
...uuid.limitations,
...(imageBase === null &&
/^\s*offset\s+symbol\s*$/mu.test(sliceOutput(byTool("dyld_info", 1)))
? [
"Export virtual addresses are unavailable because no file-backed image base was observed.",
]
: []),
...encryption.limitations,
...encryption.items.flatMap(encryptionLimitation),
];
return inspectMachoSchema.parse({
format: containerFormat === "fat" ? "mach-o-universal" : "mach-o",
selected_architecture: selectedArchitecture,
endian: load.endian,
word_size: load.wordSize,
file_type: load.fileType,
flags: load.flags,
uuid: uuid.value,
entrypoints: outsideEntrypoint
? {
...covered(load.entrypoints, false, [
...load.entrypointLimitations,
"An entrypoint lies outside the selected Mach-O slice.",
]),
total: null,
}
: covered(
load.entrypoints,
load.entrypointLimitations.length === 0,
load.entrypointLimitations,
),
architectures: covered(architectures, true),
build_metadata: covered(
load.builds,
load.buildLimitations.length === 0,
load.buildLimitations,
),
load_commands: covered(load.commands, true, load.commandLimitations),
dependencies: covered(
load.dependencies,
load.dependencyLimitations.length === 0,
load.dependencyLimitations,
),
imports: covered(imports, false, [
"dyld_info textual imports may omit chained or toolchain-unsupported metadata.",
...(importsRefusal === null
? []
: [dyldRefusalLimitation("imports", importsRefusal)]),
...(imports.some(({ name_status }) => name_status === "ambiguous")
? [
"Import text contains name, flags, library, or addend boundaries whose split is ambiguous.",
]
: []),
]),
exports: covered(exports, false, [
...(exportsRefusal === null
? [
"Merged nm/dyld_info results may be incomplete for stripped binaries.",
]
: [dyldRefusalLimitation("exports", exportsRefusal)]),
...(dyldExports.some(({ sourceSymbol }) => sourceSymbol !== undefined)
? [
"Renamed re-exports are listed under their exported name; the source library's symbol name is not reported.",
]
: []),
]),
segments: covered(
load.segments.map((segment) => ({
...segment,
sections: covered(
segment.sections,
load.segmentLimitations.length === 0,
load.segmentLimitations,
),
})),
load.segmentLimitations.length === 0,
load.segmentLimitations,
),
encryption,
provenance,
limitations,
});
};
/** Label each slice with the one lipo record sharing its physical identity. */
const encryptionCoverage = ({
format,
architectures,
encryption,
}: {
readonly format: "thin" | "fat";
readonly architectures: readonly LipoArchitecture[];
readonly encryption: MachoEncryptionRead;
}) => {
if (encryption.status !== "parsed")
return {
items: [],
total: null,
exhaustive: false,
limitations: [
encryption.status === "not-mach-o"
? "Encryption load commands were not read: the structural reader did not recognize a Mach-O image."
: `Encryption load commands were not read: ${encryption.status === "failed" ? encryption.failure.detail : encryption.reason}`,
],
};
const items = encryption.slices.map((slice) => {
const matches = architectures.filter((architecture) =>
lipoDescribesSlice(architecture, slice, format),
);
return {
...slice,
architecture: matches.length === 1 ? (matches[0]?.name ?? null) : null,
};
});
return covered(items, true);
};
const lipoDescribesSlice = (
architecture: LipoArchitecture,
slice: MachoSliceEncryption,
format: "thin" | "fat",
): boolean =>
(architecture.file_offset === null
? format === "thin" && slice.container_file_offset === 0
: architecture.file_offset === slice.container_file_offset) &&
(architecture.size === null || architecture.size === slice.size) &&
lipoDescribesCpu(architecture, slice.cpu_type, slice.cpu_subtype);
const encryptionLimitation = (slice: MachoSliceEncryption): string[] => {
const name =
slice.architecture === null
? `slice at offset ${slice.container_file_offset}`
: `${slice.architecture} slice`;
if (slice.status === "malformed" || slice.status === "unknown")
return [
`Encryption status of the ${name} is ${slice.status}: ${slice.reason ?? "no reason recorded"}.`,
];
const { range } = slice;
if (slice.status !== "encrypted" || range === null) return [];
const cryptid = slice.commands[0]?.cryptid ?? null;
return range.container_start === range.container_end
? [
`The ${name} declares encryption (cryptid ${cryptid}) over an empty range; no bytes are marked as ciphertext.`,
]
: [
`Bytes ${range.container_start}-${range.container_end} (input file offsets, end exclusive) of the ${name} are ciphertext (cryptid ${cryptid}); disassembly, decompilation, strings and references derived from them do not describe program code.`,
];
};
/** Slice output without the echoed operand path, which can contain any text. */
const sliceOutput = (capture: NativeCommandCapture): string =>
withoutEchoedPathHeader(capture.stdout, capture.arguments.at(-1));
const captureLookup =
(captures: readonly NativeCommandCapture[]) =>
(tool: string, occurrence = 0): NativeCommandCapture => {
const capture = captures.filter((item) => item.tool === tool)[occurrence];
if (capture === undefined)
throw invariantViolation(`Missing ${tool} capture`);
return capture;
};
/**
* Check whether every dyld_info export row names a symbol-table export while
* parsing the export rows in a single pass so covered binaries reuse them.
*/
const analyzeExportCoverage = (
nmOutput: string,
dyldExportsCapture: NativeCommandCapture,
imageBase: string | null,
):
| ({ readonly covered: true } & CoveredDyldExports)
| { readonly covered: false } => {
const nmNames = parseNmSymbolNames(nmOutput);
const output = sliceOutput(dyldExportsCapture);
const offsets = /^\s*offset\s+symbol\s*$/mu.test(output);
const parsed: ParsedDyldExport[] = [];
const lines = output.split("\n");
for (let index = 0; index < lines.length; index++) {
// Keep a trailing carriage return: it belongs to the exported name.
const line = lines[index]!.trimStart();
if (
line.length === 0 ||
(index === 0 && line.endsWith(":")) ||
/^-?exports:$/u.test(line) ||
/^offset\s+symbol$/u.test(line)
)
continue;
const row = parseDyldExportLine(line, offsets, imageBase, nmNames);
// The parser withholds a row only when nm names both of its readings.
if (row === null) {
if (!nmNames.has(parseDyldExportAddressRow(line)?.text ?? ""))
return { covered: false };
continue;
}
if (!nmNames.has(row.name)) return { covered: false };
parsed.push(row);
}
return { covered: true, nmNames, dyldExports: parsed };
};
// nm -j ends each name with LF; a carriage return before it is part of the name.
const parseNmSymbolNames = (output: string): ReadonlySet<string> => {
const names = new Set<string>();
for (const name of output.split("\n")) if (name.length !== 0) names.add(name);
return names;
};
const covered = <Value>(
items: readonly Value[],
exhaustive: boolean,
limitations: readonly string[] = [],
) => ({
items: [...items],
total: exhaustive ? items.length : null,
exhaustive,
limitations: [...limitations],
});
const withRuntimeName = <Value extends { readonly name: string | null }>(
symbol: Value,
): Value & { readonly runtime_name: string | null } => ({
...symbol,
runtime_name: machoRuntimeSymbolName(symbol.name),
});
const mergeMachoExports = (
dyldExports: readonly ParsedDyldExport[],
nmNames: ReadonlySet<string>,
): ParsedDyldExport[] => {
const observed = new Set<string>();
const exports: ParsedDyldExport[] = [];
for (const item of dyldExports) {
if (observed.has(item.name)) continue;
observed.add(item.name);
exports.push(item);
}
for (const name of nmNames)
if (!observed.has(name))
exports.push({
name,
address: null,
weak: null,
reexport: null,
source: "nm",
});
return exports.sort((left, right) =>
compareUnicodeCodePoints(left.name, right.name),
);
};
const fileOffsetLocations = (
macho: ReturnType<typeof inspectMachoSchema.parse>,
containerOffset: number | undefined,
sliceSize: number,
): EvidenceLocation[] => {
const locations = architectureLocations(macho.architectures.items);
if (containerOffset === undefined) return locations;
for (const entrypoint of macho.entrypoints.items)
if (
entrypoint.file_offset < sliceSize &&
Number.isSafeInteger(containerOffset + entrypoint.file_offset)
)
locations.push({
kind: "file-offset",
offset: containerOffset + entrypoint.file_offset,
});
for (const segment of macho.segments.items) {
if (
segment.file_offset === null ||
segment.file_size === null ||
segment.file_size === 0 ||
segment.file_offset + segment.file_size > sliceSize ||
!Number.isSafeInteger(
containerOffset + segment.file_offset + segment.file_size,
)
)
continue;
locations.push({
kind: "file-offset-range",
start: containerOffset + segment.file_offset,
end: containerOffset + segment.file_offset + segment.file_size,
});
}
return locations;
};
/** Project architecture slices into evidence file-offset locations. */
export const architectureLocations = (
architectures: readonly {
readonly file_offset: number | null;
readonly size: number | null;
}[],
): EvidenceLocation[] => {
const locations: EvidenceLocation[] = [];
for (const { file_offset: offset, size } of architectures) {
if (
offset === null ||
(size !== null && !Number.isSafeInteger(offset + size))
)
continue;
locations.push(
size === null
? { kind: "file-offset", offset }
: { kind: "file-offset-range", start: offset, end: offset + size },
);
}
return locations;
};
const toolArchitectureName = (tool: string, architecture: string): string =>
tool === "dyld_info" ? architecture : architectureBaseName(architecture);
const selectedArchitectureArguments = (
tool: string,
architecture: string | null,
): string[] => {
if (architecture === null) return [];
const toolArchitecture = toolArchitectureName(tool, architecture);
return tool === "dwarfdump"
? [`--arch=${toolArchitecture}`]
: ["-arch", toolArchitecture];
};
/** The lipo record slice tools read; null when tools read the file unfiltered. */
const selectArchitecture = (
target: BinaryTarget,
available: readonly LipoArchitecture[],
): Result<SelectedLipoArchitecture | null, MachoSliceSelectionRefusal> =>
// BinaryTarget lists CPU families and lipo lists slices. A universal file
// can hold several slices of one family (arm64e and arm64e.x1), and slice
// tools without -arch print every slice.
target.kind !== "executable" ||
(target.availableArchitectures.length < 2 && available.length < 2)
? ok(null)
: selectLipoArchitecture(
target.format === "mach-o-universal"
? {
mode: "admitted",
architecture: target.architecture,
slice: target.universalSlice,
}
: { mode: "architecture", architecture: target.architecture },
available,
);