mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 21:46:01 +00:00
* feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors)!: refuse malformed SQLite, pwntools and EVM inputs as target failures The SQLite engine's `format` reason is renamed to `malformed` at its owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an AnalysisTargetFailureError at the selected path with format "sqlite". The pwntools and EVM worker replies keep their wire reason "format", which their workers define, and the adapters translate it once into a malformed target failure with the profile's format (elf, elf-core, evm-bytecode) instead of an invalid_format argument issue. SQLite joins the target-failure conformance registry. BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout, inspect_recorded_crash and inspect_evm_interface report a selected file's malformed bytes as unsupported_target with details.failure_kind "malformed", format_failure, format and path, instead of invalid_request with an invalid_format issue on path. * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): expect target failure facts in the pwntools and EVM reply suites The literal-replacement scenario now reads the failure's detail instead of an issues[] message, and a malformed reply wrapped by cleanup failure reports category unsupported_target. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * test(sqlite): drop the malformed-database provider test the conformance registry covers inspect_sqlite_database/not-a-database in the target-failure registry runs the same non-SQLite bytes through the CLI and MCP, asserts the malformed target facts and checks the selected file is unchanged. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * test(sqlite): expect a malformed target for non-database bytes in the CLI suite * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(pwntools): report a short ELF header as a truncated target The layout and recorded-crash workers raise a distinct truncated reason when the file ends inside the ELF identification or header, and the decoder projects it as failure_kind truncated instead of inferring it from the message. * fix(errors)!: report managed coverage gaps and IL2CPP pair conflicts as target failures Managed readers interpret an issue code once, in managedIssueTargetFailure: a coverage gap is an unsupported target, every other rule violation is a malformed target, and the inventory metadata status is derived from that same fact. managedInspectionTargetFailure now returns only AnalysisTargetFailureError. An IL2CPP binary that parses but does not link to its metadata is a conflict target failure that lists both inputs and blames neither, in place of an invalid_request with two issue entries. Metadata version 108 is an unsupported target. The CLI spells each conflict input's field by the command's option name. BREAKING CHANGE: inspect_managed_artifact, inspect_managed_members, inspect_managed_native_boundaries and the managed comparison operations report unsupported metadata or signature forms as an AnalysisTargetFailureError (failure_kind unsupported, format pe-cli, field, offset) instead of a bare unsupported target. inspect_il2cpp_metadata reports a binary/metadata pair that does not link as code input_conflict with failure_kind conflict and details.inputs, instead of invalid_request with details.issues, and metadata version 108 with failure_kind unsupported. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * fix(errors)!: report inventory refusals as target failures of the selected path An inventory, inspection or extraction refused damaged or unsupported container bytes as an ArtifactOperationError whose reason repeated the format owner's kind. It carried no path or retry hint, so the conformance registry could not express container cases. translateArtifactFailure now takes the selected path and returns the reader's TargetFailure as an AnalysisTargetFailureError. The malformed, truncated and unsupported reasons, their classification rows and their presentation branch are deleted from ArtifactOperationError. Readers' unsupported refusals carry their format facts through unsupportedArtifact. Container cases move into the conformance registry, which now opens the target first for session tools such as inspect_artifact. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the bundle readers report a refused container as a target failure of details.path with a top-level retry. details.reason is the owner's description and details.detail is removed. * docs(il2cpp): describe pair conflicts as input_conflict with both inputs * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): raise the cleanup fixture's decode refusal with its format facts * fix(errors)!: report unsupported and unrecognized targets on the TargetFailure model AnalysisUnsupportedTargetError carried a free-text reason and remediation beside the TargetFailure model, so unsupported refusals had no format, failure_kind or retry hint, and their recovery was prose written at each producer. The class is deleted. Producers raise unsupportedTarget or unrecognizedTarget with the owner's format, and consumers read targetFailureOfKind. The projection table renders the recovery and names the operations the owner lists in related.operations. The foreign-bytes identity loop moves into the conformance registry. BREAKING CHANGE: unsupported and unrecognized targets report failure_kind, format and retry. Their remediation comes from the target-failure table; producer-written remediation sentences are folded into details.reason or replaced by details.related_operations. * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * style: format the migrated target-failure tests * test(errors): expect the PE readers' native-binary format label for foreign bytes * test(verify): expect target failures for damaged ELF, core and EVM inputs in real-provider verifiers The binary-layout, recorded-crash and EVM verifiers still expected invalid_input for malformed or truncated selected bytes. The pwntools and EVM adapters now report those as unsupported_target with failure_kind; a missing path remains invalid_input. * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * fix(artifacts): keep refusal facts on DMG verdicts and the selected bundle path hdiutil's "image not recognized" verdict raised the unsupported reason without the owner's facts, so the inventory translation treated it as a reader defect. It now carries an unsupported dmg target failure, and the reader-failure constructor requires facts for every target reason. A bundle resource refusal names the caller's selected bundle path rather than its resolved target. The real-provider verifiers and the Android, source-location acceptance tests expect the model's target-failure categories and codes. * test(errors): assert unsupported refusals' kind and format, and align verifiers and the Electron guide * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(errors): raise main's new unsupported-target fixtures through the model * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(artifacts): assert Android refusal kinds and drop the SEA registry case details.reason is the owner's description, so the boot-image refusals assert failure_kind and format. A malformed SEA blob inside an ELF stays an outer-format inventory with a recognition limitation, which the Node SEA reader tests already cover, so it is not an inspect_artifact refusal. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): pass the selected path into translated target failures translateArtifactFailure names the caller-selected path on a format refusal. Directory inspection and a retained artifact scope both know that path and now supply it. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): charge global pax records against the tar metadata budget Repeated pax global headers were copied into one map without a charge, so each header could stay inside the extended-header allowance while the map grew without a bound. The retained metadata budget is charged for the merged map's keys, values and entries before that map is allocated. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto <morluto@users.noreply.github.com> * style: format the inventory path translation and conformance suite * fix(artifacts): keep the unsupported-target migration in files the inventory merge replaced * test(errors): expect target failures for ZIP inventory refusals and input_conflict for an unlinked IL2CPP pair * test(artifacts): expect a malformed target failure for an ISO 9660 directory cycle * test(web): expect a malformed target failure on the captured source path * test(artifacts): expect a malformed ZIP target failure for a corrupt Zstandard member * test(javascript): read the owner's input facts from details.reason and recovery from the projection * test(iso9660): assert the malformed target failure fields details.reason is the owner's description. The compiled CLI refusal is identified by failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(errors): assert selection and unsupported view fields A desktop root that is not a directory is a selection failure, so the CLI reports invalid_request. An analysis view the parent cannot supply is unsupported evidence; the tests read failure_kind, format, field and related_operations. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(errors): keep binary plist UID facts on unsupported targets Pass the reader's UnsupportedBinaryPlistUidError failure through instead of rebuilding a bplist refusal that drops field and undecodedContent. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(errors): keep oversized binary plist UID facts on keyed archives Assert the reader projects format, field, and undecoded content from the parser failure instead of a rebuilt bplist refusal. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
905 lines
32 KiB
TypeScript
905 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) {
|
|
// 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.
|
|
const chainedTable = hasChainedFixups
|
|
? await readChainedImportNames(context, binary, offset, size)
|
|
: undefined;
|
|
if (chainedTable?.ok === true)
|
|
parsedImports = parseDyldImports(
|
|
sliceOutput(dyldImports),
|
|
hasChainedFixups,
|
|
undefined,
|
|
chainedTable.value,
|
|
);
|
|
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.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,
|
|
);
|