From 69a691e058e020fc327c0cdaa4709bede3bfe46b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:10:39 -0500 Subject: [PATCH] perf(apple): eliminate Mach-O multi-pass schema/export re-parses and fuse AppleDispatchCoverage scans (#13550) --- src/native/AppleDispatchCoverage.ts | 151 ++++++++---------- src/native/AppleDispatchMetadata.ts | 2 +- src/native/NativeMachoInspection.ts | 236 ++++++++++++++++------------ src/native/parsers/dyldInfo.ts | 119 +++++++------- 4 files changed, 264 insertions(+), 244 deletions(-) diff --git a/src/native/AppleDispatchCoverage.ts b/src/native/AppleDispatchCoverage.ts index 7da1cbd7a9..30c0698d53 100644 --- a/src/native/AppleDispatchCoverage.ts +++ b/src/native/AppleDispatchCoverage.ts @@ -53,68 +53,60 @@ export const pushDispatchCoverage = (input: { vtables, swift, } = input; - const classOwnedMethods = result.objc_dispatch_implementations.filter( - ({ category }) => category === undefined, - ); - const classRecords = [ - ...result.objc_classes.flatMap((record) => - record.decode?.status === "decoded" - ? [] - : [ - `class ${record.name}: ${record.decode?.reason ?? record.decode?.status ?? "decode_status_missing"}`, - ], - ), - ...result.objc_protocol_records.flatMap((record) => - record.decode.status === "decoded" - ? [] - : [ - `protocol ${record.name}: ${record.decode.reason ?? record.decode.status}`, - ], - ), - ...classOwnedMethods.flatMap((record) => - record.decode.status === "decoded" - ? [] - : [ - `method ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`, - ], - ), - ...result.objc_ivars.flatMap((record) => - record.decode.status === "decoded" - ? [] - : [ - `ivar ${record.class_name}.${record.name}: ${record.decode.reason ?? record.decode.status}`, - ], - ), - ]; + const classRecords: string[] = []; + let decodedClasses = 0; + for (const record of result.objc_classes) { + if (record.decode?.status === "decoded") decodedClasses++; + else + classRecords.push( + `class ${record.name}: ${record.decode?.reason ?? record.decode?.status ?? "decode_status_missing"}`, + ); + } + for (const record of result.objc_protocol_records) { + if (record.decode.status !== "decoded") + classRecords.push( + `protocol ${record.name}: ${record.decode.reason ?? record.decode.status}`, + ); + } + const categoryMethodReasons: string[] = []; + for (const record of result.objc_dispatch_implementations) { + if (record.decode.status === "decoded") continue; + if (record.category === undefined) + classRecords.push( + `method ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`, + ); + else + categoryMethodReasons.push( + `category method ${record.category} ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`, + ); + } + for (const record of result.objc_ivars) { + if (record.decode.status !== "decoded") + classRecords.push( + `ivar ${record.class_name}.${record.name}: ${record.decode.reason ?? record.decode.status}`, + ); + } const classReasons = [ ...failures, ...classRecords, ...(truncated || objcListScanTruncated ? ["max_records_reached"] : []), ]; - const categoryMethods = result.objc_dispatch_implementations.filter( - ({ category }) => category !== undefined, - ); - const categoryMethodReasons = categoryMethods.flatMap((record) => - record.decode.status === "decoded" - ? [] - : [ - `category method ${record.category} ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`, - ], - ); result.coverage.push({ facet: "objc_class_method_ivar_metadata", status: classReasons.length > 0 ? "partial" : "complete", reason: classReasons.join("; ") || null, examined, - decoded: result.objc_classes.filter( - ({ decode }) => decode?.status === "decoded", - ).length, + decoded: decodedClasses, }); + let decodedRelativePointers = 0; + for (const item of result.relative_pointers) { + if (item.decode.status === "decoded") decodedRelativePointers++; + } + const hasUnresolvedRelativePointers = + decodedRelativePointers < result.relative_pointers.length; const relativePointerReasons = [ ...(truncated || objcClassListScanTruncated ? ["max_records_reached"] : []), - ...(result.relative_pointers.some( - (item) => item.decode.status !== "decoded", - ) + ...(hasUnresolvedRelativePointers ? ["relative_pointer_targets_unresolved"] : []), ]; @@ -123,10 +115,14 @@ export const pushDispatchCoverage = (input: { status: relativePointerReasons.length > 0 ? "partial" : "complete", reason: relativePointerReasons.join("; ") || null, examined: result.relative_pointers.length, - decoded: result.relative_pointers.filter( - (item) => item.decode.status === "decoded", - ).length, + decoded: decodedRelativePointers, }); + let decodedCategories = 0; + for (const { decode } of result.objc_categories) { + if (decode.status === "decoded") decodedCategories++; + } + const hasUnresolvedCategories = + decodedCategories < result.objc_categories.length; const categoryFailures = categoryIssues.map( ({ code, location, message }) => `${code}${location === undefined ? "" : ` at ${location}`}: ${message}`, @@ -137,9 +133,7 @@ export const pushDispatchCoverage = (input: { truncated || objcClassListScanTruncated || categoryFailures.length > 0 || - result.objc_categories.some( - ({ decode }) => decode.status !== "decoded", - ) || + hasUnresolvedCategories || categoryMethodReasons.length > 0 ? "partial" : "complete", @@ -152,9 +146,7 @@ export const pushDispatchCoverage = (input: { : []), ].join("; ") || null, examined: categoriesExamined, - decoded: result.objc_categories.filter( - ({ decode }) => decode.status === "decoded", - ).length, + decoded: decodedCategories, }); const fixupReason = [ describeFixups(fixups), @@ -185,33 +177,28 @@ export const pushDispatchCoverage = (input: { examined: 0, decoded: 0, }); + let hasUnresolvedWitnessSlot = false; + let hasUnresolvedVtableSlot = false; + for (const { table_kind, decode } of result.swift_dispatch_slots) { + if (decode.status === "decoded") continue; + if (table_kind === "witness_table") hasUnresolvedWitnessSlot = true; + else if (table_kind === "class_vtable") hasUnresolvedVtableSlot = true; + if (hasUnresolvedWitnessSlot && hasUnresolvedVtableSlot) break; + } + const hasUnresolvedSwiftConformance = + hasUnresolvedWitnessSlot || + result.swift_conformances.some(({ decode }) => decode.status !== "decoded"); result.coverage.push({ facet: "swift_conformances_static_witness_slots", status: - swift.exhaustive && - !truncated && - !result.swift_conformances.some( - ({ decode }) => decode.status !== "decoded", - ) && - !result.swift_dispatch_slots.some( - ({ table_kind, decode }) => - table_kind === "witness_table" && decode.status !== "decoded", - ) + swift.exhaustive && !truncated && !hasUnresolvedSwiftConformance ? "complete" : "partial", reason: [ ...swift.issues.map(formatIssue), ...(truncated ? ["max_records_reached"] : []), - ...(result.swift_conformances.some( - ({ decode }) => decode.status !== "decoded", - ) || - result.swift_dispatch_slots.some( - ({ table_kind, decode }) => - table_kind === "witness_table" && decode.status !== "decoded", - ) - ? ["swift_records_unresolved"] - : []), + ...(hasUnresolvedSwiftConformance ? ["swift_records_unresolved"] : []), ].join("; ") || null, examined: swift.examined, decoded: swift.decoded, @@ -230,22 +217,14 @@ export const pushDispatchCoverage = (input: { result.coverage.push({ facet: "swift_class_vtable_descriptors", status: - vtables.exhaustive && - !truncated && - !result.swift_dispatch_slots.some( - ({ table_kind, decode }) => - table_kind === "class_vtable" && decode.status !== "decoded", - ) + vtables.exhaustive && !truncated && !hasUnresolvedVtableSlot ? "complete" : "partial", reason: [ ...vtables.issues.map(formatIssue), ...(truncated ? ["max_records_reached"] : []), - ...(result.swift_dispatch_slots.some( - ({ table_kind, decode }) => - table_kind === "class_vtable" && decode.status !== "decoded", - ) + ...(hasUnresolvedVtableSlot ? ["vtable_implementations_unresolved"] : []), ].join("; ") || null, diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index c7b1088a08..72e668d0a0 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -325,7 +325,7 @@ export function* decodeAppleDispatchMetadataSteps( vtables: vtables.facts(), swift, }); - return objcSwiftMetadataSchema.parse(result); + return result; } const OPERATION = "inspect_native_dispatch_metadata"; diff --git a/src/native/NativeMachoInspection.ts b/src/native/NativeMachoInspection.ts index 3dba1fbf78..070c79d547 100644 --- a/src/native/NativeMachoInspection.ts +++ b/src/native/NativeMachoInspection.ts @@ -26,9 +26,12 @@ import { } from "../domain/apple/machoArchitectureSelection.js"; import { parseDyldExportAddressRow, + parseDyldExportLine, parseDyldExports, parseDyldImports, } from "./parsers/dyldInfo.js"; + +type ParsedDyldExport = ReturnType[number]; import { parseLipoCapture } from "./parsers/lipo.js"; import { withoutEchoedPathHeader } from "./parsers/echoedPath.js"; import { @@ -340,16 +343,39 @@ export const inspectNativeMacho = async ( load.commands.some(({ kind }) => kind === "LC_UUID") ) return err(conflictingUuidCommandEvidence(uuidlessDyldFailure)); + 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. - if ( - dyldSliceRefusal(dyldExports) === null && - !namesEveryExport(captures[nmIndex]!.stdout, dyldExports) - ) { - const withDyldInfo = await runSliceCommand(DYLD_INFO_EXPORTS); - if (!withDyldInfo.ok) return withDyldInfo; - captures[nmIndex] = withDyldInfo.value; + let precomputedExports: + | { + readonly nmExports: ReturnType; + readonly dyldExports: ParsedDyldExport[]; + } + | undefined; + if (dyldSliceRefusal(dyldExports) === null) { + const coverage = analyzeExportCoverage( + captures[nmIndex]!.stdout, + dyldExports, + imageBase, + ); + if (coverage.covered) + precomputedExports = { + nmExports: coverage.nmExports, + dyldExports: coverage.dyldExports, + }; + else { + const withDyldInfo = await runSliceCommand(DYLD_INFO_EXPORTS); + if (!withDyldInfo.ok) return withDyldInfo; + captures[nmIndex] = withDyldInfo.value; + } } const dyldImports = captures.find( ({ tool, arguments: arguments_ }) => @@ -399,43 +425,18 @@ export const inspectNativeMacho = async ( (architectures.length === 1 ? (architectures[0]?.name ?? null) : null); const containerOffset = selectedArchitectureName === null ? undefined : offset; - const observed = normalizeMacho( - captures, - format, - context.invocation, - limitations, - load, - binary.sliceSize, - parsedImports.items, - captures[nmIndex]!, - { format, architectures, encryption }, - { - name: selectedArchitectureName, - container_file_offset: containerOffset ?? null, - }, - ); - const outsideEntrypoint = observed.entrypoints.items.some( + const outsideEntrypoint = load.entrypoints.some( ({ file_offset }) => file_offset >= binary.sliceSize, ); - const normalized = outsideEntrypoint - ? inspectMachoSchema.parse({ - ...observed, - entrypoints: { - ...observed.entrypoints, - exhaustive: false, - total: null, - limitations: [ - ...observed.entrypoints.limitations, - "An entrypoint lies outside the selected Mach-O slice.", - ], - }, - }) - : observed; 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.", + ] : [ - ...(normalized.entrypoints.items.some( + ...(load.entrypoints.some( ({ file_offset }) => file_offset >= binary.sliceSize || !Number.isSafeInteger(containerOffset + file_offset), @@ -444,7 +445,7 @@ export const inspectNativeMacho = async ( "Some entrypoint file locations are outside the selected slice or exceed the supported integer range.", ] : []), - ...(normalized.segments.items.some( + ...(load.segments.some( ({ file_offset, file_size }) => file_offset === null || file_size === null || @@ -456,30 +457,34 @@ export const inspectNativeMacho = async ( ] : []), ]; - const result = - containerOffset === undefined - ? inspectMachoSchema.parse({ - ...normalized, - limitations: [ - ...normalized.limitations, - 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.", - ], - }) - : locationLimitations.length === 0 - ? normalized - : inspectMachoSchema.parse({ - ...normalized, - limitations: [...normalized.limitations, ...locationLimitations], - }); + 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: ownedJsonValueSchema.parse({ + result: { ...result, ...(context.bundleProvenance === undefined ? {} - : { bundle_provenance: context.bundleProvenance }), - }), + : { + bundle_provenance: ownedJsonValueSchema.parse( + context.bundleProvenance, + ), + }), + } as JsonValue, limitations: result.limitations, locations: fileOffsetLocations(result, containerOffset, binary.sliceSize), }); @@ -491,7 +496,7 @@ const normalizeMacho = ( toInvocation: (capture: NativeCommandCapture) => NativeCommandInvocation, additionalLimitations: readonly string[], load: BinaryMachoProjection, - sliceSize: number, + imageBase: string | null, parsedImports: ReturnType["items"], exportNames: NativeCommandCapture, slices: { @@ -503,6 +508,11 @@ const normalizeMacho = ( readonly name: string | null; readonly container_file_offset: number | null; }, + outsideEntrypoint: boolean, + precomputedExports?: { + readonly nmExports: ReturnType; + readonly dyldExports: ParsedDyldExport[]; + }, ) => { const { architectures } = slices; const encryption = encryptionCoverage(slices); @@ -513,20 +523,15 @@ const normalizeMacho = ( const exportsRefusal = dyldSliceRefusal(dyldExportsCapture); const imports = importsRefusal === null ? parsedImports.map(withRuntimeName) : []; - const imageBase = - load.segments.find( - (segment) => - segment.file_offset === 0 && - segment.file_size !== null && - segment.file_size > 0 && - segment.file_size <= sliceSize, - )?.vm_address ?? null; - const nmExports = parseNmExports(exportNames.stdout); - const dyldExports = parseDyldExports( - sliceOutput(dyldExportsCapture), - imageBase, - new Set(nmExports.map(({ name }) => name)), - ); + const nmExports = + precomputedExports?.nmExports ?? parseNmExports(exportNames.stdout); + const dyldExports = + precomputedExports?.dyldExports ?? + parseDyldExports( + sliceOutput(dyldExportsCapture), + imageBase, + new Set(nmExports.map(({ name }) => name)), + ); const exports = uniqueSymbols([...dyldExports, ...nmExports]).map( withRuntimeName, ); @@ -581,11 +586,19 @@ const normalizeMacho = ( file_type: load.fileType, flags: load.flags, uuid: uuid.value, - entrypoints: covered( - load.entrypoints, - load.entrypointLimitations.length === 0, - load.entrypointLimitations, - ), + 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, @@ -718,32 +731,47 @@ const captureLookup = }; /** - * Whether every dyld_info export row names a symbol-table export. A row this - * parser cannot read counts as uncovered, so an unfamiliar format falls back. + * 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 namesEveryExport = ( +const analyzeExportCoverage = ( nmOutput: string, - dyldExports: NativeCommandCapture, -): boolean => { - const names = new Set(parseNmSymbolNames(nmOutput)); - return sliceOutput(dyldExports) - .split("\n") - .every((rawLine, index) => { - // Keep a trailing carriage return: it belongs to the exported name. - const line = rawLine.trimStart(); - if ( - line.length === 0 || - (index === 0 && line.endsWith(":")) || - /^-?exports:$/u.test(line) || - /^offset\s+symbol$/u.test(line) - ) - return true; - const rows = parseDyldExports(line, null, names); - // The parser withholds a row only when nm names both of its readings. - if (rows.length === 0) - return names.has(parseDyldExportAddressRow(line)?.text ?? ""); - return rows.length === 1 && names.has(rows[0]!.name); - }); + dyldExportsCapture: NativeCommandCapture, + imageBase: string | null, +): + | { + readonly covered: true; + readonly nmExports: ReturnType; + readonly dyldExports: ParsedDyldExport[]; + } + | { readonly covered: false } => { + const nmExports = parseNmExports(nmOutput); + const names = new Set(nmExports.map(({ name }) => name)); + 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, names); + // The parser withholds a row only when nm names both of its readings. + if (row === null) { + if (!names.has(parseDyldExportAddressRow(line)?.text ?? "")) + return { covered: false }; + continue; + } + if (!names.has(row.name)) return { covered: false }; + parsed.push(row); + } + return { covered: true, nmExports, dyldExports: parsed }; }; // nm -j ends each name with LF; a carriage return before it is part of the name. diff --git a/src/native/parsers/dyldInfo.ts b/src/native/parsers/dyldInfo.ts index fcc6138cfe..be3bfb7e47 100644 --- a/src/native/parsers/dyldInfo.ts +++ b/src/native/parsers/dyldInfo.ts @@ -131,6 +131,61 @@ export const parseDyldExportAddressRow = ( : { address: match[1], text: match[2] }; }; +/** Decode one already-trimmed Apple dyld export row without re-splitting lines. */ +export const parseDyldExportLine = ( + line: string, + offsets: boolean, + imageBase: string | null, + knownExportNames: ReadonlySet, +): ParsedDyldExport | null => { + // dyld_info prints `_sym (from lib)`, or `_new (_old from lib)` when the + // source library names the symbol differently. Split the trailing + // parenthesized suffix with string scans so a library path containing + // " from ", or a source symbol containing parentheses such as + // `operator()`, cannot pull the match into nested lazy quantifiers. + const reexport = parseReexportRow(line, knownExportNames); + if (reexport !== null) + return { + name: reexport.name, + address: null, + weak: null, + reexport: true, + source: reexport.source, + ...(reexport.sourceSymbol === undefined + ? {} + : { sourceSymbol: reexport.sourceSymbol }), + }; + const row = parseDyldExportAddressRow(line); + if (row === null) return null; + const exported = /^(.+?)(?:\s+\[([^\]]+)\])?$/su.exec(row.text); + if (exported?.[1] === undefined) return null; + const rawName = row.text; + const literalName = knownExportNames.has(rawName); + // If nm establishes both interpretations, the textual row cannot bind an address or flags. + // Let the caller retain the exact nm names without guessing which one owns this row. + if ( + literalName && + exported[2] !== undefined && + knownExportNames.has(exported[1]) + ) + return null; + const annotation = literalName ? undefined : exported[2]; + const absolute = /\babsolute\b/u.test(annotation ?? ""); + const address = + offsets && !absolute + ? imageBase === null + ? null + : `0x${(BigInt(imageBase) + BigInt(row.address)).toString(16)}` + : canonicalHex(row.address); + return { + name: literalName ? rawName : exported[1], + address, + weak: /\bweak-def\b/u.test(annotation ?? "") ? true : null, + reexport: false, + source: null, + }; +}; + /** Decode Apple dyld export rows, projecting export offsets to VM addresses. */ export const parseDyldExports = ( output: string, @@ -140,59 +195,17 @@ export const parseDyldExports = ( const offsets = /^\s*offset\s+symbol\s*$/mu.test(output); // dyld_info ends rows with LF. A carriage return before it belongs to the // symbol name, so export rows keep their trailing text. - return output.split("\n").flatMap((rawLine) => { - const line = rawLine.trimStart(); - // dyld_info prints `_sym (from lib)`, or `_new (_old from lib)` when the - // source library names the symbol differently. Split the trailing - // parenthesized suffix with string scans so a library path containing - // " from ", or a source symbol containing parentheses such as - // `operator()`, cannot pull the match into nested lazy quantifiers. - const reexport = parseReexportRow(line, knownExportNames); - if (reexport !== null) - return [ - { - name: reexport.name, - address: null, - weak: null, - reexport: true, - source: reexport.source, - ...(reexport.sourceSymbol === undefined - ? {} - : { sourceSymbol: reexport.sourceSymbol }), - }, - ]; - const row = parseDyldExportAddressRow(line); - if (row === null) return []; - const exported = /^(.+?)(?:\s+\[([^\]]+)\])?$/su.exec(row.text); - if (exported?.[1] === undefined) return []; - const rawName = row.text; - const literalName = knownExportNames.has(rawName); - // If nm establishes both interpretations, the textual row cannot bind an address or flags. - // Let the caller retain the exact nm names without guessing which one owns this row. - if ( - literalName && - exported[2] !== undefined && - knownExportNames.has(exported[1]) - ) - return []; - const annotation = literalName ? undefined : exported[2]; - const absolute = /\babsolute\b/u.test(annotation ?? ""); - const address = - offsets && !absolute - ? imageBase === null - ? null - : `0x${(BigInt(imageBase) + BigInt(row.address)).toString(16)}` - : canonicalHex(row.address); - return [ - { - name: literalName ? rawName : exported[1], - address, - weak: /\bweak-def\b/u.test(annotation ?? "") ? true : null, - reexport: false, - source: null, - }, - ]; - }); + const exports: ParsedDyldExport[] = []; + for (const rawLine of output.split("\n")) { + const parsed = parseDyldExportLine( + rawLine.trimStart(), + offsets, + imageBase, + knownExportNames, + ); + if (parsed !== null) exports.push(parsed); + } + return exports; }; const canonicalHex = (value: string | undefined): string | null =>