mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 14:01:00 +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>
1770 lines
58 KiB
TypeScript
1770 lines
58 KiB
TypeScript
import {
|
|
nativeCommandCleanupFailure,
|
|
closeNativeFileScope,
|
|
nativeOutputFailure,
|
|
nativeFailureWithCommandCleanup,
|
|
nativeMachoSourceFailure,
|
|
type NativeObservation,
|
|
isNativeOperation,
|
|
isNonzeroUnsignedObservation,
|
|
canonicalPath,
|
|
codeSignCaptureFailure,
|
|
codeSignArchitectures,
|
|
invocation,
|
|
nativePlistObservation,
|
|
parseEntitlements,
|
|
nativePlistDecodeFailure,
|
|
xmlSyntaxRefusal,
|
|
} from "./NativeMacosErrorProjection.js";
|
|
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
import {
|
|
bindArtifactFileCleanup,
|
|
AnalysisCleanupLeaseGroup,
|
|
ArtifactResourceScope,
|
|
withArtifactTargetIdentity,
|
|
} from "../resources/index.js";
|
|
import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js";
|
|
import { invariantViolation } from "../domain/internalInvariant.js";
|
|
import { translateNativeCommandFailure } from "./NativeCommandAnalysisError.js";
|
|
import {
|
|
plistSourceFormat,
|
|
readNativePlistBytes,
|
|
nativePlistFailure,
|
|
resolveNativePlistSelection,
|
|
unreadablePlist,
|
|
type NativePlistSelection,
|
|
resolveBundleResourcePlistSelection,
|
|
} from "./NativePlistSource.js";
|
|
import { readMachoEncryption } from "../domain/apple/machoEncryptionReader.js";
|
|
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
|
import {
|
|
APPLE_DISPATCH_METADATA_ANALYSIS_PROFILE,
|
|
nativeMacOSCapabilities,
|
|
} from "./NativeMacOSProviderMetadata.js";
|
|
import { NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY } from "./NativeMacosProviderIdentity.js";
|
|
import {
|
|
appleDispatchMetadataFailure,
|
|
inspectAppleDispatchMetadata,
|
|
} from "./AppleDispatchMetadata.js";
|
|
import {
|
|
observeNativeUi,
|
|
finishNativeUiObservation,
|
|
} from "./NativeUiObservation.js";
|
|
import { NativeUiCleanupError } from "./NativeUiCleanupError.js";
|
|
import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";
|
|
import { observeNativeCalls } from "./NativeCallObservation.js";
|
|
import { symlink, writeFile } from "node:fs/promises";
|
|
import { basename, join } from "node:path";
|
|
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
|
|
|
import { z } from "zod";
|
|
|
|
import {
|
|
createAnalysisExecution,
|
|
type AnalysisClient,
|
|
type ExecutionOptions,
|
|
type AnalysisOperation,
|
|
type AnalysisProvider,
|
|
type CapabilityDescriptor,
|
|
type ProviderIdentity,
|
|
} from "../ports/AnalysisProvider.js";
|
|
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
|
|
import {
|
|
isMachOFormat,
|
|
type BinaryTarget,
|
|
} from "../domain/binaryTargetTypes.js";
|
|
import {
|
|
isAppleDispatchMetadataTarget,
|
|
nativeDispatchMetadataInputSchema,
|
|
} from "../domain/native/objcSwiftMetadata.js";
|
|
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
AnalysisCapabilityUnavailableError,
|
|
AnalysisInputError,
|
|
AnalysisOutputError,
|
|
AnalysisTargetFailureError,
|
|
type AnalysisResourceConstraintError,
|
|
cancelledBy,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import {
|
|
DEFAULT_NATIVE_COMMAND_TIMEOUT_MS,
|
|
DEFAULT_NATIVE_UI_DEADLINE_MS,
|
|
readNativeDeadline,
|
|
} from "../domain/native/nativeDeadlines.js";
|
|
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import {
|
|
AnalysisError,
|
|
resolvedAnalysisError,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
|
import type { NativeUiObservationResult } from "../domain/native/nativeUiObservation.js";
|
|
import { machoKnownCodeSignSelector } from "../domain/apple/machoArchitectureSelection.js";
|
|
import {
|
|
bundleExecutableProvenance,
|
|
type BundleExecutableProvenance,
|
|
} from "../domain/apple/bundleExecutableProvenance.js";
|
|
import {
|
|
demangleSwiftSchema,
|
|
inspectPlistSchema,
|
|
inspectMachoSchema,
|
|
inspectSignatureSchema,
|
|
type InspectSignature,
|
|
listArchitecturesSchema,
|
|
} from "../domain/native/nativeInspection.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import {
|
|
NativeCommandFailure,
|
|
XcrunCommandRunner,
|
|
type NativeCommandCapture,
|
|
type NativeCommandRunner,
|
|
} from "../providers/NativeCommandRunner.js";
|
|
import {
|
|
withSignatureTarget,
|
|
verifySignatureTarget,
|
|
type SignatureTargetBinding,
|
|
} from "./SignatureTargetBinding.js";
|
|
import { parseCodeSignature } from "./parsers/codesign.js";
|
|
import { parseDemangledSymbols } from "./parsers/demangle.js";
|
|
import { parseLipoCapture } from "./parsers/lipo.js";
|
|
import {
|
|
readPlistJson,
|
|
readPlistJsonSource,
|
|
parsePlistBinary,
|
|
parsePlistXml,
|
|
parsePlistXmlSource,
|
|
type ParsedPlist,
|
|
} from "./parsers/plist.js";
|
|
import { XmlPlistTextDecodeError } from "../domain/propertyListXmlText.js";
|
|
import {
|
|
architectureLocations,
|
|
inspectNativeMacho,
|
|
} from "./NativeMachoInspection.js";
|
|
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
|
|
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
|
|
import { withNativeMachoSource } from "./NativeMachoSource.js";
|
|
import { readMachoCommandNames } from "../domain/apple/machoCommandNames.js";
|
|
import {
|
|
assertSelectedMachoSlice,
|
|
resolveSelectedMachoSlice,
|
|
} from "./NativeMachoSelectedSlice.js";
|
|
import {
|
|
createNativeUiHelperRuntime,
|
|
type NativeUiHelperRuntime,
|
|
} from "./NativeUiHelperRuntime.js";
|
|
import { NativeUiInterruptionControl } from "./NativeUiInterruptionControl.js";
|
|
import type { ResolvedAppBundleResourceRoot } from "../domain/apple/bundleResourceRoot.js";
|
|
import { UnsupportedBinaryPlistUidError } from "../domain/apple/plistScalars.js";
|
|
import { NATIVE_COMMAND_OUTPUT_BUDGET_BYTES } from "../domain/native/nativeCommandOutput.js";
|
|
import { errorMessage } from "../kernel/errorMessage.js";
|
|
import { sha256Hex } from "../kernel/sha256Hex.js";
|
|
|
|
type SignatureRuntimeRootFactory = () => Promise<
|
|
Pick<PrivateRuntimeRoot, "path" | "close">
|
|
>;
|
|
|
|
interface NativePlistReadContext {
|
|
readonly selection: NativePlistSelection;
|
|
readonly resources: ArtifactResourceScope;
|
|
readonly signal: AbortSignal | undefined;
|
|
readonly timeoutMs: number;
|
|
}
|
|
|
|
interface NativePlistSnapshot extends NativePlistReadContext {
|
|
readonly bytes: Buffer;
|
|
readonly sha256: string;
|
|
readonly operand: string;
|
|
}
|
|
|
|
interface NativePrivateOperand {
|
|
readonly operation: "inspect_macho" | "inspect_plist";
|
|
readonly label: string;
|
|
readonly prefix: string;
|
|
readonly sourcePath: string;
|
|
}
|
|
|
|
/** Read-only semantic provider composed from Xcode command-line utilities. */
|
|
export class NativeMacOSProvider implements AnalysisProvider {
|
|
readonly #capabilities: readonly CapabilityDescriptor[];
|
|
readonly #environment: NodeJS.ProcessEnv;
|
|
readonly #tracerFactory: () => NativeCallTracer;
|
|
readonly #privateRuntimeRootFactory: SignatureRuntimeRootFactory | undefined;
|
|
|
|
constructor(
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
|
|
environment,
|
|
),
|
|
platform: NodeJS.Platform = HOST_PLATFORM.platform,
|
|
tracerFactory?: () => NativeCallTracer,
|
|
privateRuntimeRootFactory?: SignatureRuntimeRootFactory,
|
|
) {
|
|
this.#environment = snapshotEnvironment(environment, platform);
|
|
this.#tracerFactory =
|
|
tracerFactory ?? (() => new LldbCallTracer(this.#environment));
|
|
this.#privateRuntimeRootFactory = privateRuntimeRootFactory;
|
|
this.#capabilities = nativeMacOSCapabilities(platform);
|
|
}
|
|
|
|
identity(): ProviderIdentity {
|
|
return IDENTITY;
|
|
}
|
|
|
|
capabilities(): readonly CapabilityDescriptor[] {
|
|
return this.#capabilities;
|
|
}
|
|
|
|
createClient(target: BinaryTarget): AnalysisClient {
|
|
return new NativeMacOSClient(
|
|
target,
|
|
this.runner,
|
|
this.#tracerFactory(),
|
|
this.#environment,
|
|
this.#privateRuntimeRootFactory,
|
|
);
|
|
}
|
|
|
|
createBundleResourceClient(
|
|
root: ResolvedAppBundleResourceRoot,
|
|
): AnalysisClient {
|
|
const plistAvailable = this.#capabilities.some(
|
|
({ operation, available }) => operation === "inspect_plist" && available,
|
|
);
|
|
return new NativeMacOSClient(
|
|
undefined,
|
|
this.runner,
|
|
this.#tracerFactory(),
|
|
this.#environment,
|
|
this.#privateRuntimeRootFactory,
|
|
root,
|
|
plistAvailable,
|
|
);
|
|
}
|
|
}
|
|
|
|
// Encryption range mapping in every slice shares a sixteenth of the output
|
|
// budget at the 256 projected bytes reserved per Mach-O command record.
|
|
const MACHO_ENCRYPTION_MAPPING_RECORDS = Math.floor(
|
|
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES / 16 / 256,
|
|
);
|
|
|
|
class NativeMacOSClient implements AnalysisClient {
|
|
readonly #pendingNativeUiRuntimes = new Set<NativeUiHelperRuntime>();
|
|
readonly #pendingCommandOperations = new Set<Promise<unknown>>();
|
|
readonly #signatureResources = new ArtifactResourceScope();
|
|
readonly #plistResources = new ArtifactResourceScope();
|
|
readonly #callResources = new ArtifactResourceScope();
|
|
readonly #dispatchResources = new ArtifactResourceScope();
|
|
readonly #nativeOperandResources = new ArtifactResourceScope();
|
|
readonly #machoResources = new ArtifactResourceScope();
|
|
#nativeUiTail: Promise<void> = Promise.resolve();
|
|
#closed = false;
|
|
|
|
constructor(
|
|
private readonly activeTarget: BinaryTarget | undefined,
|
|
private readonly runner: NativeCommandRunner,
|
|
private readonly tracer: NativeCallTracer,
|
|
private readonly environment: Readonly<NodeJS.ProcessEnv>,
|
|
private readonly privateRuntimeRootFactory:
|
|
| SignatureRuntimeRootFactory
|
|
| undefined,
|
|
private readonly bundleResourceRoot?: ResolvedAppBundleResourceRoot,
|
|
private readonly bundlePlistAvailable = true,
|
|
) {}
|
|
|
|
private get target(): BinaryTarget {
|
|
if (this.activeTarget === undefined)
|
|
throw invariantViolation("This provider client has no executable target");
|
|
return this.activeTarget;
|
|
}
|
|
|
|
async execute(
|
|
operation: AnalysisOperation,
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
options?: ExecutionOptions,
|
|
) {
|
|
if (this.#closed)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
operation,
|
|
"Native provider client is closed",
|
|
),
|
|
);
|
|
if (options?.signal?.aborted === true)
|
|
return err(cancelledBy(operation, options.signal));
|
|
if (operation === "health")
|
|
return ok(createAnalysisExecution(null, IDENTITY));
|
|
if (this.activeTarget === undefined && operation !== "inspect_plist")
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
operation,
|
|
"This client is bound to app resource access only.",
|
|
),
|
|
);
|
|
if (this.bundleResourceRoot !== undefined && !this.bundlePlistAvailable)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_plist",
|
|
"Property list inspection requires a macOS host.",
|
|
),
|
|
);
|
|
if (operation === "inspect_native_dispatch_metadata") {
|
|
const input = nativeDispatchMetadataInputSchema.safeParse(parameters);
|
|
if (!input.success)
|
|
return err(
|
|
analysisInputErrorFromIssues(
|
|
operation,
|
|
input.error.issues,
|
|
parameters,
|
|
{
|
|
cause: input.error,
|
|
},
|
|
),
|
|
);
|
|
if (!isAppleDispatchMetadataTarget(this.target))
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
operation,
|
|
"Binary Apple metadata requires Mach-O; other providers can report symbol-only metadata",
|
|
),
|
|
);
|
|
try {
|
|
const result = await this.#dispatchResources.run(() =>
|
|
inspectAppleDispatchMetadata(
|
|
this.target,
|
|
input.data.max_records,
|
|
this.#dispatchResources,
|
|
{
|
|
signal: options?.signal,
|
|
objcClassImportAddresses: input.data.objc_class_import_addresses,
|
|
objcClassImportAddressesComplete:
|
|
input.data.objc_class_import_addresses_complete,
|
|
maxInputBytes: input.data.max_input_bytes,
|
|
},
|
|
),
|
|
);
|
|
return ok(
|
|
createAnalysisExecution(result, result.provider, {
|
|
analysisProfile: APPLE_DISPATCH_METADATA_ANALYSIS_PROFILE,
|
|
locations: [{ kind: "artifact-path", path: this.target.path }],
|
|
limitations: result.result.coverage.flatMap(({ reason }) =>
|
|
reason === null ? [] : [reason],
|
|
),
|
|
}),
|
|
);
|
|
} catch (cause) {
|
|
return err(appleDispatchMetadataFailure(cause, this.target.path));
|
|
}
|
|
}
|
|
if (!isNativeOperation(operation))
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
operation,
|
|
"Operation is not implemented by native macOS tools.",
|
|
),
|
|
);
|
|
if (operation === "observe_native_calls") {
|
|
const result = await observeNativeCalls(
|
|
this.target,
|
|
parameters,
|
|
this.tracer,
|
|
this.#callResources,
|
|
options?.signal,
|
|
);
|
|
return result.ok
|
|
? ok(
|
|
createAnalysisExecution(result.value, IDENTITY, {
|
|
limitations: result.value.limitations,
|
|
locations: [{ kind: "artifact-path", path: this.target.path }],
|
|
}),
|
|
)
|
|
: result;
|
|
}
|
|
if (
|
|
operation === "observe_native_ui" ||
|
|
operation === "capture_native_ui_scenario"
|
|
) {
|
|
return this.#observeNativeUi(operation, parameters, options?.signal);
|
|
}
|
|
const admittedBundle = options?.bundleExecutableProvenance;
|
|
const bundleProvenance =
|
|
admittedBundle === undefined && this.activeTarget !== undefined
|
|
? bundleExecutableProvenance(this.activeTarget)
|
|
: (admittedBundle ?? undefined);
|
|
const pending = Promise.resolve().then(() =>
|
|
this.#dispatchCommand(
|
|
operation,
|
|
parameters,
|
|
options?.signal,
|
|
bundleProvenance,
|
|
),
|
|
);
|
|
this.#pendingCommandOperations.add(pending);
|
|
try {
|
|
const observation = await pending;
|
|
return observation.ok
|
|
? ok(
|
|
createAnalysisExecution(observation.value.result, IDENTITY, {
|
|
limitations: observation.value.limitations,
|
|
locations: observation.value.locations,
|
|
}),
|
|
)
|
|
: err(resolvedAnalysisError(observation.error));
|
|
} catch (cause: unknown) {
|
|
return err(nativeOutputFailure(operation, cause));
|
|
} finally {
|
|
this.#pendingCommandOperations.delete(pending);
|
|
}
|
|
}
|
|
|
|
async close(): Promise<Result<null, AnalysisError>> {
|
|
this.#closed = true;
|
|
await Promise.allSettled(this.#pendingCommandOperations);
|
|
const uiCleanupFailures = await this.#serializeNativeUi(() =>
|
|
this.#retryNativeUiCleanup(),
|
|
);
|
|
const signatureCleanup = await closeNativeFileScope(
|
|
this.#signatureResources,
|
|
"signature-snapshot",
|
|
);
|
|
const plistCleanup = await closeNativeFileScope(
|
|
this.#plistResources,
|
|
"plist-file",
|
|
);
|
|
const callCleanup = await closeNativeFileScope(
|
|
this.#callResources,
|
|
"native-call-target",
|
|
);
|
|
const dispatchCleanup = await closeNativeFileScope(
|
|
this.#dispatchResources,
|
|
"native-dispatch-metadata-target",
|
|
);
|
|
const machoCleanup = await closeNativeFileScope(
|
|
this.#machoResources,
|
|
"native-macho-target",
|
|
);
|
|
const commandCleanup = await this.#retryNativeCommandCleanup();
|
|
const nativeOperandCleanup = await closeNativeFileScope(
|
|
this.#nativeOperandResources,
|
|
"native-command-operand",
|
|
);
|
|
let result = await this.tracer.close();
|
|
const cleanupErrors = [
|
|
...(uiCleanupFailures.length === 0
|
|
? []
|
|
: [this.#nativeUiCleanupFailure(uiCleanupFailures, "close_binary")]),
|
|
...(commandCleanup === undefined ? [] : [commandCleanup]),
|
|
...(signatureCleanup === undefined ? [] : [signatureCleanup]),
|
|
...(plistCleanup === undefined ? [] : [plistCleanup]),
|
|
...(callCleanup === undefined ? [] : [callCleanup]),
|
|
...(dispatchCleanup === undefined ? [] : [dispatchCleanup]),
|
|
...(nativeOperandCleanup === undefined ? [] : [nativeOperandCleanup]),
|
|
...(machoCleanup === undefined ? [] : [machoCleanup]),
|
|
];
|
|
for (const cleanupError of cleanupErrors)
|
|
result = result.ok
|
|
? err(cleanupError)
|
|
: err(analysisErrorWithCleanupDependencies(result.error, cleanupError));
|
|
return result;
|
|
}
|
|
|
|
#observeNativeUi(
|
|
operation: "observe_native_ui" | "capture_native_ui_scenario",
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal?: AbortSignal,
|
|
) {
|
|
return this.#serializeNativeUi(async () => {
|
|
if (this.#closed)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
operation,
|
|
"Native provider client is closed",
|
|
),
|
|
);
|
|
const earlierCleanupFailures = await this.#retryNativeUiCleanup();
|
|
if (earlierCleanupFailures.length > 0)
|
|
return err(
|
|
this.#nativeUiCleanupFailure(earlierCleanupFailures, operation),
|
|
);
|
|
const deadline = readNativeDeadline(
|
|
parameters.native_ui_deadline_ms,
|
|
DEFAULT_NATIVE_UI_DEADLINE_MS,
|
|
);
|
|
if (!deadline.ok)
|
|
return err(
|
|
new AnalysisInputError(operation, { userMessage: deadline.message }, [
|
|
{
|
|
path: ["native_ui_deadline_ms"],
|
|
reason: deadline.reason,
|
|
message: deadline.message,
|
|
minimum: 1,
|
|
maximum: MAX_NODE_TIMER_DELAY_MS,
|
|
},
|
|
]),
|
|
);
|
|
const runtime = createNativeUiHelperRuntime(
|
|
this.environment,
|
|
deadline.timeoutMs,
|
|
);
|
|
const interruption = new NativeUiInterruptionControl(
|
|
signal,
|
|
runtime.signal,
|
|
deadline.timeoutMs,
|
|
);
|
|
try {
|
|
this.#pendingNativeUiRuntimes.add(runtime);
|
|
let result: Awaited<ReturnType<typeof observeNativeUi>>;
|
|
try {
|
|
result = await observeNativeUi(this.target, operation, parameters, {
|
|
environment: this.environment,
|
|
runtime,
|
|
interruption,
|
|
});
|
|
} catch (cause: unknown) {
|
|
result = err(
|
|
cause instanceof AnalysisError
|
|
? cause
|
|
: new ProviderAdapterError(IDENTITY.id, operation, { cause }),
|
|
);
|
|
}
|
|
try {
|
|
await runtime.close();
|
|
this.#pendingNativeUiRuntimes.delete(runtime);
|
|
} catch (cause: unknown) {
|
|
result = finishNativeUiObservation(result, operation, interruption);
|
|
const cleanup = this.#nativeUiCleanupFailure(
|
|
[{ runtime, cause }],
|
|
operation,
|
|
result.ok ? result.value : undefined,
|
|
);
|
|
return err(
|
|
result.ok
|
|
? cleanup
|
|
: analysisErrorWithCleanupDependencies(
|
|
result.error,
|
|
cleanup,
|
|
operation,
|
|
),
|
|
);
|
|
}
|
|
result = finishNativeUiObservation(result, operation, interruption);
|
|
return result.ok
|
|
? ok(
|
|
createAnalysisExecution(result.value, IDENTITY, {
|
|
limitations: result.value.limitations,
|
|
}),
|
|
)
|
|
: result;
|
|
} finally {
|
|
interruption.dispose();
|
|
}
|
|
});
|
|
}
|
|
|
|
#serializeNativeUi<Value>(operation: () => Promise<Value>): Promise<Value> {
|
|
const call = this.#nativeUiTail.then(operation, operation);
|
|
this.#nativeUiTail = call.then(
|
|
() => undefined,
|
|
() => undefined,
|
|
);
|
|
return call;
|
|
}
|
|
|
|
async #retryNativeUiCleanup(): Promise<
|
|
Array<{ readonly runtime: NativeUiHelperRuntime; readonly cause: unknown }>
|
|
> {
|
|
const failures: Array<{
|
|
readonly runtime: NativeUiHelperRuntime;
|
|
readonly cause: unknown;
|
|
}> = [];
|
|
for (const runtime of this.#pendingNativeUiRuntimes) {
|
|
try {
|
|
await runtime.close();
|
|
this.#pendingNativeUiRuntimes.delete(runtime);
|
|
} catch (cause: unknown) {
|
|
failures.push({ runtime, cause });
|
|
}
|
|
}
|
|
return failures;
|
|
}
|
|
|
|
async #retryNativeCommandCleanup(): Promise<AnalysisError | undefined> {
|
|
if (this.runner.retryCleanup === undefined) return undefined;
|
|
try {
|
|
const failures = await this.runner.retryCleanup();
|
|
return failures.length === 0
|
|
? undefined
|
|
: nativeCommandCleanupFailure(failures);
|
|
} catch (cause: unknown) {
|
|
return new ProviderCleanupError(
|
|
IDENTITY.id,
|
|
["native-command-process-cleanup"],
|
|
{
|
|
reason:
|
|
cause instanceof Error
|
|
? cause.message || cause.name
|
|
: String(cause) || "native command cleanup failed unexpectedly",
|
|
},
|
|
{ cause },
|
|
);
|
|
}
|
|
}
|
|
|
|
#nativeUiCleanupFailure(
|
|
failures: readonly {
|
|
readonly runtime: NativeUiHelperRuntime;
|
|
readonly cause: unknown;
|
|
}[],
|
|
operation: string,
|
|
partialObservation?: NativeUiObservationResult,
|
|
): ProviderCleanupError {
|
|
return new NativeUiCleanupError(failures, operation, partialObservation);
|
|
}
|
|
|
|
#dispatchCommand(
|
|
operation:
|
|
| "inspect_macho"
|
|
| "inspect_signature"
|
|
| "inspect_plist"
|
|
| "list_architectures"
|
|
| "demangle_swift",
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal: AbortSignal | undefined,
|
|
bundleProvenance: BundleExecutableProvenance | undefined,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
const timeout = readNativeDeadline(
|
|
parameters.native_command_timeout_ms,
|
|
DEFAULT_NATIVE_COMMAND_TIMEOUT_MS,
|
|
);
|
|
if (!timeout.ok)
|
|
return Promise.resolve(
|
|
err(
|
|
new AnalysisInputError(operation, { userMessage: timeout.message }, [
|
|
{
|
|
path: ["native_command_timeout_ms"],
|
|
reason: timeout.reason,
|
|
message: timeout.message,
|
|
minimum: 1,
|
|
maximum: MAX_NODE_TIMER_DELAY_MS,
|
|
},
|
|
]),
|
|
),
|
|
);
|
|
const timeoutMs = timeout.timeoutMs;
|
|
switch (operation) {
|
|
case "inspect_macho":
|
|
return this.#inspectMacho(
|
|
parameters,
|
|
signal,
|
|
timeoutMs,
|
|
bundleProvenance,
|
|
);
|
|
case "inspect_signature":
|
|
return this.#inspectSignature(signal, timeoutMs, bundleProvenance);
|
|
case "inspect_plist":
|
|
return this.#inspectPlist(parameters, signal, timeoutMs);
|
|
case "list_architectures":
|
|
return this.#listArchitectures(parameters, signal, timeoutMs);
|
|
case "demangle_swift":
|
|
return this.#demangle(parameters, signal, timeoutMs);
|
|
}
|
|
}
|
|
|
|
async #listArchitectures(
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
// lipo reads only Mach-O; its refusal of a PE, ELF, or plist target is not
|
|
// a tool failure that a retry or `rea doctor` could repair.
|
|
if (!isMachOFormat(this.target.format))
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"list_architectures",
|
|
"Active artifact is not Mach-O.",
|
|
),
|
|
);
|
|
try {
|
|
return await this.#machoResources.run(() =>
|
|
withNativeMachoSource(
|
|
this.target,
|
|
this.#machoResources,
|
|
signal,
|
|
async () => {
|
|
const capture = await this.#run(
|
|
"list_architectures",
|
|
"lipo",
|
|
["-detailed_info", this.target.path],
|
|
{ signal, timeoutMs },
|
|
);
|
|
if (!capture.ok) return capture;
|
|
const provenance = [invocation(capture.value, this.target.path)];
|
|
const parsed = parseLipoCapture(
|
|
capture.value,
|
|
"list_architectures",
|
|
this.target.path,
|
|
);
|
|
if (!parsed.ok) return parsed;
|
|
const { architectures } = parsed.value;
|
|
const limitations = architectures.flatMap(
|
|
(architecture) => architecture.limitations,
|
|
);
|
|
const result = listArchitecturesSchema.parse({
|
|
architectures: {
|
|
items: architectures,
|
|
total: architectures.length,
|
|
exhaustive: true,
|
|
limitations: [],
|
|
},
|
|
provenance,
|
|
limitations,
|
|
});
|
|
return ok({
|
|
result: ownedJsonValueSchema.parse(result),
|
|
limitations,
|
|
locations: architectureLocations(result.architectures.items),
|
|
});
|
|
},
|
|
),
|
|
);
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
nativeMachoSourceFailure(
|
|
cause,
|
|
this.target,
|
|
parameters,
|
|
"list_architectures",
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
async #demangle(
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
const symbols = z.array(z.string()).safeParse(parameters.symbols);
|
|
if (!symbols.success)
|
|
return err(
|
|
new AnalysisOutputError(
|
|
"demangle_swift",
|
|
"symbols were not parsed strings",
|
|
),
|
|
);
|
|
const capture = await this.#run(
|
|
"demangle_swift",
|
|
"swift-demangle",
|
|
// `--` keeps symbols that begin with `-` from selecting demangler options.
|
|
["--compact", "--", ...symbols.data],
|
|
{ signal, timeoutMs },
|
|
);
|
|
if (!capture.ok) return capture;
|
|
const provenance = [invocation(capture.value, this.target.path)];
|
|
const result = demangleSwiftSchema.parse({
|
|
symbols: parseDemangledSymbols(symbols.data, capture.value.stdout),
|
|
provenance,
|
|
limitations: [],
|
|
});
|
|
return ok({
|
|
result: ownedJsonValueSchema.parse(result),
|
|
limitations: [],
|
|
locations: [],
|
|
});
|
|
}
|
|
|
|
async #inspectSignature(
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
bundleProvenance: BundleExecutableProvenance | undefined,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
// This provider's signature inspection covers Mach-O code signatures
|
|
// only. On another container, codesign's "not signed" verdict cannot
|
|
// see a format-level signature such as a xar pkg signature, so
|
|
// reporting it would claim unsigned for a layer that was never
|
|
// evaluated.
|
|
if (this.target.kind !== "executable" || !isMachOFormat(this.target.format))
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_signature",
|
|
"Active artifact is not Mach-O; its container-level signature layer is not evaluated by codesign.",
|
|
),
|
|
);
|
|
const inspected = await withSignatureTarget(
|
|
this.target,
|
|
this.#signatureResources,
|
|
(binding) =>
|
|
this.#inspectBoundSignature(
|
|
binding,
|
|
signal,
|
|
timeoutMs,
|
|
bundleProvenance,
|
|
),
|
|
signal,
|
|
this.privateRuntimeRootFactory,
|
|
);
|
|
return inspected.ok
|
|
? ok({
|
|
result: inspected.value,
|
|
limitations: inspected.value.limitations,
|
|
locations: [],
|
|
})
|
|
: inspected;
|
|
}
|
|
|
|
async #inspectBoundSignature(
|
|
binding: SignatureTargetBinding,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
bundleProvenance: BundleExecutableProvenance | undefined,
|
|
): Promise<Result<InspectSignature, AnalysisError>> {
|
|
const architecture =
|
|
this.target.kind === "executable" ? this.target.architecture : undefined;
|
|
if (architecture === undefined)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_signature",
|
|
"No executable architecture is selected.",
|
|
),
|
|
);
|
|
const target = this.target;
|
|
const slices =
|
|
target.format === "mach-o-universal" ? target.universalSlices : undefined;
|
|
const selectedIndex =
|
|
target.format === "mach-o-universal"
|
|
? (slices?.findIndex(
|
|
(slice) => slice.offset === target.universalSlice.offset,
|
|
) ?? -1)
|
|
: -1;
|
|
if (target.format === "mach-o-universal" && selectedIndex < 0)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_signature",
|
|
"The selected Mach-O slice identity is unavailable for codesign.",
|
|
),
|
|
);
|
|
const selectedArchitecture =
|
|
slices === undefined || selectedIndex < 0
|
|
? architecture === "x86"
|
|
? "i386"
|
|
: architecture
|
|
: machoKnownCodeSignSelector(slices, selectedIndex);
|
|
if (selectedArchitecture === undefined)
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_signature",
|
|
"The selected Mach-O slice has no known codesign architecture selector.",
|
|
),
|
|
);
|
|
// A thin Mach-O already identifies its only slice. Its admitted architecture
|
|
// is a CPU family, which is not necessarily a codesign subtype selector
|
|
// (for example arm64e). Only universal containers need a selector.
|
|
const selector =
|
|
this.target.format === "mach-o-universal"
|
|
? ["-a", selectedArchitecture]
|
|
: [];
|
|
const executablePaths = [
|
|
binding.snapshotPath,
|
|
...(await canonicalPath(binding.snapshotPath)),
|
|
];
|
|
const display = await this.#captureSignature(
|
|
binding,
|
|
["-d", ...selector, "--verbose=4"],
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!display.ok) return display;
|
|
const unsigned = isNonzeroUnsignedObservation(
|
|
display.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
);
|
|
const displayFailure = codeSignCaptureFailure(
|
|
this.#signatureResources,
|
|
display.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
);
|
|
if (displayFailure !== null) return err(displayFailure);
|
|
const requirements = await this.#captureSignature(
|
|
binding,
|
|
["-d", ...selector, "-r-"],
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!requirements.ok) return requirements;
|
|
const requirementsFailure = codeSignCaptureFailure(
|
|
this.#signatureResources,
|
|
requirements.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
);
|
|
if (requirementsFailure !== null) return err(requirementsFailure);
|
|
const entitlements = await this.#captureSignature(
|
|
binding,
|
|
["-d", ...selector, "--entitlements", ":-"],
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!entitlements.ok) return entitlements;
|
|
const entitlementsFailure = codeSignCaptureFailure(
|
|
this.#signatureResources,
|
|
entitlements.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
);
|
|
if (entitlementsFailure !== null) return err(entitlementsFailure);
|
|
// codesign echoes the resolved executable path in its diagnostics.
|
|
const parsed = parseCodeSignature(
|
|
display.value.stderr,
|
|
unsigned,
|
|
executablePaths,
|
|
);
|
|
// The requirement is printed to stdout; stderr echoes the path.
|
|
const requirementText =
|
|
/designated\s*=>\s*(.+)$/mu.exec(requirements.value.stdout)?.[1] ?? null;
|
|
// Entitlements XML is printed to stdout; stderr echoes the path.
|
|
const entitlementValue = parseEntitlements(entitlements.value.stdout);
|
|
const captures = [display.value, requirements.value, entitlements.value];
|
|
const limitations = [
|
|
...parsed.limitations,
|
|
...entitlementValue.limitations.map((note) => `Entitlements: ${note}`),
|
|
"Inspected a digest-verified Mach-O byte snapshot; filesystem-bound signing context and trust validation are not examined.",
|
|
];
|
|
const { architectures, unknownSlices } = codeSignArchitectures(
|
|
parsed.format,
|
|
this.target,
|
|
);
|
|
if (architectures.length > 1 || unknownSlices)
|
|
limitations.push(
|
|
`Partial signature coverage: signature identity, hashes, designated requirement, entitlements and runtime state describe the requested ${selectedArchitecture} architecture; other slices' metadata is not returned.`,
|
|
);
|
|
if (unknownSlices)
|
|
limitations.push(
|
|
"Some Mach-O slice identities cannot be mapped to a known codesign selector; their signature states are unknown.",
|
|
);
|
|
if (
|
|
!unsigned &&
|
|
isNonzeroUnsignedObservation(
|
|
requirements.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
)
|
|
)
|
|
limitations.push(
|
|
"The designated requirement for the requested architecture is unavailable because codesign reported it unsigned.",
|
|
);
|
|
if (
|
|
!unsigned &&
|
|
isNonzeroUnsignedObservation(
|
|
entitlements.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
)
|
|
)
|
|
limitations.push(
|
|
"The entitlements for the requested architecture are unavailable because codesign reported it unsigned.",
|
|
);
|
|
const states = { checked: [] as string[], unsigned: [] as string[] };
|
|
// A thin file's admitted architecture is a CPU family (arm64 for arm64e);
|
|
// codesign's display names the slice it described.
|
|
const described =
|
|
this.target.format === "mach-o-universal"
|
|
? selectedArchitecture
|
|
: (/^Mach-O thin \(([^)\r\n]+)\)$/u.exec(parsed.format ?? "")?.[1] ??
|
|
null);
|
|
const observation = () =>
|
|
inspectSignatureSchema.parse({
|
|
...parsed,
|
|
...(bundleProvenance === undefined
|
|
? {}
|
|
: { bundle_provenance: bundleProvenance }),
|
|
designated_requirement: requirementText,
|
|
entitlements: entitlementValue.value,
|
|
slices: {
|
|
described,
|
|
architectures,
|
|
unmapped: unknownSlices,
|
|
checked: [...states.checked],
|
|
unsigned: [...states.unsigned],
|
|
},
|
|
provenance: captures.map((capture) =>
|
|
invocation(capture, binding.snapshotPath),
|
|
),
|
|
limitations,
|
|
});
|
|
if (architectures.length > 1) {
|
|
const slices = await this.#inspectSignatureSliceStates(
|
|
binding,
|
|
architectures,
|
|
executablePaths,
|
|
{ captures, limitations, states },
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!slices.ok) {
|
|
limitations.push(
|
|
"Architecture-specific signature inspection did not complete; remaining slice signing states are unknown.",
|
|
);
|
|
return err(slices.error.retainPartialObservation(observation()));
|
|
}
|
|
}
|
|
const version = await verifySignatureTarget(this.target, binding, signal);
|
|
if (!version.ok)
|
|
return err(version.error.retainPartialObservation(observation()));
|
|
return ok(observation());
|
|
}
|
|
|
|
async #inspectSignatureSliceStates(
|
|
binding: SignatureTargetBinding,
|
|
architectures: readonly string[],
|
|
executablePaths: readonly string[],
|
|
observation: {
|
|
captures: NativeCommandCapture[];
|
|
limitations: string[];
|
|
/** Slices checked so far and those reported unsigned, kept when a later slice fails. */
|
|
states: { checked: string[]; unsigned: string[] };
|
|
},
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<void, AnalysisError>> {
|
|
const { captures, limitations, states } = observation;
|
|
let unsignedNote: number | undefined;
|
|
for (const architecture of architectures) {
|
|
const slice = await this.#captureSignature(
|
|
binding,
|
|
["-d", "-a", architecture, "--verbose=4"],
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!slice.ok) return slice;
|
|
captures.push(slice.value);
|
|
if (slice.value.exitCode === 0) {
|
|
states.checked.push(architecture);
|
|
continue;
|
|
}
|
|
const failure = codeSignCaptureFailure(
|
|
this.#signatureResources,
|
|
slice.value,
|
|
binding.snapshotPath,
|
|
executablePaths,
|
|
);
|
|
if (failure !== null) return err(failure);
|
|
states.checked.push(architecture);
|
|
states.unsigned.push(architecture);
|
|
if (unsignedNote === undefined) {
|
|
unsignedNote = limitations.length;
|
|
limitations.push("");
|
|
}
|
|
limitations[unsignedNote] =
|
|
`Unsigned Mach-O slices: ${states.unsigned.join(", ")}.`;
|
|
}
|
|
return ok(undefined);
|
|
}
|
|
|
|
async #captureSignature(
|
|
binding: SignatureTargetBinding,
|
|
args: readonly string[],
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<NativeCommandCapture, AnalysisError>> {
|
|
const before = await verifySignatureTarget(this.target, binding, signal);
|
|
if (!before.ok) return before;
|
|
let capture: Result<NativeCommandCapture, AnalysisError>;
|
|
try {
|
|
capture = await this.#run(
|
|
"inspect_signature",
|
|
"codesign",
|
|
[...args, binding.snapshotPath],
|
|
{
|
|
signal,
|
|
acceptNonZero: true,
|
|
timeoutMs,
|
|
},
|
|
);
|
|
} catch (cause: unknown) {
|
|
capture = err(
|
|
new ProviderAdapterError(IDENTITY.id, "inspect_signature", {
|
|
cause,
|
|
diagnostics: {
|
|
phase: "codesign-capture",
|
|
path: this.target.path,
|
|
reason: errorMessage(cause),
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
// Verify failed captures too: a disappearing target is not a codesign
|
|
// execution failure, and later captures must never use another version.
|
|
const after = await verifySignatureTarget(this.target, binding, signal);
|
|
if (!capture.ok && !after.ok) {
|
|
const primary =
|
|
after.error instanceof AnalysisCancelledError
|
|
? analysisErrorWithCancellation(capture.error, after.error)
|
|
: after.error;
|
|
return err(
|
|
nativeFailureWithCommandCleanup(
|
|
primary,
|
|
capture.error,
|
|
"inspect_signature",
|
|
),
|
|
);
|
|
}
|
|
return after.ok ? capture : after;
|
|
}
|
|
|
|
async #inspectPlist(
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
const requested = parameters.path;
|
|
if (requested !== undefined && typeof requested !== "string")
|
|
return err(
|
|
new AnalysisOutputError("inspect_plist", "path was not a string"),
|
|
);
|
|
try {
|
|
return await this.#plistResources.run(async () => {
|
|
if (
|
|
this.activeTarget === undefined ||
|
|
this.activeTarget.kind !== "executable" ||
|
|
this.activeTarget.bundleInfoPlist === undefined
|
|
)
|
|
return this.#readPlist(requested, signal, timeoutMs);
|
|
try {
|
|
const observation = await withArtifactTargetIdentity(
|
|
this.activeTarget,
|
|
this.#plistResources,
|
|
async () => {
|
|
const result = await this.#readPlist(
|
|
requested,
|
|
signal,
|
|
timeoutMs,
|
|
);
|
|
if (!result.ok) throw result.error;
|
|
return result.value;
|
|
},
|
|
signal,
|
|
);
|
|
return ok(observation);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof AnalysisError) return err(cause);
|
|
return err(
|
|
nativePlistFailure(cause, {
|
|
path: this.activeTarget.path,
|
|
origin: "selected",
|
|
}),
|
|
);
|
|
}
|
|
});
|
|
} catch (cause: unknown) {
|
|
return err(nativePlistFailure(cause, undefined));
|
|
}
|
|
}
|
|
|
|
async #readPlist(
|
|
requested: string | undefined,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
try {
|
|
const plist =
|
|
this.bundleResourceRoot === undefined
|
|
? await resolveNativePlistSelection(this.target, requested)
|
|
: resolveBundleResourcePlistSelection(
|
|
this.bundleResourceRoot,
|
|
requested,
|
|
);
|
|
if (!plist.ok) return plist;
|
|
const fileInput: NativePlistReadContext = {
|
|
selection: plist.value,
|
|
resources: this.#plistResources,
|
|
signal,
|
|
timeoutMs,
|
|
};
|
|
const source = await readNativePlistBytes(fileInput);
|
|
if (!source.ok) return source;
|
|
const bytes = source.value;
|
|
const sha256 = sha256Hex(bytes);
|
|
return await this.#withPrivateNativeOperand(
|
|
{
|
|
operation: "inspect_plist",
|
|
label: "private plist snapshot",
|
|
prefix: "rea-plist-source-",
|
|
sourcePath: plist.value.path,
|
|
},
|
|
signal,
|
|
async (root) => {
|
|
const operand = join(root, "source.plist");
|
|
await writeFile(operand, bytes, { flag: "wx", mode: 0o400 });
|
|
return operand;
|
|
},
|
|
async (operand) => {
|
|
try {
|
|
return await this.#inspectPlistSnapshot({
|
|
...fileInput,
|
|
bytes,
|
|
sha256,
|
|
operand,
|
|
});
|
|
} catch (cause: unknown) {
|
|
return err(nativeOutputFailure("inspect_plist", cause));
|
|
}
|
|
},
|
|
);
|
|
} catch (cause: unknown) {
|
|
// Producer failures stay opaque; only scope admission failures reach the file mapper.
|
|
return err(nativeOutputFailure("inspect_plist", cause));
|
|
}
|
|
}
|
|
|
|
async #inspectPlistSnapshot(
|
|
source: NativePlistSnapshot,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
const { signal, timeoutMs, operand } = source;
|
|
const classified = await this.#run(
|
|
"inspect_plist",
|
|
"file",
|
|
["-b", operand],
|
|
{
|
|
signal,
|
|
timeoutMs,
|
|
},
|
|
);
|
|
if (!classified.ok) return classified;
|
|
const format = plistSourceFormat(classified.value.stdout, source.bytes);
|
|
if (format === "binary")
|
|
return this.#inspectBinaryPlist(source, classified.value);
|
|
const direct = await this.#inspectTextPlist(
|
|
source,
|
|
classified.value,
|
|
format,
|
|
);
|
|
return (
|
|
direct ??
|
|
(await this.#inspectConvertedPlist(source, classified.value, format))
|
|
);
|
|
}
|
|
|
|
#inspectBinaryPlist(
|
|
fileInput: NativePlistSnapshot,
|
|
classified: NativeCommandCapture,
|
|
): Result<NativeObservation, AnalysisError> {
|
|
const parsed = parsePlistBinary(fileInput.bytes);
|
|
if (!parsed.ok) {
|
|
if (parsed.error instanceof UnsupportedBinaryPlistUidError)
|
|
return err(
|
|
new AnalysisTargetFailureError(
|
|
"inspect_plist",
|
|
fileInput.selection.path,
|
|
parsed.error.failure,
|
|
{ cause: parsed.error },
|
|
),
|
|
);
|
|
return parsed.error instanceof AnalysisOutputError
|
|
? err(
|
|
unreadablePlist(
|
|
fileInput.selection,
|
|
"binary property list could not be decoded",
|
|
{ cause: parsed.error },
|
|
),
|
|
)
|
|
: err(parsed.error);
|
|
}
|
|
return ok(
|
|
nativePlistObservation({
|
|
parsed: parsed.value,
|
|
format: "binary",
|
|
path: fileInput.selection.path,
|
|
sourceSha256: fileInput.sha256,
|
|
resourceRoot: this.bundleResourceRoot,
|
|
provenance: [invocation(classified, fileInput.operand, "$PLIST")],
|
|
}),
|
|
);
|
|
}
|
|
|
|
async #inspectTextPlist(
|
|
fileInput: NativePlistSnapshot,
|
|
classified: NativeCommandCapture,
|
|
format: z.infer<typeof inspectPlistSchema>["format"],
|
|
): Promise<Result<NativeObservation, AnalysisError> | undefined> {
|
|
let parsed: ReturnType<typeof parsePlistXmlSource>;
|
|
const provenance = [invocation(classified, fileInput.operand, "$PLIST")];
|
|
if (format === "xml") {
|
|
parsed = parsePlistXmlSource(fileInput.bytes);
|
|
if (parsed.ok) {
|
|
const validated = await this.#run(
|
|
"inspect_plist",
|
|
"plutil",
|
|
["-lint", "--", fileInput.operand],
|
|
{
|
|
signal: fileInput.signal,
|
|
acceptNonZero: true,
|
|
timeoutMs: fileInput.timeoutMs,
|
|
},
|
|
);
|
|
if (!validated.ok) return validated;
|
|
if (validated.value.exitCode !== 0)
|
|
return err(
|
|
nativePlistDecodeFailure(
|
|
fileInput.selection,
|
|
validated.value,
|
|
fileInput.operand,
|
|
),
|
|
);
|
|
provenance.push(
|
|
invocation(validated.value, fileInput.operand, "$PLIST"),
|
|
);
|
|
}
|
|
if (
|
|
!parsed.ok &&
|
|
parsed.error instanceof XmlPlistTextDecodeError &&
|
|
parsed.error.reason === "unsupported-encoding"
|
|
)
|
|
return undefined;
|
|
const refusal = parsed.ok ? undefined : xmlSyntaxRefusal(parsed.error);
|
|
if (refusal !== undefined)
|
|
return await this.#inspectConvertedPlist(
|
|
fileInput,
|
|
classified,
|
|
format,
|
|
refusal,
|
|
);
|
|
} else {
|
|
const json = readPlistJsonSource(fileInput.bytes);
|
|
if (
|
|
json === undefined ||
|
|
json.rootKind === "invalid" ||
|
|
(json.rootKind !== "container" && format !== "json") ||
|
|
json.needsNumberTypes ||
|
|
json.nonFiniteNumberObserved
|
|
)
|
|
return undefined;
|
|
parsed = json.project();
|
|
}
|
|
if (!parsed.ok)
|
|
return parsed.error instanceof AnalysisOutputError ||
|
|
parsed.error instanceof XmlPlistTextDecodeError
|
|
? err(
|
|
unreadablePlist(fileInput.selection, parsed.error.message, {
|
|
cause: parsed.error,
|
|
}),
|
|
)
|
|
: err(parsed.error);
|
|
return ok(
|
|
nativePlistObservation({
|
|
parsed: parsed.value,
|
|
format,
|
|
path: fileInput.selection.path,
|
|
sourceSha256: fileInput.sha256,
|
|
resourceRoot: this.bundleResourceRoot,
|
|
provenance,
|
|
}),
|
|
);
|
|
}
|
|
|
|
async #inspectConvertedPlist(
|
|
fileInput: NativePlistSnapshot,
|
|
classified: NativeCommandCapture,
|
|
format: z.infer<typeof inspectPlistSchema>["format"],
|
|
sourceRefusal?: string,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
const { path } = fileInput.selection;
|
|
const { signal, timeoutMs, operand } = fileInput;
|
|
const json = await this.#run(
|
|
"inspect_plist",
|
|
"plutil",
|
|
["-convert", "json", "-o", "-", "--", operand],
|
|
{ signal, acceptNonZero: true, timeoutMs },
|
|
);
|
|
if (!json.ok) return json;
|
|
// JSON cannot express data, dates, or non-finite reals; plutil rejects
|
|
// such plists, so decode its XML conversion instead. JSON also prints an
|
|
// integral <real> like an <integer>, so XML identifies unsafe number types.
|
|
const jsonDecoded = json.value.exitCode === 0;
|
|
const jsonAttempt = jsonDecoded
|
|
? readPlistJson(json.value.stdout)
|
|
: undefined;
|
|
let xml: NativeCommandCapture | undefined;
|
|
let parsed: Result<
|
|
ParsedPlist,
|
|
AnalysisOutputError | AnalysisResourceConstraintError
|
|
>;
|
|
if (jsonAttempt === undefined || jsonAttempt.needsNumberTypes) {
|
|
const converted = await this.#run(
|
|
"inspect_plist",
|
|
"plutil",
|
|
["-convert", "xml1", "-o", "-", "--", operand],
|
|
{ signal, acceptNonZero: !jsonDecoded, timeoutMs },
|
|
);
|
|
if (!converted.ok) return converted;
|
|
xml = converted.value;
|
|
if (xml.exitCode !== 0) {
|
|
return err(nativePlistDecodeFailure(fileInput.selection, xml, operand));
|
|
}
|
|
parsed =
|
|
jsonAttempt === undefined
|
|
? parsePlistXml(xml.stdout)
|
|
: jsonAttempt.project(xml.stdout);
|
|
} else {
|
|
parsed = jsonAttempt.project();
|
|
}
|
|
if (!parsed.ok) return parsed;
|
|
const provenance = [
|
|
classified,
|
|
json.value,
|
|
...(xml === undefined ? [] : [xml]),
|
|
].map((item) => invocation(item, operand, "$PLIST"));
|
|
return ok(
|
|
nativePlistObservation({
|
|
parsed:
|
|
sourceRefusal === undefined
|
|
? parsed.value
|
|
: {
|
|
...parsed.value,
|
|
limitations: [
|
|
`REA's XML reader refused the source (${sourceRefusal}), but plutil read it, so the value comes from plutil's conversion rather than the original text.`,
|
|
...parsed.value.limitations,
|
|
],
|
|
},
|
|
format,
|
|
path,
|
|
sourceSha256: fileInput.sha256,
|
|
resourceRoot: this.bundleResourceRoot,
|
|
provenance,
|
|
}),
|
|
);
|
|
}
|
|
|
|
async #inspectMacho(
|
|
parameters: Readonly<Record<string, JsonValue>>,
|
|
signal: AbortSignal | undefined,
|
|
timeoutMs: number,
|
|
bundleProvenance: BundleExecutableProvenance | undefined,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
if (!isMachOFormat(this.target.format))
|
|
return err(
|
|
new AnalysisCapabilityUnavailableError(
|
|
IDENTITY.id,
|
|
"inspect_macho",
|
|
"Active artifact is not Mach-O.",
|
|
),
|
|
);
|
|
const needsPrivateOtoolOperand = /\([^/]*\)$/u.test(
|
|
basename(this.target.path),
|
|
);
|
|
const inspect = (privateOperand?: string) =>
|
|
withNativeMachoSource(
|
|
this.target,
|
|
this.#machoResources,
|
|
signal,
|
|
(source) =>
|
|
inspectNativeMacho({
|
|
target: this.target,
|
|
...(bundleProvenance === undefined ? {} : { bundleProvenance }),
|
|
...(signal === undefined ? {} : { signal }),
|
|
run: (tool, arguments_, commandSignal, acceptNonZeroIf) =>
|
|
this.#run(
|
|
"inspect_macho",
|
|
tool,
|
|
privateOperand !== undefined
|
|
? arguments_.map((argument) =>
|
|
argument === this.target.path ? privateOperand : argument,
|
|
)
|
|
: arguments_,
|
|
{
|
|
signal: commandSignal,
|
|
timeoutMs,
|
|
...(acceptNonZeroIf === undefined ? {} : { acceptNonZeroIf }),
|
|
},
|
|
),
|
|
invocation: (capture) => invocation(capture, this.target.path),
|
|
// Encryption facts come from the same identity-bound descriptor.
|
|
readEncryption: () =>
|
|
readMachoEncryption(
|
|
(at, length) =>
|
|
source.readSlice(
|
|
0,
|
|
source.bytes,
|
|
Math.min(at, source.bytes),
|
|
Math.max(0, Math.min(length, source.bytes - at)),
|
|
),
|
|
source.bytes,
|
|
MACHO_ENCRYPTION_MAPPING_RECORDS,
|
|
),
|
|
resolveSlice: (selected) =>
|
|
resolveSelectedMachoSlice(
|
|
source,
|
|
selected,
|
|
Math.floor(NATIVE_COMMAND_OUTPUT_BUDGET_BYTES / 256),
|
|
),
|
|
readSliceRange: (offset, size, at, length) =>
|
|
source.readSlice(
|
|
offset,
|
|
size ?? source.bytes - offset,
|
|
at,
|
|
length,
|
|
),
|
|
readCommandNames: async (offset, size, selected) => {
|
|
const length = size ?? source.bytes - offset;
|
|
// Binary strings can expand to hex and escaped JSON, and each
|
|
// record becomes several objects. Reserve room for those forms.
|
|
const maximum = Math.floor(
|
|
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES / 12,
|
|
);
|
|
const maximumRecords = Math.floor(
|
|
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES / 256,
|
|
);
|
|
const binary = await readMachoCommandNames(
|
|
(at, bytes) => source.readSlice(offset, length, at, bytes),
|
|
length,
|
|
maximum,
|
|
maximumRecords,
|
|
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES,
|
|
);
|
|
if (size !== null) {
|
|
if (selected === undefined)
|
|
throw invariantViolation(
|
|
"Selected Mach-O slice is unavailable",
|
|
);
|
|
assertSelectedMachoSlice(source, selected, binary);
|
|
}
|
|
return binary;
|
|
},
|
|
}),
|
|
);
|
|
try {
|
|
return await this.#machoResources.run(() =>
|
|
needsPrivateOtoolOperand
|
|
? this.#withPrivateNativeOperand(
|
|
{
|
|
operation: "inspect_macho",
|
|
label: "private otool operand",
|
|
prefix: "rea-macho-operand-",
|
|
sourcePath: this.target.path,
|
|
},
|
|
signal,
|
|
async (root) => {
|
|
const operand = join(root, "artifact.macho");
|
|
await symlink(this.target.path, operand);
|
|
return operand;
|
|
},
|
|
async (operand) => {
|
|
try {
|
|
return await inspect(operand);
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
nativeMachoSourceFailure(
|
|
cause,
|
|
this.target,
|
|
parameters,
|
|
"inspect_macho",
|
|
),
|
|
);
|
|
}
|
|
},
|
|
)
|
|
: inspect(),
|
|
);
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
nativeMachoSourceFailure(
|
|
cause,
|
|
this.target,
|
|
parameters,
|
|
"inspect_macho",
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
async #withPrivateNativeOperand(
|
|
{ operation, label, prefix, sourcePath }: NativePrivateOperand,
|
|
signal: AbortSignal | undefined,
|
|
prepare: (root: string) => Promise<string>,
|
|
inspect: (
|
|
operand: string,
|
|
) => Promise<Result<NativeObservation, AnalysisError>>,
|
|
): Promise<Result<NativeObservation, AnalysisError>> {
|
|
try {
|
|
return await this.#nativeOperandResources.run(async () => {
|
|
if (signal?.aborted) return err(cancelledBy(operation, signal));
|
|
let root: Pick<PrivateRuntimeRoot, "path" | "close">;
|
|
try {
|
|
root = await (this.privateRuntimeRootFactory?.() ??
|
|
PrivateRuntimeRoot.create({ prefix }));
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
new ProviderAdapterError(IDENTITY.id, operation, {
|
|
cause,
|
|
diagnostics: {
|
|
reason: `Unable to create a ${label}`,
|
|
path: sourcePath,
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
const owner = {
|
|
kind: "lease" as const,
|
|
resource: root.path,
|
|
lease: {
|
|
release: async () => {
|
|
const commandFailure = await this.#retryNativeCommandCleanup();
|
|
if (commandFailure !== undefined) throw commandFailure;
|
|
await root.close();
|
|
},
|
|
},
|
|
};
|
|
let result: Result<NativeObservation, AnalysisError>;
|
|
try {
|
|
const operand = await prepare(root.path);
|
|
result = signal?.aborted
|
|
? err(cancelledBy(operation, signal))
|
|
: await inspect(operand);
|
|
} catch (cause: unknown) {
|
|
result = err(
|
|
new ProviderAdapterError(IDENTITY.id, operation, {
|
|
cause,
|
|
diagnostics: {
|
|
reason: `Unable to prepare the ${label}`,
|
|
path: sourcePath,
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
const released = await this.#nativeOperandResources.release(owner);
|
|
const partial =
|
|
result.ok && (released.kind === "failed" || signal?.aborted)
|
|
? (operation === "inspect_macho"
|
|
? inspectMachoSchema
|
|
: inspectPlistSchema
|
|
).parse(result.value.result)
|
|
: undefined;
|
|
if (released.kind === "failed") {
|
|
const cleanup = new ProviderCleanupError(
|
|
IDENTITY.id,
|
|
[root.path],
|
|
{
|
|
reason: `The ${label} could not be released`,
|
|
},
|
|
{ operation, cause: released.cause },
|
|
);
|
|
if (partial !== undefined) cleanup.retainPartialObservation(partial);
|
|
new AnalysisCleanupLeaseGroup(cleanup, [released.lease]);
|
|
const primary = result.ok
|
|
? signal?.aborted
|
|
? cancelledBy(operation, signal, {
|
|
partialObservation: partial,
|
|
})
|
|
: undefined
|
|
: result.error;
|
|
return err(
|
|
primary === undefined
|
|
? cleanup
|
|
: analysisErrorWithCleanupDependencies(
|
|
primary,
|
|
cleanup,
|
|
operation,
|
|
),
|
|
);
|
|
}
|
|
if (signal?.aborted && result.ok)
|
|
return err(
|
|
cancelledBy(operation, signal, {
|
|
partialObservation: partial,
|
|
}),
|
|
);
|
|
return result;
|
|
});
|
|
} catch (cause: unknown) {
|
|
const failure = new ProviderCleanupError(
|
|
IDENTITY.id,
|
|
this.#nativeOperandResources.cleanupResources,
|
|
{
|
|
reason: "A previous private native command operand remains owned",
|
|
},
|
|
{ operation, cause },
|
|
);
|
|
bindArtifactFileCleanup(cause, failure);
|
|
return err(failure);
|
|
}
|
|
}
|
|
|
|
async #run(
|
|
operation: NativeToolName,
|
|
tool: string,
|
|
arguments_: readonly string[],
|
|
options: {
|
|
readonly signal?: AbortSignal | undefined;
|
|
readonly timeoutMs: number;
|
|
readonly acceptNonZero?: boolean;
|
|
readonly acceptNonZeroIf?:
|
|
| ((capture: NativeCommandCapture) => boolean)
|
|
| undefined;
|
|
},
|
|
): Promise<Result<NativeCommandCapture, AnalysisError>> {
|
|
// Commands borrow their enclosing operation's admission through finalization.
|
|
const captured = await this.runner.run(tool, arguments_, {
|
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
timeoutMs: options.timeoutMs,
|
|
acceptNonZero:
|
|
options.acceptNonZero ?? options.acceptNonZeroIf !== undefined,
|
|
});
|
|
if (captured.ok) {
|
|
const hasFailedExit =
|
|
captured.value.exitCode !== 0 || captured.value.signal !== null;
|
|
if (
|
|
hasFailedExit &&
|
|
options.acceptNonZeroIf !== undefined &&
|
|
!options.acceptNonZeroIf(captured.value)
|
|
)
|
|
return err(
|
|
translateNativeCommandFailure(
|
|
operation,
|
|
new NativeCommandFailure(
|
|
tool,
|
|
captured.value.signal !== null ||
|
|
(captured.value.exitCode !== null &&
|
|
captured.value.exitCode !== 0)
|
|
? "nonzero-exit"
|
|
: "io",
|
|
captured.value.exitCode,
|
|
undefined,
|
|
{
|
|
stdout: captured.value.stdout,
|
|
stderr: captured.value.stderr,
|
|
stdoutBytes: captured.value.stdoutBytes,
|
|
stderrBytes: captured.value.stderrBytes,
|
|
exitCode: captured.value.exitCode,
|
|
signal: captured.value.signal,
|
|
truncated: false,
|
|
},
|
|
),
|
|
this.#nativeOperandResources,
|
|
),
|
|
);
|
|
return captured;
|
|
}
|
|
return err(
|
|
translateNativeCommandFailure(
|
|
operation,
|
|
captured.error,
|
|
this.#nativeOperandResources,
|
|
options.timeoutMs,
|
|
),
|
|
);
|
|
}
|
|
}
|