diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 2463f8e90..3b19f1575 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|ClassHierarchyBuildStackTests|SpecializationEntryPointExecutorTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|ClassHierarchyBuildStackTests|SpecializationEntryPointExecutorTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests|StandardLibraryLeafLayoutTests|ProtocolRequirementPlacementInterfaceTests|ProtocolRequirementRightHandSideDumpTests|PrivateDeclarationSourceFileCommentsTests|PrivateDeclarationSourceFileRequestTests|ReaderKindCastScanTests|WrappedReaderInterfaceTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/AGENTS.md b/AGENTS.md index ea6d6f447..c7422fc41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This file provides guidance to coding agents when working with code in this repo A Swift library that parses Mach-O files to recover Swift metadata — types, protocols, conformances, field layouts — without loading the binary into a process. It carries its own demangler (symbolic references included) and reimplements the Swift runtime's own reading logic. `swift-section` is the companion CLI. -Requires Swift 6.2+ / Xcode 26.0+. +Requires Swift 6.3+ / Xcode 26.4+. **Detail lives in `Documentations/`, not here.** This file carries what an agent gets wrong by default; everything else is one link away. Start at [`Documentations/README.md`](Documentations/README.md) — `Internal/Modules/` for per-module reference, `Internal/` for topic notes, `Evolutions/` for the proposal per change, `Internal/TaskReports/` for per-task retrospectives. @@ -32,7 +32,7 @@ SwiftInspection and everything above it also import └── MachOCaches, MachOBase ``` -`SwiftLayout` is a peer of that spine: it depends on `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`. `TypeIndexing`, `SwiftDiffing`, `SwiftPrivateDiscriminators` and `OutputTransformer` hang off the same level as the modules that use them. +`SwiftLayout` is a peer of that spine: it depends on `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`. `TypeIndexing`, `SwiftDiffing`, `SwiftPrivateDiscriminators` and `OutputTransformer` hang off the same level as the modules that use them. `CrossReferenceAnalysis` reads machine code on MachOKit and `ARM64InstructionDecoding` (Support), which `SwiftThunkAnalysis` shares; it reaches up to `SwiftInspection`, `MachOSwiftSection` and `MachOObjCSection` to name functions the symbol table leaves unnamed (Swift metadata, `SymbolicDemangler`, Objective-C method lists) and to tell what a scan meets (class lists, type context descriptors, mangled names). **`Sources/` is grouped by layer, not flat**: `Support/`, `MachO/`, `ABI/`, `Analysis/`, `Declaration/`, `Output/`, `Commands/`, `Executables/`, `TestSupport/`, each holding the targets of that layer. SwiftPM's default `Sources/` therefore never applies — a new target goes into a group directory and declares `path: "Sources//"` in `Package.swift`. Code that locates a source file from `#filePath` assumes this depth: the fixture paths in `MachOFileName` / `MachOImageName` climb three levels to the package root, and the source scans in the tests take the module name from two levels below `Sources`. [0055-group-sources-by-layer](Documentations/Evolutions/0055-group-sources-by-layer.md). @@ -49,7 +49,7 @@ One or two lines each; the linked document is the authority. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). - **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. -- **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). +- **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. `dump` / `interface --emit-private-source-files` reach it through `SwiftDeclarationRendering`'s `PrivateDeclarationSourceFileProviding`, after one search over the whole image (`recoverSourceFiles(ofEveryDeclarationIn:)`) — asked one declaration at a time, every discriminator nothing recovers runs through all the candidates again. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). - **SwiftPrinting** — renders the model as Swift source: keywords the mangling does not carry (`class` vs `static`, `final`), bound rendering of specialized definitions, export-status annotation and `--exported-only` filtering. - **SwiftSpecialization** — generic specialization (`GenericSpecializer`, `ConformanceProvider`): in-process through the metadata accessors on a `MachOImage`, and offline on a `MachOFile` (`StaticSpecializationResult`: the instantiation's name and a `GenericArgumentBinding`, which the printer and the static layout engine render from — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)); grafts `specialize(...)` onto `TypeDefinition`. @@ -58,6 +58,8 @@ One or two lines each; the linked document is the authority. - **SwiftDiffing** — Mach-O-free ABI comparison over the indexed model: `ABIDiffer` (two-sided), `ABIEvolution` (N versions), `ABISnapshot` (the persisted baseline). [ABIDiffDesignAndLimitations.md](Documentations/Internal/ABIDiffDesignAndLimitations.md), [ABIEvolutionDesign.md](Documentations/Internal/ABIEvolutionDesign.md). - **SwiftLayout** — the static field-offset / type-layout engine: computes offline what the runtime computes, and degrades honestly when the binary does not carry the fact. [Modules/SwiftLayout.md](Documentations/Internal/Modules/SwiftLayout.md). - **SwiftThunkAnalysis** — reads an availability-conditional opaque type (a kind-9 accessor-function symbolic reference) by symbolically evaluating the thunk instead of running it. Capstone, ARM64 only. Also home of `ObjCMembers` (`ObjCMembers/`): a class's ObjC method table is its `@objc` member list, and it survives the strip that removes every `To` thunk symbol from an OS framework — the interface's only `@objc` evidence until then (the macOS 26.6 AppKit interface carried ZERO member-level `@objc`, and mis-marked `@objc dynamic` members `final`). Each entry is tied to its Swift member by the `To` thunk symbol at the IMP or — stripped — by decoding the anonymous thunk for the implementation it calls or materializes, guarded by the member's name being the importer's spelling of the selector; that gives `@objc`, the `override` of an ObjC-inherited member (invisible to Swift metadata: the compiler emits a NEW vtable entry for it, and an `@objc @implementation` class has no vtable) where an ancestor implements the selector, and `@objc(selector)` where the selector differs from the compiler's own derivation from the Swift name (never for an override or an `@objc` protocol witness, whose selectors are inherited — and therefore only when the whole ancestor chain and every adopted protocol were read, since a standalone file's bound superclass would otherwise turn every UIKit override into a false `@objc(hitTest:withEvent:)`; an `@implementation` body is NOT exempt — the compiler derives its selectors from the Swift names too and demands the header declare them). A name-only third tier for overrides ALWAYS runs and is recorded on the definition (`evidence == .selectorName`); acting on it is the consumer's call, taken through `ResolvedObjCMemberFacts` — the dump always renders it (it names every tie's evidence), the interface takes `SwiftDeclarationPrintConfiguration.infersObjCOverridesFromSelectorNames` (CLI `interface --infer-objc-overrides`, default off). That tier must NOT write `@objc` into `attributes`: the `final` recovery runs right after it and reads the attribute as proof of `@objc dynamic`, so a verdict the consumer never took would stick. The fixture's `.optimizedStripped` variant is what the tier exists for. `isOverride` / `isClassMember` on the member definitions OR in the JOINED tiers only, so `override class func` prints where `static` did; the name-only tier reaches those keywords through the resolved facts. [Modules/SwiftThunkAnalysis.md](Documentations/Internal/Modules/SwiftThunkAnalysis.md). +- **CrossReferenceAnalysis** — what each function of an in-process `MachOImage` references, read from its arm64 machine code by a hand decoder rather than Capstone (25–50 times faster; a whole macOS shared cache scans in two to three seconds): calls, tail calls, Objective-C sends, calls through an image's own stubs or through the stubs a macOS 27 / iOS 27 cache shares between all images, indirect calls, and references to Objective-C classes and Swift types. A `CrossReferenceAnalyzer` is a snapshot of the process's images, an image outside the cache going by the path dyld loaded it from; it keeps the function tables of the images it names functions in, and its class and type indexes, linkage and re-export names, for its lifetime, while whole-image scans build their tables and drop them. A callers prefilter looks for the names other images re-export a C function under too (CoreGraphics' `_CG…` for SkyLight's `_SL…`). A `CodeReferenceTable` is a value the host keeps — and a callers query uses `references(to:inImageAt:)`, which keeps only the matches: whole tables of a cache scanned on 28 threads peak at 1.5 GB. A host that keeps the references of a few images to query again and again keeps a `CodeReferenceIndex` instead (`referenceIndex(ofImageAt:)`, a quarter to a third of a table's memory, answering exactly what the filtered scans would); building one keeps the image's function table. Such a host reads ahead what a first query would read — an image's names (`prepareNames(inImageAt:)`), the prefilters' tables across all images (`preparePrefilters()`, on the calling thread alone) — counts it with `approximateByteCount(ofImageDataAt:)`, and lets go of the other images' with `releaseImageData(exceptForImagesAt:)` rather than replacing the analyzer, which would drop it all. Read a target's memory only after confirming it is mapped — data in `__text` decodes as branches to arbitrary addresses. [Modules/CrossReferenceAnalysis.md](Documentations/Internal/Modules/CrossReferenceAnalysis.md). +- **ARM64InstructionDecoding** — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. `SwiftThunkAnalysis` and `CrossReferenceAnalysis` share it. - **TypeIndexing** — `__C` module attribution (`__C.NSString` → `Foundation.NSString`), macOS-only, via SourceKit module interfaces + APINotes + a lazy ObjC-metadata index. [TypeIndexingPipeline.md](Documentations/Internal/TypeIndexingPipeline.md). - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. @@ -206,11 +208,18 @@ Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.m - **`LayoutWrapper` is `@dynamicMemberLookup` over `Layout`**, so every layout field already reads as `record.field`. Do NOT re-declare a property that only forwards to `layout`, nor one that only widens a field to `Int` (the house style casts at the use site). A same-named property of a different type shadows the dynamic member and reads as a trap. The lookup does not reach through an existential — code iterating erased conformers needs a genuine protocol member. - **`resolvedDirectOffset(from:)` needs a key path to a *stored* property of the CONCRETE `Layout`.** One formed in a generic context against a layout *protocol* addresses a witness instead; the lookup answers nil and the force-unwrap behind it traps at runtime — so a shared implementation over a layout protocol cannot use it, each conformer calls it itself. It always answers the DIRECT reading, so a relative-*indirectable* field rules out `isIndirect` first. A descriptor already exposing a named `…Offset` property is what a consumer calls; re-deriving it at the use site is what that property exists to prevent. - **Trap:** a generic read (`context.readElement(at:)`, `machO.readElement(offset:)`) whose result lands in an Optional is inferred AT the Optional and reads the Optional's in-memory shape — the field plus one tag byte — so it answers nil whenever the byte after the field is non-zero. Returning it from an optional-returning function, assigning it to an optional, `guard let x: T = try? …` and a `flatMap` closure all do this; read into an annotated non-optional local (or `… as T`) and wrap that. The byte is often padding the runtime never writes, so the symptom comes and goes with the allocator. -- **A reading API is written once, against `some ReadingContext`** (`x(in context:)`, static `resolve(at:in:)`). The Mach-O (`in machO:`) and pointer (no-argument) forms still in the tree are deprecated one-line forwarders kept until 0.24.0 ([0057-reading-context-migration](Documentations/Evolutions/0057-reading-context-migration.md)): never add a new one, never put logic in one, never call one — pass `machO.context` or `.inProcess`. A bind or rebase check goes through `context.bindRebaseResolver`, never `as? MachOFile`. +- **A reading API is written once, against `some ReadingContext`** (`x(in context:)`, static `resolve(at:in:)`). The Mach-O (`in machO:`) and pointer (no-argument) forms still in the tree are deprecated one-line forwarders kept until 0.25.0 ([0057-reading-context-migration](Documentations/Evolutions/0057-reading-context-migration.md)): never add a new one, never put logic in one, never call one — pass `machO.context` or `.inProcess`. A bind or rebase check goes through `context.bindRebaseResolver`, never `as? MachOFile`. - **Inside a constrained extension (`where Pointee: OptionalProtocol`), calling a method that is also a protocol requirement binds to the requirement — the unconstrained witness — not to the constrained overload beside it.** A guard that must run on every path lives in a private helper that the context form and the forwarders both call (`RelativeDirectPointerProtocol`); a forwarder that calls the context form by name skips it. + + +- **Ask `asMachOImage` / `asMachOFile` / `underlyingReader` (MachOKitExtensions); never cast to `MachOImage` / `MachOFile` or `MachOContext`.** A host's wrapper type (MachOKitUI's `MachOImageSource`) declares `MachOReaderWrapper` and answers for the reader beneath it; a cast cannot see through it. The cast on the in-process opaque path trapped (`Negative value is not representable`); the other 37 silently treated a wrapper as neither reader. `ReaderKindCastScanTests` fails on one. +- A capability protocol is asked of the reader first and of `underlyingReader` second (`bindRebaseResolver`). A protocol that picks a strategy by type at compile time gives `MachOReaderWrapper` a default that forwards to `Base` (`FieldLayoutRenderable`), so a wrapper conforms with an empty body. [ReadingContextAbstraction.md](Documentations/Internal/ReadingContextAbstraction.md). + + + - **Every per-image cache is a `SharedCache` with a `SharedCacheEvictionGroup`, held by composition** — never a hand-written lock plus `[key: value]` dictionary, never a subclass. The build closure goes at the call site; re-type the reader once through `swiftSectionReader` / `objcImplementationClassReader` (SwiftInspection) instead of an `as? MachOFile` / `as? MachOImage` split. diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 9e2303a91..17d8f70c4 100644 --- a/AgentPlugins/swift-section/.claude-plugin/plugin.json +++ b/AgentPlugins/swift-section/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.23.0", + "version": "0.24.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/.codex-plugin/plugin.json b/AgentPlugins/swift-section/.codex-plugin/plugin.json index aa8ec0464..b1364c508 100644 --- a/AgentPlugins/swift-section/.codex-plugin/plugin.json +++ b/AgentPlugins/swift-section/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.23.0", + "version": "0.24.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index d173cdf25..964fcf082 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -43,10 +43,11 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, `--emit-export-status`, `--exported-only`, `--jobs`, `evolution --interface`, `--supplementary-apinotes`, from 0.20.0 `--dependency-search-path`, `--infer-objc-overrides` and the whole `objc` subcommand group, from 0.22.0 -`evolution --emit-available` / `--platform`, and from 0.23.0 `interface --module-selectors` -/ `dump --enable-module-selectors`. When one is missing, say so -rather than silently producing a weaker answer — the alternative is usually "upgrade -(`brew upgrade swift-section`), or do without that annotation". +`evolution --emit-available` / `--platform`, from 0.23.0 `interface --module-selectors` +/ `dump --enable-module-selectors`, and from 0.24.0 +`interface --requirements-on-associated-types` and `--emit-private-source-files`. When one is +missing, say so rather than silently producing a weaker answer — the alternative is usually +"upgrade (`brew upgrade swift-section`), or do without that annotation". ## 1. Pick the subcommand @@ -142,8 +143,18 @@ The single most common mistake. Same underlying comment, different name: Spelled the same on both: `--emit-type-layout`, `--emit-enum-layout`, `--emit-member-addresses`, `--emit-vtable-offsets`, `--emit-expanded-field-offsets` (implies the field-offset flag), -`--emit-header`, `--emit-export-status`, `--color-scheme`, `--output-path`, -`--dependency-search-path` (§2). +`--emit-header`, `--emit-export-status`, `--emit-private-source-files`, `--color-scheme`, +`--output-path`, `--dependency-search-path` (§2). + +`--emit-private-source-files` puts a comment above each declaration whose name carries a +private discriminator, naming the source file the discriminator was derived from: +`// CodingKeys is declared in Codable.swift` above `enum Outer.(CodingKeys in _B89E…)`. The file +is recovered by hashing candidate file names, so a named file is certain, but not every one is +found; the rest read `… could not be recovered (private discriminator _…)`. `interface` prints +no discriminator anywhere else, so there this comment is what tells two same-named private types +from different files apart. A member or nested type of a private type repeats nothing, since it +is declared in that type's file. A private member of a public type names its own file, usually +the file of the extension that declares it. SE-0491 module selectors — `Swift::Int` instead of `Swift.Int`, the spelling a Swift 6.4 `.swiftinterface` uses, with every nested level naming the module that declared it @@ -157,7 +168,14 @@ switches). Only `interface` has: `--exported-only`, `--sort-members-by-offset`, `--parse-opaque-return-type`, `--show-c-imported-types`, `--resolve-c-module-names`, -`--supplementary-apinotes`, `--infer-objc-overrides`. +`--supplementary-apinotes`, `--infer-objc-overrides`, `--requirements-on-associated-types`. + +`--requirements-on-associated-types` changes where a protocol's requirements print, never which: +`associatedtype Body: SwiftUI.View` instead of `protocol View where Self.Body: SwiftUI.View`, +the way the compiler writes a `.swiftinterface`. The binary keeps only the canonical +requirement signature, so neither form says where the source wrote a requirement. One about +an associated type of a refined protocol (`Self.Element` of a `Sequence` refinement) stays in +the protocol's `where` clause either way, and `diff` / `evolution` always print that form. `--infer-objc-overrides` is off by default for a reason. An override whose body the optimizer inlined into its thunk (`viewDidHide`, `encodeWithCoder:` in an OS framework) ties to no Swift @@ -199,6 +217,10 @@ resident memory. Budget for it: `--jobs N` bounds how many index at once (default: processor count); each in-flight input holds its indexed image in memory, so lower it when memory is the constraint, not `1` for speed's sake. +- `--emit-private-source-files` searches every discriminator of the image once before the + first declaration prints, and on `dump` it first indexes the image too, which `dump` otherwise + never does. Measured on macOS 27.2 with a release build: SwiftUI's `dump` goes from 12 s to + 58 s and its `interface` from 20 s to 61 s; Foundation's `interface` barely moves. - Anything long-running belongs in a background run written to a file with `-o`, not in a foreground command that will be waited on. @@ -264,6 +286,10 @@ Attribution against a non-macOS binary is limited (it warns and degrades rather - **`// not exported`** is an export-trie fact, not an access-level claim. A missing entry means "not statically callable from outside this image", which is not the same as `internal`. +- **`… is declared in Enabled.swift of module SwiftUICore`** above a SwiftUI declaration is not a + wrong module: the discriminator was hashed with the framework's own name, while its + declarations print under their ABI module name (`SwiftUI`). **`could not be recovered`** means + no candidate file name produced the digest; it says nothing about the declaration. - **A type member printed `static`** may have been `class` in the source: the four descriptor-less `class` spellings are ABI-identical to `static`, so the printer picks the spelling that is always legal. @@ -286,6 +312,11 @@ Attribution against a non-macOS binary is limited (it warns and degrades rather `@objc` / ObjC-override facts are joined through the implementation's symbol and are missing. A vtable slot nothing names (an internal member in a stripped image) is left out; `dump` lists it as `sub_…` or ``. +- **`associatedtype Element` without `: ~Copyable` / `: ~Escapable`** does not prove the + associated type is Copyable. The binary does not record that suppression (SE-0503); it is + printed only when an extension of the protocol in the same image proves it + (`extension P where Element: ~Copyable`), which only a primary associated type + (`protocol P`) can. - **Enum-layout patterns marked "not resolved offline"** mean only the extra-inhabitant *index* is derivable statically; the concrete bytes need the live metadata. - **`@objc(Name)` above a class** is the name the Objective-C runtime knows it by, and matters diff --git a/Changelogs/0.24.0.md b/Changelogs/0.24.0.md new file mode 100644 index 000000000..7cafd529e --- /dev/null +++ b/Changelogs/0.24.0.md @@ -0,0 +1,25 @@ +# 0.24.0 + +## Breaking + +- `AccessorKind` gains `.borrowAccessor` and `.mutateAccessor`; exhaustive `switch`es must handle them. +- Reading APIs that take a Mach-O or a raw pointer now stay deprecated until 0.25.0 instead of 0.24.0. +- Requires swift-capstone 7.0.0 and MachOKitExtensions 1.3.0 or later. + +## New + +- New `--emit-private-source-files` option of `dump` and `interface`, and `emitsPrivateDeclarationSourceFiles` on their requests, names the source file of each private declaration. +- New `interface --requirements-on-associated-types` option, and `SwiftDeclarationPrintConfiguration.protocolRequirementPlacement`, writes protocol requirements on their associated types, as the compiler does. +- Supports Swift 6.4's `borrow` and `mutate` accessors and `~Copyable` associated types in `dump` and `interface`. +- New `CrossReferenceAnalysis` product finds the callers, callees and type references of functions in loaded arm64 images. +- A reader that wraps `MachOImage` or `MachOFile` is now read like the reader it wraps once it conforms to `MachOReaderWrapper`. + +## Improved + +- Offline layout comments now cover `Float16`, `StaticBigInt` and SIMD fields, `UnownedJob`, `UnownedSerialExecutor` and distributed actors with custom executors. + +## Fixed + +- Fixed protocol requirements printing the wrong type when their right-hand side is an optional or generic type. +- Fixed an extra tag byte in enum layouts with an `UnsafeContinuation` payload and two or more empty cases. +- Fixed a crash when reading a loaded image through a reader that wraps `MachOImage`. diff --git a/Documentations/Evolutions/0057-reading-context-migration.md b/Documentations/Evolutions/0057-reading-context-migration.md index 1536c188e..833409b6a 100644 --- a/Documentations/Evolutions/0057-reading-context-migration.md +++ b/Documentations/Evolutions/0057-reading-context-migration.md @@ -261,7 +261,7 @@ extension ReadingContext { 10. 0.22.0 发布(Changelog 写明废弃清单与三处行为变化)。 11. RuntimeViewer、MachOKitUI、swift-decompiler 各提迁移 PR。 -12. 0.24.0(原定 0.23.0,2026-10-15 推迟,见决策日志):删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 +12. 0.25.0(原定 0.23.0,2026-10-15 与 2026-10-26 两次推迟,见决策日志):删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 **收尾判断**(落地时写进决策日志):是否需要配套实现说明(预期更新 `ReadingContextAbstraction.md` 即可,不另写);新术语「缓存范围」登记进术语表。 @@ -306,7 +306,7 @@ extension ReadingContext { 1. 本批发现的既有问题:`FunctionTypeMetadata.extendedFlags(in:)` 与 `EnumMetadataProtocol.payloadSize(descriptor:in:)` 从泛型 `readElement` 直接返回 Optional,按 Optional 的内存形状多读一个字节,`FunctionTypeMetadataTests` 时好时坏就是它;`ContextDescriptorWrapper.resolve(at:in:) -> Self?` 出错时用 `print` 写 stdout,违反日志规则,也会弄脏 CLI 的输出。**已修复**:分支 `fix/optional-read-and-stdout-print`,[PR #130](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/130)(本 PR 合入后直接对 `next`);另查出并修了 `SwiftClassObjectIndex` 读 class flags 的一处同类写法,同批清掉的还有 `SubstitutionMap` 的 `print`。 2. 渲染 A/B 脚本加 `--skip-build`:直接使用预先经 `queued-build` 构建好的产物,脚本自己不再构建。**已合入**:分支 `chore/rendering-harness-skip-build`,合并提交 `01b57f74`(2026-10-01 直接合入 `next`,没有开 PR);用法见 [SystemFrameworkRenderingVerification.md](../Internal/SystemFrameworkRenderingVerification.md)「关键调用细节」。 -**合入之后**(编号与状态已在合入时完成):0.22.0 的 Changelog 写明废弃清单与三处行为变化;给 RuntimeViewer(`next`)、MachOKitUI、swift-decompiler 提迁移 PR;0.24.0(原定 0.23.0,2026-10-15 推迟,见决策日志)删除全部废弃转发、`DeprecatedReadingFormsTests`,以及覆盖率登记表里 13 个指针版初始化器的键。 +**合入之后**(编号与状态已在合入时完成):0.22.0 的 Changelog 写明废弃清单与三处行为变化;给 RuntimeViewer(`next`)、MachOKitUI、swift-decompiler 提迁移 PR;0.25.0(原定 0.23.0,2026-10-15 与 2026-10-26 两次推迟,见决策日志)删除全部废弃转发、`DeprecatedReadingFormsTests`,以及覆盖率登记表里 13 个指针版初始化器的键。 ## 决策日志 @@ -341,3 +341,4 @@ extension ReadingContext { | 2026-10-01 | In Progress → Implemented,编号 0057,经 [PR #129](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/129) 合入 `next` | 用户:「继续合并吧」。各共享分支上的最大编号是 0056(`next`)。分支基于 `next` @ `f7c189b8`,此后 `next` 没有新提交,合入无冲突。最后一次代码改动之后只有文档 commit,验收数据沿用「当前进度」一节:全量测试 2157 个 / 410 个套件原始退出码 0,渲染 A/B 96 对逐字节一致,三条路径性能持平 | | 2026-10-01 | 收尾判断:不另写使用指南,实现说明是 `ReadingContextAbstraction.md`「单一实现与废弃」一节;术语表的「cache scope」与「context form / Mach-O form / pointer form」已在实现批次登记;账本记第 73 节 | 迁移写法只有三种替换(`x(in: machO)` → `x(in: machO.context)`,`x()` → `x(in: .inProcess)`,`resolve(from:in:)` → `resolve(at:in:)`),废弃消息本身就给出了替代写法,0.22.0 的 Changelog 再列一遍 | | 2026-10-15 | 删除推迟到 0.24.0 | 用户决定:发 0.23.0 时 RuntimeViewer 的 `next` 已迁完(`44607ba6`),MachOKitUI(`from: "0.19.0"`,会自动解析到 0.23.0)与 swift-decompiler(跟本库 `next`)都还没迁,0.23.0 删除会让它们下次解析时编不过。0.23.0 的 Changelog 写明新期限;两个下游迁完后再删。 | +| 2026-10-26 | 删除再推迟到 0.25.0 | 用户批准按建议发 0.24.0、这一版不删。两个下游仍没迁:MachOKitUI 的 `main`(`db0d03d`,`MachOSwiftSectionDetailBuilder.swift` 里一串 `(in: source)`,依赖 `from: "0.19.0"`,会自动解析到 0.24.0)与 swift-decompiler 的 `main`(`0e186ec`,`SwiftMetadataProvider.swift` 的 `(in: machOFile)`,跟本库 `next`)。0.24.0 的 Changelog 写明新期限。 | diff --git a/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md b/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md index a2be7dcec..edb4930a4 100644 --- a/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md +++ b/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md @@ -2,7 +2,7 @@ - **状态**: Implemented - **创建日期**: 2026-10-05 -- **最后更新**: 2026-10-06 +- **最后更新**: 2026-10-21 ## 摘要 @@ -31,3 +31,5 @@ | 2026-10-06 | 后续:evolution 的归档套件改列 51 个版本 | 用户:「SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cacheVersions,把这个属性填完……只写x.y版本,忽略x.y.z版本」。每个次版本取 x.y 目录;11.0、12.0 在卷上只有 x.0.1 目录,照用户写下的第一项 `11.0.1`,12.0 取 `12.0.1`;`14.0(Internal)` 不收。`cachePaths` 改由 `cacheVersions` 生成、镜像换成 SwiftUI,这两处是用户自己改的 | | 2026-10-06 | 后续:没有 Swift 的版本跳过,不报错 | 用户:「没有swift信息不报错,跳过」。用 `ipsw dyld macho … --loads` 核对过:AppKit 本体在 11.0.1、12.0.1、13.7 没有 `__swift5_*` 节,14.0 起才有;同期 `libswiftAppKit.dylib` 里有 7 个(11.0.1)到 43 个(13.7)类型,14.0 起为 0。判断放在基类,看节名前缀;cache 里没有这个镜像也算没有 Swift,一并跳过 | | 2026-10-06 | 后续的验证 | 全部测试目标(含 IntegrationTests)编译通过,没有新警告。按用户「测试一下SwiftUI会不会爆内存」运行过一次 `evolutionInterfaceFile`,第 140 秒在 13.5 上因 MachOKit 的整数下溢崩溃,内存没到 5 GB 的上限;其余测试没有运行。实测数字见演进账本第 80 节,崩溃的根因与修复见第 81 节 | +| 2026-10-21 | 后续:macOS 11、12 在 evolution 轴上标为 `11.0`、`12.0` | AppleDB 上下载不到 macOS 11.0、12.0 的镜像,只有 11.0.1、12.0.1,卷上这两个大版本因此只有 x.0.1 目录,轴标签原先照抄目录名,12.0.1 上首次出现的声明会写成 `@available(macOS, introduced: 12.0.1)`。改为按大版本标,与 SDK 的 `@available` 用的版本一致:`cacheVersions` 仍列目录名,`ArchivedDyldCacheTests` 新加 `versionLabelsByCacheVersion` 给这两个目录另配标签,`cachePaths` 生成路径时用它;`DyldSharedCachePath` 与其他套件不动 | +| 2026-10-21 | 后续的验证 | 只编译(JHs-Mac-Studio-Ultra,Swift 6.4.2,远端依赖):全部测试目标(含 IntegrationTests)编译通过,改动的文件没有新警告;没有运行测试 | diff --git a/Documentations/Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md b/Documentations/Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md new file mode 100644 index 000000000..635003d74 --- /dev/null +++ b/Documentations/Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md @@ -0,0 +1,49 @@ +# 0070 - Swift 6.4 的 `borrow` / `mutate` 访问器与关联类型上的 `~Copyable` + +- **状态**: Implemented +- **创建日期**: 2026-10-10 +- **最后更新**: 2026-10-16 + +## 摘要 + +Swift 6.4 带来了两种二进制里会出现、而我们读不出来的声明形态,都是从 Swift 论坛 2026-08-31 的「6.4 实现状态汇总」顺藤摸瓜、再用 Swift 6.4 编出的探针库与 macOS 27 的 libswiftCore 实测确认的: + +1. **`borrow` / `mutate` 访问器**(SE-0507,6.4 默认开启)。只有这两种访问器的属性和下标,在 `interface` 与 `dump` 里整个消失;协议要求 `var element: Int { borrow mutate }` 让协议印成空的 `protocol P {}`。原因是符号索引只把 getter / setter 符号收作成员,声明模型的 `AccessorKind` 也只认 get / set / read / modify,而编译器给这两种访问器发的符号是 `…vb` / `…vz`(demangle 成 `borrowAccessor` / `mutateAccessor` 节点),vtable 与协议要求里的 method descriptor 类型是 `Method` 而不是 `Getter`。 +2. **关联类型上的 `~Copyable` / `~Escapable`**(SE-0503,6.4)。`associatedtype Element: ~Copyable` 我们印成 `associatedtype Element`,把可以是 noncopyable 的关联类型说成了 Copyable。这一条**二进制本身不记录**:IRGen 只给泛型参数发反向要求(`GenericRequirementKind.invertedProtocols`),关联类型的反向要求在 `addGenericRequirements` 里直接丢弃,协议成员的 mangled name 也不带。唯一可靠的间接证据是同一镜像里这个协议的 extension 签名写了 `where Self.Element: ~Copyable`——SE-0503 规定协议没把 `Element` 声明成可抑制时这样写会编译报错,所以出现即证明。而且只有**主关联类型**(`protocol P` 尖括号里的)能留下这种证据:SE-0503 只给 extension 补主关联类型的 `Copyable` 默认值,普通关联类型上写 `where Strategy: ~Copyable` 不抑制任何东西,mangling 里也就什么都没有(Swift 6.4 实测)。 + +## 方案 + +### `borrow` / `mutate` 访问器 + +- **符号索引**(`MachOSymbols`):`borrowAccessor` / `mutateAccessor` 与 getter / setter 同等对待——成员符号、全局符号、`isGlobal` / `isAccessor` 判断都认它们,于是 `dump` 的成员清单也随之列出它们。 +- **声明模型**(`SwiftDeclaration`):公开枚举 `AccessorKind` 新增 `.borrowAccessor` / `.mutateAccessor`(地址注释标签 `borrow` / `mutate`),`AccessorRepresentable` 新增 `hasBorrowAccessor` / `hasMutateAccessor`。`DefinitionBuilder` 选声明节点时 getter 与 borrow 都算「读访问器」,变量与下标因此不再因为没有 getter 被丢弃;协议要求走同一条路,所以协议也随之修好。属性包装器识别(`wrappedValue` 的访问器形状)与 `declaredTypeNode` 的节点下行同样认这两种节点。 +- **打印**(`SwiftPrinting`):访问器块不再写死 `get`:读访问器有 `borrow` 印 `borrow`,否则印 `get`;写访问器有 `mutate` 印 `mutate`,否则有 setter 印 `set`。SE-0507 规定 `borrow` 与 `get` 互斥、`mutate` 必须配 `borrow`,所以这条规则覆盖全部合法组合;编译器为满足协议而合成的 getter 不会盖掉 `borrow`。`let` / `var` 的判断里 `mutate` 与 setter 等价。 +- **ABI diff**(`SwiftDiffing`):成员记录的访问器 token 加 `borrow` / `mutate`。 +- **不做**:`yielding borrow` / `yielding mutate`(SE-0474)。6.4 里仍是实验特性,打开后编译器会给普通属性也合成这两种访问器(像今天的 `_read` / `_modify` 一样不该印出来),印不印要另定规则,留到 6.5 落地时单独处理。类没有这两种访问器(SE-0507 禁止),vtable 相关的分支不动。 + +### 关联类型上的 `~Copyable` / `~Escapable` + +- **推断**(`SwiftInspection`,新增 `SuppressedAssociatedTypeInference`):给定协议,查符号索引里这个协议 extension 中的全部成员符号,取每个符号 extension 节点上的泛型签名,收集主语是 `Self.<名字>`(深度 0、下标 0 的泛型参数的关联类型)的反向要求,结果按关联类型名给出 `~Copyable` / `~Escapable` 的集合。只认协议自己声明的关联类型;继承来的同名关联类型不归到这个协议上。 +- **dump**:`ProtocolDumper` 直接调用推断函数。 +- **interface**:`ProtocolDefinition.index(in:)` 把推断结果存进模型(`suppressedInvertibleProtocolsByAssociatedTypeName`),`renderProtocolAssociatedTypes` 从模型读。两条路都印 `associatedtype Element: ~Swift.Copyable`(与我们其余输出一样带模块前缀)。 +- **覆盖不全是预期的**:没有这种 extension 的协议、以及所有非主关联类型,照旧印 `associatedtype Element`。推断只有正证据,不会把 Copyable 的关联类型错印成 `~Copyable`。ABI diff / evolution 的成员记录不带这个事实——证据有无随版本里写没写 extension 变化,带上会产生假的 API 变化。 + +### 测试 + +两种形态都只有 Swift 6.4 编译器能编出来,而 CI 用 Xcode 26.6(Swift 6.3:`borrow` 访问器报「experimental feature cannot be enabled in production compiler」),`SymbolTestsCore` 也不能动(会挪动 ABI baseline 钉住的偏移)。所以测试现场编译 fixture,用 Swift 6.4 及以上的工具链:先看默认工具链,再看 `/Applications` 下其它 Xcode;找不到就整套跳过(`.enabled(if:)`),CI 上因此不跑。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-10 | Created | 抓 Swift 论坛近期帖子评估影响后,用户:「修一下」 | +| 2026-10-10 | 关联类型一项改为按 extension 证据推断 | 查编译器源码与实验后发现二进制不记录关联类型上的反向要求,先前「我们漏读」的判断有误;问过一轮,用户选「按 extension 证据推断」 | +| 2026-10-10 | 推断只对主关联类型有效,写进注释与测试 | 实测普通关联类型上的 `where Strategy: ~Copyable` 不进 mangling;fixture 留一个非主关联类型 `Strategy` 当反例 | +| 2026-10-10 | `yielding borrow` / `yielding mutate` 不在本次范围 | 6.4 里仍是实验特性,且需要「合成的不印」的规则,等 SE-0474 落地再做 | +| 2026-10-10 | `AccessorKind` 加 case 是源码不兼容变更 | RuntimeViewer 的 `RuntimeSwiftSection.swift` 对它做了穷举 `switch`,合入 `next` 前要同批给它补两个 case | +| 2026-10-10 | 测试的工具链探测去掉继承的 `SDKROOT` / `DYLD_*` | `swift test` 把自己工具链的 `SDKROOT` 与含 PrivateFrameworks 的 `DYLD_FRAMEWORK_PATH` 交给测试进程,子进程换 Xcode 27 后 `xcrun` 以 72 退出,整套被静默跳过(0.001 秒「通过」) | +| 2026-10-10 | 验证 | JHs-Mac-Studio,Xcode 26.6(Swift 6.3.3)跑测试,fixture 由 Xcode 27.0(Swift 6.4)现场编译,本地兄弟依赖。新加两套 8 个测试函数(20 个用例)全部通过;把修复代码换回 `next` 后 15 处断言失败,只有三个「不该印 `~Copyable`」的对照用例照旧通过。全量 `swift test --skip IntegrationTests`:2371 个测试 / 453 个套件,原始退出码 1,失败的只有 `MultiPayloadEnumDescriptorCacheTests` 两条,切到 `next` 原样跑同样两条、同样位置失败(本机既有问题);另有早已登记的 known issue。真实系统库 A/B(两侧 debug CLI,`next` @ `cd248de9` 对本分支):macOS 27.0 归档 cache 里 libswiftCore 的 interface 与 dump 各只差两行,正是 `BorrowingIteratorProtocol.Element` 与 `Iterable.Element` 补上 `: ~Swift.Copyable`,与 Xcode 27 SDK 里的 swiftinterface 一致;libswift_Concurrency、Combine、libswiftObservation、libswiftSynchronization、SwiftData 的 interface 与 dump 逐字节一致。macOS 27 SDK 的 `.tbd` 里没有一个导出的 borrow / mutate 访问器(stdlib 里的全是 `@_alwaysEmitIntoClient`),所以系统库这一项看不到变化。项目规定的三条 reader 路径渲染 A/B 脚本没有跑 | +| 2026-10-16 | 找回改动 | 10-10 的改动一直只暂存、没有提交,工作树在 10-12 到 10-15 之间被删。分支一次都没提交过,`merge-base --is-ancestor` 判它「已合并」,`git log --all` 也看不到它。主体从对象库里一个不可达的临时提交 `c517f4e4` 恢复(当时为了验证「修复前测试会失败」先提交、后 `reset --soft` 撤销);提交之后改的三处文档(`Modules/MachOSymbols.md` 一段、本表两行、演进账本一节)从当天的对话记录原样重放 | +| 2026-10-16 | rebase 到 0.23.0 之后的 `next` | 四处冲突与两处跟进。`DefinitionBuilder` 的两处选节点,改用局部类型那次引入的 `memberSubtree`,同时保留 `borrow` 判断。`accessorKind` 的搜索表把局部类型那次加的 `.variable` / `.subscript` 与 `borrow` / `mutate` 合在一起。两份文档索引两边的条目都保留。关联类型行调用的 `dumpInvertedProtocolsInheritance`,按模块选择器那次改成带 `resolver:` 的 async 函数:dump 用 `demangleResolver`,interface 用 `typeDemangleResolver` | +| 2026-10-16 | 合入前重新验证 | JHs-Mac-Studio,Xcode 26.6(Swift 6.3.3),本地兄弟依赖,内容与已发布的 swift-demangling 0.7.2、swift-semantic-string 0.5.0、MachOObjCSection 0.8.200、MachOKit 0.54.101、MachOKitExtensions 1.2.0 一致;fixture 按 CI 的方式用 Xcode 26.6 ad-hoc 签名现编。新加的 8 个测试函数(20 个用例)全部通过,fixture 由本机的 Xcode 27 现场编译。全量 `swift test --skip IntegrationTests`:2450 个测试 / 470 个套件,原始退出码 1,失败的只有本机既有的两条 `MultiPayloadEnumDescriptorCacheTests`(`:101`、`:130`),与 0.23.0 发版时相同;测试数比 0.23.0 多的 8 个就是新加的测试。渲染 A/B(基线 `next` @ `b7be58ec`,两侧 release,经构建队列预构建后带 `--skip-build` 跑):90 对全部逐字节一致,即归档 cache 15.5 与 26.6.2 各 12 对、iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对、MachOImage 腿 24 对;iOS 27.1 / 27.2 模拟器的框架在 cache 里、不是文件,按设计跳过。macOS 27.0 归档 cache 里的 libswiftCore(两侧 release CLI):interface 17,488 行、dump 24,521 行,各只差两行,仍是 `BorrowingIteratorProtocol.Element` 与 `Iterable.Element` 补上 `: ~Swift.Copyable` | +| 2026-10-16 | Implemented,编号 0070 | 同批给 RuntimeViewer 的 `kindString` 补上 `.borrowAccessor` / `.mutateAccessor` 两个 case。不另写使用指南或实现说明:行为说明已在 `Modules/SwiftDeclaration.md` 的「访问器种类与关联类型的抑制」与 `Modules/MachOSymbols.md`,读输出的提示在插件 skill 里。术语表不新增:`borrow` / `mutate` 访问器与「抑制的关联类型」是 SE-0507 / SE-0503 的叫法,不是本项目自造的词 | diff --git a/Documentations/Evolutions/0071-swift-capstone-7.md b/Documentations/Evolutions/0071-swift-capstone-7.md new file mode 100644 index 000000000..8b36fdb38 --- /dev/null +++ b/Documentations/Evolutions/0071-swift-capstone-7.md @@ -0,0 +1,38 @@ +# 0071 - 迁到 swift-capstone 7.0 + +- **状态**: Implemented +- **创建日期**: 2026-10-17 +- **最后更新**: 2026-10-17 + +## 摘要 + +swift-capstone 7.0 用按架构泛型的不可复制引擎 `Disassembler` 取代 6.x 的 `Capstone` 类与 +`Instruction` 类层级,旧 API 直接删除、不留过渡垫片。方案由 swift-capstone 仓库的提案《用新 Swift 特性重写 +封装层》(`Documentations/Evolutions/0003-rewrite-with-modern-swift.md`)决定,其中约定 +本库与 swift-decompiler 同批迁移。本库只有 `SwiftThunkAnalysis` 的 `CapstoneThunkDecoder.swift` 用到 +Capstone,迁移只改这一个文件,对外接口不变。 + +## 方案 + +- 每次 `decode` 建一个 `Disassembler`(创建很便宜,引擎不跨任务共享),在 `forEachInstruction` 的 + 闭包里把每条指令直接转成 `ThunkInstruction`。swift-capstone 借出的指令视图带不出闭包,不再先拿一整组 + Capstone 指令对象。`decode` / `decodeFunction` 的签名与 `Data` 入参不变。 +- 别名:改用 `alias`(`.aliasMov` → `.mov`,`.aliasCmp` → `.aliasCmp`,其余用 `identifier`),取代 + 「`(instruction, mnemonic)` 配对」。 +- 写回:改用 `writesBackBaseRegister`,取代 `isPostIndex == true || operandsString.contains("]!")`。 + `isPostIndex` 不再是可选值。 +- 写寄存器:`registersAccessed().written + implicitRegistersWritten`,与 6.x 的 + `registersAccessed.written + registersAccessedImplicitly.written` 同义。 +- 依赖:下限从 `from: "6.0.1"` 改成 `from: "7.0.0"`。7.0.0 发布之前本分支只能对着本地 swift-capstone + 编译,所以等它发布才合入 `next`。 + +没有询问就采用的假设:不在本库加新测试——`CapstoneThunkDecoderTests` 与整个 `SwiftThunkAnalysisTests` +已经用真实指令编码固定了解码结果,迁移前后应完全一致。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-17 | Created,直接进入实现 | swift-capstone 的重写提案已获用户批准(「可以,按你说的开工」),其中要求两个下游同批迁移;本库的改动只是跟随,走精简提案。 | +| 2026-10-17 | 本地验证通过,等 swift-capstone 7.0.0 发布 | 在分支 `feature/swift-capstone-7` 上,对着本地 swift-capstone(`feat/rewrite-modern-swift`)编译:用 `swift package edit` 只在 agent 的构建目录里覆盖依赖,不碰 `.worktrees/` 下共享的链接——加一个 `swift-capstone` 链接会让其他 worktree 的本地构建也切到 7.0 API。Swift 6.4.2 下 `SwiftThunkAnalysisTests` 82 个测试,以及间接用到解码器的 `ObjCMemberDumpTests`、`OpaqueWitnessDumpAnnotationTests`、`ObjCMemberRecoveryTests`、`CustomObjCClassNameInterfaceTests`、`AccessorFunctionReferenceRewriterTests` 共 52 个测试,原始退出码都是 0;随后全量 `swift test --skip IntegrationTests` 共 2450 个测试 / 470 个套件全部通过,原始退出码 0。fixture 链 `next` worktree 的 `Tests/Projects/SymbolTests/DerivedData`。 | +| 2026-10-17 | swift-capstone 7.0.0 发布,依赖下限改成 `from: "7.0.0"`;In Progress → Implemented,编号 0071,合入 `next` | 7.0.0 要求 capstone fork 6.0.101,后者修了两处上游缺陷:`cs_disasm_iter` 不清每条指令的标志、自定义助记符截坏别名。新鲜构建目录,`USING_LOCAL_DEPENDENCIES=1`(MachOKit 等仍链 `.worktrees/` 下的兄弟仓库),swift-capstone 从远端解析到 7.0.0、capstone 到 6.0.101:全量 `swift test --skip IntegrationTests` 共 2450 个测试 / 470 个套件全部通过,原始退出码 0。解析时撞上 SwiftPM 的 manifest 缓存:此前 `swift package edit` 让 swift-capstone 的 manifest 在本地路径下求过值,内容与 7.0.0 相同,缓存把那次的结果——指向本地 capstone 的路径依赖——套到了远端 7.0.0 上,解析报 `capstone` 无法解析;加 `--manifest-cache none` 即通过。编号取远程共享分支(`main`、`next`)提案编号最大值 0070 加 1。不另写使用指南或实现说明:解码边界已写在 `Modules/SwiftThunkAnalysis.md`;没有新术语。 | diff --git a/Documentations/Evolutions/0072-cross-reference-analysis.md b/Documentations/Evolutions/0072-cross-reference-analysis.md new file mode 100644 index 000000000..357596c45 --- /dev/null +++ b/Documentations/Evolutions/0072-cross-reference-analysis.md @@ -0,0 +1,209 @@ +# 0072 - 交叉引用分析:从机器码读出每个函数引用了什么 + +- **状态**: Implemented +- **创建日期**: 2026-10-16 +- **最后更新**: 2026-10-19 +- **关联**: RuntimeViewer 的 [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)。交叉引用的整体设计、前期调研与实测数据都在那里,本提案只定本库这一层。 + +## 摘要 + +新增 public target `CrossReferenceAnalysis`(`Sources/Analysis/CrossReferenceAnalysis`):给出一个镜像的函数表,以及每个函数引用了什么——直接调用与尾调用、ObjC 消息发送、super 发送、跨库调用、类型引用、间接调用及其候选目标。RuntimeViewer 的交叉引用(调用者、被调、类型引用)建在它上面。规则放在本库,沿用「二进制分析的规则放在 MachOSwiftSection,RuntimeViewer 只负责显示」的做法。 + +## 方案 + +- **读取**:只读进程内的 `MachOImage`,只支持 arm64 / arm64e。`MachOFile` 与 swift-section 子命令留给以后的提案。 +- **函数表**:边界取自 `LC_FUNCTION_STARTS`(MachOKit 在内存镜像上给出的 `FunctionStart.offset` 已经是未滑动的绝对地址,与它的文档注释不符)。名字依次取自符号表、ObjC 方法表(`ObjCClassMethodIndex`)、Swift 方法描述符的实现(`implementationSymbols`);同一地址上的多个名字(代码合并)归为一个函数;都叫不出名字时 `name` 为 `nil`,照样扫描。 +- **解码**:手写,只认调用、尾调用、间接调用、`adrp` / `add` / `ldr` 取地址、`movk` / `mov` 鉴别常量、`autda` / `ldraa` 这几类,其余指令只作废它写的寄存器。实测比 Capstone 快 25–50 倍,Capstone 只在测试里作对照。`__text` 里夹着数据,读任何跳转目标之前先确认它落在缓存的可执行映射或本镜像里。 +- **调用目标**:镜像自带的 `__objc_stubs` / `__stubs` / `__auth_stubs`(macOS 26、iOS 26 及更早,以及 Simulator);macOS 27 / iOS 27 全缓存共用的 selector 桩(`x1` 就是 selector 字符串,以字符串地址为键)与 GOT 桩(进程内读出槽位里已绑定的指针);stub island。GOT 桩与 island 的形状识别和 `MachOThunkEnvironment` 共用一份:把它的 `stubSlotAddress` / `stubIslandTarget` 抽成两边都能调用的 package 级纯函数。 +- **间接调用**:按 `autda` 的常量分出虚表(isa,0x6ae1)、value witness table(0x2e3f)与协议见证表;value witness 调用标为运行时辅助调用。虚表与见证表调用按(鉴别常量、表内偏移)反查本镜像的根声明:常量是带 `$s` 前缀的 `SILDeclRef` mangling 经 `getPointerAuthStableSipHash` 再取 `% 0xFFFF + 1`。闭包调用只给签名形态。 +- **类型引用**:`$s…Ma` 元数据访问器、`__swift_instantiateConcreteTypeFromMangledName*` / `swift_getTypeByMangledName*`(名字取自 `x0` 指向的缓存变量)、ObjC 类引用。(第二批已修订:V2 的名字取自 `x1` 指向的记录,见「第二批 ③」。) +- **运行时辅助调用**:名单由本库维护,结果里只打标记,过滤交给宿主。 +- **预筛**:按符号表的未定义符号与 `__objc_selrefs`,筛出可能引用某个符号或 selector 的镜像。(已修订:Swift 符号按链接关系筛,见「第二批 ③」;C 与 ObjC 名字还要算上别的镜像改名再导出的名字,见「审查与修复」。) +- **不缓存**:每次调用都重新读;整镜像扫描返回一个值,留多久由宿主决定(RuntimeViewer 按字节预算做 LRU),所以不新增 `SharedCache`。(已修订:分析器在自己的生命期里记住起过名的函数表、类索引、类型索引、链接关系与改名再导出的名字,见模块参考「缓存、内存与生命周期」;仍不新增 `SharedCache`,理由见 [ReviewAdjudications](../Internal/ReviewAdjudications.md) A62。) +- **分三批落地**,每批单独可用:① 函数表(符号表与函数起点)、解码、两种桩布局、selector、辅助调用标记、单函数与整镜像 API、预筛,发一个版本后 RuntimeViewer 就能开始它的第 3 步;② ObjC 方法表与 Swift 元数据命名、类型引用;③ 间接调用的表来源、鉴别常量反查与候选。 +- **测试**:解码器用合成的指令字单测;SymbolTestsCore fixture(arm64)测函数表与直接调用;arm64e 才有的形状用自编的 arm64e 目标文件和进程内的系统缓存测,并以 Capstone 的反汇编作对照。 + +第一批落地的 API。草图原是一组接收 `MachOImage` 的静态函数;实现时发现跨镜像解析目标要用到整个进程的镜像表,改成一个由宿主持有的分析器: + +```swift +public final class CrossReferenceAnalyzer: @unchecked Sendable { + /// The current process's images — the whole shared cache plus the images loaded outside it; nil off arm64. + public init?() + public let images: [MachOImage] + public let imagePaths: [String] + public func imageIndex(forPath path: String) -> Int? + public func location(ofRuntimeAddress address: UInt) -> CodeLocation? + public func functions(inImageAt imageIndex: Int) -> [CodeFunction] + public func function(containing location: CodeLocation) -> CodeFunction? + /// Names many results at once without keeping the images' tables. + public func functions(containing locations: some Sequence) -> [CodeLocation: CodeFunction] + public func symbolName(at location: CodeLocation) -> String? + public func references(madeBy function: CodeFunction) -> [CodeReference] + /// Every function's references in one image, grouped by what they reference. + public func referenceTable(ofImageAt imageIndex: Int) -> CodeReferenceTable + /// Only the references filed under `keys` — what a callers query needs. + public func references(to keys: Set, inImageAt imageIndex: Int) -> [CodeReference] + public func imageIndices(importing symbolName: String, among candidates: some Sequence) -> [Int] + public func imageIndices(referencingSelector selector: String, among candidates: some Sequence) -> [Int] +} +``` + +地址一律是 `CodeLocation`(镜像在 `images` 里的位置,加该镜像的未滑动地址),因为缓存外两个镜像的未滑动地址可能重合。实现细节见 [Modules/CrossReferenceAnalysis.md](../Internal/Modules/CrossReferenceAnalysis.md)。 + +## 第一批的实现与验证(2026-10-16) + +- **落地模块**:新 target `ARM64InstructionDecoding`(`Sources/Support`:`ARM64InstructionWord` 手写读取少数几类编码,`ARM64Trampoline` 按形状认 GOT 桩、stub island 与全缓存共用的 selector 桩);新 target `CrossReferenceAnalysis`(`Sources/Analysis`);SwiftThunkAnalysis 的 `MachOThunkEnvironment.stubSlotAddress` / `stubIslandTarget` 改用 `ARM64Trampoline`,此前用 Capstone 加寄存器跟踪认同样的形状。 +- **与方案的出入**:①API 改成宿主持有的 `CrossReferenceAnalyzer`(上文)。②分析器只记住宿主让它起过名的镜像的函数表;这不是全局的按镜像缓存,释放分析器即释放,所以仍不需要 `SharedCache`。③ObjC 方法的 `x0` 接收者提示(`methodReceiver`)这批就做了:寄存器跟踪本来就在,代价只是多一个状态。④新增 `references(to:inImageAt:)`(见下「内存」)。 +- **内存**(用库写的 release 基准量):整镜像扫描起初也记住函数表,扫完一遍 macOS 27.2 缓存后常驻 1.5 GB,改为扫描临时建表、用完即丢(`wholeImageScansKeepNoFunctionTable`,改前红、改后绿)。剩下的 1.2 GB 不是活对象(`heap` 只见一两 MB),是 28 个线程同时建整表(大镜像一张 121 MiB)后分配器没还的脏页,由峰值决定;查调用者改用只留命中引用的 `references(to:inImageAt:)` 后,同样扫完全缓存常驻约 170 MB。 +- **吞吐**:建分析器 0.02 秒;每个镜像都建整表 28 核 1.6–1.8 秒、4 线程 5.9 秒;`init` 的调用者(预筛出 2,759 个镜像)28 核 1.5 秒、4 线程 6.1 秒;`makeKeyAndOrderFront:`(105 个镜像)0.3 秒。比探针慢的部分是起名与建引用,见模块参考。 +- **懒绑定**:曾以为懒绑定的老式二进制在函数第一次调用前槽位指向 `__stub_helper`,加了退回导入名的防护和测试;测试在去掉防护后照样通过。用探针看:macOS 27.2 的 dyld 以 `RTLD_LAZY` 加载时就绑好了槽。防护是死代码,撤掉;测试改成哨兵 `LazyBindingTests`,断言调用直接解析到 `puts`。 +- **验证**(JHs-Mac-Studio-Ultra,macOS 27.2,Xcode 27.2,依赖全部走远端发布版本):`CrossReferenceAnalysisTests` 20 个测试通过,其中 `callSitesMatchCapstone` 抽样 AppKit 的 400 个函数,Capstone 找到的每一处调用与跳出函数的跳转,扫描都找到了;`SwiftThunkAnalysisTests` 82 个测试通过,包括经 stub island 解析的两个离线 iOS 缓存测试;全量 `swift test --skip IntegrationTests` 见演进账本本批一节。 +- **第一次测试的教训**:Capstone 不开 detail 模式就不给操作数,按位置取操作数会越界;比对「跳出函数的跳转」那半边因此一度什么都没比。测试现在断言这半边比对过不止一处。 +- **第一批之后的修补**(RuntimeViewer 第 3 步接入时发现):①缓存里的传统 `objc_msgSend` 发送,`x1` 不是从 selector 引用读来,而是缓存构建器改写出的字符串地址(`adrp x8; add x1, x8; b _objc_msgSend`,libobjc 的 `-[NSObject debugDescription]` 就是),第一批把它们当成对 `objc_msgSend` 的普通调用,发送整个看不见。修法是 `x1` 是 `adrp` / `add` 算出的地址时,确认它可读、到结尾是可打印字符,就当作 selector;回归测试 `classicSendsInsideTheCacheNameTheirSelector` 改前红、改后绿。②补上预筛的正确性测试:此前只断言预筛「留下了 AppKit、筛得够狠」,没断言「丢掉的镜像里真没有引用」。现在 3 个 selector 与 2 个导出函数各在被丢掉的镜像里每 16 个抽 1 个扫描,一处引用也没有。③新增 `functions(containing:)`:给一批结果起名,用完不留函数表。 +- **留给后续批次**:过滤扫描按键提前跳过(现在先建好每条引用再丢);`CodeReference` 的紧凑存储。 + +## 第二批的设计(2026-10-17,实测之后) + +方案一节对第二批只有一句「ObjC 方法表与 Swift 元数据命名、类型引用」。动手前用两个只读探针在 macOS 27.2 的缓存上实测(代码在 agent 临时目录 `Probes/CrossReferences/BatchTwo-ObjC`、`BatchTwo-Swift`,不在仓库里),有几条事实改变了做法,按它们定下第二批: + +### 起名:三个来源,都在起名时按镜像按需读 + +| 来源 | 能给多少无名起点起名(全缓存,无名共 822 万) | 代价 | +|---|---|---| +| 导出表(export trie)——第一批没读 | 140 万;iOS 真机上也在 | 每个镜像不到 1 毫秒 | +| ObjC 方法表(类、元类、分类) | 40 万(Matter 53,000 个无名里 30,863 个) | AppKit 42–86 ms;全缓存单线程 14 s,`MachOObjCSection` 内部串行,并发不变快 | +| Swift 元数据 | 146 万处被元数据指到,其中 132 万导出表也没名字 | 全缓存单线程 8.2 s,28 线程 3.3 s | + +- 每个方法实现都是 `LC_FUNCTION_STARTS` 里的函数起点。一个镜像只读自己的类列表(列表的列表里属于别的镜像的条目跳过:它们一定也在那个镜像自己的分类列表里)和自己的分类列表。元数据里没有分类名,`-[NSTextView(NSDragging) draggingUpdated:]` 读出来是 `-[NSTextView draggingUpdated:]`;有符号的照用符号(Swift 的 `@objc` 桥接函数 `…To` 与方法表名字不同,符号是对的)。 +- Swift 元数据里,名字一定能还原的:类型元数据访问器(`…Ma`)与 singleton 完成函数(`…Mr`),类型名取自描述符的上下文。虚表实现要靠方法描述符导出的 `…Tq`(去掉 `Tq` 就是方法本身的 mangled 名字),16 万处里 8.4 万有。协议见证可以由 conformance 加 requirement 重新 mangle 出 `…TW`,留到下一步。虚表里有大量空实现;指向 `__swift5_typeref` 的见证是关联类型,不是代码;async 函数指向 `{rel32 函数, u32 大小}` 记录,要再跟一步。 +- 扫描时用不到这些名字(判断一个函数是不是 ObjC 方法除外,见下),所以不在建函数表时读,只在给函数起名时(`functions(inImageAt:)`、`function(containing:)`、`functions(containing:)`)按镜像读一次、记在函数表上。 +- `CodeFunction.Name` 变成三种:`.symbol`(符号表与导出表)、`.objectiveCMethod`、`.swiftMetadata(mangledName:)`(从元数据重建的完整 mangled 名字,可以直接 demangle)。第一批占位的 `.swiftMethod(descriptorAddress:)` 去掉。 + +### ObjC:类字面量接收者、super 的类、类引用 + +- 27.2 的缓存里几乎没有 `__objc_classrefs` 了(全缓存只剩 53 个镜像、1,023 个槽)。类经 GOT 载入:镜像自己的 `__got`,或全缓存共用的 GOT 池(落在所有镜像的段之外);或 `adrp`+`add` 直接取类对象地址;super 发送仍经 `__objc_superrefs`。AppKit 里 34,256 处来自共用池、17,450 处来自自己的 `__got`、3,311 处直接取址(设计阶段那一轮探针;实现阶段重跑探针得到 3,318 / 52,668,两次的口径差别没有记下来,见「类型引用」前的实测)。 +- 槽里的值是不是类对象,用目标镜像按需建的类索引判断(`__objc_classlist` 的类与元类,名字取自 `class_ro_t`);其他槽(`__cfstring` 的 isa 之类)一律不算。类对象不能只按所在段认:9.2 万个 Swift 类与元类在 `__data` 里。 +- 发送的接收者来自类引用时记为 `classLiteral`(AppKit 11% 的发送)。`objc_opt_self`、`objc_opt_class`、`swift_getInitializedObjCClass` 视为原样返回实参(SwiftUI 的类接收者几乎都经 `objc_opt_self`)。 +- super 发送的类取发送方法自己的类(名字 `-[C sel]` 里的 `C`,或方法表给的类)。用栈槽跟踪能还原 88%,与方法自己的类对照,7,106 处一致、2 处不同,所以不做栈槽跟踪。 +- 扫描时判断一个函数是不是 ObjC 方法(`x0` 是不是接收者)仍只看名字。把无名的方法实现也算上能让 AppKit 的 self 发送从 67,848 处升到 77,696 处,但要在每次扫描时读方法表,代价与扫描本身相当;iOS 真机上符号全被抹掉,这一项影响更大,留到有更快的方法表读法时再做。 + +### 类型引用 + +- **键**:名义类型的 mangling,不带 `$s`,不带后缀:`7SwiftUI4TextV`、`Sa`、`So8NSWindowC`。泛型实例里出现的每个名义类型各算一处引用(`Array` 引用 `Sa` 和 `7SwiftUI4TextV`)。ObjC 类写成 `So<长度><名字>C`;有 ObjC 元数据的 Swift 类经元数据 +0x40 的描述符得到它自己的 mangling。不用描述符地址作键:导入的 `So…` 类型在每个用到它的镜像里各有一份描述符,标准库类型在 mangled 名字里写成文本。键一律经重新 mangle 得到——直接从 `…Mn` 符号截取,与重新 mangle 的结果在受约束扩展里的嵌套类型上不一致(SwiftUICore 4,778 个里 36 个)。 +- **来源**(括号里是 SwiftUICore 的数量): + 1. 元数据访问器调用(本镜像 15,042,跨镜像 5,649):目标属于访问器集合(各镜像 `__swift5_types` 描述符的 `accessFunction`,全缓存 34 万个,并发 0.13 s 建完)。泛型实例、存在类型、导入类型的访问器(`$sSNy10Foundation4DateVGMa`、`…_pMa`、`$sSo…Ma`)没有描述符,只能按符号名认。 + 2. 取址:`adrp`+`add` 或 GOT 载入得到访问器地址(8,060 / 6,332)、值类型元数据地址(27,057 / 4,106)或类元数据(266)。SwiftUICore 里取址比访问器调用还多。 + 3. 按 mangled 名字实例化:调用本镜像的 `__swift_instantiateConcreteTypeFromMangledName*` helper(全缓存 1,771 个 Swift 镜像有,147 万处调用,一律调本镜像的那份;没有符号时按形态认:不超过 0x90 字节、调用 `swift_getTypeByMangledNameInContext*`)。27.2 上几乎都是 V2:名字不在 `x0` 的缓存变量里,而在 `x1` 指向的 `{int32 到 __swift5_typeref 的偏移, int32 长度}` 记录里。名字里的 `\x01` / `\x02` 符号引用指向描述符,用 `SymbolicDemangler` 解开(每个约 60 µs,平均含 2.5 个名义类型)。SwiftUI 与 SwiftUICore 不用这个 helper。 + 4. ObjC 类引用,见上一节。 +- **查询**:「哪些函数引用了类型 T」不能只按键等值过滤:mangled 名字要解开才知道引用了谁,全缓存 147 万处逐个解开太慢。扫描先拿 T 的全部身份(访问器位置、元数据与类对象地址、描述符地址、mangling 文本)做结构比对——符号引用比地址、文本比子串——命中了才解开确认。 +- **预筛**:定义 T 的镜像,加上导入了 T 的 `…Mn`、`…Ma`、`…N`、`_OBJC_CLASS_$_…` 的镜像;标准库与导入的 C 类型只以文本出现在 mangled 名字里,按各镜像 `__swift5_typeref` 的字节预筛。 + +### 寄存器跟踪在汇合点的问题(第一批的缺陷,已修) + +扫描原先按指令顺序跟踪寄存器,没有处理汇合,汇合处沿用最后一条路径的值。核实结果:`-[NSString stringByAppendingString:]` 里一个块把参数放进 `x0`、下一个块放 `self`,两者跳到同一处发送 `copyWithZone:`,顺序读法把接收者说成 `self`——确实会错。先试了「无条件转移后忘掉调用方保存的寄存器」:AppKit 80 万处引用改了 1,237 处,selector 一处没变,但它把 `+[NSObject instanceMethodForSelector:]` 这类早退之后本来正确的 `self` 也丢了,弃用。最后的修法是让状态沿着分支走:向前的分支带着快照到目标处,目标处以带来的状态为准(前一条是无条件转移)或与顺序状态取交集;循环头与无人指向的落点忘掉调用方保存的寄存器。AppKit 因此多认出 9,699 处 `self` 发送、少说 78 处;release 下全缓存整表扫描 1.6–1.8 s → 2.0 s,查 `init` 的调用者 1.5 s 不变。 + +### 第二批 ①:起名的实现与验证(2026-10-17) + +- **落地**:新文件 `Scanning/ImageFallbackNames.swift`(三个来源各自按需读、记在函数表上);`ImageFunctionTable.codeFunction(at:)` 在符号表没有名字时问它;`CodeFunction.Name.swiftMethod(descriptorAddress:)` 换成 `.swiftMetadata(mangledName:)`;分析器找运行时函数时也读运行时库的导出表。target 依赖加了 `MachOObjCSection`、`MachOFoundation`、`MachOSwiftSection`、`SwiftInspection`、`Demangling`(只用于起名)。 +- **这一步没做的**:协议见证(全缓存 78 万处,最大的一类)、override 实现、witness table pattern 条目的名字;扫描时用方法表判断无名的 ObjC 方法。 +- **实测**(release,28 核):给全部函数起名,AppKit 0.24 s(方法表补 3,961、元数据补 1,147,仍无名 15,884),SwiftUICore 0.06 s(不需要补),SiriAppIntents 1.5 s(导出表 76,318、元数据 2,820),Matter 0.04 s(方法表 30,863)。每个镜像起 32 个名字、走遍整个缓存 6.9 s(4 线程 6.1 s,并发几乎不变快:耗在 Swift 运行时的泛型元数据缓存)。 +- **验证**:`FallbackNamingTests` 5 个测试(各来源与真实符号互相印证,见模块参考);`CrossReferenceAnalysisTests` 共 29 个、`SwiftThunkAnalysisTests` 82 个通过。 +- **第一次跑测试的教训**:导出表与实现的偏移可以是负的(缓存里落在本镜像头部之下),`UInt64(offset)` 当场崩溃;全部改成带环绕的加法。 + +### 第二批 ②:ObjC 类的实现与验证(2026-10-17) + +- **落地**:新文件 `Scanning/ObjectiveCClassIndex.swift`(每个镜像按需建的类索引);新的引用种类 `CodeReference.Kind.reference`(取类地址但不跳转的指令);目标 `.objectiveCClass(name:location:)`;`superMessageSend` 多了 `className`;`ReceiverClassHint.classLiteral` 有了来源;表键 `CodeReferenceTable.Key.objectiveCClass`;公开 API `objectiveCClassLocations(named:inImageAt:)`、`imageIndices(referencingObjectiveCClassAt:among:)`、`imageIndices(importingAnyOf:among:)`。 +- **与设计不同之处**: + - super 的类不取方法名或方法表,取同一函数里从 `__objc_superrefs` 载入的类,没见到时才退回方法符号。槽里就是编译器给的类,分类方法、类方法(槽里是元类)、没有符号的方法都对,扫描也不必读方法表。这一载入本身不报成类引用。Swift 代码的 super 发送不经这个槽(类来自 `self` 的运行时类或元数据访问器),类记为空:Foundation 1,803 处里 374 处、AppKit 8,336 处里 1,133 处,其余全有类。 + - 引用目标除了类名还带类对象的位置:全缓存 203,621 个类名里 18,906 个不止一个镜像定义,多是 `/System/iOSSupport` 下的 Mac Catalyst 变体。表键仍是类名。 + - 类预筛不只认 `_OBJC_CLASS_$_<名字>`:抽样里别的镜像引用某个类,6,921 对中 251 对走别名(Block 的 `isa` 是 `__NSConcreteStackBlock`,XPC 类型是 `__xpc_type_dictionary`)。预筛取定义镜像的符号表与导出表里落在类或元类地址上的全部名字。 +- **实测**:AppKit 取本镜像类的地址 3,319 处、载入类 53,026 处(与实现阶段重跑探针的 3,318 / 52,668 相差不到 1%),类字面量接收者 35,175 处(发送的 11%);SwiftUI 665 处类字面量接收者里 478 处经 `objc_opt_self`。`adr` 与字面量 `ldr` 两种形态在缓存与几个缓存外的系统 App 里都没有,不解码。 +- **性能**:类索引起初经 `MachOImage.objc.classes64` 建——它对每个类都重新查一遍 load command,撞上 Swift 运行时的泛型元数据锁——加上扫描每次查类都抢分析器的锁,全缓存整表扫描从 2.0 秒变成 4.9 秒。改为直接读 `__objc_classlist` 与 `isa`、扫描器自己缓存索引、本镜像 `__TEXT` 与非类槽在查表前排除之后,与只有分支跟踪的那次提交交替跑三轮取最好:整表 2.03 → 2.40 秒(引用多 326 万条,+17%),查 `init` 的调用者 1.54 → 1.70 秒。 +- **验证**:`ObjectiveCClassReferenceTests` 7 个测试(11 个用例),其中经 `objc_opt_self` 保留 `x0`、读 `__objc_superrefs`、预筛认别名三项在去掉做法时变红过;`CrossReferenceAnalysisTests` 共 38 个、`SwiftThunkAnalysisTests` 82 个通过。 +- **没做的**:按字符串取类(`objc_getClass("…")`,AppKit 183 处);扫描时用方法表判断无名的 ObjC 方法(见设计);Swift 的 super 发送的类。 + +### 第二批 ③:Swift 类型引用的实现与验证(2026-10-17) + +- **落地**:`Scanning/SwiftTypeIndex.swift`(每个镜像按需建:`__swift5_types` 的描述符、各自的访问器、按需算的 key);`CrossReferenceAnalyzer+SwiftTypes.swift`(`SwiftTypeIdentity`、`swiftTypeIdentity(ofDescriptorAt:)`、`swiftTypeDescriptorLocations(withKey:inImageAt:)`、`references(toSwiftType:inImageAt:)`、`imageIndices(referencingSwiftType:among:)`、`swiftTypeKeys(in:)`,以及比对器 `SwiftTypeQuery`);目标 `.swiftType(descriptor:)` 与 `.swiftTypeName(SwiftTypeName)` 换掉第一批声明了、没人产出的 `.typeMetadataAccessor` 与 `.mangledTypeName`;表键 `.swiftTypeDescriptor(CodeLocation)`;分析器认出运行时的 `swift_getTypeByMangledName…` 入口。 +- **与设计不同之处**: + - 表按描述符位置归档,不按 key(设计里说「不用描述符地址作键」)。扫描时算 key 要为每个被引用的描述符 demangle,而 key 的拼法随 demangle 的路径变:受约束扩展里的嵌套类型、其他模块类型的扩展里的 private 类型都会拼偏。位置精确、不花时间,也天然分开 Mac Catalyst 变体。设计里不用位置的两条理由由查询解决:导入的类型每个镜像一份描述符,查询按 key 比;标准库类型在名字里拼出来,查询解开名字。key 改为取自描述符的 `…Mn` 符号。 + - 查询不做文本子串比对(设计里「文本比子串」):mangling 会把同一名字里重复出现的单词换成替身,子串会漏。只有名字可能拼出来的类型才解开名字,其余只比符号引用。这条前提逐个解开 Foundation、SwiftData、libswift_Concurrency、SwiftUI 的全部名字核对过,没有例外。 + - 预筛对名字可能拼出来的类型,不按 `__swift5_typeref` 的字节筛(同一原因),凡有非空 `__swift5_*` 节的镜像都算。 +- **实测**(扫一遍):SwiftUICore 调用描述符可知的访问器 15,432 处、取元数据或访问器地址 35,140 处、经 GOT 载入 10,438 处、调用只有符号的访问器 5,259 处,不用按名字实例化;Foundation 按名字实例化 6,280 处、934 个不同名字;SwiftUI 访问器调用 63,487 处。访问器调用报出的类型与访问器符号全部一致。 +- **性能**:全缓存整表 2.1 → 3.0 秒(引用 1.16 亿 → 1.26 亿条),查 `init` 的调用者 1.6 → 1.8 秒(只查 selector 或函数时不找类与类型引用)。途中两次退化:`keep(reference(to: …))` 这种参数里修改扫描器的写法让 Swift 每次复制整个扫描器,整表一度 95 秒;类型索引每次去分析器的锁里取,等锁占掉大半时间。两处的修法见模块参考。 +- **第一批的预筛缺陷(已修)**:写类型预筛的正确性测试时发现,macOS 27.2 的缓存里 4,113 个镜像只有 245 个留着 Swift 的未定义符号(SharedWithYou 照样调用 `URL` 的访问器,却没有任何导入记录)。第一批的函数预筛按导入符号筛,只拿 C 函数测过,对 Swift 函数一直会丢掉不留导入记录的镜像里的调用者——`URL.path` 只有 44 个镜像按名字导入——RuntimeViewer 第 3 步查 Swift 方法的跨库调用者受影响。Swift 符号改按链接关系筛(直接链接,或经再导出链接到定义镜像),新增 `imageIndices(linkingImageAt:among:)` 与 `imageIndices(callingFunctionAt:symbolNames:among:)`;Swift 类的类预筛同样补上链接关系。回归测试 `swiftFunctionPrefilterKeepsEveryCaller` 在旧做法下变红。 +- **没做的**:协议的类型引用(协议描述符、存在类型、泛型约束都要另算);旧形态(V1)已经实例化的缓存变量;直接调用 `swift_getTypeByMangledName…` 时只认 `adrp` / `add` 出的名字地址。 + +### 落地顺序 + +①起名(导出表、ObjC 方法表、Swift 元数据);②ObjC 的类字面量、super 的类与类引用,以及汇合点的核实与修正;③Swift 类型引用、类型查询与预筛。每一步单独测试、单独提交。 + +### 审查与修复(2026-10-17) + +第二批落地后对两批的全部提交做了一轮审查。记录在 [2026-10-17 审查记录](../../Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md),判为不修或暂缓的登记在 [ReviewAdjudications](../Internal/ReviewAdjudications.md) A62–A67。修了的(每条都先写了修复前失败的测试): + +- **寄存器跟踪漏作废的写入**:前 / 后变址读写的基址、不带内存序的原子指令、`ldxp` / `casp` 的第二个寄存器、`umov` / `smov`、浮点转定点、SVE / SME 里写通用寄存器的指令、`sysl`、`svc`。判断改写成纯函数 `RegisterFile.registersWritten(by:)`。SwiftThunkAnalysis 的两个跟踪器对成对回写的基址同样不作废,同一轮修。 +- **改名再导出**:C 函数与类的预筛连同别的镜像改名再导出的名字一起比。缓存里 12 个镜像共 1,438 条,CoreGraphics 从 SkyLight 再导出的 1,112 条占大头,AppKit 按 CoreGraphics 的名字导入了其中 273 个。新增公开接口 `reexportedNames(ofSymbolsNamed:inImageAt:)`。 +- **缓存外镜像的路径**:取 dyld 的加载路径,不再取安装名(主程序与 bundle 没有安装名,框架的是 `@rpath/…`);安装名另建一张表给链接关系用,同名拷贝都算;插件 bundle 算主程序的依赖方。 +- **类型查询的 demangle 不再驻留**:不进全局 `NodeCache`,也不进进程级 demangle 记忆。 +- **公开接口**:`CodeReferenceTable.keys` 改为 `some Collection`;`swiftTypeDescriptorLocations(withKey:inImageAt:)` 的文档如实说明退回路径。 +- **测试**:与 Capstone 的对照改成双向;super 的类补上只有读槽位才能通过的测试。 + +循环头与跳转表落点保留 `x19`–`x28`(审查 A5)量过数据:现行做法错 0.02%–0.04% 的引用,精确修法多花 35%–60% 的扫描时间;用户看过数据后定为保持现状,作为已知局限(ReviewAdjudications A68)。 + +### 为宿主预读第一次查询要读的东西(2026-10-18) + +RuntimeViewer 在后台为已索引的镜像建好 `CodeReferenceIndex` 之后,用户发现第一次显示还要等一下,之后才秒出。量下来,第一次查询还要现读几样只读一次的东西(Debug 构建,28 核): + +| 现读的 | 何时 | 用时 | 留下的 | +|---|---|---|---| +| 补充名字的三个来源 | 第一次给某镜像的函数起名 | AppKit 0.29 s | 12 MiB | +| 每个类型的 key | 第一次按 key 找某镜像里没有符号的类型 | AppKit 0.69 s、SwiftUICore 0.44 s | 3.3 MiB | +| 整个导出表的名字集合 | 第一次判断某镜像导出了某类型没有 | SwiftUICore 0.09 s | 6 MiB | +| 改名再导出表 | 第一次跨全部已索引镜像预筛 | 3.4 s,占满 28 核 | 1 MiB | +| 链接关系 | 同上 | 0.06 s | 1 MiB | + +做法分两类: +- **能不读的不读**:按 key 找类型只给描述符名字相同的类型算 key(约 1 毫秒;从 C / ObjC 导入、在 Swift 里改了名的类型,C 名在描述符的导入信息里,也要比);判断导出与否在导出表里按名字查三个符号,不再读整张表、也不留集合。两处都对 Foundation 与 AppKit 的全部类型核对过结果不变。 +- **必须读的让宿主提前读**:`prepareNames(inImageAt:)` 读好一个镜像的三个来源、类名与类型符号;`preparePrefilters()` 读好链接关系与改名再导出表,只用调用线程(单线程 3.9 秒,并行 3.4 秒,并行几乎不快,后台不该占满所有核),读的时候来了要用它的查询等它读完而不是再读一遍。宿主拿 `approximateByteCount(ofImageDataAt:)` 把留下的计入自己的预算,用 `releaseImageData(exceptForImagesAt:)` 放掉别的镜像的、留住预读过的——换分析器会把预读的一起扔掉。 + +验证:`PreparedImageDataTests` 5 个,`SwiftTypeReferenceTests` 新增 4 个(两个测试各跑 Foundation 与 AppKit)。 + +## 后续 + +各批记下「没做的」,落地时收在这里: + +- **起名还缺的来源**:协议见证(全缓存 78 万处,最大的一类)、override 实现、witness table pattern 条目的名字;扫描时用方法表判断无名的 ObjC 方法。RuntimeViewer 0056 在 macOS 26.7 上实测:缓存里 37.8% 的函数起点没有符号,Charts、SwiftData、WidgetKit 这类 Swift 框架七到九成;名字齐全的 Swift 镜像里协议见证占全部函数的 11–18%、值见证占 4–13%,这两类都能从见证表确定名字,是补名字最值得做的两项。 +- **ObjC**:按字符串取类(`objc_getClass("…")`,AppKit 183 处);Swift 的 super 发送的类。 +- **类型引用**:协议的类型引用(协议描述符、存在类型、泛型约束);旧形态(V1)已经实例化的缓存变量;`swift_getTypeByMangledName…` 的名字地址只认 `adrp` / `add` 出的。 +- **扫描**:过滤扫描按键提前跳过(现在先建好每条引用再丢)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-16 | Created as Draft | RuntimeViewer 提案落地第二步要求先写本库的提案;整体方向用户已在那份提案里确认 | +| 2026-10-16 | 采用的假设 | 只读 `MachOImage`;target 名 `CrossReferenceAnalysis`;不新增缓存;分三批落地;GOT 桩与 island 的识别与 SwiftThunkAnalysis 共用 | +| 2026-10-16 | 状态 → Accepted → In Progress | 用户批准按本方案动手(「可以,开始第一批」),跳板识别从 SwiftThunkAnalysis 抽出共用;开始第一批 | +| 2026-10-16 | API 改为宿主持有的 `CrossReferenceAnalyzer`,位置用 `CodeLocation` | 跨镜像解析目标要整张进程镜像表;缓存外两个镜像的未滑动地址可能重合 | +| 2026-10-16 | 整镜像扫描不记函数表;新增只留命中引用的 `references(to:inImageAt:)` | 实测:记表时扫完全缓存常驻 1.5 GB;整表并发扫描的峰值让分配器留下 1.2 GB;过滤扫描后约 170 MB | +| 2026-10-16 | 不做懒绑定退回,留哨兵测试 | 探针实测 dyld 加载时就绑好懒绑定槽,防护是死代码 | +| 2026-10-16 | 补认缓存内传统发送的 selector 字符串地址;补预筛正确性测试 | RuntimeViewer 第 3 步查 `-[NSObject description]` 的调用者一条都没有,追到第一批漏认了这种形态;同时发现预筛从未被断言过「不漏」 | +| 2026-10-17 | 第二批按实测重定:加导出表起名;名字在起名时按镜像按需读;类型键用名义类型的 mangling;类型查询先结构比对再解开 | 两个只读探针实测:导出表能给 140 万个无名起点起名而第一批没读;方法表与元数据每次扫描都读,代价与扫描本身相当;27.2 上实例化的名字在 `x1` 的记录里、类引用几乎不经 `__objc_classrefs`。用户要求「继续第二批」 | +| 2026-10-17 | 寄存器状态沿着分支走(快照随前向分支到目标处,汇合取交集),不用「转移后一律忘掉」 | 核实了第一批的汇合点缺陷:`-[NSString stringByAppendingString:]` 的 `copyWithZone:` 接收者被错说成 `self`;简化版会丢掉早退之后正确的 `self`;完整版 release 开销约 10–20% | +| 2026-10-17 | 类引用的目标带类对象的位置,表键仍是类名 | 全缓存 18,906 个类名不止一个镜像定义(多是 Mac Catalyst 变体),只按名字会把两个 SwiftUI 的同名类混在一起 | +| 2026-10-17 | super 的类取 `__objc_superrefs` 的载入,退回方法符号;Swift 的不记 | 槽里就是编译器给的类,分类方法、无符号的方法都对,不必在扫描时读方法表;Swift 的类到运行时才知道 | +| 2026-10-17 | 类预筛认定义镜像在类与元类地址上的全部符号 | 抽样 4% 的跨镜像类引用走别名(`__NSConcreteStackBlock`、`__xpc_type_dictionary`),只认 `_OBJC_CLASS_$_` 会漏 | +| 2026-10-17 | 类索引直接读 `__objc_classlist` 与 `isa`,不经 `MachOImage.objc.classes64` | 后者让全缓存整表扫描从 2.0 秒变成 4.9 秒;直接读之后为 2.4 秒 | +| 2026-10-17 | Swift 类型引用的表按描述符位置归档,key 取自描述符的 `…Mn` 符号 | 扫描时算 key 要 demangle,且 key 的拼法随 demangle 路径变(受约束扩展、扩展里的 private 类型);位置精确、不花时间、分得开 Catalyst 变体 | +| 2026-10-17 | 类型查询只比符号引用;名字可能拼出来的类型(标准库、`_Concurrency`、导入)才解开名字;不做文本子串比对 | 逐个解开四个镜像的全部名字核对:其他类型在名字里都是符号引用;mangling 的单词替身会让子串比对漏 | +| 2026-10-17 | 扫描器先把引用算进局部变量再保留;类与类型索引由扫描器持有的引用类型缓存;只查 selector 或函数时不找类与类型引用 | 实测:参数里修改扫描器让整表扫描一度 95 秒;等分析器的锁占掉大半时间;selector 查询本来用不到它们 | +| 2026-10-17 | 跨镜像的 Swift 符号按链接关系预筛,不按导入符号;`imageIndices(importing:)` 只对 C 与 ObjC 符号 | 实测缓存 4,113 个镜像只有 245 个留着 Swift 未定义符号;第一批的函数预筛因此对 Swift 函数会丢掉其余镜像里的跨库调用者(只用 C 函数测过)。链接关系在缓存里完整,粗但不漏 | +| 2026-10-17 | 审查后修复:寄存器写入、改名再导出、缓存外镜像的路径与链接、类型查询的瞬时 demangle、`keys` 的类型;A7 暂缓,A6、A8 的其余两处、B5、B7 不修 | 用户批准「先按你推荐的路径修」;逐条见审查记录与 ReviewAdjudications A62–A67 | +| 2026-10-17 | 改名再导出表在第一次需要时并发走一遍所有镜像的导出表,之后随分析器留着 | 这种再导出只在 12 个镜像里,但不走一遍不知道在哪;只记改名的条目,名字只在命中时拼出 | +| 2026-10-17 | 缓存外镜像的路径取 `dladdr` 按镜像头读到的加载路径,安装名另建一张表 | 宿主拿到的是加载路径;加载命令按安装名链接;按头读不按序号,中途有镜像加载或卸载也不会错位 | +| 2026-10-17 | 循环头与跳转表落点保留 `x19`–`x28`(审查 A5)不修,作为已知局限 | 精确做法多花 35%–60% 的扫描时间,换 0.02%–0.04% 的引用;循环头全部作废会丢约 3.9 万条正确的事实。用户看过数据后选定,登记 ReviewAdjudications A68 | +| 2026-10-17 | Swift 类型的预筛先看定义镜像导不导出它的符号(`…Mn` / `…Ma` / `…N`),一个都不导出就只扫定义镜像 | 用户在 RuntimeViewer 里查 AppKit 内部结构体的类型引用,扫了几乎整个缓存、CPU 占满;内部类型别的镜像绑定不到、也拼不出名字。公开类型三个符号都导出(`URL`、`SwiftUI.Text`、`JSONEncoder` 已核对),原有「不漏引用」的测试照样通过 | +| 2026-10-18 | 新增 `CodeReferenceIndex`(`referenceIndex(ofImageAt:)`、`references(toSwiftType:in:)`、`keepFunctionTable(ofImageAt:)`):按目标分组、名字只存一份、偏移存 32 位,只留查调用者与类型引用会读的引用 | RuntimeViewer 要为已索引的镜像预先建好引用表常驻内存(用户选「紧凑表」「只放内存」)。整表一条引用约 80 字节,AppKit 67 MiB;索引 21 MiB。回答与过滤扫描逐条相同(`CodeReferenceIndexTests`)。建索引留住函数表,因为宿主会反复给结果起名;这与「整镜像扫描不留函数表」不冲突——索引只为宿主要留的少数镜像建 | +| 2026-10-18 | 新增 `prepareNames(inImageAt:)`、`preparePrefilters()`、`approximateByteCount(ofImageDataAt:)`、`releaseImageData(exceptForImagesAt:)`;按 key 找类型只算同名类型的 key;判断类型导出与否改为在导出表里按名字查 | 用户在 RuntimeViewer 里发现预先建好引用表之后第一次显示仍要等,批准把起名数据与预筛表挪进后台(刚启动、表还没建完时要等,用户认为本该如此)。实测第一次查询现读的几样里,能免的(全部类型的 key、整个导出表)改成不读,免不了的(补充名字、预筛表)交给宿主提前读;预筛表并行读几乎不快,所以预读只用调用线程,以免后台占满所有核。预读的东西计入宿主预算,宿主放掉别的镜像而不是换分析器,否则预读白做 | +| 2026-10-19 | 实现完成,合入 next,编号 0072;状态 → Implemented | RuntimeViewer 0056 的引擎与界面要用的能力都在本层,0056 的引擎与 GUI 同日合入 RuntimeViewer 的 next(它的 CLI 与 MCP 还没做,不需要本库再改)。各批「没做的」收进「后续」。配套文档已有:模块说明 `Internal/Modules/CrossReferenceAnalysis.md` 就是实现说明,使用方只有 RuntimeViewer、接口契约写在模块说明里,不另写使用指南;术语已在各批登记进 `Glossary.md` | diff --git a/Documentations/Evolutions/0073-protocol-requirement-placement.md b/Documentations/Evolutions/0073-protocol-requirement-placement.md new file mode 100644 index 000000000..e37c7714a --- /dev/null +++ b/Documentations/Evolutions/0073-protocol-requirement-placement.md @@ -0,0 +1,88 @@ +# 0073 - 协议约束可选写在各自的关联类型上 + +- **状态**: Implemented +- **创建日期**: 2026-10-20 +- **最后更新**: 2026-10-21 +- **实现分支**: `feature/protocol-requirement-placement` + +## 摘要 + +二进制只记录协议的 requirement signature,也就是编译器规范化之后的全部约束,看不出源码把一条约束写在协议的 `where` 子句里还是写在 `associatedtype` 上:两种写法编译出来完全一样。interface 现在把所有约束都堆在协议头的 `where` 子句里: + +```swift +protocol MenuBase: AppKit.XPCCodable, Swift.Identifiable where Self.MenuItemType: AppKit.MenuItemBase { + associatedtype MenuItemType +} +``` + +本提案给 interface 加一个开关,打开后把关于本协议某个关联类型的约束写到那个 `associatedtype` 上,与编译器生成 `.swiftinterface` 的写法一致: + +```swift +protocol MenuBase: AppKit.XPCCodable, Swift.Identifiable { + associatedtype MenuItemType: AppKit.MenuItemBase +} +``` + +两种写法表达的约束必须完全相同:每条约束恰好出现一次,文字不变,只换位置。 + +## 方案 + +**摆放规则**:逐条看 requirement signature。约束 `Self` 本身的(继承的协议、`AnyObject`、父类)照旧写在协议的继承子句里。其余的: + +1. conformance / superclass / layout 约束,主语恰好是 `Self.X`,且 `X` 是本协议自己声明的关联类型:写进 `associatedtype X` 的继承子句,`associatedtype X: P`。 +2. 其余约束,找它关于哪个关联类型:在主语里找第一个 `Self.X` 引用,取链的根(`Self.X.Y` 算 `X`)。same-type 约束两边都看,优先取恰好是 `Self.X` 的那一边,其次左边,再次右边。找到就写进 `associatedtype X` 的 `where` 子句,文字与原来逐字相同,比如 `associatedtype Nested: Swift.Sequence where Self.Nested.Element: Probe.Marker`。 +3. 找不到本协议的关联类型(比如只约束了继承来的 `Self.Element`):照旧写在协议的 `where` 子句里。 + +规则 2 只用于 conformance / superclass / layout / same-type 约束;inverse、same-shape 等其余种类照旧写在协议的 `where` 子句里。 + +**为什么语义不会变**:协议的 `where` 子句、关联类型的继承子句、关联类型的 `where` 子句,Swift 都把其中的约束收进同一个 requirement signature;`associatedtype X: P` 就是 `where Self.X: P`,关联类型的 `where` 子句里也可以写任何关于 `Self` 的约束。唯一会改变含义的错误,是把约束放进错误的关联类型的继承子句,所以规则 1 只认主语恰好是 `Self.X` 的约束。编译器自己的打印器恰好在这里出错:对源码 `associatedtype Child: RecursiveLeaf where Child.Leaf: Hashable`,Swift 6.3.3 的 `-emit-module-interface` 印出 `associatedtype Leaf : Swift.Hashable`,约束从 `Self.Child.Leaf` 变成了更强的 `Self.Leaf`。规则 2 取链的根,这条约束落在 `Child` 的 `where` 子句里,与源码一致。除此之外摆法与编译器相同,包括 same-type 约束不交换左右(编译器对 `Self == Self.Pointer.Target` 也原样输出)。 + +**开关与接线**: + +- `SwiftDeclarationPrintConfiguration.protocolRequirementPlacement`,类型是新的 `ProtocolRequirementPlacement`(在 SwiftPrinting,与 `SwiftDeclarationMemberSortOrder` 放在一起;`.protocolWhereClause` 是默认值,另一个是 `.associatedTypes`)。默认值下输出逐字节不变。 +- SwiftSectionKit 的 `InterfaceRequest.protocolRequirementPlacement`;CLI `interface --requirements-on-associated-types`;agent 插件的 skill 同批更新。 +- 划分是 SwiftPrinting 里的 `ProtocolRequirementPartition`(package):每条约束恰好进一个列表,列表内保持签名里的顺序。`printIncludedProtocolDefinition` 打印一个协议时只算一次,`renderProtocolDeclarationHeader` 和 `renderProtocolAssociatedTypes` 共用。认 `Self.X` 链的两个节点工具(`protocolSelfMemberNames`、`firstProtocolSelfMemberRoot(among:)`)在 SwiftDeclarationRendering 的 `Node+ProtocolSelf.swift`,附带修复也用它们。 +- `associatedtype` 的继承子句只印约束的右侧(新增 `dumpProtocolContent(resolver:in:)`)。从协议 extension 推断出的 `~Swift.Copyable` 接在这些约束后面:`associatedtype Element: P, ~Swift.Copyable`。 + +**不动**: + +- dump。dump 以信息完整为目标,约束写在哪不影响信息量。 +- diff / evolution 的协议头永远按 `.protocolWhereClause` 打印。它们的 `associatedtype` 行是按名字逐行比较的单位,约束挪走而这些行不带约束就会丢;要带上就得让 diff 比较每个关联类型的约束,超出本提案范围。它们的打印器现在本来就只用默认配置(`InterfaceVersionUnit`),显式传值是为了日后接上配置时不丢约束。 +- ABI snapshot / diff 模型。 +- RuntimeViewer:拿到新字段和默认值,设置项另议。这个开关不是 `SwiftVisibilityOption`,标记模式(`marksOptionalContent`)下照配置打印,切换要重新打印,与 `usesModuleSelectors` 一样。 + +**附带修复(单独 commit,两种写法都受益)**:`GenericContext+Dump.swift` 的 `dumpProtocolMangledName` 打印约束右侧的类型时,把整棵类型树里的关联类型名全部收集起来串成一条链,复合类型因此被印成另一条约束:`Self.Second == [Self.First]` 印成 `Self.Second == Self.First`,`Self.Fifth: GenericBase` 印成 `Self.Fifth: Self.First`,`Self.Third == (Self.First, [Self.First])` 印成 `Self.Third == Self.First.First`,`Self.Sixth == [Self]` 印成 `Self.Sixth == [A]`。dump 和 interface 共用这个函数,自 2025-08-21 写下(`fedbf876`)就是这样。改为:类型本身是 `Self.A.B` 这样的链时照旧拼写;否则把整个类型交给 resolver 打印,打印前把协议的泛型参数换成 `.constrainedExistentialSelf`(两个打印器都把它拼作 `Self`),并去掉关联类型的协议限定(上游 `NodePrinter` 会把 `Self.Seventh.[Sequence]Element` 拼成 `Self.Seventh.Swift.Sequence.Element`)。 + +**验证**: + +- 新的现场编译 fixture `ProtocolRequirementPlacementFixture`,覆盖:单个与多个协议、superclass、`AnyObject`、父类加协议、嵌套主语 `Self.X.Y`、same-type 到具体类型、两个关联类型之间、`Self == Self.X.Y`、继承来的关联类型、递归协议、复合类型右侧(含带协议限定的成员)、主语是继承来的关联类型而父类提到本协议关联类型(`Element: GenericBase`,只看主语,留在协议上)。 +- 两种写法的期望文本逐字断言(interface),复合类型右侧在 dump 与 interface 各断言一次。 +- 语义往返:把两种写法印出的协议各自用同一模块名重新编译,读回 requirement signature,用通用的 requirement dump(demangler 的默认打印,不经被测的协议打印)逐条比较,必须与原二进制完全相同。这就是「规范化之后 ABI 一样」本身。 +- diff 的协议头在 `.associatedTypes` 配置下仍与默认写法的协议头相同。 +- `~Copyable` 与继承子句合并:Swift 6.4 fixture 新增 `ConstrainedSuppressedElementContainer`(`Swift64DeclarationShapeInterfaceTests`,需要 Swift 6.4 工具链,CI 不跑)。 +- SwiftSectionKit 端到端:`DumpAndInterfaceRequestTests` 用 SymbolTestsCore 的 `ClassBoundGenericProtocol` 对比两种写法;CLI 侧 `CommandRequestMappingTests`。 +- 现有快照测试不改一行即全绿,证明默认输出不变。 + +**落地步骤**(每步单独构建通过、测试通过后提交): + +1. 【已完成,`6b758d0e`】附带修复:先用现场编译的 fixture 写出复合类型右侧的复现测试(dump 与 interface 各一处,修复前红),再改 `dumpProtocolMangledName`。 +2. 【已完成,`d618de54`】划分与 interface 接线:`ProtocolRequirementPlacement` 与划分逻辑、`SwiftDeclarationPrintConfiguration` 的新字段、协议头与关联类型行按划分打印、diff / evolution 固定集中写法;测试覆盖两种写法的期望文本、语义往返、diff 不丢约束。 +3. 【已完成,`0aa75f70`】SwiftSectionKit 与 CLI:`InterfaceRequest` 的新字段、`interface --requirements-on-associated-types`、两侧的映射测试、agent 插件的 skill、CI 的套件过滤名单。 +4. 【已完成,`07016c07`】文档与全量验证:`ProjectEvolutionLog`;SwiftSectionKit 的调用方指南与模块文档不逐个列请求字段,不需要改。全量测试(`IntegrationTests` 除外)的结果记在演进账本这一节。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-20 | Created as Draft | interface 要能选择把约束集中写在协议的 `where` 子句,还是写到各自的关联类型上;前提是两种写法语义完全相同,因为二进制里看不出源码写在哪 | +| 2026-10-20 | 继承子句只收主语恰好是 `Self.X` 的约束,不照抄编译器的摆法 | 编译器在递归协议上把 `Self.Child.Leaf: Hashable` 印成 `associatedtype Leaf: Hashable`,改变了语义 | +| 2026-10-20 | 默认保持现在的写法 | 打开即改变每一份 interface 输出和快照 | +| 2026-10-20 | 只接 interface,dump 与 diff / evolution 不接 | dump 不为可读性取舍;diff 的关联类型行不带约束,接上会丢约束 | +| 2026-10-20 | 用户批准,开始实现;附带修复按方案同批做,单独一个 commit | 语义往返测试要覆盖复合类型右侧,否则只能把这类形状排除在外 | +| 2026-10-20 | 规则 2 不处理 inverse、same-shape 等种类,留在协议的 `where` 子句 | IRGen 不为关联类型发 inverse requirement(见 `SuppressedAssociatedTypeInference`),挪动这些种类没有收益,留在原处最保守 | +| 2026-10-20 | 往返测试的比对基准用通用 requirement dump,不经被测的协议打印 | 基准若依赖被测代码,两边一起错也会通过 | +| 2026-10-20 | `~Copyable` 合并的用例放进 Swift 6.4 fixture | SE-0503 的 `~Copyable` 关联类型只有 Swift 6.4 编得出来;`ProtocolRequirementPlacementFixture` 要在 CI 的旧工具链上编 | +| 2026-10-20 | diff / evolution 的协议头显式传 `.protocolWhereClause` | 它们的打印器现在只用默认配置,显式传值防止日后接上配置时约束无处可印 | +| 2026-10-20 | 实现完成,待合并 | 验证结果记在 ProjectEvolutionLog 本节;文档判断:SwiftSectionKit 的调用方指南与模块文档不逐个列请求字段,无需改动;没有引入需要登记术语表的新词 | +| 2026-10-21 | code review(`/code-review high`)8 条:只修第 1 条,改写公开文档、演进账本与 PR 描述里说宽了的规则,fixture 加 `SubjectOnlyRequirements`,用测试钉住「conformance / superclass / layout 约束只看主语」;第 2–8 条不修 | 规则本身与本提案、编译器一致,只是 `ProtocolRequirementPlacement.associatedTypes` 的文档注释说成提到 `Self.X` 的约束都挪过去。第 2 条(两个新套件没在 CI 的工具链上跑过)用 Xcode 26.6 实跑排除。裁决登记在 ReviewAdjudications A69–A75,原始发现见 [2026-10-21 审查记录](../../Roadmaps/2026-10-21-pr135-review-findings.md) | +| 2026-10-21 | 实现完成,合入 next,编号 0073;状态 → Implemented | 用户批准按审查结论修完后直接合并。文档判断:CLI 的 `--help` 与 agent 插件的 skill 已写这个开关,不另写使用指南;实现说明就是本提案与 `ProtocolRequirementPartition` 的文档注释;没有需要登记术语表的新词 | diff --git a/Documentations/Evolutions/0074-private-declaration-source-files.md b/Documentations/Evolutions/0074-private-declaration-source-files.md new file mode 100644 index 000000000..591764b92 --- /dev/null +++ b/Documentations/Evolutions/0074-private-declaration-source-files.md @@ -0,0 +1,140 @@ +# 0074 - dump 与 interface 标出私有声明来自哪个源文件 + +- **状态**: Implemented +- **创建日期**: 2026-10-25 +- **最后更新**: 2026-10-26 +- **所属愿景**: 无 +- **关联提案**: [0063](0063-private-declarations.md)(名字经过的私有声明与按镜像反推源文件;当时明确不接 `swift-section`)、[0062](0062-local-type-context-names.md)(局部类型声明上方那行注释,本案的注释与它并排) +- **实现分支 / PR**: `feature/private-declaration-source-files`(直接合入 `next`,没有开 PR) +- **配套文档**: [Modules/SwiftPrivateDiscriminators.md](../Internal/Modules/SwiftPrivateDiscriminators.md) + +## 摘要 + +0063 把「反推 private discriminator 来自哪个源文件」下沉到了本库的 `SwiftPrivateDiscriminators`:discriminator 是 `MD5(模块名 + 源文件名)`,拿候选文件名去撞,128 位摘要对上就是确认。但除了它自己的测试,本库没有任何 target 依赖它,现在只有 RuntimeViewer 的 `Private` 标签在用。`swift-section dump` 只印 discriminator 原文(`(CodingKeys in _B89E435DF71E951D297EEE1ADCD6DDD8)`),interface 连 discriminator 也不印:fixture 里两个文件各声明了一个 `private struct PrivateDoppelganger`,interface 印出来的两个声明头一模一样,读者分不出谁是谁。本案给 dump 和 interface 加一个默认关闭的开关,打开后,凡是名字带来新 discriminator 的声明,上方都加一行注释写出它来自哪个源文件;还原不出的照实说。 + +## 方案 + +**改动位置**(明确不动的地方见本节末尾): + +- `Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift:86`:挨着 `staticFieldLayoutProvider` 加一个反推结果的 provider 属性,以及生成这行注释的 helper。provider 的协议和结果类型也放在这个模块。 +- `Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift:29`:`PrivateDiscriminatorSourceFileIndex` 遵循这个协议,并加一个批量入口。 +- `Sources/Output/SwiftDump/Dumper/` 下各 dumper 的 `body`(`EnumDumper.swift:142`、`StructDumper.swift:129`、`ClassDumper.swift:220`、`ProtocolDumper.swift:93`、`ProtocolConformanceDumper.swift:61`、`AssociatedTypeDumper.swift:96`,实现时加上 `ObjCImplementationClassDumper.swift` 的 Swift 成员行):声明头和成员行的上方。 +- `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift`:类型(`:234`,紧跟局部类型那行注释)、协议(`:351`)、扩展(`:458`)的声明头,以及 `printDefinition`(`:618`)经 `renderMember` 打的每个成员;全局声明在 `SwiftInterfaceBuilder.printRootContents()`。打印器加一个登记 provider 的方法,写法同 `addTypeNameResolver`(`:178`),登记了才打印。 +- `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:132`、`InterfaceRequest.swift:188`:请求加字段;开关打开时建 index、批量反推,再交给 dumper 或打印器。`Package.swift:809` 的 `SwiftSectionKit` 加依赖 `SwiftPrivateDiscriminators`。 +- `Sources/Executables/swift-section/Commands/DumpCommand.swift:56`、`InterfaceCommand.swift:59`:加 flag。 + +**输出**。一个声明的名字里有它外层声明没有的 discriminator 时,它上方每个这样的 discriminator 加一行注释;名字里有几个私有声明读同一个 discriminator(嵌在私有类型里的私有类型),只写最后那个。dump: + +```swift +// CodingKeys is declared in Codable.swift +enum SymbolTestsCore.CodableTests.GenericCodableTest.(CodingKeys in _B89E435DF71E951D297EEE1ADCD6DDD8) { + case element + case metadata +} +``` + +interface 里同名的两个私有类型从此能分开: + +```swift +// PrivateDoppelganger is declared in PrivateDoppelgangers.swift +struct PrivateDoppelganger { + var alphaStorage: Swift.Int64 + + init(alphaSeed: Swift.Int64) +} +// PrivateDoppelganger is declared in a source file whose name could not be recovered (private discriminator _1282F137F8790A6AF4B7E2738A640142) +struct PrivateDoppelganger { + var betaStorage: Swift.Int64 + + init(betaSeed: Swift.Int64) +} +``` + +- 两条输出用同一套写法,只在 helper 里实现一次。哈希用的模块名与声明打印的模块不同时补上模块(`// EnabledKey is declared in Enabled.swift of module SwiftUICore`);编译器合成的文件写成 `declared in the file the compiler synthesized for Foo.swift`;还原不出的写明还原不出并附上 discriminator,因为 interface 别处不印它。 +- 「外层声明」指打印时包住它的那个声明。dump 把每个类型、协议、conformance 都平铺在顶层,所以每个私有类型都有自己的一行;成员行只比它所在的类型。interface 里成员比它所在的类型、扩展或协议,嵌套的类型和协议比它的父定义,打在哪一层都一样(见决策日志)。嵌在私有类型里的类型、私有类型的成员都和外层同一个文件,不再重复;公开类型上的 `private func` 会标出它所在的文件,通常就是声明它的那个 extension 所在的文件。 +- conformance 的声明头同时看被扩展的类型和协议:遵循一个私有协议的 conformance 只能写在那个协议的文件里。 +- 类型引用不标:字段类型、函数签名里出现的私有类型,它的源文件在那个类型自己的声明上方。名字里的 discriminator 照旧,dump 里仍然带,interface 里仍然不带。 + +**接法**: + +- 协议和结果类型放在 `SwiftDeclarationRendering`。dump(`SwiftDump`)和 interface(`SwiftPrinting`)都依赖它;`SwiftPrivateDiscriminators` 依赖 `SwiftIndexing`,而 `SwiftDump` 在 `SwiftDeclaration` 之下、`SwiftPrinting` 与 `SwiftIndexing` 平级,两边都不能直接依赖它。结果类型是新的 `PrivateDeclarationSourceFile`;`PrivateDiscriminatorSourceFiles.SourceFile` 原样不动,index 遵循协议时把一个换成另一个,RuntimeViewer 的源码不用改。 +- dump:provider 装在 `DeclarationRenderConfiguration` 上,和 `staticFieldLayoutProvider` 一样由 `DumpRequest` 装;为空就不打印,不另设开关。 +- interface:`SwiftDeclarationPrintConfiguration` 不动(它是 `Equatable`,放不进 provider),provider 登记到打印器上。`SwiftInterfaceBuilder` 也不动:`InterfaceRequest` 在 `prepare()` 之后用 `builder.indexer` 建 index,登记到 `builder.printer`。 +- dump 没有索引器。开关打开时 `DumpRequest` 另建一个 `SwiftDeclarationIndexer` 并 `prepare()`,只为给 index 读名字;读完 index 就放掉它,这是 0063 已有的行为。不直接从描述符读名字:那样会少掉 extension 的名字这批候选,同一个镜像 dump 和 interface 还原出来的就会不一样。 + +**一次批量反推**: + +- 一个还原不出的 discriminator 要把五步候选全部算完,逐个声明去问的话,每遇到一个新的就整套重来。RuntimeViewer 在 Debug 构建里量过:逐个问时还原不出的每个要 3–4 秒;一次算完整个镜像是 30 秒(SwiftUICore)到 144 秒(SwiftUI)。Release 没有量过。 +- 所以打印前先一次求完。index 的批量入口收齐镜像名字(index 本来就要读)和 `SymbolIndexStore` 里成员符号、全局符号的 `privateDeclarations` 里出现的全部 discriminator,交给一次搜索;之后每个声明的查询都只是查表。 +- 候选不变,0063「不扩大到符号表的全部标识符」的决定照旧,只是一次要求的 discriminator 变多了。 + +**开关**:默认关闭,和两条输出现有的注释一样用 `--emit-*` flag:`dump --emit-private-source-files`、`interface --emit-private-source-files`。请求字段是 `DumpRequest.emitsPrivateDeclarationSourceFiles` 和 `InterfaceRequest.emitsPrivateDeclarationSourceFiles`,默认 `false`,源码兼容。 + +**明确不动**: + +- 开关关闭时 dump 与 interface 的输出逐字节不变,也不建 index、不多 `prepare()` 一次。 +- 反推算法、候选和已知文件名清单不变,还原率不变。 +- RuntimeViewer 不受影响;本案的注释不做成 `SwiftVisibilityOption`,它有自己的 `Private` 标签弹窗。 +- snapshot、diff、evolution 和 `objc` 子命令都不动;diff 的声明头本来就带 discriminator。 +- demangle 预设不动,interface header 也不加还原统计。 + +**不在这次范围内**:提高还原率;第 5 步按 discriminator 分开搜索、本可并行,release 量完后决定留作后续(见「实测」与决策日志);RuntimeViewer 在它的接口视图里接这行注释。 + +**测试**: + +- SwiftSectionKitTests 在 SymbolTestsCore 上打开开关跑 `DumpRequest` 与 `InterfaceRequest`。期望值在代码之外用 `md5 -s` 算出:`Codable.swift` 是 `_B89E…`,`Structs.swift` 是 `_930E…`,`PrivateDoppelgangers.swift` 是 `_82F1…`,`PrivateDoppelgangersSecondFile.swift` 是 `_1282…`。 + - 两个同名的 `PrivateDoppelganger` 各标各的文件。 + - 私有类型的成员和嵌套类型不重复标。 + - `PrivateDoppelgangersSecondFile.swift` 确实拼不出(复数落在名字中间),正好覆盖「还原不出」的写法。 + - 开关打开时,输出去掉注释行后与关闭时逐行相同。 +- 公开类型的私有成员:SymbolTestsCore 里没有这种形状(它的私有声明全是类型),改用 `LocalTypeFixture` 里公开类型 `Holder` 的 `private func hiddenValues()`,dump 与 interface 各一条;这两条按惯例声明 `ExclusiveImageAccess`。 +- 注释 helper 的单元测试:模块名不同、合成文件、私有声明没有名字、一个名字带两个 discriminator。 +- 批量入口:整镜像只搜一次,之后都是查表;provider 答的就是搜到的。 +- `NestedDefinitionRegionContractTests` 加一个打开注释的变体,两种读取路径:嵌套定义从父定义里摘出来,与单独打印逐字相同。 +- 关闭时不变:现有 dump、interface 快照基线一个都不改;改动碰到每个类型头和成员行的打印路径,落地前再跑一次 A/B 验证。 +- CLI:SwiftSectionCommandTests 测两个 flag 映射到请求字段。 +- 实数据:release CLI 在 macOS 27 的 SwiftUI、SwiftUICore、Foundation 上打开开关跑 dump 与 interface,记下耗时(与关闭时比)和还原数,写回本提案。 + +**实测**(2026-10-26,本机 macOS 27.2 的 dyld shared cache,release CLI):三个镜像、两条输出打开开关后都只多了注释行,去掉注释行与关闭时逐行相同。 + +| 镜像 | dump 关 → 开 | interface 关 → 开 | 名字里的 discriminator | 还原不出 | +|---|---|---|---|---| +| Foundation | 3.9 → 8.6 秒 | 9.1 → 9.7 秒 | 142 | 20 | +| SwiftUICore | 8.2 → 25.5 秒 | 12.6 → 27.7 秒 | 553 | 58 | +| SwiftUI | 11.8 → 58.1 秒 | 19.9 → 61.0 秒 | 840 | 167 | + +「名字里的 discriminator」是 dump 输出里出现过的全部不同 discriminator,成员的也算在内。多出的时间几乎全在搜还原不出的那些:第 3、5 步按 discriminator 各算一遍;interface 那一列的差就是整镜像反推本身,dump 还多一次 `prepare()`。 + +**文档**:同批更新 `Modules/SwiftPrivateDiscriminators.md`(宿主多了 CLI,加上批量入口)、`Modules/SwiftSectionKit.md`(两个新字段、dump 另建的索引器)、`Modules/SwiftInterface.md`(打印器的登记方法),以及 `AgentPlugins/swift-section` 的 skill(新 flag 和这行注释);在 ProjectEvolutionLog 记一节。实现时另改了 README 的 dump / interface 两节、AGENTS.md 里这个模块的那一行,并把两个新套件加进 CI 的过滤名单。调用方指南 `Documentations/SwiftSectionKit.md` 不逐个列请求字段,不用改。术语表没有新词,「private declaration」已经登记过。 + +**落地步骤**(每一步单独构建、相关测试通过后提交): + +1. ✅ 接缝:`SwiftDeclarationRendering` 里的协议、结果类型与注释 helper;index 遵循协议、加批量入口(`@_spi(Support)` 的 `recoverSourceFiles(ofEveryDeclarationIn:)`)。测 helper 和批量入口。 +2. ✅ dump:各 dumper 打注释;`DumpRequest` 的字段、索引器与 index;`dump` 的 flag。测 dump 一侧。 +3. ✅ interface:打印器的登记方法与各打印点;`InterfaceRequest` 的字段;`interface` 的 flag。测 interface 一侧。 +4. ✅ 文档、skill、实数据量测与 A/B 验证。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-25 | Created as Draft | 用户问 dump 和 interface 会不会输出反推出的文件名。核实两边都不会:`SwiftPrivateDiscriminators` 除自己的测试外没有任何 target 依赖,0063 当时明确不接 `swift-section`;release CLI 在 SymbolTestsCore 上的 dump 有 170 行带 discriminator,一个文件名也没有,interface 连 discriminator 都没有 | +| 2026-10-25 | dump 和 interface 都接 | 未提问自定。沿用「新的识别能力默认两条输出都接」 | +| 2026-10-25 | 默认关闭,用 `--emit-private-source-files` 打开 | 未提问自定。整镜像反推在 Debug 构建里要 30–144 秒,release 未量;两条输出现有的注释也都要显式打开 | +| 2026-10-25 | 写成声明上方的注释,名字里的 discriminator 不替换 | 未提问自定。dump 要留着 discriminator 原文;两条输出新增的事实一律写成注释 | +| 2026-10-25 | 只标带来新 discriminator 的声明 | 未提问自定。私有类型的成员和嵌套类型必然与它同一个文件,逐个重复只是噪音;公开类型上的私有成员才说明它在哪个文件 | +| 2026-10-25 | dump 打开开关时另建索引器读名字 | 未提问自定。直接从描述符读会少掉 extension 的名字这批候选,同一镜像 dump 与 interface 的还原结果会不一样 | +| 2026-10-25 | 打印前一次批量反推 | 未提问自定。逐个声明问,每个还原不出的都要把五步重算一遍 | +| 2026-10-25 | 用户批准(Draft → Accepted),开始实现 | 方案与全部假设照单通过 | +| 2026-10-25 | 结果类型另起一个,`SourceFile` 不下沉 | 实现时发现:RuntimeViewerCore 开了 `MemberImportVisibility`,按 SE-0444 它读 `fileName` 这些成员要 import 声明它们的模块,下沉后留 typealias 也可能逼它多加一行 import;在接缝处换一下类型只多几行 | +| 2026-10-25 | 批量入口取一个索引器,`@_spi(Support)` | 成员符号要从索引器的镜像查,全局声明要读它的定义;index 按索引器建的两个初始化方法本来就是这个 SPI | +| 2026-10-26 | dump 另建的索引器活到 dump 结束 | 实现时发现:索引器最后一次释放会回收它 `prepare()` 建的缓存,其中就有 dump 读成员的符号索引;index 读完名字就放掉索引器,不留住的话 dump 后半段要把符号索引重建一遍 | +| 2026-10-26 | dump 的成员行只标 struct / enum / class 的成员与 vtable 方法、`@objc @implementation` 类的 Swift 成员、协议的默认实现 | conformance 的 witness 行与 class 的 override 行不标:witness 至少和 conformance 一样可见,私有的只会出现在私有类型或私有协议的 conformance 里,声明头那行已经写了文件;override 私有方法罕见,而且它的节点在注释之后才解析出来 | +| 2026-10-26 | 打开开关时报一条进度、索引事件交给输出 | 整镜像反推在大框架上要等一阵才出第一个声明;interface 本来就这样报,两条输出一致 | +| 2026-10-26 | interface 里嵌套的类型和协议,外层取打印时包住它的父类型,不取名字里的上下文 | 实现时发现:局部类型名字的上下文是声明它的函数,函数在 interface 里不打印在它上方;按名字的上下文算,`private func hiddenValues()` 里的 `Hidden` 就会漏标 | +| 2026-10-26 | 嵌套定义的外层取父定义,与打印层级无关 | 第 3 步起先只在嵌套打印(`level > 1`)时排除父定义的 discriminator;自查时发现它违反 `marksNestedDefinitions` 的契约:RuntimeViewer 把嵌套定义从父定义的打印里摘出来用,单独打印必须与摘出来的逐字相同。改成任何层级都比父定义,`NestedDefinitionRegionContractTests` 加了打开注释的变体。fixture 里没有嵌在私有类型里的类型,所以这个变体抓不到改之前那处差别(按 fixture 的形状推断,没有退回旧代码实测),它守的是注释行在嵌套区域里的缩进,以及以后再出现只跟层级有关的差别 | +| 2026-10-26 | 实测后维持默认关闭,并行化留作后续 | 见「实测」:SwiftUI 的 dump 从 12 秒变成 58 秒、interface 从 20 秒变成 61 秒,多出的几乎全是搜还原不出的 167 个;第 5 步按 discriminator 各自独立,要提速可以并行,这次不做 | +| 2026-10-26 | A/B 跑缓存与模拟器两条腿,不跑进程内那条 | 开关关闭时三种读取路径走的是同一段打印代码,新增的只是一处「没有 provider 就返回」的判断;进程内那条要两侧各编一次 release 测试包、各跑十几分钟。缓存与模拟器两条腿覆盖 dump 与 interface 的全部打印路径 | +| 2026-10-26 | interface 的进度行照旧走 stdout | `interface` 的 CLI 一直把进度行打到 stdout(「Preparing to build Swift interface...」也在那里),新提示跟着走;`dump` 的进度在 stderr,也是它的老规矩 | +| 2026-10-26 | 实现完成,待合并 | 四个落地步骤都已提交推送。全量 `swift test --skip IntegrationTests` 2565 个测试通过、退出码 0;开关关闭时的渲染 A/B 54 对全部逐字节一致;量测见「实测」。文档:三份模块参考、README、AGENTS.md 的模块说明、插件 skill 与演进账本已同步;不另写使用指南或实现说明(没有签名里看不出的调用契约,实现取舍都在模块参考里),术语表没有新词 | +| 2026-10-26 | 合入 `next`,编号 0074;状态 → Implemented | 用户看过后批准直接合并、不开 PR。开工以来 `next` 没有新提交,合并后的 tree 就是验证过的那棵,沿用上一行的全量测试与 A/B 结果,没有重跑。没做的两项留作后续:第 5 步并行化,RuntimeViewer 在接口视图里接这行注释。文档判断同上一行:不另写使用指南或实现说明,术语表没有新词 | diff --git a/Documentations/Evolutions/0075-wrapped-reader-recognition.md b/Documentations/Evolutions/0075-wrapped-reader-recognition.md new file mode 100644 index 000000000..9c4ec81c5 --- /dev/null +++ b/Documentations/Evolutions/0075-wrapped-reader-recognition.md @@ -0,0 +1,115 @@ +# 0075 - 包装类型读取器的识别:库看穿宿主的包装,按底下的读取器回答 + +- **状态**: Implemented +- **创建日期**: 2026-10-13 +- **最后更新**: 2026-10-26 +- **所属愿景**: 无 +- **关联提案**: [0057-reading-context-migration](0057-reading-context-migration.md)(`ReadingContext.bindRebaseResolver` 已经让包装类型声明自己能解 bind / rebase)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(按镜像缓存以读取器的 `identifier` 为键) +- **实现分支 / PR**: 本库 `fix/wrapped-reader-recognition`(直接合入 `next`,没有开 PR);MachOKitExtensions `feature/reader-wrapper`,2026-10-26 快进成 `main` 并发 1.3.0 +- **配套文档**: [Internal/ReadingContextAbstraction.md](../Internal/ReadingContextAbstraction.md)「包装类型读取器」一节;术语表 [reader wrapper](../Glossary.md) + +## 摘要 + +MachOKitUI 把 `MachOImage` 包成 `MachOImageSource`、把 `MachOFile` 包成 `MachOFileSource` 交给本库,两者都转发全部读取,`identifier` 与背后的读取器相同。在 MachOViewer 里查看一个已加载镜像的 Swift section 时进程崩溃:`Fatal error: Negative value is not representable`,崩溃点是 `SymbolicDemangler.swift:469`(0.22.0 上是 320 行)。原因是本库判断「读取器是不是本进程里的镜像 / 是不是文件」时写死了具体类型:next 上 16 个文件共 38 处,加上 MachOKitExtensions 的 `asMachOImage`,以及一处转成库内部协议 `ObjCImplementationClassReading` 的取法。包装类型一处都走不进对应的路径。崩溃的那一处把 opaque type descriptor 的位置按「文件偏移」存进节点:描述符落在地址更低的另一个已加载镜像里时偏移是负数,转成 `UInt64` 就 trap。其余各处不崩,结果却悄悄变差或出错:符号按原值入索引、成员地址从 shared region 起点算、三个 ObjC 索引对包装类型是空的;一个不转发 `MachOBindRebaseResolving` 的文件包装还会让整份 interface 读到未解析的 chained fixup 原值而段错误。这个口子以前开过一半:`c348fd58`(2026-04-26)为包装类型加了 `MachOBindRebaseResolving`,`77e536f5`(2026-06-03)随后新增进程内 opaque 指针路径时又写死了 `MachOContext`。本提案让宿主的类型声明「我是另一个读取器的包装」,库里每个「这是哪种读取器」的问题都问到包装底下的读取器;解析不了的引用不再 trap;源码扫描测试防止写死的类型判断回来。 + +## 方案 + +**1. MachOKitExtensions 1.3.0:一个泛型包装协议,三个取法。** 只描述「包装」这个关系,不列举库认识哪些读取器:`Base` 可以是任何读取器,宿主自定义的读取器类型也能被包装,包装也能套包装。 + +```swift +public protocol MachOReaderWrapper: MachORepresentableWithCache { + associatedtype Base: MachORepresentableWithCache + + var base: Base { get } +} + +extension MachORepresentableWithCache { + /// The reader beneath every layer of wrapping; `self` when it wraps nothing. + public var underlyingReader: any MachORepresentableWithCache { … } +} + +extension MachORepresentable { + public var asMachOImage: MachOImage? { … } // 放宽:看穿包装 + public var asMachOFile: MachOFile? { … } // 新增 +} +``` + +契约写进协议的文档注释:遵循者在每个偏移读到的内容与 `base` 完全一样,`identifier` 也相同。按镜像的缓存(符号索引、ObjC 索引、demangle 记忆缓存……)以 `identifier` 为键,包装类型和底下的读取器共用同一份。`address(forOffset:)` 经 `asMachOImage` 取镜像,放宽后包装过的 cache 镜像打印的成员地址与局部类型的位置名随之正确。 + +**2. 本库:判据的两个源头与 opaque 引用。** + +- `Package.swift` 的 MachOKitExtensions 下限从 `1.1.2` 抬到 `1.3.0`。 +- `MachOContext.runtimePointer(at:)` 改用 `machO.asMachOImage`;`TypeContextDescriptorProtocol.swift:31` 取 metadata accessor 也走它,包装类型从此能用进程内 metadata。`bindRebaseResolver` 先问读取器自己,再问 `underlyingReader`。 +- `SymbolicDemangler`:opaque type descriptor 的节点值由 `context.runtimePointer(at:)` 决定——能给出本进程指针就存绝对地址(`MachOContext` 与 `InProcessContext` 得到的值和以前逐位相同),否则存偏移。偏移转不成 `UInt64`(负数)时,这个 symbolic reference 当作解析不了(resolver 返回 `nil`,与它里面其他失败的处理相同),不再 trap。`.direct`、`.indirect` 两支与 `accessorFunctionReference` 一起改。读这个节点值的两处(`Node+OpaqueType.swift:365/443`、`OpaqueReferenceSpelling.swift:74`)问 `asMachOImage`,与生产方用同一个判据。 + +**3. 本库:其余写死的判断改成 `asMachOImage` / `asMachOFile`。** 行号按 next @ `956b4e09`: + +| 文件 | `MachOImage` 判断 | `MachOFile` 判断 | +|---|---|---| +| `Analysis/SwiftInspection/SymbolicDemangler.swift` | 451、465(见第 2 条) | — | +| `MachO/MachOReading/ReadingContext/MachOContext.swift` | 136(见第 2 条) | — | +| `Analysis/SwiftLayout/ImageReference.swift` | 151、164、178 | 154、167、181 | +| `Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift` | 34 | 32 | +| `Analysis/SwiftInspection/ObjCAncestorResolver.swift` | 207 | 203 | +| `Analysis/SwiftInspection/ObjCClassMethodIndex.swift` | 163、399 | 161、396 | +| `Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift` | 393 | 388 | +| `MachO/MachOSymbols/SymbolIndexStore.swift` | 620 | 784(提到循环外只问一次) | +| `MachO/MachOSymbols/SymbolValueOffsetConverter.swift` | — | 37 | +| `MachO/MachOSymbols/MachO+Symbol.swift` | — | 19 | +| `Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift` | 365、443 | 281、399、605 | +| `Output/SwiftDeclarationRendering/DependentMemberProjection.swift` | 97、141 | 91、136 | +| `Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift` | 111 | 106 | +| `Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift` | 74 | — | +| `Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift` | 73 | — | +| `Output/SwiftPrinting/InterfaceHeader.swift` | 100 | 99 | + +另外三处不是写死的类型转换,同样认不出包装: + +- `MachORepresentableWithCache+ReaderKinds.swift` 的 `objcImplementationClassReader` 转成 SwiftInspection 的内部协议,包装类型遵循不了,改为从 `underlyingReader` 取;`swiftSectionReader` 自己转不成时也退到 `underlyingReader`。 +- `FieldLayoutRenderable` 按类型在编译期选渲染后端,所有打印器都要求它。新增 `FieldLayoutRenderable+MachOReaderWrapper.swift`:对 `MachOReaderWrapper` 的七个静态 witness 都转给 `Base`,包装类型写一个空的遵循就能进打印器。 +- `DependentMemberProjection.project` 拆包后在 `MachOFile` / `MachOImage` 的 universe 里投影,原来的 `as? MachO` 回转会把包装类型的结果整个丢掉。返回值改为 `Projection`,`image` 抹成 `any MachOSwiftSectionRepresentableWithCache`,重写器经一个泛型辅助函数打开它(SE-0352)。这个函数是 `package` 级别,不算公开 API。 + +**4. 明确不动的地方。** + +- 按类型静态约束的 API:`ImageUniverse+DependencyClosure.swift:27/42`、`GenericSpecializer.swift:778/1306/1846`、`GenericSpecializer+StaticSpecialization.swift:24/78`、`DependencyClosure.swift:90/100`。它们不是运行时判断,持有包装类型的宿主自己传 `base`。 +- MachOObjCSection 内部对 `self` 的 `as? MachOFile`:那里的 `self` 永远是裸类型(包装类型的 `objc` 转发给背后的读取器)。 +- 没有声明 `MachOReaderWrapper` 的包装类型:行为与以前相同,只是原来 trap 的地方变成「这个引用解析不了」。 + +**5. 测试。** 每条在修复前都确认是红的,修完转绿,永久保留。测试用的包装读取器 `ForwardingMachOReader` 放 `MachOTestingSupport`,转发全部读取要求(带默认实现的也转),`Declaration` 区分声明与不声明 `MachOReaderWrapper` 两种。 + +| 测试 | 修复前 | 修复后 | +|---|---|---| +| `WrappedReaderDemanglingTests`(SwiftInspectionTests):子进程里经包装 demangle 进程内 SwiftUI 的全部 associated type witness。声明的包装与裸 `MachOImage` 逐个节点相同,且至少出现一个 opaque 引用,任何宿主上都跑。不声明的包装那条先确认至少有一个引用落在 SwiftUI 之下、再确认不 trap;这种引用只在 SwiftUICore 映射在 SwiftUI 下方时存在——macOS 27 起的 cache 布局(本机 27 上 SwiftUICore 的 `__TEXT` 在 `0x190404000`,SwiftUI 在 `0x19A048000`),macOS 15 与 26 都放在上方——所以这条按已加载 cache 的镜像表判断布局,只在这种布局下启用(落地前核查时这样拆开,见决策日志)。 | 两条都以 SIGTRAP 结束 | 通过 | +| `WrappedReaderInterfaceTests`(SwiftInterfaceTests):fixture `SymbolTestsCore` 分别经 `MachOFile`、进程内 `MachOImage` 及各自的包装打印 interface(全部注释与文件头都开),逐字节相同;包装先打印。 | 测试进程 SIGSEGV(文件包装读到未解析的 fixup 原值) | 通过 | +| `WrappedReaderSymbolTests`(MachOSymbolsTests):包装 cache 里的 Combine 后 `swiftSymbols` 与裸文件相同;Combine 自己的类型描述符符号按偏移查得到;包装进程内 cache 镜像 Foundation 后 `address(forOffset:)` 与裸镜像相同。 | 三条都失败(272 + 1 + 3 处) | 通过 | +| `ReaderKindCastScanTests`(SwiftInterfaceTests):`Sources/`(`TestSupport` 除外)里不许出现对 `MachOImage` / `MachOFile` / `MachOContext<…>` 的类型转换;另一条确认扫描能看见转换、不会误报泛型约束。 | 列出上表 38 处 | 通过 | + +MachOKitExtensions 自己的 `MachOReaderWrapperTests`:声明的文件包装、包装的包装、不声明的包装、成员地址四种语义,23 个测试全过。 + +**6. 验收与文档。** 跑完整测试(不含 `IntegrationTests`);这次改了读取器与 demangle 路径,按规定跑三条读取路径的渲染 A/B,输出必须逐字节相同。文档:`Internal/ReadingContextAbstraction.md` 新增「包装类型读取器」一节;术语表登记 reader wrapper;`AGENTS.md` 加一个条件块「判断读取器种类用三个取法,不写类型转换」;MachOKitExtensions 的 README 与提案索引登记;`ProjectEvolutionLog` 随代码写一节,节号落地时分配;发版时写进当次的 Changelog(0.23.0 没赶上,见决策日志)。CLI 的参数与输出不变,agent 插件不用改。 + +**7. 下游。** MachOKitUI 升到含本提案的本库版本(0.23.0 之后的下一个版本)与 MachOKitExtensions 1.3.0 后,给 `MachOImageSource` / `MachOFileSource` 各加一行遵循 `MachOReaderWrapper`(`base` 返回它们持有的 `machO`),同时删掉 `MachOSwiftSectionDetailBuilder.demangleTypeNode` 里的特判;`MachOFileSource` 手写的 `MachOBindRebaseResolving` 转发可留可删。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-13 | Created as Draft | 来源:MachOKitUI 会话交接。用户选定方案 B:给包装类型一个协议,把写死的判断改成按协议判断,负偏移不再 trap。交接方在 MachOKitUI 里先做了只绕开崩溃点的方案 A。 | +| 2026-10-13 | 协议放 MachOKitExtensions,发 1.3.0 | 用户选择。和 `MachOBindRebaseResolving`、`asMachOImage` 放在一起;放本库 `MachOReading` 的话,`asMachOImage` 与 `address(forOffset:)` 仍只认裸类型,包装过的 cache 镜像打印的成员地址照样是错的。 | +| 2026-10-13 | `MachOFile` 一侧一起改 | 用户选择。同一类问题:`SymbolValueOffsetConverter` 只给裸 `MachOFile` 换算符号值,依赖闭包、ObjC 祖先链、thunk 读取也只认裸类型。 | +| 2026-10-13 | 随 0.23.0 从 next 发 | 用户选择。MachOKitUI 已用方案 A 挡住崩溃点,不单独从 main 发 0.22.1。 | +| 2026-10-13 | 直接打开 dyld cache 文件不会出负偏移 | 交接方的怀疑,已核实:cache 文件里 `MachOFile` 的偏移以 shared region 起点为基准(MachOKitExtensions 的 `resolveRebase` 返回「目标地址 − sharedRegionStart」),cache 里任何地址都不低于起点;独立文件是文件偏移。实测:现有 CLI 从本机 macOS 27 cache 文件 dump 整个 SwiftUI 的 associatedTypes(4960 条,765 处展开到 `ModifiedContent`,没有未展开的 opaque 引用),正常退出。 | +| 2026-10-13 | 否决:草案初稿的两个协议 `MachOImageBacked` / `MachOFileBacked` | 用户要求再想更优雅的接口。按具体类型各开一个协议,包装第三种读取器就得再加一个协议,把库认识的类型写进了扩展点。 | +| 2026-10-13 | 否决:`enum MachOReaderKind { case file, image }` 作为 `MachORepresentableWithCache` 的必需要求 | 用户否决:用户自定义一个 MachO 类型就必须改库,违反开闭原则。 | +| 2026-10-13 | 采用:泛型包装协议 `MachOReaderWrapper`(`associatedtype Base`) | 只描述「包装」这个结构性事实,`Base` 可以是任何读取器;库在一处(三个取法)看穿包装,能力协议与编译期选策略的协议也经它对包装生效。MachOKitExtensions 只加接口,1.3.0 不破坏兼容。用户说「先改试试」,开始实现。 | +| 2026-10-13 | 生产方改用 `runtimePointer(at:)` 判断 | 它本来就是「这个 context 是否映射在本进程」的协议要求,生产方与消费方共用同一个判据。 | +| 2026-10-13 | 不从 `identifier == .image(ptr)` 推断进程内镜像 | 隐式约定,只覆盖 `MachOImage` 一侧;`identifier` 是缓存身份,不是类型契约。 | +| 2026-10-13 | `FieldLayoutRenderable` 给包装类型默认实现 | 打印器全都要求它,包装类型原本要手写七个静态转发;默认实现让它写一个空遵循即可,按 `Base` 的后端渲染。 | +| 2026-10-13 | 符号测试只查 Combine 自己的描述符符号 | 符号表也列出 Combine 引用的外部描述符(`$ss12StaticStringVMn`),它们不在 Combine 的任何偏移上;收窄后修复前 272 处失败、修复后 0 处,仍能区分修复前后。 | +| 2026-10-13 | 试做验收 | 在两个沙盒里构建(本地 sibling;swift-demangling 与 MachOObjCSection 用各自远端 `next` 的导出副本,因为本机这两个 sibling 的 `next` 落后于远端)。全量测试(不含 `IntegrationTests`)只红了 `Arm64eSignedVWTPointer` 的 strip 探针一条,单独重跑 3/3 通过、基线也通过,与本次改动无交集,按偶发处理。渲染 A/B:归档 cache 26.6 / 15.5、模拟器 runtime 15.5–26.5、进程内镜像三条读取路径共 96 对,全部逐字节一致。 | +| 2026-10-14 | 提交并推送两个功能分支 | 用户看过试做结果后要求提交推送。发 MachOKitExtensions 1.3.0 与合进 next 另等用户决定;本库 `Package.swift` 已要求 1.3.0,所以发版必须在落地之前。 | +| 2026-10-26 | 合并前核查:`WrappedReaderDemanglingTests` 依赖宿主的 cache 布局,拆开 | 代码能干净合进 `next`:基线 `956b4e09` 之后又进了 50 多个提交,只有两份索引表冲突,合并结果里写死的读取器转换为 0。但「至少一个引用落在 SwiftUI 之下」只在 SwiftUICore 映射在 SwiftUI 下方时成立,这是 macOS 27 起的布局;macOS 15 与 26 都放在上方(26.6:`0x22d953000` 对 `0x1b594e000`),这条在 macOS 26 宿主上必红,CI 不跑这个套件所以没人发现。用户批准先修再落地:声明的包装那条在任何宿主上比较,只要求至少出现一个 opaque 引用(修复前它在任何宿主上都会红);落在下方的引用改作不声明的包装那条的前提,用 `.enabled(if:)` 按已加载 cache 的镜像表(`DyldCacheLoaded.current`)判断布局,判断时不加载任何镜像。 | +| 2026-10-26 | `ReaderKindCastScanTests` 与 `WrappedReaderInterfaceTests` 进 CI 名单 | 前者只读源码、后者只读 fixture,符合 CI 只跑不依赖开发机环境的规则;另两个读系统 dyld cache 或把 SwiftUI 加载进进程,留在本地。 | +| 2026-10-26 | MachOKitExtensions 1.3.0 发版 | 用户批准。`feature/reader-wrapper` 快进成 `main`,打空消息的注释 tag,与以往版本一样不建 GitHub Release;发前在该提交上跑 MachOKitExtensions 自己的 23 个测试全过,发后只走远端依赖的副本能解析到 1.3.0。 | +| 2026-10-26 | 合入 `next`,编号 0075;状态 → Implemented | 用户批准。先把 `next@7adbe83c` 合进功能分支(两份索引表两边都保留),在最终 tree 上重跑:全量 2574 个测试全过、退出码 0;渲染 A/B 96 对全部逐字节一致(各腿对数见演进账本第 106 节)。0.23.0 发版时本提案还在等 MachOKitExtensions 1.3.0,改随下一个版本发。文档判断:`ReadingContextAbstraction.md` 的「包装类型读取器」一节就是实现说明;宿主只需写一行遵循,写法在 MachOKitExtensions 的 README 里,不另写使用指南;术语表的 reader wrapper 实现时已登记,没有新词。 | +| 2026-10-26 | 后续项:量进程内指针解析的额外开销 | `MachOContext.bindRebaseResolver` 在每次指针解析时都会被调用;对进程内 `MachOImage`,它现在多做两次失败的协议转换和一次 existential 装箱(`MachOImage` 32 字节,超出内联缓冲)。全量与 A/B 只验证了正确性,没量时间;要在性能足够的机器上按 instructions retired 对比前后。 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index aca67f42f..039abaa18 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -79,3 +79,10 @@ | [0067](0067-nested-field-offset-memoization.md) | 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 | Implemented | | [0068](0068-nested-definition-regions.md) | 在父定义的打印结果里标出嵌套子定义的边界 | Implemented | | [0069](0069-offline-generic-specialization.md) | 离线泛型特化:不经 runtime 特化泛型类型并完整打印 | Implemented | +| [0070](0070-borrow-accessors-and-suppressed-associated-types.md) | Swift 6.4 的 `borrow` / `mutate` 访问器与关联类型上的 `~Copyable` | Implemented | +| [0071](0071-swift-capstone-7.md) | 迁到 swift-capstone 7.0:解码器改用 `Disassembler` | Implemented | +| [0072](0072-cross-reference-analysis.md) | 交叉引用分析:从机器码读出每个函数引用了什么 | Implemented | +| [0073](0073-protocol-requirement-placement.md) | 协议约束可选写在各自的关联类型上 | Implemented | +| draft | [evolution 与 diff 区分「不存在」和「看不见」](draft-evolution-unobservable-presence.md) | Accepted | +| [0074](0074-private-declaration-source-files.md) | dump 与 interface 标出私有声明来自哪个源文件 | Implemented | +| [0075](0075-wrapped-reader-recognition.md) | 包装类型读取器的识别:库看穿宿主的包装,按底下的读取器回答 | Implemented | diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md new file mode 100644 index 000000000..249034ce1 --- /dev/null +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -0,0 +1,77 @@ +# Draft - evolution 与 diff 区分「不存在」和「看不见」 + +- **状态**: Accepted +- **创建日期**: 2026-10-24 +- **最后更新**: 2026-10-24 +- **所属愿景**: 无 +- **关联提案**: [0013](0013-swift-evolution-interface-builder.md)(evolution 联合接口)、[0060](0060-evolution-interface-available-annotations.md)(`@available` 只在生命周期能完整表达时才发)、[0024](0024-exported-declaration-flag.md)(类型与协议的导出状态) +- **实现分支 / PR**: `feature/evolution-unobservable-presence`(worktree `.worktrees/MachOSwiftSection-EvolutionUnobservablePresence`,基于 `next`) +- **配套文档**: [ABIEvolutionDesign.md](../Internal/ABIEvolutionDesign.md)、[ABIDiffDesignAndLimitations.md](../Internal/ABIDiffDesignAndLimitations.md) 第 6 节(符号化状态不对称) + +## 摘要 + +evolution 和 diff 把每个声明在每个版本里只记成「在」或「不在」,分不出「不存在」和「这个版本看不见」。macOS 13.0–14.8 dyld shared cache 里的 SwiftUI 被剥掉了全部 local Swift 符号(11.x、12.x 与 15.0 以后都保留),非导出的函数、计算属性、初始化器在这些版本里一个都看不到,代码却都在(13.0 有 19.3 万个函数入口,只有 3.5 万个有名字)。结果 macOS 27.0 SwiftUI 跨 51 个版本的 evolution 里,有 5,189 条声明在 12.7 和 15.0 都在、中间却显示为缺席,多数印成 `removed in 13.0 · added in 15.0`;「removed in 13.0」之后再没出现的 13,033 条与只有一个 `added in 15.0` 事件的 12,329 条里,靠非导出符号才看得见的那部分,真实的变化可能发生在 13.0 到 15.0 之间的任何一版,却被钉在了端点上;对 12.7 和 13.0 做 diff,也会把这些声明报成删除并判为 breaking。本案让快照记下镜像有没有 local Swift 符号、每个成员是否导出,evolution 和 diff 据此把被剥的版本里本来就看不见的声明记为看不见而不是删除;一段看不见的版本两侧状态相同时按两侧推断、并在输出里标出,两侧不同时记成一个区间事件。 + +## 方案 + +**快照多记两件事**。`ABISnapshotDocument.currentFormatVersion` 从 7 升到 8,旧快照照已有的 `unsupportedFormatVersion` 报错、要求重新生成。 + +- 镜像级:有没有 local Swift 符号。判据是符号表里一个非外部的 `_$s` 符号都没有(STABS 不算)。`SymbolIndexStore` 的建表扫描本来就只从符号表收 local Swift 符号,在那里顺手记下,和 `ExportFacts.hasExportInformation` 放在一起;`SwiftDiffableInterfaceBuilder.snapshot()` 冻结时写进 `ABISnapshot`。 +- 成员级:`MemberRecord` 加一个可选的导出判定,用 `--emit-export-status` 注释那个 `isExportedIncludingDerivedSymbols`(`Tj`、`Tq` 这类派生入口导出也算导出)。和 `hasDefaultImplementation` 一样只是判定用的元数据,不进 key。判定在 SwiftInterface 一侧做、以闭包交给 `ABIDiffer.snapshot(of:)`,SwiftDiffing 仍然不碰 Mach-O。 + +**哪些声明在没有 local Swift 符号的版本里看不见**: + +- 只靠符号才出现的成员:函数、计算属性和下标、初始化器、`deinit`、全局变量和全局函数,而且它在前后最近一次看得见的版本里不是导出的。只要有一侧不是导出的或判定不出,就算看不见。 +- 成员全是上面这种的普通 extension(不是 conformance 的那种)本身也看不见,因为它只由成员撑起。 +- 其余照旧看得见,缺席就是真的缺席:类型、协议、conformance、存储属性、enum case、关联类型和关联类型 witness、`pwtslot:` 记录,以及导出的成员。 + +**按两侧推断**。规则放在 SwiftDiffing,evolution 和 diff 共用: + +- 一段连续看不见的版本,两侧观测到的状态相同,就推断中间也是这个状态,没有事件。两侧都在时记为「看不见、推断存在」;两侧都不在时推断为不在,仍记为看不见。依据:在都带符号的年份里,两端都在、中间某版真的缺席的声明只占 0.15%(11.0–12.7,16,184 条里 25 条)到 0.6%(15.0–27.0,24,553 条里 148 条);一直都在的声明不带位图、没算进分母,所以这两个数是上限。 +- 两侧状态不同,就记成一个区间事件:变化发生在两侧之间的某一版。`modified` 同样处理,比较两侧的记录。 +- 挨着版本轴两端的一段不推断。 +- 只比两个版本是这条规则的特例:一侧没有 local Swift 符号时,在那一侧看不见的成员既不算删除也不算新增,在 diff 的报告与 JSON 里单独列出,不参与 breaking 判定。「N == 2 时 evolution 与 diff 给出的变化一致」的保证继续成立。 + +**模型只增不改**,`evolution --json` 现有的字段原样保留: + +- `MemberLineage` / `ContainerLineage` 保留 `presence: [Bool]`,含义改为「观测到或推断为存在」;另加一个逐版本的状态数组,区分观测到存在、观测到不存在、看不见但推断存在、看不见。 +- 有看不见的版本的 lineage 即使没有事件也要收录,否则接口标不出推断;`EvolutionAnnotationIndex`「查不到就是全程都在、从未变化」的约定因此仍然成立。 +- `LineageEvent` 加一个「最早可能发生在哪一版」,只有区间事件才有;`versionIndex` 仍是第一次观测到新状态的那一版,兼容性判定把区间事件算在这一步。 + +**显示**: + +- evolution 联合接口和 lineage 报告的位图多两个符号:`◌` 看不见,`◍` 看不见、推断存在;图例说明这两个符号,并列出哪些版本没有 local Swift 符号。只有推断、没有事件的声明,注释写 `inferred present in 13.0–14.8`;区间事件写 `removed between 12.7 and 15.0`、`added between 12.7 and 15.0`。 +- `@available`:涉及区间事件的不发,沿用 0060 的可表达性规则;推断存在的位置按存在算。 +- diff 的文本报告和 `--json` 多一节,列出看不见的成员。`diff --interface` 的 `-` / `+` 这次不动,写进 `ABIDiffDesignAndLimitations.md` 第 6 节。 +- 单版本的 `dump` / `interface` 不受影响。 + +**不在这次范围内**: + +- 用汇编特征跨版本找回被剥的名字。测量办法是取两个都带符号的版本,把后一版的非导出名字藏起来,再从前一版借名字并与真名核对:小版本之间给出的声明名字约 99.5% 准,跨一个大版本约 91%,跨三年 63%–70%。进入 13.0 的那一步正好跨大版本,从 15.0 往回到 14.8 的那一步无法测量,只适合将来作为另一层推断。 +- 用元数据直接观测被剥版本里的成员(witness table、vtable 槽位、协议描述符、ObjC 方法表),另开提案。 +- 被剥前后身份变了的声明:协议要求在被剥的版本里变成 `pwtslot:` 记录、私有类型丢了 discriminator、同一个全局变量在两种状态下由不同的符号撑起。那 1,447 条 `added in 13.0 · removed in 15.0` 里有一部分属于这类。 + +**测试**:SwiftDiffingTests 用手工构造的快照覆盖两侧都在、两侧都不在、三种区间事件(added、removed、modified)、挨着轴端、导出成员与元数据记录的真缺席、普通 extension 整体看不见、一侧被剥时 N == 2 的 diff 与 evolution 一致、v8 编解码;`SymbolIndexStore` 的判据用 `ObjCImplementationFixture` 的 `.strippedLocals` 变体和普通变体各测一次;`EvolutionMarkingTests` 覆盖新符号、新短语、图例和区间事件不发 `@available`。实数据用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution,核对那 5,189 条都变成推断存在,并统计区间事件的数量。 + +**文档**:同批更新 `ABIEvolutionDesign.md`、`ABIDiffDesignAndLimitations.md` 第 6 节、`Modules/SwiftInterface.md`,在术语表登记 unobservable,并更新 `AgentPlugins/swift-section` 的 skill(evolution 输出多了两个符号和两种短语)。 + +**落地步骤**(每一步单独构建通过、相关测试通过后提交): + +1. 快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 +2. SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 +3. evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 +4. 文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-24 | Created as Draft | macOS 27.0 SwiftUI 的 evolution 里大批「removed in 13.0 · added in 15.0」经核实是 13.0–14.8 剥掉了 local Swift 符号造成的:这些版本的 nlist 里没有一个 `_$s` 函数或变量符号,函数入口数却比 12.7 还多,`App.main()` 照样调用 12.7 里叫 `runApp` 的那个函数;同期 libswiftCore、Combine、AppKit 的符号计数平稳 | +| 2026-10-24 | 范围定为 evolution 加 diff 的判定层,`diff --interface` 的渲染不动 | 一轮提问定案。同一条规则放在 SwiftDiffing 共用层,保住「N == 2 时 evolution 与 diff 一致」;diffable 渲染器按两侧结构直接比对,改它另算 | +| 2026-10-24 | 推断默认开启,并在位图与注释里标出 | 一轮提问定案。有符号的年份里两端都在、中间真缺的比例上限只有 0.15%–0.6%,比任何匹配都准;标出来是为了不把推断当成观测 | +| 2026-10-24 | 不做汇编匹配找回名字 | 测量结果见方案:跨一个大版本约一成名字给错,而进入 13.0 的那一步正是跨大版本,从 15.0 往回的那一步无法验证 | +| 2026-10-24 | 自动识别被剥的版本,不加手动开关 | 未提问自定。实测 SwiftUI 各版本的剥离是全有或全无;有 Swift 代码却一个 local Swift 符号都没有的镜像,几乎只会是被剥过的 | +| 2026-10-24 | 区间事件不发 `@available` | 未提问自定。沿用 0060「事实不能完整表达就不发属性、由注释兜底」 | +| 2026-10-24 | 模型只增不改,`presence: [Bool]` 保留 | 未提问自定。它是 `evolution --json` 的现有输出,脚本可能依赖;本机的下游仓库(RuntimeViewer、MachOKitUI、swift-decompiler)都不读 lineage 模型 | +| 2026-10-24 | 落地拆成四步 | 精简提案原本没有落地步骤;按「快照事实 → 判定规则 → 接口呈现 → 文档与实数据」拆开,每一步都能单独构建和测试 | +| 2026-10-24 | 用户批准(Draft → Accepted),开始实现 | 方案与全部假设照单通过 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 781324851..66f7b9470 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -73,9 +73,16 @@ - **主要出现在**:`Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift`、`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`、`Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift` - **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) +### cache-shared stub(全缓存共用桩) + +macOS 27 与 iOS 27 的 dyld shared cache 不再给每个镜像留自己的 `__objc_stubs` / `__auth_stubs`(这两个段在镜像里大小为 0),而是把桩收成整个缓存共用的一份,放在不属于任何镜像的区域:ObjC 消息走 selector 桩(`adrp x1; add x1; b `,`x1` 就是 selector 字符串),跨库调用走 GOT 桩(`adrp x17; add x17; ldr x16, [x17]; braa x16, x17`)。同一个 selector 在不同子缓存里各有一份桩,所以认 selector 要以字符串地址为键。与 stub island 的区别:island 自己算出目标、不读槽位。macOS 26、iOS 26 及更早,以及 Simulator 的缓存仍是镜像自带的桩。 + +- **主要出现在**:`Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift`、`Sources/Analysis/CrossReferenceAnalysis/Scanning/ReferenceScanner.swift` +- **延伸阅读**:[Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md)、[0072-cross-reference-analysis](Evolutions/0072-cross-reference-analysis.md) + ### context form / Mach-O form / pointer form(读取接口的三种形式) -同一个读取接口曾经最多有三份手写实现:context form 收 `some ReadingContext`(`name(in: context)`、静态 `resolve(at:in:)`),Mach-O form 收一个 Mach-O reader、按偏移读(`name(in: machO)`、`resolve(from:in:)`),pointer form 不收读取器、直接用裸指针读本进程内存(`name()`、`resolve(from: pointer)`)。2026-09-30 起 context form 是唯一实现,另外两种是 0.22.0 废弃、0.24.0 删除的一行转发(`machO.context` / `.inProcess`)。 +同一个读取接口曾经最多有三份手写实现:context form 收 `some ReadingContext`(`name(in: context)`、静态 `resolve(at:in:)`),Mach-O form 收一个 Mach-O reader、按偏移读(`name(in: machO)`、`resolve(from:in:)`),pointer form 不收读取器、直接用裸指针读本进程内存(`name()`、`resolve(from: pointer)`)。2026-09-30 起 context form 是唯一实现,另外两种是 0.22.0 废弃、0.25.0 删除的一行转发(`machO.context` / `.inProcess`)。 - **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、`Sources/MachO/MachOPointers/`、`Sources/MachO/MachOResolving/Resolvable.swift` - **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) @@ -290,6 +297,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:`Sources/Analysis/SwiftInspection/PrivateDeclarations.swift`、`Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift` - **延伸阅读**:[提案 0063](Evolutions/0063-private-declarations.md)、[Modules/SwiftPrivateDiscriminators.md](Internal/Modules/SwiftPrivateDiscriminators.md) +### reader wrapper(包装读取器,`MachOReaderWrapper`) + +宿主自己的读取器类型:手里拿着一个 `MachOFile` 或 `MachOImage`,把读取协议的每个要求原样转发给它(MachOKitUI 的 `MachOFileSource` / `MachOImageSource`)。声明 MachOKitExtensions 的 `MachOReaderWrapper` 之后,库里每个「这是哪种读取器」的问题——`asMachOImage`、`asMachOFile`、`underlyingReader`——都问到它底下的读取器;不声明,库就把它当成两种都不是,读得出,但进程内路径、符号偏移换算、ObjC 与依赖闭包这些按读取器种类做的事都做不了。契约是在每个偏移读到的内容与底下的读取器相同,`identifier` 也相同(两者共用按镜像的缓存)。 + +- **主要出现在**:MachOKitExtensions `MachOReaderWrapper.swift`、`Sources/MachO/MachOReading/ReadingContext/MachOContext.swift`、`Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderable+MachOReaderWrapper.swift`、`Tests/SwiftInterfaceTests/ReaderKindCastScanTests.swift` +- **延伸阅读**:[提案 0075](Evolutions/0075-wrapped-reader-recognition.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) + ### renamed class(改名类,`@objc(Name)` / `@_objcRuntimeName(Name)`) 源码给 ObjC 运行时另起了名字的 Swift 类:类对象的 `class_ro_t` 名是源码写的名字(`NSScrollPocket`),而不是 `_TtC6AppKit14NSScrollPocket` 这样的 mangling。二进制里只剩类元数据 flag 字里的 `HasCustomObjCName` 与名字本身,`SwiftClassObjectIndex` 顺着类元数据自带的描述符指针把它们配到 Swift 类上(父类在另一个 resilience domain、不进 classlist 的类读 metadata pattern)。本仓库凡是「demangle 运行时名找 Swift 类」的地方都要为它回退,否则一律配不上——成员恢复与布局引擎以前就是这样漏掉它们的。interface 与 dump 打印 `@objc(Name)`,原生 Swift 对象模型的类打印 `@_objcRuntimeName(Name)`。 diff --git a/Documentations/Internal/Modules/CrossReferenceAnalysis.md b/Documentations/Internal/Modules/CrossReferenceAnalysis.md new file mode 100644 index 000000000..a676abb7b --- /dev/null +++ b/Documentations/Internal/Modules/CrossReferenceAnalysis.md @@ -0,0 +1,181 @@ +# CrossReferenceAnalysis + +从 arm64 机器码里读出一个镜像的函数表,以及每个函数引用了什么:直接调用与尾调用、ObjC 消息发送、`super` 发送、经桩的跨库调用、间接调用、ObjC 类引用、Swift 类型引用。只在进程内读 `MachOImage`,只支持 arm64 / arm64e。RuntimeViewer 的交叉引用功能(调用者、被调、类型引用)建在它上面。 + +- 提案:[0072-cross-reference-analysis](../../Evolutions/0072-cross-reference-analysis.md)(本库这一层);整体设计、实测数据在 RuntimeViewer 的 [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)。 +- 依赖:MachOKit、`ARM64InstructionDecoding`;第二批起还有 `MachOObjCSection`(方法表、类的只读数据)、`MachOSwiftSection` 与 `SwiftInspection`(Swift 元数据与 `SymbolicDemangler`)、`Demangling`——给符号表没有名字的函数起名,以及认出扫描碰到的类与类型(类列表、类型描述符、mangled 名字)。不依赖 Capstone。 + +## 子系统 + +| 子系统 | 文件 | 分工 | +|---|---|---| +| 1. 指令字与跳板 | `ARM64InstructionDecoding` 模块的 `ARM64InstructionWord`、`ARM64Trampoline` | 手写读取少数几类 A64 编码;按形状认 GOT 桩、stub island 与全缓存共用的 selector 桩。与 SwiftThunkAnalysis 共用 | +| 2. 地址空间 | `CrossReferenceAnalyzer` | 进程里全部镜像(整个共享缓存加缓存外已加载的镜像)、各镜像的路径与安装名、`__TEXT` 的内存区间、缓存的可执行与可读映射、`objc_msgSend` 与运行时辅助函数的位置;给函数起名要用的函数表按需建一次并记住。宿主可以预先读好一个镜像起名、查类、查类型要用的一切(`prepareNames(inImageAt:)`),放掉其余镜像的(`releaseImageData(exceptForImagesAt:)`),并估算一个镜像留着多少(`approximateByteCount(ofImageDataAt:)`,`Scanning/ApproximateSize`) | +| 3. 函数表 | `Scanning/ImageFunctionTable` | 函数起点(`LC_FUNCTION_STARTS` 与 `__text` 里的符号取并集)、主名与代码合并留下的别名、辅助函数、镜像自带的 `__objc_stubs` / `__stubs` / `__auth_stubs`、`__objc_selrefs`、放类引用的槽(`__got`、`__auth_got`、`__objc_classrefs`)与 `__objc_superrefs`、各段的地址区间 | +| 3a. 补充名字 | `Scanning/ImageFallbackNames` | 符号表没有名字的函数,依次从导出表、ObjC 方法表、Swift 元数据起名;起名时按镜像按需读,扫描不读 | +| 3b. 类索引 | `Scanning/ObjectiveCClassIndex` | 一个镜像定义的类与元类,按地址;直接读 `__objc_classlist` 与各类的 `isa`。扫描时按需建、分析器记住;类名只在报出引用时读 | +| 3c. 类型索引 | `Scanning/SwiftTypeIndex` | 一个镜像 `__swift5_types` 列出的描述符与各自的元数据访问器;类型的 key 按需算,优先取 `…Mn` 符号;按 key 找类型时只算描述符名字相同的那几个 | +| 4. 扫描 | `Scanning/ReferenceScanner`、`Scanning/RegisterFile`、`Scanning/RuntimeHelperNames` | 逐条解码、跟踪寄存器、解析调用目标 | +| 5. 结果 | `Models/*` | `CodeLocation`、`CodeFunction`、`CodeReference`、`CodeReferenceTarget`、按目标分组的 `CodeReferenceTable`,以及给宿主常驻用的紧凑版 `CodeReferenceIndex` | +| 6. 预筛与过滤 | `CrossReferenceAnalyzer+Prefiltering`、`CrossReferenceAnalyzer+Linkage`、`Scanning/RenamedReexportIndex`、`references(to:inImageAt:)` | 按未定义符号(只对 C 与 ObjC 符号,连同别的镜像改名再导出的名字)、链接关系(Swift 符号)、`__objc_selrefs`、类对象上的符号筛出可能引用某个符号、selector 或类的镜像;扫描时只留命中的引用;`preparePrefilters()` 让宿主在后台单线程预先读好链接关系与改名再导出表 | +| 7. 类型查询 | `CrossReferenceAnalyzer+SwiftTypes` | Swift 类型的身份、预筛与按类型的扫描;`SwiftTypeQuery` 比对描述符位置与名字里的符号引用 | + +## 关键契约 + +### 地址 + +`CodeLocation` 是(镜像在 `images` 里的位置,镜像自己的未滑动地址)。缓存外两个镜像的未滑动地址可能重合,所以位置必须带镜像。跨镜像的查找一律换成运行时地址(未滑动地址加该镜像的 slide)再查 `__TEXT` 区间表,算完再换回 `CodeLocation`。 + +**镜像的路径是 dyld 加载它的路径。** 缓存里的镜像就是安装名;缓存外的取 `dladdr` 按镜像头读到的加载路径——App 的主程序与插件 bundle 没有安装名(`MachOImage.path` 为空),App 自带的框架的安装名是 `@rpath/…`,哪个都对不上宿主手里的路径(交叉引用审查 B3,2026-10-17 之前就是这样,缓存外的镜像查不到)。另有一张「安装名 → 镜像」的表给加载命令解析链接关系用:同一安装名的两份拷贝(两个插件各带一份同一框架)都算;`imageIndex(forPath:)` 先按路径、再按安装名找。用 `-bundle_loader` 链接宿主的插件经 `EXECUTABLE_ORDINAL` 绑定主程序,没有加载命令指向它,所以每个 bundle 都算作主程序的依赖方。 + +MachOKit 在内存镜像上给出的 `FunctionStart.offset` 已经是未滑动的绝对地址(迭代器以 `__TEXT` 的 vmaddr 起算),与它的文档注释「相对 mach header 的偏移」不符;当成偏移再加一次基址,会得到范围外的地址、整张表被滤空。 + +### 两种桩布局 + +macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用桩)](../../Glossary.md)。 + +| 缓存 | ObjC 消息 | 跨库调用 | +|---|---|---| +| macOS 15 至 26、iOS 26 及更早的真机,以及 Simulator | 镜像自己的 `__objc_stubs`(经 MachOKit `objcStubs(in:)` 读 selector 引用) | 镜像自己的 `__stubs` / `__auth_stubs`(MachOKit `stubs(in:)` 给出槽位) | +| macOS 27、iOS 27 真机 | 镜像里的段大小为 0;`bl` 落到全缓存共用的 selector 桩:`adrp x1; add x1; b `,`x1` 就是 selector 字符串 | 全缓存共用的 GOT 桩:`adrp x17; add x17; ldr x16, [x17]; braa x16, x17` | + +同一个 selector 在不同子缓存里各有一份共用桩(macOS 27.2:被调用的 155 万个桩只对应 104 万个字符串),所以 selector 以字符串为键,不以桩地址为键。GOT 槽在进程内已经绑定,读出指针、去掉指针认证位就是目标;读之前先确认槽位落在缓存的映射里。 + +不经桩、直接 `bl` / `b` 到 `objc_msgSend` 的传统写法还有第三种形态:缓存构建器把读 selector 引用的 `adrp` / `ldr` 改写成了 `adrp` / `add` 出字符串本身的地址,指令里只剩字符串地址。macOS 27.2 的 `-[NSObject debugDescription]` 就是 `adrp x8; add x1, x8, #…; b _objc_msgSend`(`objc_msgSend` 在 `/usr/lib/objc/libobjcMsgSend.dylib` 里)。所以传统发送的 selector 两处都要认:`x1` 从本镜像的 `__objc_selrefs` 读来,或 `x1` 是 `adrp` / `add` 算出的地址;后者要确认它落在映射里、到结尾为止是不含空格的可打印字符(最长 1,024 字节),不满足就不当作发送。第一批漏了后一种,这些发送全被当成对 `objc_msgSend` 的普通调用;RuntimeViewer 第 3 步查 `-[NSObject description]` 的调用者时发现。 + +### 读任何目标之前先确认它可读 + +`__text` 里夹着数据(跳转表之类,缓存镜像的 `LC_DATA_IN_CODE` 是空的),按指令解码会得到指向任意地址的「跳转」。扫描只在目标落在某个镜像的 `__TEXT`、或缓存的可执行映射里时才去读那里的指令;读槽位前确认它在缓存或镜像的映射里。探针第一次全量扫描就崩在没做这一步上。 + +### 寄存器跟踪只记确定的事 + +`RegisterFile` 只记录 `adrp` / `adr` / `add` 算出的地址、从已知地址加载的槽位、ObjC 方法入口时 `x0` 里的接收者、指针认证常量,以及「这个寄存器的值是从内存读来的」和读取时的偏移。不建模的指令一律作废它写的寄存器(宁可多忘,不留陈旧的值);调用作废 `x0`–`x18` 与 `x30`——原样返回所传类的三个函数例外,`x0` 留着(见「类引用」)。PAC 与 AUT 原地签名或认证,寄存器的含义不变,保留;XPAC 作废。 + +一条指令写哪些寄存器由 `RegisterFile.registersWritten(by:)` 按 A64 的编码分组判断,容易漏的几类:前 / 后变址的读写(单寄存器与寄存器对、通用与 SIMD 寄存器都一样)会改掉基址寄存器;原子指令不论内存序都返回旧值,不带内存序的那种(`ldadd`、`swp`)编码像存储;`ldxp` 写第二个寄存器,`casp` 写 `Rs` 与 `Rs+1`;`umov` / `smov`、浮点转整数与转定点写通用寄存器;SVE / SME 里有几条写通用寄存器(`cntd`、`addvl`、`rdsvl`);`mrs` 与 `sysl`;`svc` 的结果在 `x0`、`x1`。第一批漏了其中大半(交叉引用审查 A1);`RegisterFileTests` 用汇编器编出的 48 条指令逐条核对,并用 Capstone 的寄存器访问表独立核对那张表没有漏项(Capstone 把 `cas` / `casp` 的基址也算作被写,架构上并不写,测试里列为已知偏差)。SwiftThunkAnalysis 的两个跟踪器同一轮补上了成对回写的基址。 + +**寄存器状态沿着分支走(第二批)。** 一个函数内:向前的分支(条件跳转与 `b`)把当时的寄存器状态带到目标处;目标处若前一条是无条件转移(`b`、`br`、`ret`),就以带来的状态为准,否则与顺序走下来的状态取交集——同一个寄存器两条路径放的东西一致才保留。无条件转移之后没有分支指向的指令(跳转表的落点之类)、以及向后分支的目标(循环头,回边的状态此时还不知道)忘掉调用方保存的寄存器。第一批只按指令顺序往下读,汇合处会沿用最后一条路径的值:`-[NSString stringByAppendingString:]` 里一个块把参数放进 `x0`、下一个块放 `self`,两者跳到同一处发送 `copyWithZone:`,顺序读法把接收者说成 `self`。这一改动让 AppKit 80 万处引用里 9,699 处发送多认出了 `self`(前一条路径的调用冲掉了 `x0`,而实际到达的路径没有),78 处不再说 `self`,selector 几乎不受影响;release 下全缓存整表扫描由 1.6–1.8 s 变为 2.0 s。快照是定长值(`SIMD32`),不分配内存;待到的目标与循环头按地址排序、随扫描游标前进。只记「无条件转移后忘掉」的简化版试过,会丢掉 `+[NSObject instanceMethodForSelector:]` 这类早退之后的正确接收者,弃用。 + +**已知局限(审查 A5,2026-10-17)。** 循环头与没人指向的落点只作废 `x0`–`x18`,`x19`–`x28` 可能带着到不了那里的旧值:`-[NSMenuItem _titlePathForUserKeyEquivalents]` 的循环把 `x22` 从 `self` 换成父菜单项再跳回,循环头之后的发送仍被说成发给 `self`。量过(release,六个大镜像 332 万条引用、257 个抽样镜像 711 万条):对含循环的函数反复扫到回边状态不变的精确做法,与现行做法相差 0.04% / 0.02% 的引用,扫描多花 42% / 61%;循环头一律全部作废则会丢掉约 3.9 万条正确的事实(`self` 发送少 15%)。只作废「循环里写过的寄存器」的近似试了几版,都还会丢掉正确的事实,弃用。数据与抽查见 [2026-10-17 审查记录](../../../Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md) A5。看过数据后决定保持现状,理由与复审条件见 [ReviewAdjudications A68](../ReviewAdjudications.md)。 + +### 尾调用与跳转表 + +`b` / 条件跳转的目标在本函数之外就是尾调用。经寄存器的 `br`:带认证的(`braa` 等)一律算尾调用;不带认证的,只有寄存器的值是从内存读来的(函数指针)才算——跳转表的目标是 `add` 算出来的,不算。 + +### 运行时辅助调用 + +`RuntimeHelperNames` 维护名单:libobjc 的 retain / release / autorelease / weak 系列,Swift 运行时的 retain / release / bridgeObject / unknownObject / unowned / weak / beginAccess / endAccess,编译器写进每个镜像的 `___swift_*_boxed_opaque_existential*` / `___swift_memcpy*`,以及以 `WO` 加小写字母结尾的 outlined 值操作。跨镜像的辅助函数只在 libobjc、libswiftCore、libswift_Concurrency 里找;镜像内的在该镜像的函数表里标出。结果只打标记,过滤交给宿主。 + +### 类引用(第二批) + +一条指令取了某个类对象的地址、但不跳转,就是一处类引用:`CodeReference.Kind.reference`,目标 `.objectiveCClass(name:location:)`。macOS 27.2 的缓存里几乎没有 `__objc_classrefs` 了,类有三种取法:`adrp` / `add` 出本镜像的类对象(AppKit 3,319 处);从本镜像的 `__got` / `__auth_got` 载入;从缓存放在所有镜像之外的共用 GOT 池载入别的镜像的类(AppKit 后两种合计 53,026 处)。缓存外的二进制还经 `__objc_classrefs`。别的槽里即使放着类指针也不算:常量字符串的 `isa`(`__cfstring`)、缓存某个类的全局变量都不是对类的静态引用。`adr` 与字面量 `ldr` 两种形态在 AppKit、SwiftUI、Foundation 与几个缓存外的系统 App 里一处都没有,不解码。元类的引用按它的类报。 + +**一个值是不是类对象,看它所在的镜像列没列它。** 不能按所在的节判断:缓存里 9.2 万个 Swift 类与元类放在 `__data` 而不是 `__objc_data`。`ObjectiveCClassIndex` 直接读 `__objc_classlist` 与每个类的 `isa`(即元类),不经 `MachOImage.objc.classes64`——后者对每个类都重新查一遍 load command,扫描全缓存时让整表扫描慢了一倍。类名只在要报出引用时经 `MachOObjCSection` 读 `class_ro_t`(类已被运行时实现时经 `class_rw_t`)。 + +**类的身份带位置。** 全缓存 203,621 个类名里有 18,906 个不止一个镜像定义——多是 `/System/iOSSupport` 下的 Mac Catalyst 变体,两个 SwiftUI 都定义 `_TtC7SwiftUI13PinnedBarView`。引用表的键是类名(`CodeReferenceTable.Key.objectiveCClass`,预筛与过滤都按它),引用目标另带类对象的 `CodeLocation`,宿主按位置区分。`objectiveCClassLocations(named:inImageAt:)` 把宿主手里的(镜像,类名)换成位置。 + +**类字面量接收者。** 发送时 `x0` 里是这样取来的类,接收者记为 `.classLiteral(名字)`(AppKit 35,175 处,发送的 11%)。`objc_opt_self`、`objc_opt_class`、`swift_getInitializedObjCClass` 原样返回传入的类,调用之后 `x0` 不作废:Swift 调 ObjC 类方法先过 `objc_opt_self`,SwiftUI 665 处类字面量接收者里 478 处经它。 + +**super 发送的类**取同一函数里从 `__objc_superrefs` 载入的类:分类方法(`-[NSDictionary(NSKeyValueCoding) valueForKey:]` 得到 `NSDictionary`)、类方法(槽里是元类,按类报)、没有符号的方法都对;没见到这种载入就退回方法符号里的类。这一载入本身不算类引用——它是编译器实现 `super` 的方式,报出来只会让每个调 `super` 的方法都「引用」了自己的类。Swift 代码的 super 发送不经 `__objc_superrefs`,类来自 `self` 的运行时类或元数据访问器的返回值,扫描不知道,类记为空:Foundation 1,803 处 super 发送里有 374 处、AppKit 8,336 处里有 1,133 处是这种,其余都有类。 + +**预筛**(`imageIndices(referencingObjectiveCClassAt:among:)`):定义这个类的镜像,加上导入了类或元类地址上任一符号的镜像——定义镜像的符号表与导出表里落在这两个地址上的全部名字都算。抽样实测,别的镜像引用某个类时 96% 导入 `_OBJC_CLASS_$_<名字>`,其余走别名:Block 字面量的 `isa` 是 `__NSConcreteStackBlock`,XPC 类型是 `__xpc_type_dictionary` 之类。只认 `_OBJC_CLASS_$_` 会漏掉它们。 + +按字符串取类(`objc_getClass("NSFoo")`,AppKit 183 处)不算类引用。 + +**代价**(release,28 核,与只有分支跟踪的那次提交交替跑三轮取最好):全缓存整表 2.03 → 2.40 秒(引用多了 326 万条,+17%),查 `init` 的调用者 1.54 → 1.70 秒,`makeKeyAndOrderFront:` 0.29 → 0.33 秒。扫描器自己缓存类索引,查类不抢分析器的锁;地址落在本镜像 `__TEXT`、或载入的槽是本镜像的非类槽时,在任何查表之前就排除。 + +### Swift 类型引用(第二批) + +一处 Swift 类型引用有三种来源,都报成 `.reference` 种类: + +1. **调用类型的元数据访问器。** 调用照常报一条,另加一条目标为 `.swiftType(descriptor:)` 的引用。访问器靠各镜像 `__swift5_types` 列出的描述符认(描述符 +12 处是访问器的相对指针),`Scanning/SwiftTypeIndex` 按需给每个镜像建一份。 +2. **取访问器或元数据的地址。** `adrp` / `add` 出、或从 GOT 槽载入访问器地址,或结构体、枚举、`Optional`、导入类型的元数据——元数据首字是种类(0x200–0x204),次字是描述符。Swift 类的元数据就是它的 ObjC 类对象,按类引用报(见上一节)。 +3. **按 mangled 名字实例化。** 调用本镜像的 `__swift_instantiateConcreteTypeFromMangledName…` 辅助函数,或运行时的 `swift_getTypeByMangledName…`。macOS 27.2 上几乎都是 V2:`x1` 指向 `{到名字的 int32 偏移, int32 长度}` 记录;旧形态的名字在 `x0` 的缓存变量里,类型一经实例化缓存里就只剩元数据,名字读不到,不报。没有符号的辅助函数按形态认:不超过 0x90 字节、调用运行时那几个入口;读 `[x1]` 的是 V2。目标是 `.swiftTypeName(.mangledName(location:length:))`:名字里可能夹着符号引用,解开一个要几十微秒,扫描不解开,表也不按类型归档它。没有描述符的访问器——泛型实例(`$sSay7SwiftUI4TextVGMa`)、存在类型、导入类型——按符号名认,报 `.swiftTypeName(.accessorSymbol(…))`。 + +**表按描述符位置归档**(`CodeReferenceTable.Key.swiftTypeDescriptor`),不按类型的 key。key 是名义类型的 mangling(`7SwiftUI4TextV`、`Sa`),取自描述符的 `…Mn` 符号(demangle 再 mangle,与名字、符号里的拼法一致);没有符号时才 demangle 描述符的上下文,而那样拼出的 key 会偏:受约束扩展里的嵌套类型带上扩展的要求(SwiftUICore 有 58 处访问器调用拼法不同),其他模块类型的扩展里的 private 类型干脆丢了自己(Foundation 的 `Mutex<…>.LockResult` 成了 `15Synchronization5MutexV`)。位置没有这些问题,扫描时也不必解开任何东西。从名字取 key 时,泛型实参各算一个类型,嵌套在泛型类型(或它的受约束扩展)里的类型去掉父类型的实参:`Regex.Match` 是 `17_StringProcessing5RegexV5MatchV` 加上 `AnyRegexOutput`。 + +**查询**(`references(toSwiftType:inImageAt:)`)带一个比对器:访问器与元数据的引用比描述符位置;名字逐字节走,符号引用(`\x01` 直接、`\x02` 经指针)指向的描述符就是这个类型,就算提到了它。只有名字可能直接拼出来的类型——标准库、`_Concurrency`、从 C / ObjC 导入的,key 以 `s` 或 `S` 开头——才解开名字确认;文本子串比对不可靠,mangling 会把同一名字里重复出现的单词换成替身。前提是其他类型在名字里一定以符号引用出现:在 Foundation、SwiftData、libswift_Concurrency、SwiftUI 里逐个解开全部名字核对过,没有例外(AppIntentsServices 有 56 处 key 对不上,原始字节全是符号引用,是那个镜像没有 `…Mn` 符号造成的拼法差别)。导入的类型每个用到它的镜像各有一份描述符,比的是 key。Swift 类同时比它的 ObjC 类对象的位置。macOS 与 Mac Catalyst 变体里的同一个类型按位置分开。协议没有类型描述符,不在这一批。 + +宿主的用法:类型对象 → 描述符位置(或经 `swiftTypeDescriptorLocations(withKey:inImageAt:)`,先找 `…Mn` 符号)→ `swiftTypeIdentity(ofDescriptorAt:)` → 预筛 → 每个候选镜像 `references(toSwiftType:inImageAt:)`。`swiftTypeKeys(in:)` 解开一个 `SwiftTypeName`,供显示用。 + +按 key 找类型,`…Mn` 符号在符号表里逐条比、在导出表里按名字查(不读整个导出表)。找不到符号时——缓存里的内部类型都是这样——只给描述符名字(`+8` 处的 `Name`)与 key 末段相同的类型算 key 再比:key 解开一次取出末段的名字(private 与局部类型取声明名),读不出名字的才退回给每个类型都算。从 C / ObjC 导入、在 Swift 里改了名的类型(`URLSession.ResponseDisposition`、`RunLoop.Mode`、`CFURL`),描述符的名字是 Swift 名,key 拼的却是 C 名(`So31NSURLSessionResponseDispositionV`、`So13NSRunLoopModea`、`So8CFURLRefa`);C 名记在名字后面的导入信息里——描述符标志位 `HasImportInfo`(第一个字的第 18 位)为真时,名字后面跟着若干以 NUL 结尾、首字母是标签的串,空串结束,`N` 开头的那段是 C 名——两个都比。头一版只比 Swift 名,Foundation 与 AppKit 有 115 个导入类型因此找不到,核对全部类型的测试当场抓到。2026-10-18 之前每个类型都算一遍,一次 demangle 一个,AppKit 的第一次查找在 Debug 构建下要 0.7 秒、SwiftUICore 0.4 秒;现在约 1 毫秒。`typeLookupsCompareSameNamedTypesOnly` 对 Foundation 与 AppKit 的全部类型核对两种查法结果相同,且读不出名字的 key 不到 1%。 + +**预筛**(`imageIndices(referencingSwiftType:among:)`):定义镜像本身;定义镜像导出了这个类型的符号时(描述符 `…Mn`、元数据访问器 `…Ma`、元数据 `…N` 任何一个),再加上能绑定到它的镜像(按链接关系,见下一节),类再并上类预筛;名字可能拼出来的类型——标准库的、导入的,每个镜像都可能自己命名——凡是 Swift 镜像都算。**一个符号都没导出的类型(内部类型)只可能被定义镜像引用**:别的镜像要引用它,只能经这几个符号绑定,或者在名字里拼出它,而内部类型在别的模块里拼不出来。2026-10-17 之前没有这条,AppKit 的内部结构体 `NSSmartNamingSuggestion` 一次类型引用查询要扫所有链接 AppKit 的镜像——几乎整个缓存,Debug 构建下要好几分钟(用户实测,CPU 占满);现在只扫 AppKit 一个(测试 `typesNoImageExportsAreLookedForInTheirOwnImage`,并对链接 AppKit 的镜像每 64 个抽 1 个确认确实没有引用)。导出了没有,在导出表里按名字查这三个符号(`exportsSymbol(named:fromImageAt:)`);2026-10-18 之前把整个导出表读成集合留着,SwiftUICore 第一次要 0.1 秒(Debug)、留下 6 MiB(`exportLookupsAgreeWithTheWholeTrie` 对 Foundation 与 AppKit 的全部类型核对两种查法结果相同)。Swift 函数不需要同样处理:缓存里没导出的函数在进程内看不到本地符号,没有 `.symbol` 名字,本来就不会按链接关系去扩大候选。 + +**代价**(release,28 核,与只有分支跟踪的那次提交交替跑):全缓存整表 2.1 → 3.0 秒(引用 1.16 亿 → 1.26 亿条),查 `init` 的调用者 1.6 → 1.8 秒——只查 selector 或函数时不找类与类型引用,发送处的类字面量接收者照认。踩过两个坑。一是 `keep(reference(to: …))` 这种写法:参数里修改扫描器,外层又在同一个扫描器上调非 mutating 方法,Swift 只好每次把整个扫描器连同它的备忘字典复制一份,整表扫描一度要 95 秒——第一批的 `keep` 是静态方法,没有这个问题。二是类型索引若每次都去分析器的锁里取,等锁占掉大半时间;现在扫描器自己留一份(`ScanIndexes`,引用类型,解析调用目标的非 mutating 路径也用得上)。 + +### 预筛:缓存几乎不留 Swift 的未定义符号 + +macOS 27.2 的缓存里,4,113 个镜像只有 245 个在符号表里留着 Swift 的未定义符号(libswift 系列、Foundation、CoreData、AXCoreUtilities 等),其余的绑定 Swift 符号后什么也不留:SharedWithYou 留了 314 个未定义符号,全是 C 函数与 ObjC 类,可它照样经全缓存共用的 GOT 桩调用 `URL` 的元数据访问器;AppKit 的 5,085 个里也没有一个 `$s…`。所以「导入了某个符号的镜像」只对 C 与 ObjC 符号成立。第一批的函数预筛只拿 C 函数(`CFRelease`、`dispatch_async`)测过,对 Swift 函数一直是错的:查 `URL.path` 的调用者时只留下按名字导入它的 44 个镜像,其余调用它的镜像全被丢掉(`swiftFunctionPrefilterKeepsEveryCaller` 在旧做法下变红)。 + +**改名再导出。** 一个镜像可以把别的镜像的符号换个名字导出:libsystem_c 把 libsystem_platform 的 `__platform_strlen` 导出成 `_strlen`,CoreGraphics 把 SkyLight 的 1,112 个 `_SL…` 函数导出成 `_CG…`,UIFoundation 把 CoreText 的 `CTEmojiImageAsset` 类导出成 `NSEmojiImageAsset`。调用方导入的是新名字——AppKit 按 CoreGraphics 的名字导入了 273 个 SkyLight 函数——所以按导入预筛时这些名字也要比。macOS 27.2 的缓存里 12 个镜像共 1,438 条这样的再导出。`RenamedReexportIndex` 在第一次需要时并发走一遍所有镜像的导出表,只记改名的再导出(名字只在命中时拼出),按「被再导出的镜像与名字」归档,之后留着;`reexportedNames(ofSymbolsNamed:inImageAt:)` 顺着改名再改名、以及经伞形框架整体再导出的情形找全别名(acfsSupport 从 CoreServices 再导出 Metadata 的 `_kMDConfigErase`)。函数预筛与类预筛都把别名一并比对。2026-10-17 之前没有这一步,查 `__platform_strlen`、`_SLSMainConnectionID` 的跨库调用者会漏掉 AppKit(`RenamedReexportTests`)。 + +这张表与链接关系是跨全部已索引镜像查询的第一次必读的,宿主可以用 `preparePrefilters()` 在后台预先读好。它只用调用线程:Debug 构建单线程读完 macOS 27.2 缓存 144 MiB 的导出表要 3.9 秒,28 核并行也要 3.4 秒——并行几乎不快,后台工作不该为此占满所有核(`serialAndConcurrentReadsAgree` 核对两种读法结果相同)。表只建一次:建的时候来了要用它的查询,会等它建完,而不是再读一遍(`prefiltersAreBuiltOnce`)。链接关系 Debug 下约 60 毫秒。 + +Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,`CrossReferenceAnalyzer+Linkage`):一个镜像只能绑定到它链接的镜像,以及这些镜像(层层)再导出的镜像的符号,这些加载命令在缓存里完整保留——SwiftUI 再导出 SwiftUICore,链接 SwiftUI 的镜像就算能绑定 SwiftUICore。比按导入粗得多(链接 Foundation 的镜像数以千计),但不漏。宿主查函数的调用者用 `imageIndices(callingFunctionAt:symbolNames:among:)`:C 与 ObjC 名字按导入,Swift 名字按链接。Swift 类的类预筛、Swift 类型的类型预筛同理。链接关系第一次用到时读一遍所有镜像的加载命令,之后留着。 + +### 名字从哪来(第二批) + +`CodeFunction.name` 依次取:符号表(`` 当没有);导出表(一个缓存镜像的符号表不一定带导出的符号——SiriAppIntents 的只有两条,导出表却给它的 76,318 个函数起了名;iOS 真机的缓存抹掉本地符号,导出表还在);ObjC 方法表(类、元类、本镜像的分类;列表的列表里属于别的镜像的条目跳过,它们一定也在那个镜像自己的 `__objc_catlist` 里;元数据不记分类名,读出来是 `-[NSTextView draggingUpdated:]`);Swift 元数据(类型的元数据访问器 `…Ma` 与 singleton 完成函数 `…Mr`,名字取描述符的 `…Mn` 符号,没有就经 `SymbolicDemangler` 从描述符重建;虚表实现取方法描述符的 `…Tq` 符号,没有就不起;async 实现先跟一步 `{rel32 函数, u32 大小}` 记录)。Swift 元数据给的名字是不带 C 前缀下划线的完整 mangled 名字(`.swiftMetadata(mangledName:)`),可以直接 demangle。 + +这些名字只在起名时(`codeFunction(at:)`,即 `functions(inImageAt:)`、`function(containing:)`、`functions(containing:)`、`symbolName(at:)`)按镜像读一次、记在函数表上;三个来源各自按需读,前面的来源已经起了名,后面的就不读。扫描不读它们:扫描只需要知道一个函数是不是 ObjC 方法(决定 `x0` 是不是接收者),这一点仍只看符号名。 + +宿主要第一次查询也不等,用 `prepareNames(inImageAt:)` 预先读好(2026-10-18,RuntimeViewer 的预先准备):三个来源全读、类索引里的类名全读、类型索引的 `…Mn` 符号读好,函数表留住。每个函数的 Swift 名字仍在第一次给它起名时重建并记住。Debug 构建实测: + +| 镜像 | 用时 | 留下的(连同函数表,`approximateByteCount(ofImageDataAt:)` 估算) | 引用索引 | +|---|---|---|---| +| AppKit | 0.33 s | 13.9 MiB | 21.1 MiB | +| SwiftUICore | 0.28 s | 12.5 MiB | 10.0 MiB | +| Foundation | 0.16 s | 7.1 MiB | 9.7 MiB | +| libswiftCore | 0.08 s | 3.1 MiB | 1.7 MiB | + +估算按集合的容量与元素步长、字符串的堆存储算,不计分配器的取整;同一次运行里 malloc 的实测增量比它多一成左右。 + +代价(release,28 核):给一个镜像的全部函数起名,AppKit 0.24 s(方法表补了 3,961 个、Swift 元数据补了 1,147 个),SiriAppIntents 1.5 s,Matter 0.04 s(方法表补了 30,863 个)。每个镜像起 32 个函数的名字、走遍整个缓存要 6.9 s,4 线程 6.1 s——并发几乎不变快:时间耗在 Swift 运行时的泛型元数据缓存(查找与锁等待)和加载命令的动态转换上,来自 `MachOObjCSection` 与元数据读取代码的泛型实现。宿主给大批结果起名时应只给要保留的那些起。 + +分析器自己找 `objc_msgSend`、`objc_msgSendSuper2` 与运行时辅助函数的位置时,也读运行时库的导出表,不只读符号表。 + +### 缓存外镜像的 GOT 槽 + +缓存外的镜像(第三方 App 自己的二进制)经自己的 `__stubs` / `__auth_stubs` 调别的镜像,槽位由 dyld 在加载时绑定,按 macOS 11 部署目标、不用 chained fixups 编出来的懒绑定二进制也一样:macOS 27.2 上以 `RTLD_LAZY` 加载,函数第一次被调用之前槽里已经是目标地址。所以扫描直接读槽。`LazyBindingTests` 是这件事的哨兵:哪天 dyld 不再在加载时绑定,槽会指回镜像自己的 `__stub_helper`,测试变红,那时再退回桩上的导入名。 + +### 缓存、内存与生命周期 + +库里没有全局的按镜像缓存(因此不需要 `SharedCache`,理由见 [ReviewAdjudications](../ReviewAdjudications.md) A62)。`CrossReferenceAnalyzer` 记住宿主让它起过名的镜像的函数表(`functions(inImageAt:)`、`function(containing:)`、`references(madeBy:)`);整镜像扫描(`referenceTable(ofImageAt:)`、`references(to:inImageAt:)`)临时建表、用完即丢;给一批结果起名用 `functions(containing:)`,同样临时建表——查 `init` 的调用者会碰到 2,759 个镜像,逐个记住又是上 GB——早先扫描也记表,扫完一遍 macOS 27.2 缓存后常驻 1.5 GB(`wholeImageScansKeepNoFunctionTable` 钉住)。 + +第二批起分析器还在自己的生命期里留着:扫描碰到的每个镜像的类索引(类与元类按地址,类名读过的记住)与类型索引(描述符与访问器,key 算过的记住),链接关系,以及改名再导出表。它们以缓存里的类与类型的总数为上限(macOS 27.2 有 203,621 个类名),没有单独测过占用;下面那个约 170 MB 的数字是第二批之前测的。宿主想放掉,用 `releaseImageData(exceptForImagesAt:)` 放掉指定镜像以外按镜像留着的一切——函数表连同读过的名字、类索引、类型索引;链接关系与改名再导出表不按镜像,留着——或者换一个分析器。RuntimeViewer 的会话在缓存外的镜像变化时换分析器;起过名的镜像(预先准备的除外)超过 64 个时,只放掉预先准备之外的。2026-10-18 之前后一种情况也是换分析器,预先读好的名字跟着丢了,下一次查询又得重读。 + +分析器存活期间若有缓存外的镜像被卸载,再读它会读到已释放的内存;极少见,没有防(A63)。名字的解开一律是瞬时的:类型查询碰到的访问器符号与 mangled 名字不进全局的 `NodeCache`,也不进进程级的 demangle 记忆(交叉引用审查 B2,`TypeNameRetentionTests`),按镜像的 `demangleContext` 记忆随镜像淘汰。 + +`CodeReferenceTable` 是值,宿主想留多久就留多久,按 `approximateByteCount` 计预算(不含字符串的堆存储;同一次扫描里重复的名字共用一份)。大镜像的整表很大(GeoServices 约 121 MiB,全缓存合计约 9 GB),28 个线程同时建整表时峰值约 1.5 GB,分配器之后还留着 1.2 GB 脏页不还。**查调用者用 `references(to:inImageAt:)`**:扫描时只留命中的引用,同样扫完全缓存后常驻约 170 MB(4 线程约 106 MB)。 + +**要为少数几个镜像常驻、反复查,用 `CodeReferenceIndex`**(`referenceIndex(ofImageAt:)`,2026-10-18 为 RuntimeViewer 的预先准备新增)。它按目标分组存放:选择子、导入名、类名每个只存一份,引用所在的函数与指令存成相对 `__text` 起点的 32 位偏移(一条 16 字节),只留查调用者与查类型引用会读的引用,间接调用与落在镜像外的跳转不留。macOS 27.2 实测(`approximateByteCount`,含名字的堆存储):AppKit 21 MiB(整表 67 MiB,87.5 万条引用里留 85.6 万条),Foundation 9 MiB(34),SwiftUICore 9 MiB(35),libswiftCore 1 MiB(7)。`index.references(to:)` 与 `references(toSwiftType:in:)` 回答的和过滤扫描完全相同,顺序也相同(按指令地址,同一条指令的调用排在它顺带的类型引用前面)。建索引会**留住**镜像的函数表——给结果起名要用;名字本身还要第一次起名时读,宿主要连这一步也提前,再调 `prepareNames(inImageAt:)`(见上文「名字从哪来」)。分析器被换掉后,索引照样能读(它不持有分析器),宿主用 `keepFunctionTable(ofImageAt:)` 让新分析器重新留住。`referenceIndex(ofImageAt:reportingProgress:)` 每扫 2,048 个函数报一次进度,回答「停」就不建了。Debug 构建建 AppKit 的索引约 6 秒。 + +分析器是一个快照:之后才加载的镜像需要新的分析器。 + +## 吞吐(macOS 27.2,28 核的 Mac Studio) + +| 操作 | 现在(28 核) | 第一批:28 核 / 8 线程 / 4 线程 | +|---|---|---| +| 建分析器(4,114 个镜像:缓存的 4,113 个,加基准程序自己) | 0.06 秒 | 0.02 秒 | +| 每个镜像都建整表 | 3.0 秒(1.26 亿条引用) | 1.6–1.8 / 3.5 / 5.9 秒(1.16 亿条) | +| `init` 的调用者:预筛出 2,759 个镜像再过滤扫描 | 0.05 + 1.8 秒 | 0.05 + 1.5 秒 / — / 6.1 秒 | +| `makeKeyAndOrderFront:` 的调用者:105 个镜像 | 0.06 + 0.33 秒 | 0.06 + 0.26 秒 | + +比第一批多出来的是寄存器状态沿着分支走(约 +10–20%)、类引用与 Swift 类型引用(整表约 +45%,只查 selector 或函数时约 +10%)。「现在」一列是在别的会话同时编译、负载较高的机器上交替跑多轮取的最好值。 + +单线程解码 AppKit 约 187 MiB/s,比 Capstone 快 25–50 倍(RuntimeViewer 提案落地第一步的探针)。库比探针慢一些(4 线程扫完整个缓存,探针 4.1 秒,库 5.9–6.3 秒),多出来的是起名、建 `CodeReference` 与 selector 字符串;过滤扫描也是先建好每条引用再丢弃,按键提前跳过是能做的优化。 + +## 测试锚点 + +- `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。 +- `CrossReferenceAnalyzerTests`(只在 arm64 进程里跑):`-[NSWindow makeKeyAndOrderFront:]` 发出的三条消息及接收者;SwiftUICore 经桩调用 `swift_beginAccess` 落到 libswiftCore;按键过滤与整表一致;整镜像扫描不留函数表;给一批结果起名也不留;预筛;`branchesCarryTheirStateToTheirTargets` 与 `pathsThatDisagreeLeaveTheRegisterUnknown`:寄存器状态沿着分支走(见上文),后者在第一批的顺序读法下失败;`classicSendsInsideTheCacheNameTheirSelector`:libobjc 的 `-[NSObject debugDescription]` 认出发给 `self` 的 `description`(上文「两种桩布局」末段的第三种形态);`selectorPrefilterKeepsEverySender` / `importPrefilterKeepsEveryCaller` / `swiftFunctionPrefilterKeepsEveryCaller`:预筛只丢掉引用不到主体的镜像(最后一个是 Swift 函数,见上文「预筛:缓存几乎不留 Swift 的未定义符号」)——在它丢掉的镜像里每 16 个抽 1 个扫描,一处引用也不许有(Debug 构建扫完整个缓存要几分钟,所以抽样);`callSitesMatchCapstone` 抽样 400 个 AppKit 函数,双向比对:Capstone 找到的每一处调用与跳出函数的跳转,扫描都找到了;扫描报的每一处也都是 Capstone 眼里的调用或跳转(`br` 除外,Capstone 分不出跳转表与尾调用)。Capstone 不开 detail 模式就不给操作数,那半边比对曾因此什么都没比,测试断言比对过不止一处。 +- `ObjectiveCClassReferenceTests`:AppKit 里三种取法都有(取本镜像类的地址、载入本镜像的类、载入别的镜像的类,`NSString` 在其中);`+[NSThread currentThread]` 发给类字面量 `NSNotificationCenter`;`_BenchmarkHost._started(test:)` 经 `objc_opt_self` 发给 `NSApplication`;分类方法与类方法的 super 类;Block 里的 super 发送按 `__objc_superrefs` 得到所在方法的类(Block 的符号不是方法名,只有槽位能给出类;分类方法那个测试里槽位与符号给出的类相同,分辨不出);Matter 里没有符号的方法,super 类与方法表一致;两个 SwiftUI 的同名类各自指向自己;类预筛(`NSWindow`、`NSUUID`、`__NSStackBlock__`、`OS_xpc_dictionary`)丢掉的镜像里抽样一处引用也没有。其中三个在去掉对应做法时变红过:经 `objc_opt_self` 不保留 `x0`、不读 `__objc_superrefs`、预筛只认 `_OBJC_CLASS_$_`。 +- `SwiftTypeReferenceTests`:SwiftUICore 里访问器调用报出的类型与访问器符号全部一致(一万处以上);紧邻的 `adrp` / `add` 取出的地址上若有符号,报出的类型与符号一致;Foundation 的名字取自 `x1` 的记录、落在 `__swift5_typeref`、能解开;Foundation 与 SwiftData 里,查询保留的名字恰是解开后提到该类型的名字(40 个最常被符号引用的类型;另四个标准库类型,查询退回的正是同一套解开,所以它们只守着符号引用不指错描述符);两个 SwiftUI 的同名类型按位置分开;类型预筛(Foundation 的 `URL` 与 `JSONEncoder`、SwiftUICore 的 `Text`)丢掉的镜像里抽样一处引用也没有——按导入符号预筛时三者都漏;Foundation 与 AppKit 的每一个类型,按名字先筛再比 key 的查找与比每个类型的 key 结果相同(`typeLookupsCompareSameNamedTypesOnly`),按名字查导出表与读整个导出表判断导出与否相同(`exportLookupsAgreeWithTheWholeTrie`)。 +- `FallbackNamingTests`:导出表给的名字落在导出的地址上(SiriAppIntents);AppKit 里方法表给的名字与 `-[C sel]` 符号一致(去掉分类名后 99.9% 以上);SwiftUICore 里从元数据重建的名字与真实的 `…Ma`、`…Mr`、方法符号一致(99% 以上);Matter 的方法在没有符号时由方法表起名;SiriAppIntents 几乎每个类型的访问器都有名字,重建的名字 demangle 出来是元数据访问器。 +- `StandaloneImageTests`:SymbolTestsCore fixture 经自己的桩调用 libswiftCore,没有一条停在只有名字的导入上;它的路径是加载路径而不是 `@rpath/…`,安装名也能查回它;测试包(`MH_BUNDLE`,没有安装名)的路径等于 `dladdr` 给的;测试包算作主程序的依赖方。 +- `RegisterFileTests`:48 条汇编器编出的指令,每条写的寄存器都被作废,Capstone 的寄存器访问表独立核对这张表;普通读写只作废目标寄存器。 +- `RenamedReexportTests`:AppKit 按 `_strlen`、`_CGSMainConnectionID` 调用 `__platform_strlen`、`_SLSMainConnectionID`,CharacterPicker 按 `NSEmojiImageAsset` 引用 CoreText 的类,三者的预筛都留住了它们;别名经伞形框架的那一种(`_xkMDConfigErase`)。 +- `TypeNameRetentionTests`:类型查询解开的访问器符号、mangled 名字与描述符符号都不留在全局 `NodeCache` 与进程级 demangle 记忆里(用每次随机的名字,与并行跑的测试互不干扰)。 +- `LazyBindingTests`:现编一个懒绑定的 dylib,见上文「缓存外镜像的 GOT 槽」。 +- `PreparedImageDataTests`(每个测试用自己的分析器):`prepareNames(inImageAt:)` 之后三个来源、类名、类型符号都已读好,给 Foundation 全部函数起的名字与不预读时相同;估算随留着的东西增减,放掉后为零;`releaseImageData(exceptForImagesAt:)` 只留指定镜像(连同读过的名字),其余放掉、之后照样能起名;一个线程预读预筛表、另一个线程同时要用,表只建一次;单线程读与并行读导出表结果相同。 +- `CodeReferenceIndexTests`:Foundation 整表的每一个键,索引给出的引用与整表逐条相同、顺序相同,条数等于整表里有键的加上 Swift 类型名;AppKit 里一次查几个键(selector、libswiftCore 的函数、`NSWindow`)与过滤扫描逐条相同;Foundation 里 `URL`、`JSONEncoder`(类,经类对象)与标准库的 `Sa`(名字里拼出来,要解开)从索引查与按类型扫描逐条相同;索引不到整表的一半大;建索引留住函数表;进度从 0 报到函数总数,回答「停」就不建。 diff --git a/Documentations/Internal/Modules/MachOSymbols.md b/Documentations/Internal/Modules/MachOSymbols.md index 795b7034b..73c97e4fa 100644 --- a/Documentations/Internal/Modules/MachOSymbols.md +++ b/Documentations/Internal/Modules/MachOSymbols.md @@ -25,6 +25,8 @@ MachOSymbols 是**符号索引**层:把一个镜像的符号表和 export trie `SymbolIndexStore.Storage` 里**不驻留 `Node` 类树,也不驻留符号名 `String`**。建索引时每个符号 demangle 到一棵临时树上,分类完就 intern 进这个镜像的 `NodeStoreBuilder`;全局 `NodeCache` 全程不参与,`Storage` 一放,整个镜像的内存占用就跟着走。 +成员与全局变量按入口节点归类:getter、setter,以及 SE-0507 的 `borrow` / `mutate` 访问器(`vb` / `vz`)都算属性或下标的成员符号——只声明后两者的属性没有 getter 符号,漏了它们整个成员就不见了。`_read` / `_modify` 及其新 ABI 版本不收进成员桶。 + 存储形态是每个唯一符号名一行 16 字节的 `SymbolRow`(规范化偏移 + 名字字节的打包引用)。名字有两个来源:`MachOImage` 的行直接指进镜像 mmap 的 LINKEDIT 字符串表(零拷贝、干净页,代价是这张表要求镜像保持加载);`MachOFile` 的行和 export trie 解出来的名字进表内部的私有连续缓冲区。名字反查是在 `rowsSortedByName` 排列上做字节级二分。 **规范化偏移的口径**就是上层按偏移查询用的那一套:独立文件是文件偏移,cache 内的镜像是 `未滑动地址 - sharedRegionStart`,`MachOImage` 是距 mach header 的偏移。`MachOKit` 给 `MachOFile` 符号的 `offset` 却是原始 `n_value`,也就是虚拟地址(它的文档注释写的是「file offset」,不对)。换算统一走 `SymbolValueOffsetConverter`。dylib 的 `__TEXT` 链接在 0,地址和文件偏移恰好相等,所以独立文件这一支长期没有换算,直到主可执行文件(`__TEXT` 在 0x100000000)暴露出来:每个符号都被归到高出 0x100000000 的位置,成员地址打印成两倍基址,vtable 槽也对不上名字。 diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index b2d261e4a..2ff1161ae 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -21,6 +21,8 @@ | SwiftPrinting | — | 待写 | | SwiftSpecialization | — | 待写 | | SwiftThunkAnalysis | [SwiftThunkAnalysis.md](SwiftThunkAnalysis.md) | ✅ 已写(入门:[AccessorThunkResolutionExplained.md](../AccessorThunkResolutionExplained.md)) | +| CrossReferenceAnalysis | [CrossReferenceAnalysis.md](CrossReferenceAnalysis.md) | ✅ 已写(提案 [0072-cross-reference-analysis](../../Evolutions/0072-cross-reference-analysis.md)) | +| ARM64InstructionDecoding | [CrossReferenceAnalysis.md](CrossReferenceAnalysis.md) | ✅ 已写(与 CrossReferenceAnalysis 同篇:手写的指令字读取与跳板形状,SwiftThunkAnalysis 也用) | | SwiftAttributeInference | — | 待写 | | SwiftDeclaration | [SwiftDeclaration.md](SwiftDeclaration.md) | ✅ 已写 | | SwiftDeclarationRendering | — | 待写 | diff --git a/Documentations/Internal/Modules/SwiftDeclaration.md b/Documentations/Internal/Modules/SwiftDeclaration.md index 924290634..f3304f6ee 100644 --- a/Documentations/Internal/Modules/SwiftDeclaration.md +++ b/Documentations/Internal/Modules/SwiftDeclaration.md @@ -108,6 +108,12 @@ SE-0436 的类在 `__swift5_*` 里没有身影,模型里它就是那个 `__C.X `FunctionDefinition` / `VariableDefinition` / `SubscriptDefinition` 各有一个 `objcMember: ObjCMember?`——这个成员实现的 ObjC 方法:selector、是否类方法、覆写的祖先(可空)、证据档位、selector 是否为源码里 `@objc(name)` 写出的。`isOverride` 与 `isClassMember` 都 OR 上 `objcMember?.isOverride`(覆写的类方法必须打 `class`);联结上的成员缺 `.objc` 属性就补上(OS 框架 strip 掉了 `To` thunk 符号,方法表是 `@objc` 的唯一证据);printer 在 `hasExplicitSelector` 时打 `@objc(selector)`。表联结不上的覆写方法**始终**按名字归属一次(第三档),结果照样写进 `objcMember`(`evidence == .selectorName`)——但**不写 `attributes`**,因为紧跟其后的 `final` 还原会把 `@objc` 读成 `@objc dynamic` 的证据,那是消费者还没下的裁决。用不用这一档由消费者决定:`resolvedObjCMemberFacts(trustingSelectorNameEvidence:)`(`ResolvedObjCMemberFacts.swift`)按裁决一次性给出 `attributes` / `isOverride` / `isClassMember` / `isFinal`,printer 传 `SwiftDeclarationPrintConfiguration.infersObjCOverridesFromSelectorNames`。定义自己的 `isOverride` / `isClassMember` 只认前两档(`ObjCMember.isJoinedOverride`)。它由 `Building/ObjCMemberApplication` 在 `TypeDefinition.index(in:)`(`applyThunkAttributes` 之后、`recoverFinalMembers` 之前——`final` 还原用 `@objc` 排除 `@objc dynamic`)和 `SwiftDeclarationIndexer.indexExtensions()`(`__C` 类的 extension 与本镜像 Swift 类的 extension)里从 `SwiftThunkAnalysis.ObjCMembers` 的表 join 上来:函数按自己的符号名,属性 / 下标先按 getter 再按任一 accessor 符号,`init` 按 allocator 符号换 initializer 后缀。第三档「只按名字」的覆写推断也在这里做。这个事实**不进** ABI 快照。详见 [ObjCMemberRecovery.md](../ObjCMemberRecovery.md)。 +### 访问器种类与关联类型的抑制(Swift 6.4) + +`AccessorKind` 除 get / set / read / modify 外还有 SE-0507 的 `borrowAccessor` / `mutateAccessor`(符号后缀 `vb` / `vz`)。只声明了这两种访问器的属性、下标与协议要求没有 getter 符号,`DefinitionBuilder` 因此把 getter 与 `borrow` 都当作「读访问器」来选声明节点;打印出的访问器块由 `hasBorrowAccessor` / `hasMutateAccessor` 决定(`{ borrow mutate }`),旁边编译器为满足协议合成的 getter / setter 不盖掉它们。`yielding borrow` / `yielding mutate`(SE-0474)还没有接。 + +`ProtocolDefinition.suppressedInvertibleProtocolsByAssociatedTypeName` 记 `associatedtype Element: ~Copyable`(SE-0503)。二进制本身不记录这个声明,这里只装 `SwiftInspection.SuppressedAssociatedTypeInference` 从本镜像里该协议的 extension 签名证明出来的部分,而且只有主关联类型留得下证据;没有条目不代表关联类型是 Copyable。这个事实**不进** ABI 快照:证据有无随版本里写没写 extension 变化。详见提案 [0070-borrow-accessors-and-suppressed-associated-types](../../Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md)。 + ## 相关文档 - [DeclarationModelMemoryFootprint.md](../DeclarationModelMemoryFootprint.md)——模型内存占用与瘦身。 diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index 389ec7357..cd038dd30 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -44,6 +44,8 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 两个全局块各带一个 `where !printer.isExcludedByExportFilter(globalSymbolNames:)`。绕过 `printRoot` 的宿主要自己装 scope,否则扩展一腿 fail-open。 详见 [ExportedOnlyInterfaceFiltering.md](../ExportedOnlyInterfaceFiltering.md)。 +**私有声明的源文件注释**(提案 [0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)):printer 经 `setPrivateDeclarationSourceFileProvider(_:)` 拿 provider,不放进 `SwiftDeclarationPrintConfiguration`(它是 `Equatable`,放不进一个 provider),builder 本身不动。打印点有五处:类型、协议、扩展的声明头,`renderMember` 里每种成员的第一行,以及 `printRootContents()` 的两个全局块——全局块是 `BlockList`,每行注释单独做一项,列表会在每项前换行。嵌套的类型与协议跟它的父定义比,打在哪一层都一样:`marksNestedDefinitions` 要求单独打印与从父定义里摘出来的逐字相同(`NestedDefinitionRegionContractTests` 有打开注释的变体)。也不跟名字里的上下文比:局部类型名字的上下文是声明它的函数,函数不打印在它上方。 + **`SwiftInterfaceBuilderExtraDataProvider`**:外部数据源的注入缝,纯生命周期钩子——`Sendable` + 一个默认为空的 `setup()`(提案 0015 之前它还继承 printer 的 resolver 协议,强迫所有 provider 都是类型名解析器)。「会不会回答 printer 查询」是正交能力:provider 按需另行声明 `SwiftPrinting` 的角色协议(`ModuleNameResolving` / `CImportedNameResolving` / `OpaqueTypeResolving`,均 refine 空标记协议 `TypeNameResolving`),`addExtraDataProvider(_:)` 用 `as? any TypeNameResolving` 命中才把它转发给 printer——所以一个 resolver 型 provider 一头挂在 builder 的 prepare 生命周期上,一头挂在打印热路径上,而纯 setup 型 provider(只预热缓存之类)也是合法形态。两个已知实现:`TypeIndexing.SwiftInterfaceBuilderTypeNameProvider`(`__C` 模块归属,跨模块,声明两个名字角色)和本模块的 `SwiftInterfaceBuilderOpaqueTypeProvider`(声明 `OpaqueTypeResolving`,见子系统 2)。 **`SwiftInterfaceBuilderDependencies` + `DependencyPath`**:把「主 binary + 它的依赖镜像」凑成一组,按 reader 分特化——`MachOFile` 版从 `DependencyPath`(单个 Mach-O 路径 / dyld cache 路径 / 宿主系统 cache)按 install name 匹配装载,装载失败走 `renderingDegraded` 事件(默认无 handler 也有 os_log 地板);`MachOImage` 版直接按名字向 dyld 要。消费者是 CLI 的 `InterfaceCommand` 与 `TypeIndexing`(依赖过滤 + 惰性 ObjC 元数据索引都需要依赖镜像清单)。 diff --git a/Documentations/Internal/Modules/SwiftLayout.md b/Documentations/Internal/Modules/SwiftLayout.md index 2cd33f97e..25741a343 100644 --- a/Documentations/Internal/Modules/SwiftLayout.md +++ b/Documentations/Internal/Modules/SwiftLayout.md @@ -44,9 +44,13 @@ SwiftLayout 是**静态聚合布局引擎**:不加载进程、不调用 metada `KnownLayoutTable` 是标准库类型的冻结布局,`BuiltinTypeLayoutIndex` 读镜像的 `__swift5_builtin` 段——编译器为「反射推不出结构的类型」内嵌的整体布局,也就是**导入的 C 值类型**和**多 payload 枚举**。解析器在走自己的结构化 struct / enum 路径之前先查它。 +libswiftCore 的 builtin 段还多一类记录:编译器 builtin 叶子类型(`Builtin.Int1`、`Builtin.BridgeObject`、`Builtin.FPIEEE16`……)的布局,也就是每个标准库类型最终落到的那一层。编译器只在编译标准库时收集它们,所以只有 libswiftCore 有;索引按 builtin 名建 key,libswiftCore 里的字段直接用这些记录。其它镜像里的 builtin 字段(`_Concurrency` 的 `Builtin.Job` / `Builtin.Executor`、actor 的人造存储字段)没有记录,由解析器的兜底表回答。 + +两张写死的表——`KnownLayoutTable` 和兜底表——都以二进制为准:`StandardLibraryLeafLayoutTests` 用 libswiftCore 自己的字段记录与叶子记录把冻结表的每一项重算一遍,兜底表里 libswiftCore 也有记录的叶子逐个对记录,没有记录的叶子对活的 value witness table,任何一项对不上测试就红。运行时仍然先查冻结表:它不需要找到 libswiftCore,单镜像场景也能回答,而这些 `@frozen` 类型在 64 位 Apple 平台上算出来本来就和表一样。 + 顶层入口还会拿 foreign(C 导入)struct 描述符跟 builtin 记录**交叉校验**:Swift 的 field record 看不见 C 的位域和填充,一旦两边不一致,以 builtin 的整体事实为准,并把每个字段降级为 `.unknown(.foreignTypeFieldOffsetsUnavailable)`——宁可说不知道,也不报一串自信的错偏移。有一种不一致形态已被证明安全(issue #116):当每个结构化字段都正好落在前序字段尺寸之和、且该和等于 builtin 的整体尺寸时,两种布局都没有藏填充的余地,逐字段偏移可信。 -**精度这件事上,leaf 的 extra inhabitant 数是最容易出错、后果最隐蔽的一环**:托管指针族饱和到 `0x7FFF_FFFF`,unsafe pointer 族只保留 null(XI 1),`weak` 引用字 XI 0 且非 bitwise-takable,`unowned`(safe)引用字恰好 XI 1。这些值都逐条对着活的 value witness table 和 IRGen / runtime 源码核过,`WholeTypeLayoutVsRuntimeTests` 对每个 fixture 类型断言完整的五元组。数值本身与推导见 [StaticLayoutEngine.md](../StaticLayoutEngine.md)。 +**精度这件事上,leaf 的 extra inhabitant 数是最容易出错、后果最隐蔽的一环**:托管指针族(以及 task / job 指针 `Builtin.RawUnsafeContinuation`、`Builtin.Job`)饱和到 `0x7FFF_FFFF`,unsafe pointer 族只保留 null(XI 1),`weak` 引用字 XI 0 且非 bitwise-takable,`unowned`(safe)引用字恰好 XI 1。这些值都逐条对着活的 value witness table 和 IRGen / runtime 源码核过,`WholeTypeLayoutVsRuntimeTests` 对每个 fixture 类型断言完整的五元组。数值本身与推导见 [StaticLayoutEngine.md](../StaticLayoutEngine.md)。 ### 4:三个桥接 diff --git a/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md index 3fc37c8ee..e1db68a08 100644 --- a/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md +++ b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md @@ -1,7 +1,7 @@ # SwiftPrivateDiscriminators 模块 > 模块参考文档(module reference),随代码维护。读者:维护者。 -> 来历与取舍见提案 [0063-private-declarations](../../Evolutions/0063-private-declarations.md);本文负责全貌与分工。 +> 来历与取舍见提案 [0063-private-declarations](../../Evolutions/0063-private-declarations.md);接进 dump 与 interface 见提案 [0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)。本文负责全貌与分工。 ## 模块定位 @@ -9,7 +9,10 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 它只管反推。名字里读得到哪些私有声明,由 `SwiftInspection` 的 `DemanglingNode.privateDeclarations` 回答,那是所有名字都要用的轻量接口;本模块带着 2007 个已知文件名的清单,只有要反推的宿主才依赖它。 -宿主目前是 RuntimeViewer:侧栏的 `Private` 标签弹窗里显示 discriminator 与反推出的文件名,引擎进程按镜像持有一个 `PrivateDiscriminatorSourceFileIndex`。 +宿主有两个: + +- RuntimeViewer:侧栏的 `Private` 标签弹窗里显示 discriminator 与反推出的文件名,引擎进程按镜像持有一个 `PrivateDiscriminatorSourceFileIndex`,每次只问弹窗那一行的。 +- `swift-section dump` / `interface` 的 `--emit-private-source-files`(`SwiftSectionKit` 的 `emitsPrivateDeclarationSourceFiles`):打印前用 `recoverSourceFiles(ofEveryDeclarationIn:)` 把整个镜像一次求完,再经 `SwiftDeclarationRendering` 的 `PrivateDeclarationSourceFileProviding` 交给 dumper 和打印器,每个声明问一次、都是查表。注释的写法和「只标外层没有的 discriminator」的规则在 `PrivateDeclarationSourceFileComments`,两条输出共用。 ## 文件 → 子系统对照 @@ -17,7 +20,7 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 |---|---| | 1. 搜索本身(纯函数) | `PrivateDiscriminatorSourceFiles.swift`:五步候选、`Search`(摘要比对、合成文件、一段字节两种读法)、`Candidates`(从名字里读出的模块名与标识符)、`Digest128` | | 2. 已知文件名 | `PrivateDiscriminatorSourceFiles+KnownFileNames.swift`,由 `Scripts/GenerateKnownSwiftSourceFileNames.sh` 生成,不手改 | -| 3. 按镜像取候选、记答案 | `PrivateDiscriminatorSourceFileIndex.swift` | +| 3. 按镜像取候选、记答案;整镜像批量求;给 dump / interface 的 provider | `PrivateDiscriminatorSourceFileIndex.swift` | ## 关键契约 @@ -30,6 +33,8 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 - RuntimeViewer 提案里的还原率是 macOS 26.7 上用侧栏那批候选量的,本 index 没有重新量。搜索本身没有上限,所以候选多出来只会让还原出的变多。 - 不扩大到符号表的全部标识符:RuntimeViewer 当时量过,只多三个百分点,候选却多一个数量级。 - **名字在第一次请求时才读,每个答案都记住**,还原不出也记。宿主按镜像持有,随镜像释放。 +- **要打印整个镜像的宿主先批量求一次**:`recoverSourceFiles(ofEveryDeclarationIn:)`(`@_spi(Support)`,取一个索引器)把名字里的 discriminator 和符号索引里成员符号、索引器全局声明的 discriminator 一起交给一次搜索。逐个声明去问的话,每个还原不出的都要把五步候选全部算一遍;一起问时第 1、2、4 步只算一次。候选不变,只是要求的 discriminator 多了:一个只写了 `extension View { private func … }` 的文件,名字里看不到它的 discriminator。Release 构建下一次求完整个镜像,SwiftUICore 约 15 秒、SwiftUI 约 41 秒(macOS 27.2,interface 开关前后之差,数据见提案的「实测」),几乎全花在还原不出的那些上;第 5 步按 discriminator 各自独立,要提速可以从这里并行。 +- **结果类型有两个**:搜索本身返回 `PrivateDiscriminatorSourceFiles.SourceFile`,给 dump / interface 的是 `SwiftDeclarationRendering` 的 `PrivateDeclarationSourceFile`,index 遵循 `PrivateDeclarationSourceFileProviding` 时换一下。没有把前者挪下去留 typealias:RuntimeViewerCore 开了 `MemberImportVisibility`,读挪走的类型的成员可能要多 import 一个模块。 - **名字在锁外读,搜索在锁内。** `PrivateDiscriminatorSourceFileIndex` 的状态全在一把 `NSLock` 下。 - 读名字要打印镜像里的每个名字,而 AGENTS.md 规定不能持锁 demangle。 - 请求可能来自 512 KB 栈的协作线程,所以整批名字放进 `StackSafeExecutor.withLargeStack` 里读,一批只切一次线程;栈够大的线程就地读。 @@ -45,7 +50,10 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 - 名字只读一次,还原不出的不再搜(`searchCount`); - 名字在大栈上读; - 两个并发的首次请求都读名字、只搜一次; - - 名字读完放掉索引器。 + - 名字读完放掉索引器; + - 整镜像批量求只搜一次,之后每个都是查表;provider 答的就是搜到的,还原不出的答 `nil`、不再搜。 +- 注释的写法与该标哪些:`Tests/SwiftDeclarationRenderingTests/PrivateDeclarationSourceFileCommentsTests.swift`(模块名不同、合成文件、还原不出、没有名字的私有声明、一个名字两个 discriminator、外层已有的不标)。 +- 两条输出端到端:`Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift`,SymbolTestsCore 上两个同名 `PrivateDoppelganger`(第二个文件 `PrivateDoppelgangersSecondFile.swift` 拼不出,正好测还原不出的写法),加 `LocalTypeFixture` 里公开类型 `Holder` 的私有方法 `hiddenValues()`。 - `Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift`,读运行中系统的 dyld shared cache,不进 CI,因为它的 discriminator 是 macOS 27.2 上取的: - Foundation 的 `__JSONEncoder` → `JSONEncoder.swift`; - SwiftUICore 的 `EnabledKey` → SwiftUICore 的 `Enabled.swift`,钉住模块名取镜像文件名。 @@ -55,5 +63,5 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 ## 相关文档 -- 提案:[0063-private-declarations](../../Evolutions/0063-private-declarations.md) +- 提案:[0063-private-declarations](../../Evolutions/0063-private-declarations.md)、[0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)(接进 dump 与 interface) - 局部类型与占位名:[0062-local-type-context-names](../../Evolutions/0062-local-type-context-names.md) diff --git a/Documentations/Internal/Modules/SwiftSectionKit.md b/Documentations/Internal/Modules/SwiftSectionKit.md index a2d1f8eba..9fef0f58b 100644 --- a/Documentations/Internal/Modules/SwiftSectionKit.md +++ b/Documentations/Internal/Modules/SwiftSectionKit.md @@ -58,6 +58,7 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 - **按用途建模**:互斥的选项用 enum 表达,非法组合在类型上写不出来——`ABIDiffRequest.Report` 只能是 change list / summary / JSON / annotated interface 之一,`FieldOffsetComments` 把「expanded 隐含 flat」做成了 `.none / .flat / .expanded`。只对某一种报告有意义的选项做成那个 case 的关联值:diff 的 `annotatedInterface(format:includesBreakingChangeVerdict:)`,evolution 的 `annotatedInterface(availabilityAttributes:)`(`@available` 属性只有 annotated interface 才有;`.none` / `.inferredPlatform` / `.platform(_:)` 对应命令行的「不给 `--emit-available`」「只给 `--emit-available`」「再加 `--platform`」)。命令行的 flag 组合校验(`--json and --interface are mutually exclusive`)留在包装层的 `validate()`,原文不动。 - **请求是 `Equatable` 的值**,`run` 的依赖(输出端、环境)是参数而不是字段。包装层的测试靠这一点:解析 flag → `makeRequest()` → 与期望请求比较(`CommandRequestMappingTests`)。 - **库只报告,不退出**:`ABIDiffOutcome.hasBreakingChange` 等结论由包装层对照 `--fail-on-breaking` 决定是否 `throw ExitCode.failure`。`diff --interface` 只在 `includesBreakingChangeVerdict` 时才额外算一遍 change-list diff,和原来「只有 CI 闸门需要它」的取舍一致。 +- **私有声明的源文件**(`emitsPrivateDeclarationSourceFiles`,提案 [0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)):两个请求共用 `PrivateDeclarationSourceFileRecovery`,先对整个镜像批量反推一次,再把 index 交给 dumper(`DeclarationRenderConfiguration.privateDeclarationSourceFileProvider`)或打印器(`setPrivateDeclarationSourceFileProvider(_:)`)。`interface` 用 builder 自己的索引器,在 `prepare()` 之后装上。`dump` 本来不建索引器,打开时另建一个只为让 index 读名字,并且**让它活到 dump 结束**:索引器最后一次释放会回收它 `prepare()` 建的缓存,其中就有 dump 读每一行成员的符号索引,提前放掉的话 dump 后半段要重建一遍。关着时两条路径都不建 index、不多 `prepare()`。 - **命令行拼写留在包装层**:模板名还是字面模板(`TransformerTemplateResolver`)、`--transformer-config` 的 JSON 文件、逗号分隔的 `--labels` / `--sections`、`--c-type-replacement` 的 `a=b`、demangle 的二十多个覆盖开关,都由包装层解释成库的值类型(`Transformer.SwiftConfiguration`、`[ObjCPrimitiveTypePattern: String]`、`DemangleOptions`…)再交给请求。代价见下一节的偏差 2。 ## 5. 与拆分前的行为差异(只有两类) @@ -69,7 +70,7 @@ stdout、stderr、退出码、每个子命令的 `--help` 都与拆分前逐字 ## 6. 测试锚点 -- `Tests/SwiftSectionKitTests/`:每个请求对 SymbolTestsCore fixture 端到端跑(`ABIRequestTests`、`DumpAndInterfaceRequestTests`、`ObjCRequestTests`、`TransformerRequestTests`),加纯逻辑(`MachOSourceTests` 里的胖二进制是测试现场拼的单切片胖文件,不依赖宿主;`InterfaceAnnotationStyleTests`;从 CLI 搬来的 `ObjCDumpDiagnosticsTests`)。`ABIRequestTests` 整个套件共用一份 fixture 的 snapshot 文档(静态 `Task`),只索引一次。它测 `@available` 平台推断失败时,平台不同的输入是现场改写了 `LC_BUILD_VERSION` 的 fixture 副本(`FixtureFiles.makeCopy(of:buildPlatform:in:)`);副本的 UUID 与原件相同,每个按镜像的缓存都会把它当成原件,所以只能交给在索引之前就结束的用例。`RecordingOutput` 只实现 `write(_:)`,所以用它的用例同时在测 `write(_:declaring:)` 的默认实现;要看每块声明是什么,用 `DeclarationRecordingOutput`(两个方法都实现,按顺序记下每块产物和它带的声明)。 +- `Tests/SwiftSectionKitTests/`:每个请求对 SymbolTestsCore fixture 端到端跑(`ABIRequestTests`、`DumpAndInterfaceRequestTests`、`ObjCRequestTests`、`TransformerRequestTests`),加纯逻辑(`MachOSourceTests` 里的胖二进制是测试现场拼的单切片胖文件,不依赖宿主;`InterfaceAnnotationStyleTests`;从 CLI 搬来的 `ObjCDumpDiagnosticsTests`)。`ABIRequestTests` 整个套件共用一份 fixture 的 snapshot 文档(静态 `Task`),只索引一次。它测 `@available` 平台推断失败时,平台不同的输入是现场改写了 `LC_BUILD_VERSION` 的 fixture 副本(`FixtureFiles.makeCopy(of:buildPlatform:in:)`);副本的 UUID 与原件相同,每个按镜像的缓存都会把它当成原件,所以只能交给在索引之前就结束的用例。`RecordingOutput` 只实现 `write(_:)`,所以用它的用例同时在测 `write(_:declaring:)` 的默认实现;要看每块声明是什么,用 `DeclarationRecordingOutput`(两个方法都实现,按顺序记下每块产物和它带的声明)。`PrivateDeclarationSourceFileRequestTests` 的 dump 与 interface 各共用一份打开开关的 fixture 输出(静态 `Task`,四个用例只跑一次);公开类型的私有成员用 `LocalTypeFixture`,那两条用例按惯例声明 `ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)`,测试目标因此依赖 `MachOTestingSupport`。 - `Tests/SwiftSectionCommandTests/`:原有的解析测试;`CommandRequestMappingTests`(flag → 请求)、`CommandLineErrorTranslationTests`(库错误 → 历史文案与退出码)、`StandardStreamOutputTests`(内存流读回字节;`Rainbow.enabled` 与 `outputTarget` 是进程全局量,套件 `.serialized` 并在测试内钉住、用完还原)、`CommandLineStreamWriteScanTests`。 - `PrintFailureEventTests.libraryModulesWriteToNoProcessStream` 的豁免名单只有 `swift-section` 和 `MachOTestingSupport`,`SwiftSectionKit` 自动被扫描:库里出现任何 `print` / `fputs` / `FileHandle.standard*` 都会变红。 diff --git a/Documentations/Internal/Modules/SwiftThunkAnalysis.md b/Documentations/Internal/Modules/SwiftThunkAnalysis.md index 1de4c2fff..bfef02a2a 100644 --- a/Documentations/Internal/Modules/SwiftThunkAnalysis.md +++ b/Documentations/Internal/Modules/SwiftThunkAnalysis.md @@ -32,7 +32,7 @@ SwiftThunkAnalysis 干一件事:**不执行 thunk,把它算出来**。 | 输入 | 状态 | |---|---| -| dyld shared cache 里的镜像(macOS 14.7 – 26.6、iOS 设备 cache、iOS 27 模拟器 cache) | 完整解析。跨镜像调用是 rebase 地址或镜像间跳板(读槽的 stub / 算地址的 stub island),都跟得下去 | +| dyld shared cache 里的镜像(macOS 14.7 – 26.6、iOS 设备 cache、iOS 27 模拟器 cache) | 完整解析。跨镜像调用是 rebase 地址或镜像间跳板(读槽的 stub / 算地址的 stub island),都跟得下去;跳板的形状由 `ARM64InstructionDecoding` 的 `ARM64Trampoline` 认,与 CrossReferenceAnalysis 共用一份(此前用 Capstone 加寄存器跟踪认,行为相同) | | 独立文件(第三方 app、iOS 26 及更早的模拟器运行时、即时编译的 fixture) | 完整解析,前提是给得出依赖搜索路径。跨镜像调用全是 GOT bind(只有名字),靠依赖镜像的 export trie + accessor 索引解名 | | 编译器合并的 `…MaTm` accessor | 跟进函数体求值(真正的 accessor 从 `x3` 传入,函数体只查缓存再 `blr x3`) | | 按名字引用的、属于**别的镜像**的 opaque 类型 | 重新 mangle 出描述符符号名、定位镜像、在那个镜像里展开 | @@ -42,21 +42,25 @@ SwiftThunkAnalysis 干一件事:**不执行 thunk,把它算出来**。 ### Capstone v6 的解码边界 -依赖使用 `from: "6.0.0"` 和 `AARCH64` trait。v6 的指令编号可能是底层操作码, -但操作数已经采用显示别名的形状,例如 `cmp` 是 `SUBS` 编号加两个比较输入, -`mov x0, sp` 是 `ADD` 编号加两个寄存器。解码器同时核对编号与 mnemonic, -再按别名解释操作数;只有改类型名的迁移会静默丢失这些操作。 -普通 `orr` 没有复制语义,仍走未建模指令的寄存器作废通路。 +依赖 swift-capstone 7 的 `AARCH64` trait。解码器创建一个 `Disassembler`,在 `forEachInstruction` +的闭包里把每条指令就地转成 `ThunkInstruction`:swift-capstone 借出的指令视图带不出闭包,Capstone 的任何 +东西都不会留到 `decode` 返回之后。 -立即数的 `lsl` 修饰必须计入数值,完整 `mov` 常量不得重复移位。 -v6 不再提供通用 `writeBack` 属性:后索引用 `isPostIndex`,前索引读 Capstone -输出的 `]!` 标记。仅凭基址出现在写寄存器列表中不能判定写回,因为 `ldr x0, [x0]` -也会写 `x0`。后索引的访问偏移为零,更新量不是本次访问的偏移。 -现有求值器仍保守处理写回的成对访存,未新增栈更新模拟。 +capstone v6 的指令编号可能是底层操作码,但操作数已经采用显示别名的形状,例如 `cmp` 是 `SUBS` 编号加两个 +比较输入,`mov x0, sp` 是 `ADD` 编号加两个寄存器。解码器按 swift-capstone 报告的别名(`alias` 为 +`.aliasMov`、`.aliasCmp`)决定怎么解释操作数;6.x 没有这个字段时靠「编号 + mnemonic」配对,做的是同一件 +事。普通 `orr` 没有复制语义,仍走未建模指令的寄存器作废通路。 + +立即数的 `lsl` 修饰必须计入数值,完整 `mov` 常量不得重复移位。写回读 swift-capstone 的 +`writesBackBaseRegister`:只在基址寄存器被更新时为真(前索引 `[x1, #8]!`、后索引 `[x1], #8`)。它不是 +Capstone 自己的 `writeback` 标志——那个标志对任何绑定操作数都置位,`movk`、`cas` 也算。仅凭基址出现在写 +寄存器列表中同样不能判定写回,因为 `ldr x0, [x0]` 也会写 `x0`。后索引的访问偏移为零,更新量不是本次访问 +的偏移。现有求值器仍保守处理写回的成对访存,未新增栈更新模拟。 这些契约由 `CapstoneThunkDecoderTests` 的真实指令编码固定;跨仓库方案沿用 [已交付工作分支的嵌套字段提案](https://github.com/MxIris-Reverse-Engineering/swift-decompiler/blob/2e038982a8d19600d6cd082bcf42603f4f52115b/docs/evolutions/draft-nested-coordinate-field-extents.md)。 -本次 v6 迁移的授权与验证记录见[项目演进日志](../ProjectEvolutionLog.md#58-capstone-v6-解码与反编译器依赖对齐)。 +v6 迁移的授权与验证记录见[项目演进日志](../ProjectEvolutionLog.md#58-capstone-v6-解码与反编译器依赖对齐),迁到 +swift-capstone 7 见[提案](../../Evolutions/0071-swift-capstone-7.md)。 ### 三条故意的拒绝 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 59464dc18..1d694fcd4 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2176,13 +2176,14 @@ ## 80. 测试用的 dyld shared cache 路径按版本取 -- **时间段**:2026-10-05,后续于 2026-10-06。 +- **时间段**:2026-10-05,后续于 2026-10-06、2026-10-21。 - **动机**:用户要「DyldSharedCachePath改成String Type Enum结构体,支持传递版本返回路径」,并「再加一个SwiftInterfaceBuilderTests加上Diff和Evolution版本」。原来每用一个归档 cache 都得给 enum 加一个 case、手写完整路径,evolution 的 IntegrationTests 还要另写一份与路径一一对应的版本标签数组。 - **关键决策**(轻量档提案,问过一轮):**① 以 `String` 为原始值的结构体**,写法同 `SymbolicManglingReference.Kind`;原有 8 个 case 变成同名 `static let`,调用点不改。**② 版本函数只有 `macOS(_:)` / `iOS(_:)`**,按 `/Volumes/DyldSharedCaches/<平台>/<版本>/dyld_shared_cache_arm64e` 拼,不检查文件在不在;模拟器 runtime 的 cache 路径带 build 号,版本推不出,继续写死。**③ 三个 IntegrationTests 套件各加一个 `ArchivedDyldCacheTests`**,只填版本号;evolution 那个拿版本号当轴标签,并打开 `@available(macOS, …)` 输出。**④ 顺带发现的两处不改**(用户选「都先不动」):`macOS_26_5_1` 指向的目录是空的,diff 套件里两处一跑就失败;`iOS_18_5` / `iOS_26_1` 指向没挂载的 `/Volumes/Generic`,全仓没有调用。 - **落地模块**:`MachOFixtureSupport`(`DyldSharedCachePath`);`MachOTestingSupportTests` 新增 `DyldSharedCachePathTests`;`IntegrationTests` 的三个 `ArchivedDyldCacheTests` 与 `SwiftEvolutionInterfaceDumpTests` 两个辅助函数的 `availabilityAnnotationPlatform` 参数。 - **验证**:全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,远端依赖)2270 个测试 / 423 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。IntegrationTests 只编译、不运行:新类编译通过、没有新警告,三个默认版本在卷上都有 cache 文件。 - **后续(同日):`versionLabel`**:用户要 evolution 那边不再另写标签。`DyldSharedCachePath` 加 `versionLabel`,和路径一起在构造时给出:`macOS(_:)` / `iOS(_:)` 拿传入的版本当标签,其余常量直接写明(`current` 标为 `current`,标签不一定是系统版本,这是用户定的);因此不再遵循 `RawRepresentable`。`MultiVersionDyldCacheImageTests` 删掉 `cacheLabels`,轴标签取 `versionLabel`,默认三个 cache 的标签与原来手写的相同。没有从 cache 文件解析版本:cache 头的 `osVersion` 不带补丁号(26.5.2 读出 26.5.0),macOS 11 的 cache 里是 0.0.0。验证:按用户要求只编译,全部测试目标(含 IntegrationTests)编译通过、没有新警告,没有运行测试。 - **后续(2026-10-06):evolution 的归档套件铺满 macOS 11–27,没有 Swift 的版本跳过**:`SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests` 改列 `cacheVersions`(卷上 macOS 11.0.1 → 27.0 每个次版本一个 cache,共 51 个;11.0、12.0 只有 `11.0.1`、`12.0.1`),`cachePaths` 由它生成,镜像换成 SwiftUI(这两处是用户改的)。`MultiVersionDyldCacheImageTests` 跳过 cache 里没有该镜像、或镜像没有 `__swift5_*` 节的版本,不再报错:AppKit 在 macOS 14 之前把 Swift API 放在 `libswiftAppKit.dylib`,本体在 11.0.1–13.7 没有 Swift 节,不跳过时每个这样的版本都会以 error 级别写进四条提取失败。规模参考(`next` 的 debug 版 CLI 走同一条 `--interface` 路径,AppKit 51 个版本、28 路并行):178 s,峰值内存 0.78 GB;同时打开的文件峰值 2749 个,其中 2214 个是本机 cache——MachOKit 的 `FullDyldCache.host` 每访问一次就重新打开、映射一遍本机 cache,而库里默认的依赖搜索路径每个版本都会访问它(未处理)。SwiftUI 51 个版本目前跑不完:测试第 140 秒在 13.5 上崩溃(崩溃前峰值 2.2 GB),读 Swift 类的 ObjC RO 数据时,MachOKit `DyldChainedFixupPointer._rebaseTargetRuntimeOffset` 里的 `UInt64` 减法下溢;CLI 路径同样会崩,崩在另一个旧版本上。根因是同一个 SwiftUI 构建出现在 13.5 和 13.6 两个 cache 里、按镜像的缓存撞 key,修复见第 81 节。只跑 14.4 → 27.0 的 23 个版本能跑完:CLI 用时 26 分钟,峰值 4.64 GB,出现在成员索引阶段,渲染阶段约 2.6–2.9 GB;照此推算 51 个版本的峰值在 6–8 GB。(成员索引阶段的峰值其实主要是读子 cache 时堆积的 autorelease 池,修掉之后 51 个版本以 4.86 GB 的峰值跑完,见第 82 节。)验证:只编译,全部测试目标(含 IntegrationTests)编译通过、没有新警告;按用户要求运行过一次 `evolutionInterfaceFile`(如上,崩溃),其余测试没有运行。 +- **后续(2026-10-21):macOS 11、12 的轴标签写成 `11.0`、`12.0`**:AppleDB 上下载不到 macOS 11.0、12.0 的镜像,只有 11.0.1、12.0.1,卷上这两个大版本的目录因此是 x.0.1;轴标签原先照抄目录名,`@available` 里会写出 `introduced: 12.0.1`。`ArchivedDyldCacheTests` 新加 `versionLabelsByCacheVersion`,给这两个目录另配大版本标签,与 SDK 的 `@available` 一致;`cacheVersions` 仍列目录名,`DyldSharedCachePath` 和其他套件不动。验证:只编译,全部测试目标(含 IntegrationTests)编译通过、改动的文件没有新警告,没有运行测试。 - **关联文档**:[0061-dyld-shared-cache-path-versions](../Evolutions/0061-dyld-shared-cache-path-versions.md)(轻量档提案)。 - **对应版本**:不进发布产物,只改测试支撑代码与测试。 @@ -2512,6 +2513,185 @@ - **关联文档**:[Changelogs/0.23.0.md](../../Changelogs/0.23.0.md);MachOObjCSection 的[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/0.8.200/Documentations/Internal/RelativeListsAcrossSubCacheFiles.md)。 - **对应版本**:0.23.0。 +## 99. Swift 6.4 的 borrow / mutate 访问器与关联类型上的 `~Copyable` + +- **时间段**:2026-10-10 写成,2026-10-16 找回并合入 `next`。 +- **动机**:抓 Swift 论坛近期帖子评估影响时,顺着 2026-08-31 的「6.4 实现状态汇总」实测出两个缺口:只声明 SE-0507 `borrow` / `mutate` 访问器的属性、下标与协议要求在 interface 与 dump 里整个消失;SE-0503 的 `associatedtype Element: ~Copyable` 印成 `associatedtype Element`。用户:「修一下」。 +- **关键决策**:**① borrow / mutate 全链认**:符号索引把 `vb` / `vz` 当作成员与全局变量的访问器符号,`AccessorKind` 加两个 case,`DefinitionBuilder` 把 `borrow` 当读访问器选声明节点,访问器块按 `hasBorrowAccessor` / `hasMutateAccessor` 印 `{ borrow mutate }`。**② 关联类型的抑制只能推断**:查编译器源码确认二进制不记录这个声明(IRGen 只给泛型参数发反向要求),改由本镜像里该协议 extension 签名上的 `Self.X: ~Copyable` 证明;实测只有主关联类型留得下这种证据,用户在「推断」与「不修、只记成限制」之间选了推断。结论不进 ABI 快照。**③ `yielding borrow` / `yielding mutate` 不做**,等 SE-0474 落地。**④ 测试现场用 Swift 6.4 编 fixture**:CI 的 Swift 6.3 编不出 `borrow`,`SymbolTestsCore` 也不能动;找不到 6.4 工具链就跳过。**⑤ 找回再合入**:10-10 的改动一直只暂存、没有提交,工作树在 10-12 到 10-15 之间被删。分支一次都没提交过,`merge-base --is-ancestor` 把它判成「已合并」。10-16 从对象库里一个不可达的临时提交加当天对话记录里的三处文档修改恢复,rebase 到 0.23.0 之后的 `next`:`DefinitionBuilder` 改用 `memberSubtree`,关联类型行改用带 `resolver:` 的 `dumpInvertedProtocolsInheritance`。经过见提案决策日志。 +- **公开 API 与行为变化**:`AccessorKind` 新增 `.borrowAccessor` / `.mutateAccessor`(**源码不兼容**:RuntimeViewer 的 `RuntimeSwiftSection.swift` 对它穷举 `switch`,合入时同批补上);`AccessorRepresentable.hasBorrowAccessor` / `hasMutateAccessor`;`ProtocolDefinition.suppressedInvertibleProtocolsByAssociatedTypeName`。 +- **落地模块**:MachOSymbols(`SymbolIndexStore` 的成员 / 全局 / 访问器判断)、SwiftDeclaration(`AccessorKind`、`Accessor`、`DefinitionBuilder`、`WrappedPropertyRecovery`、`ProtocolDefinition`)、SwiftInspection(新增 `SuppressedAssociatedTypeInference`)、SwiftPrinting(`AccessorBlockKeywords`、成员打印器、关联类型行)、SwiftDump(`ProtocolDumper`)、SwiftDeclarationRendering(`WrappedValueAccessorSymbol`)、SwiftDiffing(访问器 token);测试支持新增 `Swift64DeclarationShapesFixture`。 +- **验证**(细节见提案决策日志): + - 10-10 在 `next` @ `cd248de9` 上:新测试在修复前有 15 处断言失败,修复后全部通过。 + - 10-16 rebase 之后,在 JHs-Mac-Studio 上用 Xcode 26.6 跑,依赖链本地兄弟仓库,内容与已发布版本一致: + - 全量 `swift test --skip IntegrationTests` 共 2450 个测试 / 470 个套件,失败的只有本机既有的两条 `MultiPayloadEnumDescriptorCacheTests`。 + - 渲染 A/B 以 `b7be58ec` 为基线,90 对全部逐字节一致:两份归档 cache、四个 iOS 模拟器 runtime,加上 MachOImage 腿。 + - macOS 27.0 的 libswiftCore,interface 与 dump 都只多出两处 `: ~Swift.Copyable`。 +- **关联文档**:[0070-borrow-accessors-and-suppressed-associated-types](../Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「访问器种类与关联类型的抑制」、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)、`AgentPlugins/swift-section` 的 skill(新增一条读输出的提示)。 +- **对应版本**:0.24.0。`AccessorKind` 新增 case 会让下游的穷举 `switch` 编不过,写进了 0.24.0 Changelog 的 Breaking。 + +## 100. 迁到 swift-capstone 7.0 + +- **时间段**:2026-10-17,分支 `feature/swift-capstone-7`,swift-capstone 7.0.0 发布后当天合入 `next`。 +- **动机**:swift-capstone 7.0 用按架构泛型的不可复制引擎 `Disassembler` 取代 6.x 的类 API,旧 API + 直接删除;它的重写提案约定本库与 swift-decompiler 同批迁移。用户批准该提案:「可以,按你说的开工」。 +- **关键决策**:① 只改 `CapstoneThunkDecoder.swift`,`decode` / `decodeFunction` 的签名与 `Data` 入参不变; + ② 每条指令在 `forEachInstruction` 的闭包里直接转成 `ThunkInstruction`;③ 别名改看 `alias`,写回改看 + `writesBackBaseRegister`,不再靠「编号 + mnemonic」配对与匹配 `]!`;④ 依赖下限从 6.0.1 改成 7.0.0, + 等 swift-capstone 7.0.0 发布才合入。 +- **落地模块**:SwiftThunkAnalysis(`Instructions/CapstoneThunkDecoder.swift`)。 +- **验证**(细节见提案决策日志): + - 发布前对着本地 swift-capstone,以 `swift package edit` 只在 agent 的构建目录里覆盖依赖、不动共享的 + `.worktrees/` 链接。Swift 6.4.2:`SwiftThunkAnalysisTests` 82 个测试,加上间接用到解码器的 5 个套件 + 52 个测试;全量 `swift test --skip IntegrationTests` 共 2450 个测试 / 470 个套件全部通过。 + - 发布后在新鲜构建目录里重跑全量,swift-capstone 从远端解析到 7.0.0、capstone 到 6.0.101,其余依赖仍链 + 兄弟仓库:2450 个测试 / 470 个套件全部通过。原始退出码都是 0。 + - 坑:`swift package edit` 留下的 manifest 求值缓存会把指向本地 capstone 的路径依赖套到远端 7.0.0 上, + 解析失败;`swift package resolve --manifest-cache none` 一次即可。 +- **关联文档**:[0071-swift-capstone-7](../Evolutions/0071-swift-capstone-7.md)、 + [Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)「Capstone v6 的解码边界」。 +- **对应版本**:0.24.0。对外 API 不变,但依赖图里的 swift-capstone 从 6.x 换成 7.x:同时直接依赖 + swift-capstone 6 的下游会解析失败,写进了 0.24.0 Changelog 的 Breaking。 + +## 101. 交叉引用分析,第一批 + +- **时间段**:2026-10-16(单日)。 +- **动机**:RuntimeViewer 要做交叉引用(调用者、被调、类型引用),它的提案 0056-cross-references 把分析逻辑定在本库。那份提案的落地第一步先实测了前提:进程内能读没加载的缓存镜像;手写解码扫完整个 macOS 27.2 缓存只要 1–4 秒,比 Capstone 快 25–50 倍;macOS 27 / iOS 27 的缓存把镜像自带的桩收成了全缓存共用的一份。用户批准本库的精简提案(「可以,开始第一批」)后动手。 +- **关键决策**: + - ① 新 target `CrossReferenceAnalysis`:只读进程内的 `MachOImage`,只认 arm64 / arm64e,手写解码、不用 Capstone。 + - ② API 由宿主持有的 `CrossReferenceAnalyzer` 提供,它是进程镜像的快照(整个共享缓存加缓存外已加载的镜像);位置一律用 `CodeLocation`(镜像序号加未滑动地址),因为缓存外两个镜像的未滑动地址可能重合。提案草图原是一组接收 `MachOImage` 的静态函数,跨镜像解析目标要整张镜像表,所以改了。 + - ③ 跳板形状(GOT 桩、stub island、全缓存共用的 selector 桩)抽成新 target `ARM64InstructionDecoding` 的 `ARM64Trampoline`,SwiftThunkAnalysis 的 `MachOThunkEnvironment` 改用它,行为不变(用户选择共用,否了另写一份)。 + - ④ 没名字的函数照样扫描:缓存里一半函数没有符号,它们发出的调用约占一半。 + - ⑤ 不加全局的按镜像缓存:分析器在自己的生命周期内记住函数表,引用表是值,宿主按 `approximateByteCount` 自己管。 +- **落地模块**:`ARM64InstructionDecoding`(新,Support 层)、`CrossReferenceAnalysis`(新,Analysis 层,public product)、`SwiftThunkAnalysis`(`MachOThunkEnvironment` 的两个跳板读取)、`Package.swift`。测试:新 `CrossReferenceAnalysisTests`。 +- **实现中的两处修正**:整镜像扫描起初也记住函数表,扫完一遍 macOS 27.2 缓存常驻 1.5 GB,改为临时建表;整表并发扫描的峰值又让分配器留下 1.2 GB 脏页(活对象只有一两 MB),新增只留命中引用的 `references(to:inImageAt:)`,同样扫完全缓存后约 170 MB。另曾为懒绑定加过一处退回导入名的防护,探针实测 dyld 加载时就绑好槽,防护是死代码,撤掉后留哨兵测试。 +- **验证**:JHs-Mac-Studio-Ultra(macOS 27.2、Xcode 27.2、Swift 6.4.2),新 scratch,依赖全部从远端解析,fixture 链主检出现编的那份(`Tests/Projects` 无改动)。`CrossReferenceAnalysisTests` 20 个测试通过,其中 `callSitesMatchCapstone` 抽样 400 个 AppKit 函数与 Capstone 逐条对照调用与跳出函数的跳转,`wholeImageScansKeepNoFunctionTable` 改前红、改后绿。`SwiftThunkAnalysisTests` 82 个通过,含经 stub island 解析的离线 iOS 缓存测试。全量 `swift test --skip IntegrationTests` 跑了两次:改跳板识别后 2,458 个测试 / 471 个套件,最终代码 2,462 个 / 473 个,原始退出码都是 0,跳过的只有 3 个默认关闭的研究探针。release 基准:建分析器 0.02 秒,每个镜像都建整表 28 核 1.6–1.8 秒、4 线程 5.9 秒,`init` 的调用者(预筛出 2,759 个镜像)28 核 1.5 秒。渲染 A/B 未跑:这批不碰 demangle、打印、索引与读取栈,只换了 thunk 分析认跳板的实现,由它的测试覆盖。 +- **接入时的修补**:RuntimeViewer 第 3 步查 `-[NSObject description]` 的调用者一条都没有,追到缓存里的传统 `objc_msgSend` 发送——缓存构建器把读 selector 引用改写成了 `adrp` / `add` 出字符串地址,第一批没认,这些发送全被当成对 `objc_msgSend` 的普通调用。补认这种形态(回归测试改前红、改后绿),并补上预筛「不漏」的抽样测试(此前只测了「筛得够狠」)。另加 `functions(containing:)`,给一批结果起名不留函数表。 +- **关联文档**:[0072-cross-reference-analysis](../Evolutions/0072-cross-reference-analysis.md)、[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)、[Glossary.md](../Glossary.md)「cache-shared stub」、RuntimeViewer 的 [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)。 +- **对应版本**:0.24.0。 + +## 102. 交叉引用分析,第二批:起名、类引用、Swift 类型引用与宿主预读 + +- **时间段**:2026-10-17 – 2026-10-18;2026-10-19 合入 next,提案编号 0072。 +- **动机**:第一批只认符号表里的名字,而 macOS 27.2 缓存里一半函数起点没有符号;类型引用也还没有。动手前两个只读探针实测了起名来源、类引用与按 mangled 名字实例化在 27.2 上的真实形态,第二批据此重定(见提案「第二批的设计」)。 +- **① 起名(已落地)**:符号表之后依次取导出表、ObjC 方法表、Swift 元数据(访问器、singleton 完成函数、带 `Tq` 的虚表实现),起名时按镜像按需读,扫描不读。导出表一项就给全缓存 140 万个无名起点起了名。`CodeFunction.Name.swiftMethod` 换成 `.swiftMetadata(mangledName:)`。 +- **寄存器跟踪的汇合点(已修)**:第一批按指令顺序读,汇合处沿用最后一条路径的值(`-[NSString stringByAppendingString:]` 的 `copyWithZone:` 接收者被说成 `self`)。改为状态沿着分支走:快照随前向分支带到目标处,汇合处取交集,循环头忘掉调用方保存的寄存器。快照是 `SIMD32` 定长值,release 下整表扫描开销约 10–20%。 +- **② ObjC 类引用(已落地)**:一个值是不是类对象,看它所在的镜像列没列它(直接读 `__objc_classlist` 与 `isa`);取类地址的指令记为 `.reference` 种类的引用,目标带类对象的位置(全缓存 1.9 万个类名不止一个镜像定义,多是 Mac Catalyst 变体)。类字面量接收者经 `objc_opt_self` 也认得;super 发送的类取同一函数里 `__objc_superrefs` 的载入,分类方法、无符号的方法都对,Swift 的不记。类预筛认定义镜像在类与元类地址上的全部符号:4% 的跨镜像引用走 `__NSConcreteStackBlock` 这类别名。类索引起初经 `MachOImage.objc.classes64` 建,让整表扫描慢了一倍,改为直接读;最终整表扫描 +17%。 +- **③ Swift 类型引用(已落地)**:三种来源——调用元数据访问器、取访问器或值类型元数据的地址、按 mangled 名字实例化(27.2 上是 V2:名字在 `x1` 指向的 `{偏移, 长度}` 记录里)。表按描述符位置归档;类型查询比描述符位置与名字里的符号引用,只有标准库与导入的类型才解开名字——其他类型在名字里一定是符号引用,四个镜像逐个核对过。key 取自 `…Mn` 符号,描述符上下文拼出的 key 在受约束扩展与扩展里的 private 类型上会偏。性能:整表 2.1 → 3.0 秒;途中参数里修改扫描器的写法让 Swift 每次复制整个扫描器,一度 95 秒。协议的类型引用不在这一批。 +- **预筛的 Swift 缺陷(已修)**:缓存 4,113 个镜像只有 245 个留着 Swift 未定义符号,第一批按导入符号的函数预筛对 Swift 函数会丢掉其余镜像里的跨库调用者(只用 C 函数测过)。Swift 符号改按链接关系(直接链接或经再导出)预筛,新增 `imageIndices(linkingImageAt:among:)`、`imageIndices(callingFunctionAt:symbolNames:among:)`;RuntimeViewer 查调用者要改用后者。 +- **审查与修复(10-17)**:两批全部提交审一轮([审查记录](../../Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md),不修或暂缓的登记在 [ReviewAdjudications](ReviewAdjudications.md) A62–A68)。修了:寄存器跟踪漏作废的写入(变址读写的基址、原子指令、成对寄存器、SVE / SME 里写通用寄存器的指令等,判断改成纯函数 `RegisterFile.registersWritten(by:)`,SwiftThunkAnalysis 的两个跟踪器同修);预筛连同别的镜像改名再导出的名字一起比(缓存 12 个镜像 1,438 条,新增 `reexportedNames(ofSymbolsNamed:inImageAt:)`);缓存外镜像取 dyld 的加载路径,安装名另建一张表;类型查询的 demangle 不再驻留。循环头与跳转表落点保留 `x19`–`x28`(A5)量过:错 0.02%–0.04% 的引用,精确做法多花 35%–60% 的扫描时间,用户定为已知局限(A68)。 +- **④ 宿主预先准备(10-18)**:`CodeReferenceIndex`(`referenceIndex(ofImageAt:)`)按目标分组、名字只存一份、偏移存 32 位,只留查调用者与类型引用会读的引用,AppKit 21 MiB 对整表 67 MiB,回答与过滤扫描逐条相同。第一次查询还要现读的几样也交给宿主提前读:`prepareNames(inImageAt:)`(AppKit 0.29 秒的三个起名来源、类名与类型符号)、`preparePrefilters()`(链接关系与改名再导出表,只用调用线程),`approximateByteCount(ofImageDataAt:)` 计入宿主的预算,`releaseImageData(exceptForImagesAt:)` 只放掉别的镜像的。能不读的不读:按 key 找类型只算同名类型的 key,判断导出与否在导出表里按名字查。验证:`CodeReferenceIndexTests` 6 个、`PreparedImageDataTests` 5 个、`SwiftTypeReferenceTests` 新增 4 个。 +- **关联文档**:[0072-cross-reference-analysis](../Evolutions/0072-cross-reference-analysis.md)、[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)、RuntimeViewer 的 [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)。 +- **对应版本**:0.24.0。 + +## 103. builtin 叶子布局以二进制为准 + +- **时间段**:2026-10-20(单日),分支 `fix/builtin-leaf-layouts`,当天合入 `next`。 +- **动机**:核对 `KnownLayoutTable` 的数值在 libswiftCore 的 `__swift5_builtin` 段里有没有。实读 macOS 26.7 的 libswiftCore:段里没有 `Swift.Int` 这类条目,只有 58 条 `Builtin.*` 叶子记录和少数不透明类型;冻结表的每个值都能沿 libswiftCore 的字段记录推到这些叶子,数值一致。核对时发现引擎从来没用上这些叶子记录,兜底表还有错值和缺项。 +- **关键决策**: + - ① 不在运行时改成「能访问依赖闭包就优先用计算结果」。表里的类型都是 `@frozen`,64 位 Apple 平台上算出来只会和表一样;改了不会更准,反而要先修叶子问题(否则 `Bool` 立刻变成 XI 0)、每个镜像都要把排在 libswiftCore 前面的依赖全部索引一遍,回退条件也得改成「算不出就回退」。用户批准改为:冻结表照旧先查,把「表与二进制一致」写成测试,同时修叶子记录与兜底表。 + - ② `BuiltinTypeLayoutIndex` 给 `Builtin.*` 记录按 builtin 名(`Builtin.Int1`)建 key。6 月那次修复按 demangle 出的限定名建 key,只照顾了 nominal 记录,叶子记录落回裸 mangling(`Bi1_`),求解器按 `Builtin.Int1` 查,从第一版起就没命中过。 + - ③ 兜底表对齐二进制与 IRGen:`Builtin.Int1` 的 XI 从 0 改为 254;`Builtin.RawUnsafeContinuation` 从 XI 1 改为饱和(IRGen 把它当成不为 null、避开低 4 GiB 的 aligned pointer);补上 `FPIEEE16`、`Job`(同上一类)、`Executor`(两个字,16 字节)、`NonDefaultDistributedActorStorage`(与 default actor 一样 12 个字)。只补字段里真会出现、又没有记录的叶子:`IntLiteral`、`Vec*`、`UnsafeValueBuffer` 只出现在 libswiftCore 的字段里,由记录回答;`ImplicitActor` 不会是存储属性的类型。 +- **落地模块**:SwiftLayout(`BuiltinTypeLayoutIndex`、`StaticTypeLayoutResolver` 的 `builtinPrimitiveLayout`、`KnownLayoutTable` 的文档注释);测试新增 `StandardLibraryLeafLayoutTests`,并加进 CI 的套件过滤列表。 +- **输出变化**:离线 dump / interface 的布局注释里,`Float16`、`StaticBigInt` 字段与 SIMD 存储类型的 `Builtin.Vec*` 字段不再是 unknown;`_Concurrency` 的 `UnownedJob`、`UnownedSerialExecutor` 能算出来;以 `UnsafeContinuation` 为 payload、带两个以上 empty case 的 enum 不再多一个 tag byte;带自定义 executor 的 distributed actor 的字段偏移能算出来;dump libswiftCore 本身时 `Builtin.Int1` 字段的 XI 从 0 变成 254。冻结表的数值没有变。 +- **验证**: + - 新套件在修复前 25 处断言失败(原始退出码 1),修复后 6 个测试、25 个用例全部通过(退出码 0)。冻结表的一致性检查在修复前只有 `Swift.Bool` 一项对不上(XI 0 对 254),其余各项本来就与 libswiftCore 的元数据一致。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,macOS 26.7,依赖全部从远端解析):2532 个测试 / 485 个套件,7 处失败,都与本批无关——本机既有的两条 `MultiPayloadEnumDescriptorCacheTests`;`FallbackNamingTests` 与 `SwiftTypeReferenceTests` 共 4 处,它们按 macOS 27.2 缓存挑的镜像在 26.7 上不存在,且 CrossReferenceAnalysis 不依赖 SwiftLayout;`SharedCacheResolveSwiftConcurrencyTests` 的计时断言 1 处,单独重跑通过。 + - 用 0.23.0 的 CLI 与本分支的 CLI dump 宿主缓存里的 libswiftCore 与 libswift_Concurrency(`--emit-type-layout`),逐条比对布局注释:变化全部落在 builtin 叶子字段上——libswiftCore 多出 80 条注释、libswift_Concurrency 多出 6 条,数值改变的只有 `Bool._value`、`UnsafeContinuation.context` 与包着它的 `AsyncThrowingStream._Storage.State.continuation`。 + - 渲染 A/B 未跑:这批只改 SwiftLayout 的叶子布局,不碰 demangle、打印、索引与读取栈。 +- **关联文档**:[StaticLayoutEngine.md](StaticLayoutEngine.md)「叶子 XI 精确建模」与 builtin 记录的两条实测发现、[Modules/SwiftLayout.md](Modules/SwiftLayout.md)「已知布局表与 builtin 段」。 +- **对应版本**:0.24.0。 + +## 104. 协议约束可选写在各自的关联类型上 + +- **时间段**:2026-10-20 至 2026-10-21,分支 `feature/protocol-requirement-placement`(PR #135),2026-10-21 合入 `next`。 +- **动机**:二进制只记录协议规范化之后的 requirement signature,看不出源码把一条约束写在协议的 `where` 子句还是 `associatedtype` 上,两种写法编译出来完全一样。interface 一直把约束全部集中在协议头的 `where` 子句里,编译器写 `.swiftinterface` 时则挂在各自的关联类型上(`associatedtype Failure: Swift.Error`)。用户要求能在两种写法之间选,前提是两种写法语义完全相同。 +- **关键决策**: + - ① 继承子句只收主语恰好是 `Self.X` 的 conformance / superclass / layout 约束。这三类约束只看主语:主语是从 `X` 起头的成员链(`Self.X.Y`)时,原样写进 `associatedtype X` 的 `where` 子句;主语与本协议的关联类型无关时留在协议的 `where` 子句,即使父类的泛型实参提到了本协议的关联类型(`Sequence` 的细化协议里 `Self.Element: GenericBase` 不挪到 `First`)。same-type 约束两边都看,优先取恰好是 `Self.X` 的一边,其次左边成员链的根,再次右边类型里第一条从本协议关联类型起头的链。只涉及继承来的关联类型的约束,以及 inverse、same-shape 约束,留在协议的 `where` 子句。不照抄编译器:用 Swift 6.3.3 的 `-emit-module-interface` 实测,它把递归协议的 `Self.Child.Leaf: Hashable` 印成 `associatedtype Leaf : Swift.Hashable`,约束变成了更强的 `Self.Leaf: Hashable`。 + - ② 默认保持集中写法,只接 interface(`SwiftDeclarationPrintConfiguration.protocolRequirementPlacement`、`InterfaceRequest.protocolRequirementPlacement`、`interface --requirements-on-associated-types`)。dump 不接;diff / evolution 的协议头固定集中写法,因为它们的 `associatedtype` 行不带约束。 + - ③ 调研时发现,现有输出把约束右侧的复合类型压扁成另一条约束(`Self.Second == [Self.First]` 印成 `Self.Second == Self.First`,`[Self]` 印成 `[A]`),dump 与 interface 都受影响,自 2025-08-21 写下就是这样。单独一个提交修掉:类型参数照旧拼写,其余类型整个交给 resolver,打印前把泛型参数换成两个打印器都拼作 `Self` 的 `.constrainedExistentialSelf`,并去掉成员的协议限定。 + - ④ 语义由往返测试保证:两种写法印出的协议各自重新编译,读回 requirement signature 与原二进制逐条比对;比对基准用通用的 requirement dump,不经被测的协议打印。 +- **落地模块**:SwiftDeclarationRendering(`Node+ProtocolSelf.swift`、`dumpProtocolMangledName`、`dumpProtocolContent(resolver:in:)`)、SwiftPrinting(`ProtocolRequirementPlacement`、`ProtocolRequirementPartition`、协议头与关联类型行)、SwiftInterface(diff 的协议头)、SwiftSectionKit、swift-section、agent 插件的 CLI skill。测试新增现场编译的 `ProtocolRequirementPlacementFixture`、`ProtocolRequirementPlacementInterfaceTests`、`ProtocolRequirementRightHandSideDumpTests`(两个套件加进 CI 的过滤名单),Swift 6.4 fixture 新增 `ConstrainedSuppressedElementContainer`。 +- **输出变化**:默认写法下只有右侧是复合类型的协议约束变了,从错的变成对的。用改动前的 CLI(10/19 的 next)与本分支的 CLI 生成宿主缓存里五个镜像的 interface 逐字节对比:libswiftCore、Combine、libswift_Concurrency、Foundation 完全相同;SwiftUICore 只有一行不同,正是这个 bug 的真实命中——`AccessibilityOptionalPropertiesKey` 的 `Self.PropertyValue == Self.NonOptionalPropertyValue?` 原先漏了 `?`,读成两个类型相同。新写法只在开关打开时出现,与编译器的写法一致;唯一不同是成员链里套着本协议关联类型的约束挂在链的根上:`Collection` 的 `Self.Indices.Index == Self.SubSequence.Index` 挂在 `Indices` 上,编译器挂在 `Index` 上,两者语义相同。 +- **验证**: + - 新套件全部通过。两次临时变异检查都按预期变红(退出码 1):退回旧的压扁写法后,复合类型的 12 处断言(dump、interface 各 6 处)、`CompositeRequirements` 的期望文本和两种写法的往返测试全部失败,印出的协议根本编译不过;照抄编译器、把 `Self.Child.Leaf: Hashable` 放进 `Leaf` 的继承子句后,能编译通过,但 `.associatedTypes` 写法的往返测试因读回的约束集合不同而失败。 + - 三个实现提交各自检出后都构建通过,对应套件通过。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,macOS 26.7,Xcode 27.0 / Swift 6.4):2348 个测试 / 452 个套件跑完,6 处失败都是本机已知的红——两条 `MultiPayloadEnumDescriptorCacheTests`;`FallbackNamingTests` 与 `SwiftTypeReferenceTests` 共 4 处(按 macOS 27.2 缓存挑的镜像在 26.7 上不存在)。另有 `SwiftPrintingTests`、`SwiftSpecializationTests` 两个 bundle 以 SIGSEGV 退出:崩在 `GenericSpecializationTestingEnvironment` 对进程内 SymbolTestsCore 镜像做 `SwiftDeclarationIndexer.prepare()` 时(`ProtocolConformance.init` 经间接指针读到空地址),基线 `7d181357` 在同一工具链下同样崩溃,与本批无关;排除用到这个环境的 6 个套件后,两个 bundle 其余 93 个测试通过。 + - 构建与测试是离线做的:当天 github.com 连不上,新 scratch 解析不了依赖,于是拷用本机另一个 scratch 已下载的依赖仓库和同一份 `Package.resolved`(35 个包,全部是远端发布版)。这份解析只在 Swift 6.4 下一致,所以当时没有在 CI 的 Xcode 26.6 上跑,review 时补跑了,见下面最后一条。 + - 渲染 A/B 没有按完整流程跑(这批不是大重构),改为上面五个宿主镜像的 interface 逐字节对比。 + - code review(2026-10-21,`/code-review high`,8 条发现):只有第 1 条要改。`ProtocolRequirementPlacement.associatedTypes` 的文档注释和本节的关键决策 ① 把规则说宽了,实现本身与提案、编译器一致。两处改了措辞(PR 描述同改),fixture 加 `SubjectOnlyRequirements`,用测试钉住「conformance / superclass / layout 约束只看主语」:Swift 6.3.3 的 `-emit-module-interface` 对同一源码也把这条约束留在协议头上;在沙盒里临时让 superclass 约束也看右侧(旧措辞的说法),只有这条新用例变红,往返测试照样通过。其余 7 条登记在 [ReviewAdjudications.md](ReviewAdjudications.md) A69–A75。用 CI 的工具链(Xcode 26.6 / Swift 6.3.3,依赖从远端重新解析)在 PR 头和修正后各跑一次两个新套件与 `DumpAndInterfaceRequestTests`、`CommandRequestMappingTests`:都是 45 个测试全部通过,退出码 0,只跑了 debug。修正只动了测试和一段文档注释,全量测试没有重跑。 +- **关联文档**:提案 [0073-protocol-requirement-placement](../Evolutions/0073-protocol-requirement-placement.md);review 记录 [2026-10-21-pr135-review-findings](../../Roadmaps/2026-10-21-pr135-review-findings.md)。 +- **对应版本**:0.24.0。 + +## 105. dump 与 interface 标出私有声明来自哪个源文件 + +- **时间段**:2026-10-25 至 2026-10-26,分支 `feature/private-declaration-source-files`,2026-10-26 直接合入 `next`(没有开 PR)。 +- **动机**:0063 把「反推 private discriminator 来自哪个源文件」搬进了本库(`SwiftPrivateDiscriminators`),但只有 RuntimeViewer 的 `Private` 标签在用。`swift-section dump` 只印 discriminator 原文,interface 连它也不印:SymbolTestsCore 里两个文件各声明的 `private struct PrivateDoppelganger`,在 interface 里印出来一模一样。 +- **关键决策**: + - ① 新开关 `--emit-private-source-files`,两个子命令同名,请求字段 `emitsPrivateDeclarationSourceFiles`,默认关闭。 + - ② 声明上方加一行注释(`// CodingKeys is declared in Codable.swift`),两条输出用同一套写法(`SwiftDeclarationRendering` 的 `PrivateDeclarationSourceFileComments`);哈希用的模块与声明打印的模块不同时写出模块,还原不出的附上 discriminator。只标外层没有的 discriminator:私有类型的成员和嵌套类型不重复,公开类型的私有成员标出自己的文件。interface 里嵌套定义的外层是它的父定义,与打印层级无关,因为 `marksNestedDefinitions` 要求单独打印与从父定义里摘出来的逐字相同。 + - ③ 打印前对整个镜像批量反推一次(`recoverSourceFiles(ofEveryDeclarationIn:)`),名字、成员符号、全局声明里的 discriminator 一起搜;逐个声明去问的话,每个还原不出的都要把五步候选全部算一遍。候选不变。 + - ④ 接缝放在 `SwiftDeclarationRendering`(`PrivateDeclarationSourceFileProviding` 与新的结果类型 `PrivateDeclarationSourceFile`),index 遵循它。搜索的结果类型没有挪下来,因为 RuntimeViewerCore 开了 `MemberImportVisibility`。 + - ⑤ dump 本来没有索引器,打开开关时另建一个只为读名字,并留到 dump 结束:它最后一次释放会回收自己建的缓存,其中有 dump 读成员的符号索引。 +- **落地模块**:SwiftDeclarationRendering、SwiftPrivateDiscriminators、SwiftDump(各 dumper)、SwiftPrinting(打印器)、SwiftInterface(全局块)、SwiftSectionKit、swift-section、README 与 agent 插件的 CLI skill。 +- **输出变化**:关闭时逐字节不变。打开后只多注释行,interface 另多一条进度提示,照它的老规矩走 stdout。本机 macOS 27.2 的 cache、release CLI: + + | 镜像 | dump 关 → 开 | interface 关 → 开 | 名字里的 discriminator | 还原不出 | + |---|---|---|---|---| + | Foundation | 3.9 → 8.6 秒 | 9.1 → 9.7 秒 | 142 | 20 | + | SwiftUICore | 8.2 → 25.5 秒 | 12.6 → 27.7 秒 | 553 | 58 | + | SwiftUI | 11.8 → 58.1 秒 | 19.9 → 61.0 秒 | 840 | 167 | + + 多出的时间几乎全在搜还原不出的那些:第 3、5 步按 discriminator 各算一遍。 +- **验证**: + - 新套件全部通过:`PrivateDeclarationSourceFileCommentsTests`(写法与该标哪些)、`PrivateDeclarationSourceFileRequestTests`(两条输出端到端,SymbolTestsCore 加 `LocalTypeFixture`)、`PrivateDiscriminatorSourceFileIndexTests` 新增的两条(批量入口、provider),`NestedDefinitionRegionContractTests` 新增打开注释的变体(两种读取路径),`CommandRequestMappingTests` 的两个 flag。两个新套件加进了 CI 的过滤名单。 + - 每个实现提交各自构建通过、对应套件通过;`SwiftDumpTests`(105)、`SwiftInterfaceTests` 与 `SwiftPrintingTests`(357)的快照基线一个都没改。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,macOS 27.2,默认的 Xcode 27 / Swift 6.4,远端依赖,fixture 链主检出那份 Xcode 26.x 编的):22 个测试包、2565 个测试全部通过,原始退出码 0。 + - 渲染 A/B(开关关闭):基线是 `next@122cfd2f` 的 `git archive` 沙盒,两侧共用一份 `Package.resolved`、各编一个 release CLI;存档 cache 26.6、15.5 与 iOS 15.5 / 18.5 / 26.5 模拟器 runtime,54 对 dump / interface 全部逐字节一致。进程内(MachOImage)那条腿没跑,理由在提案的决策日志里。 + - 插件:`claude-isolated plugin validate` 对插件目录与 marketplace(`--strict`)都通过;skill 里提到的每个 flag 都能在各子命令的 `--help` 里找到。Codex 的 `validate_plugin.py` 本机没有,没跑;插件清单没改,只改了 skill 正文。 + - 开发中自查出一处:interface 起先只在嵌套打印时排除父定义的 discriminator,违反 `marksNestedDefinitions` 的契约,已改为任何层级都比父定义(见提案决策日志)。 +- **关联文档**:提案 [0074-private-declaration-source-files](../Evolutions/0074-private-declaration-source-files.md);[Modules/SwiftPrivateDiscriminators.md](Modules/SwiftPrivateDiscriminators.md)。 +- **对应版本**:0.24.0。 + +## 106. 包装类型读取器的识别 + +- **时间段**:2026-10-13 至 2026-10-26,分支 `fix/wrapped-reader-recognition`,2026-10-26 直接合入 `next`(没有开 PR);MachOKitExtensions 同日发 1.3.0。 +- **动机**:MachOKitUI 把 `MachOImage` / `MachOFile` 包成 `MachOImageSource` / `MachOFileSource` 交给本库,在 MachOViewer 里查看已加载镜像的 Swift section 时进程崩溃:`Fatal error: Negative value is not representable`(`SymbolicDemangler`,0.22.0 第 320 行)。本库判断读取器种类时写死了具体类型(next 上 16 个文件共 38 处,加上 MachOKitExtensions 的 `asMachOImage`),包装类型一处都走不进对应的路径。崩溃的那处把落在更低地址镜像里的 opaque type descriptor 存成负偏移再转 `UInt64`;其余各处不崩,结果却悄悄变差:符号按原值入索引、成员地址从 shared region 起点算、三个 ObjC 索引为空,不转发 bind / rebase 的文件包装还会让 interface 读到未解析的 chained fixup 原值而段错误。 +- **关键决策**: + - 接口放 MachOKitExtensions 1.3.0:泛型协议 `MachOReaderWrapper`(`associatedtype Base`、`var base`)加三个取法:`underlyingReader`、`asMachOImage`(放宽为看穿包装)、`asMachOFile`(新增)。先后否决两种设计:按具体类型各开一个协议(`MachOImageBacked` / `MachOFileBacked`),以及 `MachORepresentableWithCache` 上的封闭枚举 `MachOReaderKind`。两者都把库认识的读取器写进了扩展点,用户自定义一个读取器类型就得改库,违反开闭原则。 + - 38 处写死的判断改走三个取法。另外三处同样认不出包装:`objcImplementationClassReader` / `swiftSectionReader` 改为退到 `underlyingReader`;`FieldLayoutRenderable` 对包装类型给默认实现(七个静态 witness 转给 `Base`),包装写一个空遵循即可进打印器;`DependentMemberProjection` 去掉会丢掉包装结果的 `as? MachO` 回转。`bindRebaseResolver` 先问读取器自己,再问 `underlyingReader`。 + - `SymbolicDemangler` 的 opaque 节点值由 `context.runtimePointer(at:)` 决定:能给出本进程指针就存绝对地址,否则存偏移;读节点值的两处用同一个判据。偏移转不成 `UInt64` 时这个引用当作解析不了,不再 trap。 + - 按类型静态约束的 API(`GenericSpecializer`、`DependencyClosure`、`ImageUniverse+DependencyClosure`)不动,持有包装类型的宿主自己传 `base`。 + - `AGENTS.md` 加一条规则:判断读取器种类只用三个取法、不写类型转换;`ReaderKindCastScanTests` 扫描 `Sources/`(`TestSupport` 除外)防止写死的转换回来。 + - 合并前核查发现 `WrappedReaderDemanglingTests` 依赖宿主的 cache 布局:「至少一个引用落在 SwiftUI 下方」只在 SwiftUICore 映射在 SwiftUI 下方时成立,这是 macOS 27 起的布局,macOS 15 与 26 都放在上方(26.6 上 SwiftUICore 在 `0x22d953000`,SwiftUI 在 `0x1b594e000`)。于是拆开:「声明的包装与镜像逐节点相同」在任何宿主上跑,只要求至少出现一个 opaque 引用;落在下方的引用改作「不声明的包装不 trap」那条的前提,按已加载 cache 的镜像表判断布局,只在 SwiftUICore 位于下方时启用。`ReaderKindCastScanTests` 与 `WrappedReaderInterfaceTests` 只读源码和 fixture,进 CI 名单;另两个套件读系统 cache 或把 SwiftUI 加载进进程,留在本地。 +- **落地模块**:MachOReading(`MachOContext`)、MachOSymbols(`SymbolIndexStore`、`SymbolValueOffsetConverter`、`MachO+Symbol`)、SwiftInspection、SwiftLayout(`ImageReference`)、SwiftThunkAnalysis(`ObjCMethodThunkReferences`)、SwiftIndexing、SwiftDeclarationRendering、SwiftPrinting(`InterfaceHeader`)、MachOTestingSupport(`ForwardingMachOReader`);MachOKitExtensions(`MachOReaderWrapper.swift`)。 +- **验证**: + - 新测试,修复前都确认是红的:`WrappedReaderDemanglingTests`(子进程 SIGTRAP → 通过)、`WrappedReaderInterfaceTests`(测试进程 SIGSEGV → 包装与裸读取器的 interface 逐字节相同)、`WrappedReaderSymbolTests`(272 + 1 + 3 处失败 → 通过)、`ReaderKindCastScanTests`(列出 38 处 → 通过)。MachOKitExtensions 自己的 23 个测试全过。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Xcode 27 默认工具链,`USING_LOCAL_DEPENDENCIES=1`;本机 swift-demangling 与 MachOObjCSection 的 `next` 落后远端,沙盒里用各自远端 `next` 的导出副本):2400 余个测试,原始退出码 0,但 `Arm64eSignedVWTPointer` 的 strip 探针红了一条;同一构建单独重跑 3/3 通过、基线也通过,与本次改动无交集,按偶发处理。 + - 渲染 A/B(基线为 next `956b4e09` 加 MachOKitExtensions 1.2.0):**96 对全部逐字节一致**——归档 cache 15.5 与 26.6 各 12 对,iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器 48 对,MachOImage 腿 24 对。 + - 落地验证,在把 `next@7adbe83c` 合进功能分支后的最终 tree 上跑(JHs-Mac-Studio-Ultra,macOS 27.2,Xcode 26.6,只走远端依赖、MachOKitExtensions 1.3.0,fixture 按 CI 的方式 ad-hoc 签名):全量 `swift test --skip IntegrationTests` 2574 个测试 / 493 个套件全部通过,原始退出码 0,`WrappedReaderDemanglingTests` 的两条都跑了。渲染 A/B 的基线是 `next@7adbe83c`,两侧依赖只有 MachOKitExtensions 不同(1.2.0 对 1.3.0):**96 对全部逐字节一致**,各腿对数同上,MachOImage 腿是 macOS 27.2 的进程内镜像。 +- **关联文档**:提案 [0075-wrapped-reader-recognition](../Evolutions/0075-wrapped-reader-recognition.md)、[ReadingContextAbstraction.md](ReadingContextAbstraction.md)「包装类型读取器」一节、术语表 [reader wrapper](../Glossary.md)、`AGENTS.md` 新增的读取器种类规则。 +- **对应版本**:0.24.0。0.23.0 发版时它还在等 MachOKitExtensions 1.3.0,没有跟上。依赖下限:MachOKitExtensions 1.3.0(2026-10-26 已发版)。下游:MachOKitUI 升级后给两个包装类型各加一行 `MachOReaderWrapper` 遵循,并删掉 `demangleTypeNode` 里的特判。 + +## 107. 0.24.0 发版 + +- **时间段**:2026-10-25 至 2026-10-26。 +- **动机**:用户要求审核 `next` 是否适合发版,看过审核结论后批准按建议发 0.24.0。自 0.23.0 以来 `next` 多了第 99–106 节的工作:borrow / mutate 访问器与关联类型上的 `~Copyable`、swift-capstone 7、交叉引用分析、builtin 叶子布局、协议约束的写法、私有声明的源文件注释,以及包装类型读取器的识别。审核期间 `next` 又合入第 105、106 节,验证随之补到最终代码上。 +- **关键决策**: + - **① 废弃的读取接口再推迟到 0.25.0**(用户按建议批准)。MachOKitUI 的 `main`(`from: "0.19.0"`,会自动解析到 0.24.0)与 swift-decompiler 的 `main`(跟本库 `next`)都还在调用,这一版删除会让它们下次解析时编不过。AGENTS.md、术语表、`ReadingContextAbstraction.md` 与文档索引改成 0.25.0,0057 的决策日志补记,Changelog 的 Breaking 写明新期限。 + - **② evolution「看不见的版本」不进这一版**(用户按建议批准)。提案在 `next` 上是 Accepted,实现留在 `feature/evolution-unobservable-presence`;合进来会带来快照格式 8,要在合并结果上重新验证。 + - **③ 包装类型读取器的修复赶上了这一版**:MachOKitExtensions 1.3.0 在审核期间发版,第 106 节随之合入,依赖下限抬到 1.3.0。 + - **④ Changelog 1,563 字符**,一句话一条,比普通版本 1,500 的预算多 63 个:三条破坏性变化(`AccessorKind` 的两个新 case、废弃期限顺延、swift-capstone 7.0.0 与 MachOKitExtensions 1.3.0 的下限)和五项新接口。 + - **⑤ 更正 README 与 AGENTS.md 的工具链要求**:`swift-tools-version` 自 0.22.0 起就是 6.3(`26c9012f`),两处一直写 Swift 6.2 / Xcode 26.0,改为 Swift 6.3 / Xcode 26.4。README 说 `MetadataReader` 别名只保留一个版本,四个版本后它还在,去掉了这个期限。 + - **⑥ 版本号**:`Version.swift`、两个 `plugin.json` 改为 0.24.0,README 的安装示例同步,product 表补上 `CrossReferenceAnalysis` 和 0.23.0 起就漏掉的 `SwiftPrivateDiscriminators`;插件 skill 把 `interface --requirements-on-associated-types` 与 `--emit-private-source-files` 标为 0.24.0 起。 +- **落地模块**:`Sources/Executables/swift-section/Version.swift`、`AgentPlugins/swift-section/`(两个 `plugin.json`、skill)、`Changelogs/0.24.0.md`、`README.md`、`AGENTS.md`、本账本(第 99–106 节的对应版本、本节),以及术语表、`ReadingContextAbstraction.md`、文档索引与 0057(废弃期限)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上做,Xcode 26.6,只走远端依赖,源码是 `git archive` 导出的干净副本,scratch 是新的。 + - 审核起点 `24c39555`:全量 `swift test --skip IntegrationTests` 2541 个测试 / 487 个套件,原始退出码 0,fixture 按 CI 的方式 ad-hoc 签名现编;照 `release.yml` 的 x86_64 与 arm64 release 构建都是 0 warning。渲染 A/B 以 0.23.0 为基线(`--skip-image-part`):72 对里 18 对不同,外加手动比的 macOS 27.2 SwiftUI / SwiftUICore 4 对,差异全部是第 104 节修掉的三个协议头(`AccessibilityOptionalPropertiesKey` 与 `AccessibilityOptionalPropertyKey` 的 `?`、`PlatformViewRepresentable` 的 ``、`SliderTickContent` 的 `SliderTick`)。 + - 最终代码 `ecd7a521`:第 106 节落地时在同一 tree 上跑过全量,2574 个测试 / 493 个套件通过,A/B `7adbe83c` → `ecd7a521` 96 对一致(含 MachOImage 腿)。本节补跑了照 `release.yml` 的双架构 release 构建,编译 warning 为 0,两个二进制都能运行;又跑了 A/B `24c39555` → `ecd7a521`,72 对全部逐字节一致。依赖解析到 MachOKit 0.54.101、MachOKitExtensions 1.3.0、MachOObjCSection 0.8.200、swift-demangling 0.7.2、swift-semantic-string 0.5.0、swift-capstone 7.0.0、capstone 6.0.101、swift-objc-dump 0.8.101。 + - 发版提交:arm64 release 构建的 `--version` 输出 0.24.0;skill 写到的每个 flag 都在各子命令的 `--help` 里;`claude-isolated plugin validate` 对插件目录与 marketplace(`--strict`)都通过。 + - 本机没有 `release.yml` 用的 Xcode 26.4,以 26.6 代替。 +- **关联文档**:[Changelogs/0.24.0.md](../../Changelogs/0.24.0.md)。 +- **对应版本**:0.24.0。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ReadingContextAbstraction.md b/Documentations/Internal/ReadingContextAbstraction.md index 083824c4b..299519182 100644 --- a/Documentations/Internal/ReadingContextAbstraction.md +++ b/Documentations/Internal/ReadingContextAbstraction.md @@ -159,7 +159,7 @@ extension RelativeDirectPointerProtocol { ## Usage Examples -Since the single-implementation pass (below, 2026-09-30) the `ReadingContext` form is the only one to call. The Mach-O form (`in: machO`) and the pointer form (no reader argument) are deprecated forwarders until 0.24.0. +Since the single-implementation pass (below, 2026-09-30) the `ReadingContext` form is the only one to call. The Mach-O form (`in: machO`) and the pointer form (no reader argument) are deprecated forwarders until 0.25.0. ```swift // A Mach-O file or image: pass its context. @@ -261,7 +261,7 @@ Sources/ | **1. Add Infrastructure** | Add `ReadingContext`, `MachOContext`, `InProcessContext` | Non-breaking | | **2. Add Extensions** | Add `resolve(at:in:)` to `Resolvable` and pointer protocols | Non-breaking | | **3. Gradual Migration** | New code uses `ReadingContext` API | Progressive | -| **4. Deprecation** | The `ReadingContext` form becomes the only implementation; the Mach-O and pointer forms are deprecated forwarders (0.22.0) and removed (0.24.0, postponed from 0.23.0) | Done 2026-09-30, see below | +| **4. Deprecation** | The `ReadingContext` form becomes the only implementation; the Mach-O and pointer forms are deprecated forwarders (0.22.0) and removed (0.25.0, postponed twice from 0.23.0) | Done 2026-09-30, see below | ## Benefits @@ -319,7 +319,7 @@ Two deliberate decisions worth keeping in mind: 提案:[0057-reading-context-migration](../Evolutions/0057-reading-context-migration.md)。 -每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份是一行转发(`machO.context` / `InProcessContext.shared`),标 `@available(*, deprecated)`,0.24.0 删除(原定 0.23.0,下游未迁完而推迟)。下面是代码里看不出来、下次维护会踩的几点。 +每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份是一行转发(`machO.context` / `InProcessContext.shared`),标 `@available(*, deprecated)`,0.25.0 删除(原定 0.23.0,下游未迁完而两次推迟)。下面是代码里看不出来、下次维护会踩的几点。 ### 转发必须原地保留 @@ -361,6 +361,21 @@ Two deliberate decisions worth keeping in mind: - `ValueMetadataProtocol.descriptor(in:)` 等经绝对指针读取的字段,对 dyld shared cache 里的镜像,偏移口径不对:`fileOffset(of:)` 给的是 cache 文件内的偏移,读取却按 `unslidVirtualAddress - sharedRegionStart` 来理解。三种形式本来就一样,这次既没修好也没弄坏。 - `EnumMetadataProtocol.payloadSize` 的返回类型是 `StoredSize?`,泛型读取按 9 字节的 `Optional` 去读,和 AGENTS.md 里的 Optional 读取陷阱同类。迁移之后已单独修复并验证,同时修了 `FunctionTypeMetadata.extendedFlags` 与 `SwiftClassObjectIndex` 读 class flags 的两处同类写法,见 [ProjectEvolutionLog.md](ProjectEvolutionLog.md)「Optional 读取多读一个 tag byte」一节。 +## 包装类型读取器(2026-10,提案 0075-wrapped-reader-recognition) + +宿主常把 `MachOFile` / `MachOImage` 包进自己的类型,再把读取协议的每个要求原样转发过去(MachOKitUI 的 `MachOFileSource` / `MachOImageSource`)。读本身没问题,问题出在「这是哪种读取器」:库里 38 处写的是 `as? MachOImage` / `as? MachOFile`,包装类型一处都进不去。崩的那处是 opaque 引用:经包装读进程内镜像时,描述符位置按偏移存进节点,落在地址更低的另一个镜像里就是负数,转 `UInt64` 时 trap。其余各处悄悄降级:符号按 `n_value` 原值入索引、成员地址从 shared region 起点算、ObjC 祖先链与依赖闭包不建,文件包装不转发 `MachOBindRebaseResolving` 时整份 interface 还会读到未解析的 chained fixup 原值而段错误。 + +现在的规则: + +- **读取器种类只问三个取法**(MachOKitExtensions):`asMachOImage`、`asMachOFile`、`underlyingReader`。宿主的类型声明 `MachOReaderWrapper`(`associatedtype Base`,`var base: Base`)之后,三者都问到它底下的读取器,包装可以套包装,`Base` 也可以是宿主自己的读取器类型。库里不再对 `MachOImage` / `MachOFile` 做类型转换,`ReaderKindCastScanTests` 扫 `Sources/`(`TestSupport` 除外)强制这一点。 +- **能力协议先问自己、再问底下的读取器**:`MachOContext.bindRebaseResolver` 先看包装类型自己是否遵循 `MachOBindRebaseResolving`,没有就用 `underlyingReader` 的;建 ObjC 索引用的 `objcImplementationClassReader` 直接取 `underlyingReader`,因为 `ObjCImplementationClassReading` 是 SwiftInspection 的内部协议,外面的包装类型遵循不了。 +- **按类型在编译期选策略的协议给包装类型默认实现**:`FieldLayoutRenderable` 对 `MachOReaderWrapper` 的每个静态 witness 都转给 `Base`,包装类型写一个空的遵循就能进打印器,按底下读取器的后端渲染。 +- **opaque 引用的生产方与消费方用同一个判据**:`SymbolicDemangler` 存进 `Node.index` 的值由 `context.runtimePointer(at:)` 决定,能给出本进程指针就存绝对地址,否则存偏移,偏移为负就当这个引用解析不了;读回来的 `Node+OpaqueType` 与 `OpaqueReferenceSpelling` 问读取器的 `asMachOImage`,而 `MachOContext.runtimePointer(at:)` 正是建在它上面。两边改其中一边,另一边就会把绝对地址当偏移读(或反过来)。 +- **契约**:包装类型在每个偏移读到的内容与底下的读取器相同,`identifier` 也相同。按镜像的缓存(符号索引、ObjC 索引、反混淆 memo)以 `identifier` 为键,包装类型和底下的读取器共用一份;没声明 `MachOReaderWrapper` 的包装类型会和底下的读取器共用缓存,却在按种类分支的地方算出不同的结果,所以 MachOKitUI 的绕过修复要求同一个镜像的 demangle 全部走裸 `MachOImage`。 +- **投影结果的读取器类型**:`DependentMemberProjection.project` 拆包后在 `MachOFile` / `MachOImage` 的 universe 里投影,结果的 `image` 是那个 universe 的读取器,不是调用方的类型,所以返回值把它抹成 `any MachOSwiftSectionRepresentableWithCache`,重写器经一个泛型辅助函数打开它。 + +没动的:按类型静态约束的 API(`GenericSpecializer where MachO == MachOImage`、`ImageUniverse.dependencyClosure(root:)`、`DependencyClosure` 的两个约束扩展)不是运行时判断,持有包装类型的宿主自己传 `base`。 + ## Future Considerations 1. **Async Support**: Add `AsyncReadingContext` for async reading operations diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 17f4f250e..7bd3950b8 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -731,3 +731,173 @@ 3. 第二、三处的锁保护的是不线程安全的计算器 memo。要把 demangle 挪出锁,得把计算器改成线程安全的,代价大,而收益只在上面两个条件同时成立时才有。 - **既往修复**:无。规则来自第 9 条(`lateDemangledNode`,2026-08-03 修)。第一处 `:118` 的锁(`7ebed7d3`,2026-06-24)是专门为防止并发重复建表加的;第二处的锁随读取器特化引入(`1af4ea24`,2026-06-22)。其余几处(`268159bd`、`72b5c5f6`、`01fe2f82`、`758314ff`)都写在规则进 AGENTS.md(2026-09-14)之后,从写法看,当时把规则理解成了「所有查询都要拿的锁」。 - **复审条件**:有宿主在协作线程或 libdispatch 线程上并发调用上面列出的同步入口;又出现没包执行器、能走到这几把锁的 async 入口(像这次的 `TypeDefinition.specialize`);`MachOFile` 改成支持并发读;或者有宿主在 macOS 15 以下的实测里卡在这些锁上。 + +--- + +## A62 — `CrossReferenceAnalysis` 的按镜像缓存用手写锁加字典,不用 `SharedCache`(交叉引用审查 B7,**有意设计**) + +- **裁决**:不修(2026-10-17)。 +- **发现**:AGENTS.md 要求按镜像的缓存一律用 `SharedCache`,不写「手写锁加 `[键: 值]` 字典」。`CrossReferenceAnalyzer` 的函数表、类索引、类型索引、链接关系与改名再导出表,`ObjectiveCClassIndex` 的类名、`SwiftTypeIndex` 的 key、`ImageFunctionTable` 的补充名字,都是 `NSLock` 加字典。 +- **复现 / 是否误报**:写法属实。不是缺陷:结果对、无竞态(都在锁外建、锁内先到先得)。 +- **与 main 基线对比**:模块是 `feature/cross-reference-analysis` 新写的,main 上没有。 +- **为什么不修**:这些缓存都属于一个 `CrossReferenceAnalyzer` 实例,随实例释放;宿主想放掉内存就丢掉分析器(RuntimeViewer 的会话在镜像变化或起名过的镜像超过 64 个时换新的)。`SharedCache` 管的是进程级、按镜像键、要靠注册表统一淘汰的缓存,套在实例级的缓存上反而让它们比分析器活得久。 +- **既往修复**:无。模块文档「缓存、内存与生命周期」从第一批起就这样写。 +- **代码锚点**:`CrossReferenceAnalyzer.swift` 的存储属性注释;模块文档 [CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)。 +- **复审条件**:分析器改成进程级单例,或这些缓存改由别的长寿对象持有。 + +--- + +## A63 — 分析器存活期间缓存外镜像被卸载(交叉引用审查 B5) + +- **裁决**:不修,文档写明(2026-10-17)。 +- **发现**:分析器在创建时记下缓存外镜像的 `MachOImage` 与映射区间。之后若有镜像被 `dlclose` 真正卸载,再读它会读到已释放的内存,`isMapped` 仍说可读。 +- **复现 / 是否误报**:机制属实,没有构造复现:要恰好在一次查询进行中卸载一个缓存外镜像。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么不修**:每次读之前查一遍 dyld 的镜像表,代价落在扫描的热路径上;而触发要求一次查询(一到几秒)里恰好有镜像被卸载,macOS 上 `dlclose` 真正卸载的情形本来就少(带 ObjC 或 Swift 元数据的镜像不会被卸载)。RuntimeViewer 的会话在缓存外的镜像列表变化时换新的分析器。 +- **既往修复**:无。 +- **代码锚点**:`CrossReferenceAnalyzer` 的类型文档注释。 +- **复审条件**:出现了查询中途卸载导致的崩溃报告;或宿主开始频繁加载、卸载插件(例如逐个分析一批 bundle)。 + +--- + +## A64 — 缓存构建器优化过的直接跳转型桩不跟;槽位指向镜像之外时不退回导入名(交叉引用审查 A7,**暂缓**) + +- **裁决**:暂缓(2026-10-17):真实存在,但本机造不出修复前会失败的测试。 +- **发现**:`ImageFunctionTable` 只收 MachOKit 读成 `.viaSlot` 的桩。缓存构建器优化过的桩(单条 `b target`,或 `adrp x16; add x16; br x16`)MachOKit 读成 `.direct(target)`,槽位为空,调用于是退回桩的导入名(`.importedSymbol`),拿不到目标函数。另外槽位里的指针落在所有镜像之外时,解析返回 `.unrecognized`,挡住了退回导入名。 +- **复现 / 是否误报**:macOS 27.2 的缓存镜像已经没有桩(AppKit、libswiftCore、libsystem_c、Foundation、libobjc 的 `__auth_stubs` / `__stubs` 都是 0 字节),缓存外镜像的桩都经槽位;所以本机复现不了。`.direct` 桩存在于 macOS / iOS 26 及更早的缓存里,引擎在被查看的进程里扫,用户在这些系统上用时会遇到:调用按导入名报——按名字查调用者仍能找到,按位置的不行,改名再导出的别名(交叉引用审查 B1)也对不上。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么暂缓**:修法简单(`.direct` 的目标按运行时地址解析;槽位解析为 `.unrecognized` 时退回名字),但仓库规则要求修复带修复前失败的测试,本机没有 26.x 的进程可扫。 +- **既往修复**:无。第一批(`0c0ebce3`)在 macOS 27.2 上写成,那时缓存已无桩。 +- **复审条件**:有 macOS 26 或 iOS 26 的环境可跑测试(另一台机器、或用户批准的 Simulator)——那时先写测试再修,同时让 RuntimeViewer 的调用者键带上改名再导出的别名(只有按名字报的调用需要它)。 + +--- + +## A65 — `bc.cond` 不解码;共用 selector 桩读字符串前不检查(交叉引用审查 A8) + +- **裁决**:不修 / 疑似误报(2026-10-17)。同一条里的第三处——`svc` 不作废 `x0`、`x1`——属实,已随 A1 修(`RegisterFileTests`)。 +- **发现**:一、`bc.cond`(FEAT_HBC,位 4 置位)不被当成条件跳转。二、`ReferenceScanner` 认出全缓存共用的 selector 桩后,只确认 selector 地址的第一个字节可读就当字符串用,没有 `selectorString(atRuntimeAddress:)` 那样的可打印与终止符检查。 +- **复现 / 是否误报**:一、Apple 的核心没有实现 FEAT_HBC,编译器不生成 `bc.cond`。二、只有严格匹配 `adrp x1; add x1; b ` 的跳板才被认作 selector 桩,`x1` 只指向缓存的 selector 字符串区;造不出会读坏的输入。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么不修**:两处都没有可触发的输入;规则要求修复带会变红的测试。 +- **既往修复**:无。 +- **复审条件**:Apple 的核心加入 FEAT_HBC;共用 selector 桩换了形态,或别的跳板形态也能落进同一分支。 + +--- + +## A66 — 向前目标的排序插入、夹在代码里的数据线性查找(交叉引用审查 A6,性能) + +- **裁决**:不修(2026-10-17,数据裁决)。 +- **发现**:`ReferenceScanner.carry(to:)` 把向前分支的目标连同约 640 字节的寄存器快照插进按地址排序的数组,近处的分支插在一长串远处目标前面时整体搬动;`ImageFunctionTable.isInDataInCode` 对每条指令线性查找。 +- **复现 / 是否误报**:属实,量过(release,临时测量测试,记录在 [2026-10-17 审查记录](../../Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md) A6):向前目标最多的几个巨型函数每条指令慢 5–9 倍(JavaScriptCore 的 `FTL::LowerDFGToB3::compileNode` 61 ms,WebCore 的 `FormatConverter::convert` 25 ms),占各自镜像扫描时间的 8%–13%;数据区间在抽样的 257 个缓存镜像里一条都没有。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么不修**:慢只在少数巨型函数上,每个几十毫秒;跨库查询是 27 个线程并发扫几千个镜像,这几个函数不在关键路径上。 +- **既往修复**:无。排序数组加游标是 `00c5a040` 有意的选择(扫描只往前走,每条指令只比一个元素),当时没考虑快照的大小。 +- **复审条件**:采用循环的精确做法(含循环的函数要扫两遍,见审查记录 A5);或有用户在具体镜像上感到慢。修法现成:排序数组只存 16 字节的「目标、快照序号」,快照另放一个只追加的数组。 + +--- + +## A67 — 交叉引用测试钉着 macOS 27.2 的代码形态,却没有按系统版本门控(交叉引用审查 D6、D7) + +- **裁决**:不修,只改注释(2026-10-17)。 +- **发现**:`CrossReferenceAnalysisTests` 的一些断言钉着 macOS 27.2 编出来的具体代码(`-[NSWindow makeKeyAndOrderFront:]` 发出的三条消息、SiriAppIntents 与 Matter 剥掉了哪些符号、Mac Catalyst 的 SwiftUI 路径),套件只按「arm64 且有共享缓存」启用,在别的系统版本上会失败而不是跳过;`FallbackNamingTests` 的注释还说「换系统版本也成立」。`knowsEveryImageOfTheSharedCache` 只查数量大于 1,000。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么不修**:CI(macOS 26 的 runner)不跑这些套件;本地开发机都在 macOS 27.2 上。按系统版本门控会让它们在别的版本上悄悄不跑,不如失败时显眼——升级系统后要更新的是这些期望值。注释已改为如实说明(`FallbackNamingTests` 与 RuntimeViewer 的 `CrossReferenceQueryTests`)。 +- **既往修复**:无。 +- **复审条件**:CI 开始跑这些套件,或开发机分布到多个系统版本。 + +--- + +## A68 — 循环头与跳转表落点保留 `x19`–`x28` 的旧值(交叉引用审查 A5) + +- **裁决**:不修,作为已知局限(2026-10-17,用户看过测量数据后决定)。 +- **发现**:分支跟踪在循环头(向后分支的目标)与没人指向的落点(跳转表的各个 case)只作废调用方保存的 `x0`–`x18`,被调方保存的 `x19`–`x28` 留着文本上前一块末尾的值。循环体改了其中一个再跳回,循环头之后的指令仍按进循环前的值认:`-[NSMenuItem _titlePathForUserKeyEquivalents]` 的循环把 `x22` 从 `self` 换成父菜单项,循环头之后的 `_titleForUserKeyEquivalents` 发送仍被说成「发给 self、精确」。 +- **复现 / 是否误报**:属实。量过(release、单线程,临时测量测试,数据与抽查见 [2026-10-17 审查记录](../../Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md) A5):与「含循环的函数反复扫到回边状态不变」的精确做法相比,现行做法在六个大镜像(332 万条引用)里有 0.04% 的引用不同、在 257 个抽样镜像(711 万条)里有 0.02%,几乎都是循环里那次发送的「精确 / 按 selector」标记,另有极少数 Swift 间接调用认错表内槽位。 +- **与 main 基线对比**:模块新写,main 上没有。 +- **为什么不修**:精确做法的扫描时间多 42% / 61%(外加跳转表落点的变体多 34% / 54%),全缓存的跨库查询从约 2–3 秒变成约 3–5 秒,换来的是 0.02%–0.04% 的引用;RuntimeViewer 按接收者类不同只把结果降为「按 selector」、不排除,所以这些错误不会让发送类的调用者从结果里消失。循环头一律全部作废更快,却会丢掉约 3.9 万条正确的事实(`self` 发送少 15%),更差。只作废「循环里写过的寄存器」的近似试了几版,都还会丢掉正确的事实(`@synchronized` 的异常落点、循环前的 `adrp` 被算进循环),弃用。模块参考的「已知局限」一段写明了这一点。 +- **既往修复**:无。`00c5a040`(分支跟踪)给循环头的理由是「回边的状态此时还不知道」,这个理由对 `x19`–`x28` 同样成立,当时只作废 `x0`–`x18` 是疏漏,不是有意的取舍。 +- **复审条件**:有用户报告循环里的发送或 Swift 间接调用认错、并且影响了判断;或扫描变快到多 40%–60% 也无所谓(例如改成存盘索引)。修法:照审查记录 A5「测量方法」第 2 条的精确做法实现(第一遍乐观,循环头取上一遍回边带回的状态的交集,扫到不再变化,8 遍封顶);测量代码没有留在仓库里。同时重议 A66:含循环的函数要扫两遍以上,向前目标的插入成本跟着翻倍。 + +--- + +## A69 — 两个新套件进了 CI 的过滤名单,却只在 Xcode 27 上跑过(PR #135 review 发现 2,**误报**) + +- **裁决**:误报(2026-10-21,用 CI 的工具链实跑排除)。原始发现与本轮其余各条见 [2026-10-21 审查记录](../../Roadmaps/2026-10-21-pr135-review-findings.md)。 +- **发现**:PR #135(协议约束可选写在各自的关联类型上)把 `ProtocolRequirementPlacementInterfaceTests`、`ProtocolRequirementRightHandSideDumpTests` 加进 `.github/workflows/macOS.yml` 的过滤名单,PR 自己的验证却只用了 Xcode 27.0(Swift 6.4):当天 github.com 连不上,依赖是拷来的一份只有 Swift 6.4 认的解析。审查担心这两个套件在 CI 的 Xcode 26.6 上编不过或失败。 +- **复现 / 是否误报**:误报。在 `git archive` 出来的 PR 头副本里,用 `/Applications/Xcode.app`(Xcode 26.6,Swift 6.3.3,与 CI 相同)从远端重新解析依赖,跑这两个套件和 PR 改过的 `DumpAndInterfaceRequestTests`、`CommandRequestMappingTests`:4 个套件 45 个测试全部通过,`swift test` 的原始退出码是 0。补上发现 1 的 fixture 协议之后,在同一副本里又跑了一遍,同样全部通过。只跑了 debug 配置,CI 还会跑 release。现场编译的 fixture 固定了语言模式(`-swift-version 5`),所以新旧工具链按同一种语言模式编译它。 +- **与 main 基线对比**:新加的套件,基线没有。 +- **为什么不修**:没有问题可修。合进 `next` 的 PR 不跑 CI,这两个套件要到下次发版合进 `main` 时才第一次在 CI 上跑。 +- **既往修复**:出过同类问题:`a2725835`(2026-09-27)修的是换到 Xcode 27 后一个现场编译 fixture 的测试全红,修法就是固定语言模式。本 PR 的 fixture 从一开始就固定了。 +- **复审条件**:CI 换工具链版本;fixture 开始依赖随工具链变化的产物(比如 `-emit-module-interface` 的输出);或 CI 的 release 配置在这两个套件上变红。 + +--- + +## A70 — 协议约束的右侧把 `SwiftDumpConformance` 当普通文字印出(PR #135 review 发现 3,**误报**) + +- **裁决**:误报(2026-10-21)。 +- **发现**:`GenericContext+Dump.swift` 的 `dumpProtocolContent(in:builder:)` 遇到 `.conformance` 内容时印 `Standard("SwiftDumpConformance")`(PR 头第 364 行),旁边 `dumpContent` 的同一处印的是 `Error("SwiftDumpConformance")`(第 251 行)。审查认为 PR 新加的 `associatedtype` 继承子句会走到这里,把占位文字当成类型名印出来。 +- **复现 / 是否误报**:构造不出来。`.conformance` 内容只来自 SameConformance 这一种约束(`GenericRequirementDescriptor.content` 把 `.sameConformance` 映射成 `.conformance`),而编译器生成二进制的 IRGen 从不发出它(编译器的 `lib/` 里没有生成它的代码),运行时遇到它也只是标着 `FIXME` 跳过(`ProtocolConformance.cpp:1906`、`:2062`)。就算真出现,`ProtocolRequirementPartition` 也把它归入「其他种类」,留在协议的 `where` 子句里,进不了 `associatedtype` 的继承子句。 +- **与 main 基线对比**:基线既有。`next` 上 `dumpProtocolContent` 的第 363 行就是这样,协议的 `where` 子句一直经过它。 +- **为什么不修**:走不到的分支。为它手工造一个带 SameConformance 约束的二进制、写一个修前会失败的测试,代价远大于收益。 +- **既往修复**:`f223b210`(2026-01-22)把 `dumpContent` 那一处改成了 `Error`,漏了 `dumpProtocolContent` 这一处,只改了一半。不是回归。 +- **复审条件**:编译器开始发出 SameConformance 约束,或划分规则不再把它留在协议的 `where` 子句。那时把这一处改成 `Error`,并补测试。 + +--- + +## A71 — 默认写法下每个协议多读一次关联类型名(PR #135 review 发现 4) + +- **裁决**:不修(2026-10-21)。 +- **发现**:`SwiftDeclarationPrinter.swift:377` 为每个协议建 `ProtocolRequirementPartition` 时都读一次 `descriptor.associatedTypes(in:)`,默认的 `.protocolWhereClause` 用不到这份名单;`renderProtocolAssociatedTypes` 打印 `associatedtype` 行时又读一遍。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:本 PR 新引入。 +- **为什么不修**:`ProtocolDescriptor.associatedTypes(in:)` 只是读一次相对指针指向的字符串、按空格切开,比起打印整个协议可以忽略;也写不出修前会失败的测试。 +- **既往修复**:无。同类先例 A26(每次调用多一点固定开销,判不修)。 +- **复审条件**:profiling 显示协议打印的热点在这里,或 `associatedTypes(in:)` 变成昂贵的操作。 + +--- + +## A72 — `.associatedTypes` 写法下每条约束的主语 demangle 两次(PR #135 review 发现 5,**部分误报**) + +- **裁决**:不修(2026-10-21)。 +- **发现**:开关打开时,`ProtocolRequirementPartition.location(of:among:in:)` 为了判断位置 demangle 一次约束的主语(`ProtocolRequirementPartition.swift:74`),打印时再 demangle 一次。审查说这是两倍的工作量。 +- **复现 / 是否误报**:调用确实重复,「两倍工作量」不成立:`SymbolicDemangler.demangleType(for:in:)` 按镜像记忆化(`SymbolicDemanglerCache`),第二次命中缓存,只是从已驻留的 `NodeReference` 重建一棵很小的树。 +- **与 main 基线对比**:本 PR 新引入,只在打开开关时发生,默认写法不经过这里。 +- **为什么不修**:成本小,而且只在可选路径上。同类的瞬态重建在 A3 实测只占打印时间约 1%。 +- **既往修复**:无。同类先例 A3。 +- **复审条件**:记忆化被关掉或不再跨调用保留;或 profiling 显示这里是热点。 + +--- + +## A73 — 现场编译 fixture 的辅助代码有 42 份副本(PR #135 review 发现 6) + +- **裁决**:本 PR 不修,留待单独的重构(2026-10-21)。 +- **发现**:`ProtocolRequirementPlacementFixture.swift:153` 起的 `CompiledLibraries`、`WorkingDirectoryCleanup` 和起 `xcrun swiftc` 进程的代码,是测试支持里又一份几乎一样的副本。 +- **复现 / 是否误报**:属实,而且比审查说的多:审查说有 6 份,`next` 上实际已有 41 份,本 PR 加了第 42 份。 +- **与 main 基线对比**:基线既有,本 PR 多加一份。 +- **为什么本 PR 不修**:合并成一个共享函数要改 41 个测试文件,与本 PR 的改动无关。副本的代价有据可查:`d2cacc50`(2026-08-09,先读完 stderr 再等进程退出,防止死锁)和 `a2725835`(2026-09-27,固定语言模式)当年都只修了一份。现在 41 份里还有 25 份没固定语言模式,只是因为它们都不生成随语言模式变化的产物(比如 `.swiftinterface`),暂时没出事。本 PR 的副本两处修法都带上了。 +- **既往修复**:没有人合并过这些副本。相关条目 A45(每个测试重编一次 fixture,判不修)。 +- **复审条件**:下次又要给这些副本同改一处时(新工具链要求新参数、要把诊断收进失败信息之类),先合并成一个共享的编译函数再改;或专门立项做这个重构。 + +--- + +## A74 — 继承子句的拼写循环有三份(PR #135 review 发现 7,**有意设计**) + +- **裁决**:不修(2026-10-21)。 +- **发现**:`SwiftDeclarationPrinter+Headers.swift:238` 新加的 `associatedtype` 继承子句循环,与协议头的继承子句循环、dump 的 `ProtocolDumper.declaration` 里那份形状相同。 +- **复现 / 是否误报**:部分属实。新循环与协议头的循环形状相同,但两者调用不同的打印函数(关联类型这边用 `dumpProtocolContent`,只印约束右侧;协议头用 `dumpContent`),后面还要接 `~Copyable` 的合并。PR 同时把 `where` 子句抽成了 `renderRequirementWhereClause`,打印器内部的重复其实变少了。 +- **与 main 基线对比**:dump 与 interface 各有一份协议头,基线既有。 +- **为什么不修**:dump 与 interface 分开是有意的;把三行的循环体抽成公共函数,要传的参数比循环本身还多。 +- **既往修复**:无。`aa233bc0`(2026-06-17,抽出 SwiftDeclarationRendering、让 SwiftDump 成为不被其他模块依赖的叶子模块)的提交说明写着「the two paths intentionally diverge」。 +- **复审条件**:继承子句的拼写规则要改、三处都得同步时,先合并再改。 + +--- + +## A75 — diff / evolution 的协议头由调用方手工传入「约束全留在协议上」(PR #135 review 发现 8,**有意设计**) + +- **裁决**:不修(2026-10-21)。 +- **发现**:`SwiftDeclarationPrinter+DiffRendering.swift:76` 的 `printProtocolHeader` 手工构造 `ProtocolRequirementPartition`(`associatedTypeNames: []`、`.protocolWhereClause`),不读打印配置。审查担心以后有人改成按配置走,约束会悄悄丢掉。 +- **复现 / 是否误报**:不会悄悄发生:`ProtocolRequirementPlacementInterfaceTests.diffHeaderKeepsEveryRequirement` 在 `.associatedTypes` 配置下打印 diff 的协议头,再与默认写法的协议头比较,改成按配置走就会变红。 +- **与 main 基线对比**:新代码。 +- **为什么不修**:diff / evolution 的 `associatedtype` 行按名字逐行比较、不带约束,约束挪过去就丢了。显式传值正是为了防这件事,提案 [0073-protocol-requirement-placement](../Evolutions/0073-protocol-requirement-placement.md) 的决策日志记了这个选择。 +- **既往修复**:无。 +- **复审条件**:diff 开始比较每个关联类型的约束(那时 `associatedtype` 行要带上约束,协议头才能按配置走)。 diff --git a/Documentations/Internal/StaticLayoutEngine.md b/Documentations/Internal/StaticLayoutEngine.md index 8d95cf46c..e06beb4fe 100644 --- a/Documentations/Internal/StaticLayoutEngine.md +++ b/Documentations/Internal/StaticLayoutEngine.md @@ -25,7 +25,7 @@ Sources/Analysis/SwiftLayout/ ├── StaticTypeLayout.swift # 输出值类型 (size/stride/alignmentMask/XI/isBitwiseTakable) ├── BasicLayout.swift # runBasicLayout 内核(performBasicLayout 离线移植) ├── KnownLayoutTable.swift # 硬编码 stdlib 固定布局表 -├── BuiltinTypeLayoutIndex.swift # __swift5_builtin 整体布局索引:C-imported 值类型 + multi-payload enum,按 demangle 还原的限定名建 key +├── BuiltinTypeLayoutIndex.swift # __swift5_builtin 整体布局索引:C-imported 值类型 + multi-payload enum,按 demangle 还原的限定名建 key;libswiftCore 独有的 Builtin.* 叶子记录按 builtin 名(Builtin.Int1)建 key ├── NodeTypeNaming.swift # 从 demangle Node 提取限定类型名 / 协议限定名(忽略泛型参数);ObjC class 节点(__C.X)取裸名 ├── GenericArgumentEnvironment.swift # 阶段 5/6/8:实例化节点的 (depth,index)→实参 Node 映射 + 自定义 top-down 语法替换;实参沿 nominal 父链**逐层收集**(最外层 bound-generic = depth 0,覆盖 `Environment.Content` 与多级 `Outer.Inner`);实参可为类型 / value(integer)/ pack;tuple/pack 内的具体 pack expansion 就地展开(含单元素坍缩与转发扁平化) ├── StaticTypeLayoutResolver.swift # 递归求解器:Node.Kind 分派 + memoization(含实例化 key 防环)+ 泛型环境线程化 @@ -49,6 +49,7 @@ Tests/SwiftLayoutTests/ ├── DependencyClosureLayoutTests.swift # 跨依赖闭包:DistributedActorTest 对 runtime vector 自动校验 + resilient 字面值锁定 + 单镜像 partial 回归守卫 + MachOFile 离线路径 ├── ObjCAncestorLayoutTests.swift # 阶段 4:ObjCMembersTest/ObjCBridge 闭包重算对 runtime vector 自动校验(均 [8])+ 无字段 ObjCBridgeWithProto + 单镜像 partial 回归守卫 ├── BuiltinTypeLayoutTests.swift # builtin 整体布局回退:multi-payload enum + __C.NSDecimal 索引对 runtime VWT 自动对拍 + resolver 端到端 +├── StandardLibraryLeafLayoutTests.swift # builtin 叶子与冻结表对二进制(读宿主 dyld shared cache):libswiftCore 的叶子记录按 builtin 名可查 + 兜底叶子 == libswiftCore 的记录(14 个)+ Float16 / StaticBigInt 经依赖闭包 == runtime VWT + _Concurrency 的 Job / Executor / RawUnsafeContinuation 承载类型 == runtime VWT + 两种 actor 存储 96/16 + KnownLayoutTable 每一项 == libswiftCore 自己的元数据算出的布局 ├── EdgeTypeKindLayoutTests.swift # 边角函数 kind:cFunctionPointer / objCBlock / escapingObjCBlock = 单指针,对比 thick functionType ├── ObjCProtocolExistentialTests.swift # ObjC 协议 existential:objCProtocolBareName 单元 + 纯/多/混合(any NSCopying[& Swift]) class-bound 布局 ├── MultiPayloadEnumStructuralTests.swift # multi-payload enum 结构化兜底:multiPayloadEnumLayout 直接算对 runtime VWT(spare-bits + indirect)+ XI 逐枚举相等 + `Optional` 包装 size/stride 对 runtime `MemoryLayout` 端到端相等(XI 错则多/少 1 个 tag 字节,必被抓住);泛型描述符跳过(无参 accessor 调不得——真值经非泛型 holder 走 GenericSpareBitsEnumLayoutTests) @@ -70,9 +71,9 @@ Tests/SwiftLayoutTests/ ## 核心算法 - **`BasicLayout.compute`**:照搬 `Metadata.cpp:2321-2360`。逐字段 `offset = roundUpToAlignMask(accumulator, fieldAlignMask)`,累加用 **size 不是 stride**,尾部 padding 只进 stride。struct 起点 0;class 起点 = 父类 instance size(= 父类 `size`,根类 16 = `HeapObject`),递归父类;tuple 起点 0。**同时求整体 XI = 字段中最大者**(`swift_initStructMetadata`:“use the field with the most”,与 tuple 同规则),随 `AggregateLayout` 带出;`asStaticTypeLayout()` 直接采用。**曾漏此步致 struct XI 恒 0**:`asStaticTypeLayout(extraInhabitantCount:)` 默认 0、`computeStructLayout` 从不传播,于是**任何 struct 的整体 XI 都记成 0**。后果是「payload 为带 XI 的 struct(如包类引用的 `SwiftUI.Font`)」的**单 payload 枚举**误加一个 tag 字节(`Text.Style.TextStyleFont` 本应 8 字节算成 9/stride 16),并把外层聚合的后续字段偏移整体推移。修复即把 tuple 早已做对的 max-over-fields 下放进 `compute`,struct/tuple/class 共用(class 聚合的该值不作为 class *值* 的 XI,无人读取,无害)。class 值作字段时仍取 `.pointerSized`(引用 XI),不受影响。 -- **`StaticTypeLayoutResolver`**:按 `Node.Kind` 分派。`builtinTypeName` → KnownLayoutTable / `builtinPrimitiveLayout`(含 `Builtin.DefaultActorStorage` 特判,见下);`class`/`boundGenericClass` → 一个指针(**不递归字段,天然破环**);`structure` → **BuiltinTypeLayoutIndex 回退**(C-imported 值类型,见下)或 known 表 / 递归 descriptor;`enum` → EnumLayoutBridge;`protocolList`·`protocolListWithAnyObject`·`protocolListWithClass`·`existentialMetatype`·`symbolicExtendedExistentialType`(受约束 existential) → ExistentialLayoutBridge;`dependentMemberType`(关联类型) → DependentMemberTypeBridge;`builtinFixedArray`(含 `InlineArray` 特判) → fixed-array 公式;`tuple`/`functionType`(thick=2 words)/`cFunctionPointer`·`objCBlock`·`escapingObjCBlock`(单指针=1 word)/`weak`·`unowned`·`unmanaged`(**引用存储:宽度由 referent 决定**,普通类引用 1 word,class-bound existential 则保留见证表字,见「引用存储不坍缩 existential」)/`metatype`(thin=0/thick=8) 各自处理;其余抛 `unknown` 降级。memoize 按限定名,`inProgressKeys` 防环兜底。 +- **`StaticTypeLayoutResolver`**:按 `Node.Kind` 分派。`builtinTypeName` → 字段所属镜像的 builtin 叶子记录(只有 libswiftCore 带,见下)/ `builtinPrimitiveLayout` 兜底(含两种 actor 存储,见下);`class`/`boundGenericClass` → 一个指针(**不递归字段,天然破环**);`structure` → **BuiltinTypeLayoutIndex 回退**(C-imported 值类型,见下)或 known 表 / 递归 descriptor;`enum` → EnumLayoutBridge;`protocolList`·`protocolListWithAnyObject`·`protocolListWithClass`·`existentialMetatype`·`symbolicExtendedExistentialType`(受约束 existential) → ExistentialLayoutBridge;`dependentMemberType`(关联类型) → DependentMemberTypeBridge;`builtinFixedArray`(含 `InlineArray` 特判) → fixed-array 公式;`tuple`/`functionType`(thick=2 words)/`cFunctionPointer`·`objCBlock`·`escapingObjCBlock`(单指针=1 word)/`weak`·`unowned`·`unmanaged`(**引用存储:宽度由 referent 决定**,普通类引用 1 word,class-bound existential 则保留见证表字,见「引用存储不坍缩 existential」)/`metatype`(thin=0/thick=8) 各自处理;其余抛 `unknown` 降级。memoize 按限定名,`inProgressKeys` 防环兜底。 - **`EnumLayoutBridge`**:no-payload(最小 tag 字节)+ single-payload(含 `Optional`,用 payload 的 extra inhabitants 编码空 case,溢出才加 tag 字节)。`getEnumTagCounts` 公式从 runtime `EnumImpl` 移植。**multi-payload enum** 两条路解析:①首选 `BuiltinTypeLayoutIndex` 整体布局(编译器 emit 的精确值,见下);②无 builtin descriptor 时**结构化兜底**——`multiPayloadEnumLayout` 复用 `SwiftInspection.EnumLayoutCalculator`(`GenEnum.cpp`/`TypeLowering.cpp` 的离线移植):payload 区 = 最大 payload case 的尺寸,tag 编码在公共 spare bits(取自该 enum 的 `MultiPayloadEnumDescriptor`,`__swift5_mpenum` 段)或退而附加 extra tag bytes(`calculateTaggedMultiPayload`)。indirect case 的 payload 按单指针计。**泛型 MPE 按「记录存在性」分流(2026-08-05 修正,此前模型错误)**:编译器只为**静态 fixed**(布局与实参无关)的 MPE 发射 builtin + mpenum 记录(`GenReflection.cpp` `emitFieldDescriptor` 的门槛 `payload>1 && !needsPayloadSizeInMetadata()`),这类泛型 enum 的完整 VWT 烘焙在 metadata pattern 里、运行时从不重算(`Swift.Dictionary.Iterator._Variant` 40/40/XI 126 即典型,未绑定形态与所有实例化共享同一布局),故 builtin/spare-bits 两条路对泛型节点(实例化或未特化)照常放行——记录命中即编译器原话;而**依赖实参**的泛型 MPE(某 payload 布局需要实参,如 `Environment.Content` 的裸 `Value`)一条记录都没有,走 runtime `swift_initEnumMetadataMultiPayload` 的 tagged 公式:附加 tag 字节,**未用 tag 值即 extra inhabitants**(`(1 << (numTagBytes×8)) − numTags`,4 字节 tag 饱和,capped `MaxNumExtraInhabitants`)——`Optional.Content>` 形态因此精确(阶段 8)。`!AllowFixedLayoutOptimizations` 时(GenEnum.cpp:7192)编译器自己也清空 spare bits 退回与 runtime 一致的 tagged 布局且不发记录,故「记录存在 ⇔ spare-bits/fixed」在构造上精确、零启发式。跨镜像场景在 `compute()` 里补查**定义镜像**的 builtin 索引(enum 记录由声明模块发射,与 imported C 的逐引用方发射不同),顺带闭合 mask>16k 不发 mpenum 记录的边角。 -- **`BuiltinTypeLayoutIndex`(整体布局回退)**:`__swift5_builtin` 段的 `BuiltinTypeDescriptor` 记录了「reflection 无法结构化推导布局」类型的**整体布局**(size/stride/align/XI/bitwiseTakable)——即**imported C 值类型**(`__C.CGRect`/`__C.NSDecimal`/…)与 **multi-payload enum**。编译器在**每个反射性引用该类型的镜像**(如把它当存储字段的类型所在镜像)里都 emit 一份,故「使用方镜像」必带。求解器在 `structureLayout`/`enumLayout` 里对 `structure`/`enum` 节点(enum 侧含泛型实例化与未特化泛型——见上条「记录存在性」分流)先查 `originImage.builtinLayoutIndex`:命中(C 类型、multi-payload enum)即返回该整体布局;未命中(普通 struct/enum 不 emit builtin descriptor)落回结构化路径。enum 记录由**声明模块**发射(imported C 记录才是逐引用方发射),跨镜像 enum 在 `compute()` 里补查定义镜像的索引。索引侧跳过 typeref 为**具体 bound-generic 实例化**(`Foo`)的记录——按剥参数 key 收录会误配到其它实例化(5 个 OS 镜像实测为零例,纯防御);泛型声明记录 demangle 出来就是无参数的普通 nominal 引用,key 天然与查找侧一致。对「作为字段」的场景只需整体 size/align/stride,故无需 C struct 内部偏移、也无需 multi-payload 的 spare-bit 分析。descriptor 的 `typeName` 是**符号引用**(裸串为空),故按 demangle 还原的限定名建 key(与求解器查找侧同一格式)。语义同 resilient:「针对这组具体二进制」。 +- **`BuiltinTypeLayoutIndex`(整体布局回退)**:`__swift5_builtin` 段的 `BuiltinTypeDescriptor` 记录了「reflection 无法结构化推导布局」类型的**整体布局**(size/stride/align/XI/bitwiseTakable)——即**imported C 值类型**(`__C.CGRect`/`__C.NSDecimal`/…)与 **multi-payload enum**。编译器在**每个反射性引用该类型的镜像**(如把它当存储字段的类型所在镜像)里都 emit 一份,故「使用方镜像」必带。求解器在 `structureLayout`/`enumLayout` 里对 `structure`/`enum` 节点(enum 侧含泛型实例化与未特化泛型——见上条「记录存在性」分流)先查 `originImage.builtinLayoutIndex`:命中(C 类型、multi-payload enum)即返回该整体布局;未命中(普通 struct/enum 不 emit builtin descriptor)落回结构化路径。enum 记录由**声明模块**发射(imported C 记录才是逐引用方发射),跨镜像 enum 在 `compute()` 里补查定义镜像的索引。索引侧跳过 typeref 为**具体 bound-generic 实例化**(`Foo`)的记录——按剥参数 key 收录会误配到其它实例化(5 个 OS 镜像实测为零例,纯防御);泛型声明记录 demangle 出来就是无参数的普通 nominal 引用,key 天然与查找侧一致。对「作为字段」的场景只需整体 size/align/stride,故无需 C struct 内部偏移、也无需 multi-payload 的 spare-bit 分析。descriptor 的 `typeName` 是**符号引用**(裸串为空),故按 demangle 还原的限定名建 key(与求解器查找侧同一格式)。语义同 resilient:「针对这组具体二进制」。**libswiftCore 另带 `Builtin.*` 叶子记录**:编译器只在编译标准库时把字段里出现的 builtin 类型收进 builtin 段(`GenReflection.cpp` 的 `addBuiltinTypeRefs`,外加 `getOrCreateSpecialStlibBuiltinTypes` 的几个特例),macOS 26.7 的 libswiftCore 151 条记录里有 58 条是叶子。叶子记录的 `typeName` 是普通 mangling(`Bi1_`),按 demangle 出的 builtin 名(`Builtin.Int1`)建 key,与求解器 `builtinTypeName` 分支的查找键一致,所以 libswiftCore 里的字段直接用二进制自己的叶子布局;其它镜像里的 builtin 字段(`_Concurrency`、actor 的人造存储字段)都没有记录,走 `builtinPrimitiveLayout` 兜底。 - **`GenericArgumentEnvironment`(具体 bound-generic 实例化作字段,阶段 5)**:`MyBox` 作字段时,基础 generic descriptor 的字段记录存的是依赖参数(`A` = `dependentGenericParamType(depth,index)`)。做**纯语法 Node 替换**、不调任何 metadata accessor / PWT:从 `boundGeneric*` 节点自带的 `typeList` 按**位置**取具体实参(depth-0 下 index i ↔ typeList[i]),建 `(depth,index)→Node` 映射;解析字段/payload/超类类型前,先 demangle 再用一个 `Node.Rewriter`(Demangling)把节点里的 `dependentGenericParamType` 深度替换为具体实参节点,然后照常 `layout(forTypeNode:)`。深度替换意味着 `(A,B)`、`Pair` 等也一并替换,递归再自然重建子环境;`structureLayout`/`enumLayout` 命中 `boundGeneric*` 时按节点建环境、并以**实例化 key**(remangle)memoize,使 `Foo`/`Foo` 区分缓存与防环(`memoizedInstantiationLayout` 跳过 KnownLayoutTable 探测)。**仅限 depth-0 参数**;实参可为纯类型、**value(`.integer`/`.negativeInteger`,SE-0452)**或**扁平 pack(SE-0393)**——仅当 pack 实参自身仍含未展开 expansion(未解析的转发形态)时环境才整体降级为空(避免位置错配),depth>0 的参数保持降级。`class Sub: Base` 经 `superclassStartLayout` 先把超类节点按子类环境替换、再据替换后的 `Base` 建超类环境递归。**纯语法的副带修复**:单 payload 泛型枚举 `enum E{case a(Second)}` 现按 payload 字段记录 + 环境替换取**正确参数**(旧逻辑无条件取 `typeList.first` 会取错第 0 个实参)。 - **Pack expansion 展开(阶段 6)**:替换递归改为**自定义 top-down**(弃用 bottom-up 的 `Node.Rewriter`)——展开是**上下文相关**的:expansion 实例 i 里的 pack 参数引用要解析成 pack 的第 i 个元素而非整包;bottom-up 会先把 pattern 里的引用替换成整个 `.pack` 节点,与 `(repeat Pair)` 这类 pattern 中的**字面 pack** 无法区分。`.tuple` 节点:packExpansion 元素按 count(替换后须为具体 `.pack`)逐元素实例化 pattern(经 `packElementEnvironment(atIndex:)` 把 pack 绑定缩窄为第 i 元素)后拼接;空 pack → 空 tuple;展开后**恰好 1 个无标签元素 → 坍缩为该元素本身**(一元素无标签 tuple 不存在,runtime 对其直接返回元素 metadata)。`.pack` 字面量:含 expansion 的子节点(`Foo` 转发形态的 `Pack{PackExpansion(…)}`)展开拼接成扁平 pack。count 未具体绑定的 expansion 原样保留,交给求解器按 `genericParameterUnsubstituted` 降级。类型侧的简化前提(编译器强制):**一个泛型类型最多声明一个 type pack、enum 不能声明 type pack**。 - **Fixed array / value generics(阶段 6)**:求解器新增 `builtinFixedArray` 分派(`Builtin.FixedArray`):`count ≤ 0` → empty;否则 **size = stride = element.stride × count**(count = 1 也不回收尾部 padding)、align/bitwiseTakable 随元素、**XI 取首元素**——从 runtime `swift_getFixedArrayTypeMetadata`/`FixedArrayCacheEntry::tryInitialize` 移植,与 IRGen `convertBuiltinFixedArrayType`、RemoteInspection `ArrayTypeInfo` 三方一致。`Swift.InlineArray` 与其唯一 stored field `Builtin.FixedArray` 布局恒等,在 `structureLayout` 里特判直接走同一公式(descriptor 在 stdlib,与 `Optional` 特判同理,单镜像可算;依赖闭包可达 stdlib 时结构化路径 + 环境替换算得同一结果)。tuple 的 XI 同步修正为**取元素中最多者**(runtime `swift_getTupleTypeMetadata` 语义,旧实现恒 0)——`Optional<(Int16, Bool)>` 不再多算 1 个 tag 字节。 @@ -122,7 +123,7 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **`Optional` 特判**:其 descriptor 在 stdlib 不在本 image,直接从 payload 类型按 single-payload(1 空 case)计算。 - **marker 协议在 mangled field 名里已被剥离**:`any (P & Sendable)` 的 field 类型 demangle 后只剩 `P`(`sendableComposition` 实测),故 witness 计数直接数协议个数即可,无需识别/排除 marker。 - **existential class-bound 不能只看 Node 形态**:`any ClassBoundProtocolTest` 的 Node 是普通 `ProtocolList`(非 `WithAnyObject`),但结果是 16 字节 class existential。必须解析协议 descriptor 的 class 约束(`ProtocolContextDescriptorFlags.classConstraint`)。为此 `ImageReference` 额外建「协议限定名 → class 约束」索引;协议在 `__swift5_protos`(经 `protocolDescriptors`),与类型的 `__swift5_types`(`contextDescriptors`)是**不同 section**,须分别遍历。 -- **`Builtin.DefaultActorStorage` = 96 字节、对齐 16**:`NumWords_DefaultActor`(12) × pointer size,对齐为 pointer 对齐的 2 倍。本 fixture 未 emit 其 builtin descriptor,故在 `builtinPrimitiveLayout` 按常量给出,移植自 runtime reflection lowering 的 `getDefaultActorStorageTypeInfo()`。actor 类型(如 `ActorTest = [16, 112]`)由此完全解析。 +- **`Builtin.DefaultActorStorage` = 96 字节、对齐 16**:`NumWords_DefaultActor`(12) × pointer size,对齐为 pointer 对齐的 2 倍。本 fixture 未 emit 其 builtin descriptor,故在 `builtinPrimitiveLayout` 按常量给出,移植自 runtime reflection lowering 的 `getDefaultActorStorageTypeInfo()`。actor 类型(如 `ActorTest = [16, 112]`)由此完全解析。`Builtin.NonDefaultDistributedActorStorage`(带自定义 executor 的 distributed actor 的人造存储字段)IRGen 按 `NumWords_NonDefaultDistributedActor`(同为 12)个字、两倍指针对齐 lower,2026-10-20 起共用这条兜底;此前缺这一项,这类 actor 的字段全部降级。 - **`TypeLowering.cpp`(RemoteInspection)是官方离线 lowering,是本引擎的权威对照**:existential 与 default-actor 公式均以它为准,并经 runtime accessor 真值交叉验证。 - **`MachOFile.imagePath` 返回的是 install name(LC_ID_DYLIB),不是磁盘路径**:框架的 install name 是 `@rpath/Foo.framework/.../Foo`。故 `MachOFile` 闭包的显式 search path 不能由已加载 root 的 `imagePath` 字符串替换得出,须另给真实磁盘路径;依赖名匹配统一归一到 **bare name**(末段去扩展名,即 `MachOImage(name:)` 的语义)。 - **闭包须容忍缺段**:纯 ObjC/C dylib(libobjc、libsystem_*)无 `__swift5_types`/`__swift5_protos`,许多镜像无 `__swift5_builtin`。`ImageReference`/`BuiltinTypeLayoutIndex` 把 `sectionNotFound` 视作「该镜像无此类内容」返回空,而非让整个闭包构建失败。 @@ -131,7 +132,7 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **ObjC 起点取 `instanceSize` 而非 `instanceStart`,且 realized 类不可读 `classROData`(阶段 4 的关键坑)**:调研单点 finding 主推「读 `class_ro_t.instanceStart`」,实测**否决**——(1) `instanceStart` 是 ObjC 类自身首 ivar 起点(= 其父类大小),dyld cache 上常写 0;Swift 子类字段起点应是父类 **`instanceSize`**(`NSObject` = 8)。(2) **in-process 的 `NSObject` 是 realized 类**,`classROData(in: MachOImage)` 返回 `nil`(`data` 指向 `class_rw_t`),须经 `classRWData → classROData`(或 `ext.classROData`)回退取 instance ro;offline 的 cache `MachOFile` 则 `classROData` 直接可读。唯一在 in-process 与 cache 两条 reader 上都正确且一致的值是 instance `class_ro_t.instanceSize`(= `ObjCClass.info(in:).instanceSize`,但 `ObjCClassIndex` 直接读 ro、不解析 methods/ivars/metaclass,故更轻)。 - **ObjC 索引随 Swift 索引同步惰性折入,无额外扫描**:`resolveObjCClassInstanceSize` 复用 `resolveType` 的 `indexNextDependency` 折入机制(ObjC 索引在 `ImageReference.init` 里一并构建、`mergeIndexes` 一并合并)。又因 ObjC 父类在 `superclassStartLayout` 里**先于** Swift `resolveType` 判断,ObjC 名不会触发「Swift 全 miss → 折满 551 镜像」;折到 libobjc 命中 `NSObject` 即停,比旧路径(ObjC 名走 `resolveType` 折满全闭包再抛错)更快。 - **`objc.classes64` / `info(in:)` 是 `MachOFile`/`MachOImage` 具体重载(非协议泛型)**:故 `ObjCClassIndex` 与 `ImageReference` 的 ObjC 索引构建须按 `as? MachOImage` / `as? MachOFile` 向下转型分派,复刻 `ImageUniverse+DependencyClosure` 的 `where MachO == …` 拆分写法。 -- **`BuiltinTypeDescriptor.typeName` 是符号引用,裸串为空——必须 demangle 才有 key**:`__swift5_builtin` 段实测**不含** `Builtin.*` 条目,全是 imported C 值类型(`__C.NSDecimal`/`__C.CGRect`/…)与 multi-payload enum;其 `typeName` 指向 context descriptor(相对指针),`typeString` 为空字符串。旧 `BuiltinTypeLayoutIndex` 按 `typeString` 建 key,把全部条目塞进 key `""`(互相覆盖)→ 索引等于失效、且只在 `builtinTypeName` 分支被查(而该段无 `Builtin.*`),实为死代码。修复:用 `MetadataReader.demangleType` 还原成限定名(`__C.NSDecimal` / `SymbolTestsCore.Enums.MultiPayloadEnumTests`)建 key。 +- **nominal 记录的 `BuiltinTypeDescriptor.typeName` 是符号引用,裸串为空——必须 demangle 才有 key**:用户镜像和 OS 框架的 `__swift5_builtin` 段**不含** `Builtin.*` 条目,全是 imported C 值类型(`__C.NSDecimal`/`__C.CGRect`/…)与 multi-payload enum;其 `typeName` 指向 context descriptor(相对指针),`typeString` 为空字符串。旧 `BuiltinTypeLayoutIndex` 按 `typeString` 建 key,把全部条目塞进 key `""`(互相覆盖)→ 索引等于失效、且只在 `builtinTypeName` 分支被查,实为死代码。修复:用 `MetadataReader.demangleType` 还原成限定名(`__C.NSDecimal` / `SymbolTestsCore.Enums.MultiPayloadEnumTests`)建 key。**「不含 `Builtin.*`」对 libswiftCore 不成立**(2026-10-20 发现):编译器只在编译标准库时收集 builtin 叶子,libswiftCore 的段里正是全部叶子记录,`typeName` 是普通 mangling(`Bi1_`)。上面那次修复让这些记录落回裸串 key(`Bi1_`),求解器却按 demangle 出的 `Builtin.Int1` 查,所以从第一版起它们就没被用上过,叶子答案全部来自兜底表——兜底表里 `Builtin.Int1` 的 XI 记成 0,也没有 `FPIEEE16` / `IntLiteral`,`Float16`、`StaticBigInt` 字段因此解不出。现在叶子记录按 builtin 名建 key。 - **builtin descriptor 由「使用方」镜像 emit,故查 `originImage`**:编译器在每个**反射性引用**该类型的镜像里都 emit 一份 builtin descriptor(实测 fixture 自己就带 `__C.NSDecimal`、Foundation 也带一份)。所以解析某字段类型时查**字段所属镜像**(`originImage`,求解器已线程化)的 builtin 索引正中靶心,无需跨镜像合并。 - **builtin 回退限非实例化节点**:builtin key 是 generic-argument-free 的限定名(`nominalQualifiedName` 会剥泛型实参),查表前须确认节点未被实例化,避免 `Foo` 与 `Foo` 撞到同一 key;`Optional` 等泛型枚举继续走结构化/payload 路径。判据在阶段 8 从 `node.kind`(非 `boundGeneric*`)改为**环境为空**——`Enum(BoundGeneric…, Content)` 形态的 kind 是裸 `.enum`,但实参在父链上、层层可见于环境。 - **ObjC 祖先的类字段起点不是「祖先 instanceSize」,而是「本类 ro.instanceStart + moveIvars 滑动」**:静态发射的非泛型 Swift 类把 ivar 从**自己** `class_ro_t.instanceStart`(编译期对父类尺寸的假设;resilient ObjC 父类模式下仅为 base 8 一类的最小值)起排;realize 时若实际父类尺寸超过它,ObjC runtime(objc4 `moveIvars`)把全部 ivar **整体滑动**,滑动量按**本类 ivar 最大对齐**向上取整——所以字段块起点保持与编译期同余,而不是落在实际父类尺寸上(`NSTableHeaderCell` 实际 241,`AppKitTableHeaderCell` 的 Bool 字段在 248 不在 241)。dyld cache 镜像更进一步:cache builder 已预 realize,盘上 `instanceStart` 就是滑动后的最终值(实测 248/120)。Swift runtime 侧(`Metadata.cpp` `initClassFieldOffsetVector:3778-3785`)对 ObjC 父类同样从 `rodata->InstanceStart` 起排再交给 ObjC 滑动;对 Swift 父类则取精确 `super->getInstanceSize()` 不取整——该路径只有泛型/singleton 初始化(resilient 父类)的类走,而这类类**不在** `__objc_classlist`。故引擎的判据即 classlist 成员资格:查到本类 `instanceStart` → `start = instanceStart + (superEnd > instanceStart ? roundUp(superEnd − instanceStart, maxOwnFieldAlign) : 0)`;查不到(泛型 / singleton)→ 维持原「实际父类尺寸起排」。源码改过运行时名的类(`@objc(Name)`,app 二进制里很常见)classlist 名不是 mangling、demangle 不出 key,以前也落进这一支;现在查不到时再按描述符向 `SwiftClassObjectIndex` 取它自己的 `instanceStart`(提案 `0052-objc-custom-class-name`,见 [CustomObjCClassNames.md](CustomObjCClassNames.md)),两种算法只在父类尺寸不是本类最宽字段对齐的整数倍时分叉。普查里 3 个类各错 4–8 字节(`AppKitTableHeaderCell` 一族、`SplitViewChildController`)由此清零。注意 classlist 名是 legacy `_TtC…` mangling,demangle 后取 `.class` 节点建 `nominalQualifiedName` key(`demangleAsNode` 外层是 `.global` 包裹,直接建名会全表落空)。见 `ObjCAncestorSlideLayoutTests`。 @@ -149,11 +150,13 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **`String` 冻结表 XI 从 1 改为 `MaxNumExtraInhabitants`(0x7FFFFFFF)**:`_StringObject` 第二字是 tagged discriminator,保留海量非法位型,运行期即 max。旧值 1(“够撑 `Optional`”)对**两个以上空 case** 的 String-payload 单枚举不够——`enum{case value(String);case none;case error}`(fixture `SinglePayloadEnumTest`)只有 1 个空位可用、第 2 个空 case 溢出成 tag 字节 → size 17(应为 16)。这是同一类「under-report XI → 枚举虚增字节」的第三个实例,根源在冻结表而非 `computeStructLayout`。 - **叶子 XI 精确建模(收敛完成,不再是近似)**:所有叶子的 XI 现按逐类实测 runtime VWT + 编译器源码出处收敛为精确值,`WholeTypeLayoutVsRuntimeTests` 对每个 fixture struct/enum **连 XI 与 bitwise-takability 一起精确断言**。分类如下(64 位 Darwin;`LeastValidPointerValue = 0x1_0000_0000` 使所有受管指针饱和到 `MaxNumExtraInhabitants` = 0x7FFF_FFFF): - **受管指针字(`.pointerSized`,0x1000 → 0x7FFF_FFFF)**:类/堆对象引用、indirect box、`Array`/`Dictionary`/`Set`/`ContiguousArray` 的 buffer 引用、thick metatype 与 existential 的 metadata 字、C 函数指针与 ObjC block(代码地址同样避开保留低 4 GiB)、`Unmanaged` / `unowned(unsafe)`(IRGen `UNCHECKED_REF_STORAGE`:“same spare bits as managed heap objects”)。出处:runtime `KnownMetadata.cpp` / IRGen `ExtraInhabitants.cpp` 的 `getHeapObjectExtraInhabitantCount` 饱和推导 + 逐类 VWT 实测。 - - **unsafe 指针族(新 `.rawPointer`,XI = 1)**:`UnsafeRawPointer` 等全家、`OpaquePointer`、`AutoreleasingUnsafeMutablePointer`、`CVaListPointer`、`Builtin.RawPointer`/`RawUnsafeContinuation`——只有 null 非法(C 指针可以合法指进低 4 GiB),`UnsafeRawPointer??` 实测 9 字节即为证。**这是曾经的 size 级 bug**:旧值 4096 会把「2 个空 case 压在 raw pointer 上」的枚举算成 8(真值 9,1 个空 case 溢出 tag 字节)。 + - **unsafe 指针族(新 `.rawPointer`,XI = 1)**:`UnsafeRawPointer` 等全家、`OpaquePointer`、`AutoreleasingUnsafeMutablePointer`、`CVaListPointer`、`Builtin.RawPointer`——只有 null 非法(C 指针可以合法指进低 4 GiB),`UnsafeRawPointer??` 实测 9 字节即为证。**这是曾经的 size 级 bug**:旧值 4096 会把「2 个空 case 压在 raw pointer 上」的枚举算成 8(真值 9,1 个空 case 溢出 tag 字节)。 + - **task / job 指针(`Builtin.RawUnsafeContinuation`、`Builtin.Job`,`.pointerSized`,XI 0x7FFF_FFFF)**:IRGen 按 `AlignedRawPointerTypeInfo` lower(`GenType.cpp`),这种指针不会是 null,也不会落在 `LeastValidPointerValue` 以下,所以 XI 和受管引用一样饱和,与 `Builtin.RawPointer` 不同。2026-10-20 之前 `RawUnsafeContinuation` 被归进上一类(XI 1),以 `UnsafeContinuation` 为 payload、带两个以上 empty case 的 enum 会多算一个 tag byte;`Builtin.Job` 则完全没有,`UnownedJob` 字段解不出。`Builtin.Executor` 是两个字:identity 字(XI 同 heap object)加实现字,16 字节、对齐 8、bitwise-takable(`GenConcurrency.cpp` 的 `ExecutorTypeInfo`),同样是 2026-10-20 补上的。三者都由 `StandardLibraryLeafLayoutTests` 对 runtime VWT 断言。 - **thick 函数(新 `.thickFunction`,XI 0 → 0x7FFF_FFFF,takable false → true)**:XI 来自函数指针字(`KnownMetadata.cpp` `ThickFunctionBox` 取 `FunctionPointerBox::numExtraInhabitants`)。**这也是曾经的 size 级 bug**:旧 XI=0 把 `Optional<() -> Void>` 算成 17(真值 16),任何「optional 闭包字段后还有字段」的 struct 偏移全部推错(实测 trailing 应落 0x10、旧引擎落 0x18)。takable 同步修正——移动 (fn, context) 对只是转移所有权,无需 fixup。 - **weak 存储(新 `.weakReference`,XI = 0,takable = false)**:weak 引用在 referent 死亡后合法变 null,null 不能编码 tag;移动需 side-table 更新(`swift_weakTakeInit`)。出处:RemoteInspection `TypeLowering.cpp:1553` + VWT 实测。**注意这三项是「引用字」的取值,不是整个字段的**——referent 为 class-bound existential 时字段不止一个字,见下条。 - **unowned(safe)存储(新 `.unownedReference`,XI = 1,takable = true)**:ObjC interop 下 IRGen 保守放弃 spare bits(`GenHeap.cpp` `getReferenceStorageExtraInhabitantCount`:“null is the only extra inhabitant allowed”),实测「2 空 case 压 unowned」枚举 size 9 为证。**注意 RemoteInspection(`TypeLowering.cpp` 注释)声称 unowned 沿用底层引用的 XI——与 IRGen 与实测 VWT 相悖,官方离线实现在此有误,本引擎按 runtime 对齐(再次超越官方离线实现)**。takable = true 只适用于 referent 是**单个 Swift 类**的原生形态;referent 为 existential(引用计数未知)时 runtime 取非 takable 形态,见下条。 - **`Builtin.Word` → 整数**(`.fixedWidthScalar(8)`,XI 0):pointer-*sized* 不等于 pointer,旧 `.pointerSized` 记 4096 是错的。 + - **`Builtin.Int1` → `.bool`(XI 254)**:一个字节只存 0 或 1,其余 254 个位模式都是 extra inhabitant,与 `Swift.Bool` 相同。兜底表曾记成 `.fixedWidthScalar(1)`(XI 0);因为 libswiftCore 的叶子记录一直没被用上,libswiftCore 自己的 `Bool` 结构化算出来就是 XI 0(用户镜像里的 `Bool` 被冻结表挡住,不受影响)。2026-10-20 改正,同时补上 `Builtin.FPIEEE16`(2 字节,`Float16` 的存储)。兜底表里 libswiftCore 也有记录的叶子,现在由 `StandardLibraryLeafLayoutTests` 逐个对记录断言。 - **0-case 枚举(uninhabited / 命名空间 enum)XI = 0**:`numElements <= 1` 走 IRGen `SingletonEnumImplStrategy`,无 singleton → `getFixedExtraInhabitantCount` = 0;旧 no-payload 公式给 `2^0 − 0 = 1`,被五元组 sweep 一次性抓出(fixture 里所有命名空间 enum 齐刷刷 mismatch)。 多 payload 枚举 XI 此前已精确(`MultiPayloadEnumStructuralTests`)。 - **引用存储不坍缩 existential:`weak`/`unowned`/`unowned(unsafe)` 的宽度由 referent 决定,不恒为 1 word**(2026-07-26,用户实报 SwiftUI `StyledTextResponder` 字段偏移全线错位):`weak` 等修饰符只作用在**对象引用字**上,referent 若是 **class-bound existential**,见证表字照样留在字段里。实测(macOS 26.5 runtime):`weak var x: (any P)?` = **16 字节**(对象字 + 1 见证表字)、`any P & Q` = **24**,而 `AnyObject` 与 **`@objc` 协议** existential(都不带 Swift 见证表)= **8**;`unowned` / `unowned(unsafe)` 同宽。旧实现对 `.weak`/`.unowned`/`.unmanaged` 三个 node kind 无条件返回单字,于是**每少一张见证表就少 8 字节**。 diff --git a/Documentations/README.md b/Documentations/README.md index c8ffe1712..4e89fe70d 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -78,6 +78,7 @@ selects names using each access's offset and width. | [Modules/SwiftLayout.md](Internal/Modules/SwiftLayout.md) | SwiftLayout 模块参考:静态布局引擎的能力边界与八个子系统(入口与递归求解、基础累加、已知布局表与 builtin 交叉校验、三个桥接、无实参也能算的那部分、ObjC 互操作、镜像查找面),四条关键契约(降级是产品的一部分、实参永远赢过推断、官方离线实现不是标准答案、跨模块偏移按具体部署算)。 | | [Modules/SwiftPrivateDiscriminators.md](Internal/Modules/SwiftPrivateDiscriminators.md) | SwiftPrivateDiscriminators 模块参考:从 private discriminator 反推源文件的三个子系统(纯函数的五步候选搜索、生成的已知文件名清单、按镜像取候选并记住答案的 index),关键契约(只会还原不出、不会还原错;模块名候选的先后;候选与 RuntimeViewer 侧栏对象表的差别;名字首次请求才读,在锁外、在大栈上读,读完放掉索引器)与测试锚点。 | | [Modules/SwiftThunkAnalysis.md](Internal/Modules/SwiftThunkAnalysis.md) | SwiftThunkAnalysis 模块参考:kind-9 accessor thunk 符号求值的模块视角索引——五个子系统、按输入形态列的当前能力表(含 macOS 27 cache 打不开这个已知缺口)、三条故意的拒绝、dyld cache 偏移口径与 `ExportedSymbol.offset` 两个静默出错点、测试如何 scope 一个读不出来的 resolver。 | +| [Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md) | CrossReferenceAnalysis 模块参考(含 ARM64InstructionDecoding):从 arm64 机器码读出函数表与每个函数的引用——地址口径(`CodeLocation`、MachOKit `FunctionStart.offset` 其实是绝对地址)、macOS 27 / iOS 27 起全缓存共用的 selector 桩与 GOT 桩、读任何目标前先确认可读、寄存器只记确定的事、尾调用与跳转表的区分、运行时辅助调用名单、分析器的生命周期与吞吐。 | | [ProjectEvolutionLog.md](Internal/ProjectEvolutionLog.md) | 编年演进账本:逐工作弧(Foundation 解析 → demangler → 模块化 → SwiftLayout → SwiftDiffing/ABI evolution …)的时间段/动机/关键决策/落地文档/版本对应,含每批次必须追加的维护约定。 | | [ReviewAdjudications.md](Internal/ReviewAdjudications.md) | Review 已裁决清单:判定为「不修 / 误报」的发现及结论、理由、复审条件;每轮 code review 先对照此表,已裁决且理由仍成立的直接跳过。 | | [SwiftModularizationMigration.md](Internal/SwiftModularizationMigration.md) | The `SwiftInterface` monolith → layered peer modules refactor; where everything moved. | @@ -159,7 +160,7 @@ selects names using each access's offset and width. | [Evolutions/0053-shared-cache-composition-and-eviction-registry.md](Evolutions/0053-shared-cache-composition-and-eviction-registry.md) | **提案 0053(Implemented)**:按镜像缓存整治——`SharedCache` 的并发核心不动,改它周围四件事:每实例的内存压力 `removeAll()` 绕过「最后一个 indexer 才驱逐」的认领规则且回收不到被活引用钉住的存储,整个去掉、改为注册表暴露显式 API;基类 `buildStorage(for: some MachORepresentableWithCache)` 把读者类型擦掉、6 个子类各自 `as?` 再分派,改为不可继承的组合式原语、构建闭包在调用点给;每次查找把 identifier 装箱成 `AnyHashable` 并哈希整条路径,改为只哈希 UUID / 指针的 `SharedCacheKey`;同线程同键重入静默死锁,改为带信息的 precondition。驱逐收口到下沉至 `MachOCaches` 的 `SharedCacheRegistry`(eviction group 加 dependents 表),两个手写 Store 并入。暂不改名,句柄 API 待测量后另议。 | | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | | [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | -| [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.24.0 删除(原定 0.23.0);范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | +| [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.25.0 删除(原定 0.23.0,两次推迟);范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/0058-swift-section-kit.md](Evolutions/0058-swift-section-kit.md) | **提案 0058(Implemented)**:把 swift-section 的功能抽成对外 product `SwiftSectionKit`——每个子命令一个按用途建模的请求类型(`DumpRequest`、`ABIDiffRequest`……),输出交给调用方注入的输出端,测试换成内存记录器即可断言;CLI 只剩 flag 声明与校验、flag → 请求映射、库错误翻译回历史文案、诊断的流路由和退出码。输出逐字节保持,只有两处有意偏差(写流统一走 `fputs` / `fwrite`;参数层面的错误先于打开二进制报出)。 | | [Evolutions/0059-dump-declaration-identity.md](Evolutions/0059-dump-declaration-identity.md) | **提案 0059(Implemented)**:`DumpRequest` / `ObjCDumpRequest` 交出每个顶层声明时附上种类与名字(`DumpedDeclaration`),`SwiftSectionOutput` 新增带默认实现的 `write(_:declaring:)` 接收;默认实现转给 `write(_:)`,CLI 输出逐字节不变。让宿主不必自己重建索引就能按声明拆文件(首个宿主:ReverseEngineeringToolbox 的「每个类型一个文件」)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | @@ -170,6 +171,13 @@ selects names using each access's offset and width. | [Evolutions/0067-nested-field-offset-memoization.md](Evolutions/0067-nested-field-offset-memoization.md) | **提案 0067(Implemented)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/0068-nested-definition-regions.md](Evolutions/0068-nested-definition-regions.md) | **提案 0068(Implemented)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [Evolutions/0069-offline-generic-specialization.md](Evolutions/0069-offline-generic-specialization.md) | **提案 0069(Implemented)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | +| [Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md](Evolutions/0070-borrow-accessors-and-suppressed-associated-types.md) | **提案 0070(Implemented)**:Swift 6.4 的两种声明形态。SE-0507 的 `borrow` / `mutate` 访问器:只声明它们的属性、下标与协议要求原先在 interface 与 dump 里整个消失,现在符号索引、声明模型、打印都认,印成 `{ borrow mutate }`。SE-0503 关联类型上的 `~Copyable` / `~Escapable`:二进制不记录这个声明,改为从本镜像里该协议的 extension 签名推断(只有主关联类型留得下证据),有证据才印 `associatedtype Element: ~Swift.Copyable`。测试现场用 Swift 6.4 工具链编 fixture,找不到就跳过。 | +| [Evolutions/0071-swift-capstone-7.md](Evolutions/0071-swift-capstone-7.md) | **提案 0071(Implemented)**:迁到 swift-capstone 7.0。`SwiftThunkAnalysis` 的解码器改用不可复制的 `Disassembler`,在 `forEachInstruction` 的闭包里把每条指令就地转成 `ThunkInstruction`;别名改看 `alias`,写回改看 `writesBackBaseRegister`。只改 `CapstoneThunkDecoder.swift`,对外接口不变;依赖下限从 swift-capstone 6.0.1 提到 7.0.0。 | +| [Evolutions/0072-cross-reference-analysis.md](Evolutions/0072-cross-reference-analysis.md) | **提案 0072(Implemented)**:新 target `CrossReferenceAnalysis`——从 arm64 机器码读出一个镜像的函数表与每个函数引用了什么(直接调用、ObjC 消息、跨库调用、类型引用、间接调用及其候选),认 macOS 27 / iOS 27 起全缓存共用的桩与更早的镜像自带桩;RuntimeViewer 交叉引用功能(0056-cross-references)的分析层。 | +| [Evolutions/0073-protocol-requirement-placement.md](Evolutions/0073-protocol-requirement-placement.md) | **提案 0073(Implemented)**:interface 的新开关 `protocolRequirementPlacement`(CLI `interface --requirements-on-associated-types`),打开后把关于协议自己某个关联类型的约束写到那个 `associatedtype` 上(`associatedtype Failure: Swift.Error`),摆法与编译器写 `.swiftinterface` 时一致;唯一不照抄的是递归协议的 `Self.Child.Leaf: Hashable`,编译器把它挂到 `Leaf` 上改变了含义,这里挂在 `Child` 上。默认仍全部写在协议的 `where` 子句,输出逐字节不变;dump 与 diff / evolution 不接。两种写法表达的约束相同,由往返编译测试保证。顺带修好约束右侧的复合类型被印成另一条约束的 bug(`Self.Second == [Self.First]` 印成 `Self.Second == Self.First`),dump 与 interface 都受影响。 | +| [Evolutions/draft-evolution-unobservable-presence.md](Evolutions/draft-evolution-unobservable-presence.md) | **提案 draft(Accepted)**:evolution 与 diff 区分「不存在」和「看不见」——macOS 13.0–14.8 的 SwiftUI 被剥掉了全部 local Swift 符号,非导出成员在这些版本里全部缺席,27.0 的 51 版 evolution 因此有 5,189 条假缺口(`removed in 13.0 · added in 15.0`)。快照记下镜像有没有 local Swift 符号、每个成员是否导出(格式版本 8),被剥版本里本来就看不见的声明记为看不见;一段看不见的版本两侧状态相同时按两侧推断并在位图里画 `◍`,两侧不同时记成区间事件(`removed between 12.7 and 15.0`)。规则放在 SwiftDiffing,diff 的判定一并适用,`diff --interface` 的渲染不动。 | +| [Evolutions/0074-private-declaration-source-files.md](Evolutions/0074-private-declaration-source-files.md) | **提案 0074(Implemented)**:dump 与 interface 标出私有声明来自哪个源文件——0063 的反推能力(`SwiftPrivateDiscriminators`)原先只有 RuntimeViewer 在用,dump 只印 discriminator 原文,interface 连它也不印,同名的两个私有类型印出来一模一样。新开关 `--emit-private-source-files`(默认关)打开后,名字带来新 discriminator 的声明上方加一行 `// X is declared in Y.swift`,还原不出的照实写;打印前对整个镜像批量反推一次,dump 为此另建索引器读名字,候选与还原算法不变。SwiftUI 上 dump 从 12 秒变成 58 秒,多出的几乎全花在还原不出的那些上。 | +| [Evolutions/0075-wrapped-reader-recognition.md](Evolutions/0075-wrapped-reader-recognition.md) | **提案 0075(Implemented)**:MachOKitUI 把 `MachOImage` / `MachOFile` 包一层交给本库,库里 16 个文件 38 处写死具体类型的判断(外加一处转成内部协议的取法、打印器要求的 `FieldLayoutRenderable`)都认不出它:进程内镜像的 opaque 引用按负偏移转无符号数而 trap,文件包装让 interface 段错误,其余各处悄悄降级。MachOKitExtensions 1.3.0 加泛型包装协议 `MachOReaderWrapper`(`associatedtype Base`),`asMachOImage` 放宽、新增 `asMachOFile` 与 `underlyingReader`,库里每个「这是哪种读取器」的问题都问到包装底下的读取器;`FieldLayoutRenderable` 给包装类型默认实现;解析不了的引用不再 trap;源码扫描测试防止写死的类型判断回来。依赖 MachOKitExtensions 1.3.0。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **`SymbolIndexStore` 内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);`SymbolIndexStore` 在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Package.swift b/Package.swift index b25a80ac1..d18ff9dbe 100644 --- a/Package.swift +++ b/Package.swift @@ -154,7 +154,10 @@ extension Package.Dependency { // instance each time, which `DyldCache.fileIO` keys its mapping on. // 1.1.2 adds `FullDyldCache.cachedHost`, the system cache opened // once per process rather than once per dependency locator. - from: "1.1.2", + // 1.3.0 adds `MachOReaderWrapper`, through which every reader-kind + // question (`asMachOImage`, `asMachOFile`, `underlyingReader`) + // sees through a host's wrapper type. + from: "1.3.0", ), ) @@ -228,7 +231,7 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/swift-capstone", - from: "6.0.1", + from: "7.0.0", traits: capstoneTraits, ), ) @@ -328,6 +331,14 @@ extension Target { path: "Sources/Support/Utilities", ) + /// Hand decoding of the few A64 encodings the analyses read, and the + /// trampoline shapes the linker and the dyld cache builder emit. Shared + /// by `SwiftThunkAnalysis` and `CrossReferenceAnalysis`. + static let ARM64InstructionDecoding = Target.target( + name: "ARM64InstructionDecoding", + path: "Sources/Support/ARM64InstructionDecoding", + ) + static let MachOCaches = Target.target( name: "MachOCaches", dependencies: [ @@ -551,6 +562,7 @@ extension Target { .product(.Capstone), .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .target(.Utilities), + .target(.ARM64InstructionDecoding), .target(.MachOCaches), .target(.MachOFoundation), .target(.MachOSwiftSection), @@ -559,6 +571,24 @@ extension Target { path: "Sources/Analysis/SwiftThunkAnalysis", ) + /// What each function of an image references, read from its arm64 + /// machine code in process (evolution proposal `cross-reference-analysis`). + static let CrossReferenceAnalysis = Target.target( + name: "CrossReferenceAnalysis", + dependencies: [ + .product(.MachOKit), + .product(.MachOObjCSection), + .product(.Demangling), + .target(.ARM64InstructionDecoding), + .target(.MachOFoundation), + .target(.MachOSwiftSection), + // `SymbolicDemangler`: a type's name from its descriptor when no + // symbol spells it. + .target(.SwiftInspection), + ], + path: "Sources/Analysis/CrossReferenceAnalysis", + ) + static let SwiftDump = Target.target( name: "SwiftDump", dependencies: [ @@ -632,16 +662,19 @@ extension Target { /// Recovers the source files private discriminators were derived from: /// MD5 over candidate file names, drawn from an indexed image's names and /// a generated list of known file names (evolution proposal - /// `private-declarations`). + /// `private-declarations`). Its index is what tells dump and interface + /// those files (`private-declaration-source-files`). static let SwiftPrivateDiscriminators = Target.target( name: "SwiftPrivateDiscriminators", dependencies: [ .product(.MachOKit), .product(.MachOObjCSection), .product(.Demangling), + .target(.MachOFoundation), .target(.MachOSwiftSection), .target(.SwiftInspection), .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), ], path: "Sources/Declaration/SwiftPrivateDiscriminators", @@ -793,6 +826,7 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftDiffing), .target(.SwiftInterface), + .target(.SwiftPrivateDiscriminators), .target(.TypeIndexing), .target(.Utilities), .product(.MachOKit), @@ -1060,6 +1094,8 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftSpecialization), .target(.SwiftInterface), + // The nested-definition contract with source-file comments on. + .target(.SwiftPrivateDiscriminators), .product(.MachOKitExtensions), .target(.MachOTestingSupport), .target(.MachOFixtureSupport), @@ -1115,6 +1151,21 @@ extension Target { swiftSettings: testSettings, ) + static let CrossReferenceAnalysisTests = Target.testTarget( + name: "CrossReferenceAnalysisTests", + dependencies: [ + .target(.CrossReferenceAnalysis), + .target(.ARM64InstructionDecoding), + .product(.MachOKit), + .product(.Capstone), + .product(.Demangling), + .target(.MachOSwiftSection), + .target(.MachOReading), + .target(.SwiftInspection), + ], + swiftSettings: testSettings, + ) + static let SwiftAttributeInferenceTests = Target.testTarget( name: "SwiftAttributeInferenceTests", dependencies: [ @@ -1161,6 +1212,9 @@ extension Target { dependencies: [ .target(.SwiftSectionKit), .target(.MachOFoundation), + // `LocalTypeFixture` and `ExclusiveImageAccess`, for the source + // files of a public type's private members. + .target(.MachOTestingSupport), .target(.SwiftDeclaration), .target(.SwiftDiffing), .target(.SwiftOutputTransformer), @@ -1178,6 +1232,7 @@ extension Target { .target(.SwiftPrivateDiscriminators), .target(.SwiftInspection), .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), .target(.MachOFixtureSupport), .target(.MachOTestingSupport), @@ -1277,6 +1332,7 @@ let package = Package( .library(.SwiftLayout), .library(.SwiftDeclarationRendering), .library(.SwiftThunkAnalysis), + .library(.CrossReferenceAnalysis), .library(.SwiftDump), .library(.SwiftDeclaration), .library(.SwiftAttributeInference), @@ -1294,6 +1350,7 @@ let package = Package( targets: [ // Library .Utilities, + .ARM64InstructionDecoding, .SwiftOutputTransformer, .MachOCaches, .MachODependencies, @@ -1309,6 +1366,7 @@ let package = Package( .SwiftLayout, .SwiftDeclarationRendering, .SwiftThunkAnalysis, + .CrossReferenceAnalysis, .SwiftDump, .SwiftDeclaration, .SwiftAttributeInference, @@ -1345,6 +1403,7 @@ let package = Package( .SwiftPrintingTests, .SwiftDeclarationRenderingTests, .SwiftThunkAnalysisTests, + .CrossReferenceAnalysisTests, .SwiftAttributeInferenceTests, .SwiftDiffingTests, .SwiftSectionCommandTests, diff --git a/README.md b/README.md index b38d469b8..4a424f2ab 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ On top of that model it generates complete Swift interfaces, diffs a module's AB ## Requirements -- Swift 6.2+ -- Xcode 26.0+ +- Swift 6.3+ +- Xcode 26.4+ - macOS 10.15+ / iOS 13+ / tvOS 13+ / watchOS 6+ / visionOS 1+ ## MachOSwiftSection Library @@ -33,7 +33,7 @@ Add the package to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.23.0"), + .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.24.0"), ], targets: [ .target( @@ -68,6 +68,7 @@ Declare every product whose module you import. In particular, `MachOSwiftSection | `SwiftInspection` | Symbol attribution and runtime metadata analysis — `SymbolicDemangler` (formerly `MetadataReader`), `EnumLayoutCalculator`, `ClassHierarchyDumper`. | | `SwiftLayout` | The static layout engine: field offsets, type layouts and enum layouts computed offline, the way the runtime computes them at load time. | | `SwiftThunkAnalysis` | Reads a type stored behind a metadata accessor thunk (availability-conditional opaque types, noncopyable fields) by evaluating its ARM64 code instead of running it, and ties a class's ObjC method table to its Swift members. | +| `CrossReferenceAnalysis` | What each function of a loaded arm64 image calls and references — functions, Objective-C classes, Swift types — read from its machine code. `MachOImage` only. | | `SwiftSpecialization` | Runtime specialization of generic types (`GenericSpecializer`). | | `TypeIndexing` | Attributes `__C` types to their real module (`__C.NSString` → `Foundation.NSString`) through SDK module interfaces and APINotes. macOS only. | @@ -80,6 +81,7 @@ Declare every product whose module you import. In particular, `MachOSwiftSection | `SwiftDiffing` | ABI comparison over the indexed model, with no Mach-O needed: `ABIDiffer`, `ABIEvolution`, `ABISnapshot`. | | `SwiftDeclaration` | The declaration model shared by indexing, printing and diffing. | | `SwiftIndexing` | Builds the declaration model from an image. | +| `SwiftPrivateDiscriminators` | Recovers the source file a private discriminator was derived from, by hashing candidate file names. | | `SwiftPrinting` | Renders the declaration model as Swift source. | | `SwiftAttributeInference` | Infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). | | `SwiftDeclarationRendering` | The comment rendering shared by dump and interface (field layouts, opaque types, specialized metadata). | @@ -167,7 +169,7 @@ Generated interfaces reflect a wide range of Swift language features: - `EnumLayoutCalculator` — compute the on-disk layout of Swift enums, including single-payload and multi-payload (tagged and untagged) cases. Mirrors the ABI rules in `swift/ABI/Enum.h`. - `ClassHierarchyDumper` — walk a class's inheritance chain across Swift/ObjC boundaries (requires `@_spi(Internals) import SwiftInspection`, `MachOImage` only). -- `SymbolicDemangler` — demangle types, symbols, context descriptors, and build generic signatures against a Mach-O (requires `@_spi(Internals) import SwiftInspection`). Named `MetadataReader` before 0.20.0; the old name remains as a deprecated alias for one release. +- `SymbolicDemangler` — demangle types, symbols, context descriptors, and build generic signatures against a Mach-O (requires `@_spi(Internals) import SwiftInspection`). Named `MetadataReader` before 0.20.0; the old name remains as a deprecated alias. #### Run a swift-section Command from Code @@ -207,7 +209,7 @@ You can get the swift-section CLI tool in three ways: - **GitHub Releases**: Download from [GitHub releases](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/releases) - **Homebrew**: Install via `brew install swift-section` -- **Build from Source**: Build with `./build-executable-product.sh` (requires Xcode 26.0 / Swift 6.2+ toolchain), or build and install in one step with `./install.sh [install-directory]` (defaults to `/usr/local/bin`, using `sudo` only when that directory is not writable) +- **Build from Source**: Build with `./build-executable-product.sh` (requires Xcode 26.4 / Swift 6.3+ toolchain), or build and install in one step with `./install.sh [install-directory]` (defaults to `/usr/local/bin`, using `sudo` only when that directory is not writable) ### Usage @@ -284,6 +286,20 @@ swift-section dump --emit-header /path/to/binary swift-section dump --emit-export-status /path/to/binary ``` +**Source files of private declarations:** +```bash +# Comment each declaration whose name carries a private discriminator +# (`(CodingKeys in _B89E…)`) with the source file the discriminator was derived +# from: `// CodingKeys is declared in Codable.swift`. The file is recovered by +# hashing candidate file names, so a named file is certain; one no candidate +# produces reads `could not be recovered`, with its discriminator. A member of +# a private type repeats nothing; a public type's private member names its own +# file. The image is indexed and every discriminator searched once before the +# first declaration prints, which takes a while for a framework the size of +# SwiftUI. +swift-section dump --emit-private-source-files /path/to/binary +``` + **Addresses and ordering:** ```bash # The address of each member's symbol @@ -457,9 +473,15 @@ swift-section interface --emit-export-status /path/to/binary # anything without export evidence (and every `override` / `@objc` member) is # kept, so an `-enable-testing` build keeps its `internal` declarations. swift-section interface --exported-only /path/to/binary + +# The source file each private declaration comes from, as `dump` prints it. +# The interface prints no private discriminator anywhere else, so this is what +# tells two same-named private types from different files apart; an +# unrecovered file is named by its discriminator. +swift-section interface --emit-private-source-files /path/to/binary ``` -All three flags default to off, keeping default output byte-identical. +All four flags default to off, keeping default output byte-identical. **Working with dyld shared cache:** diff --git a/Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md b/Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md new file mode 100644 index 000000000..1b6ee65b7 --- /dev/null +++ b/Roadmaps/2026-10-17-cross-reference-analysis-review-findings.md @@ -0,0 +1,146 @@ +# 交叉引用分析审查记录(`feature/cross-reference-analysis`,2026-10-17) + +审查对象:`feature/cross-reference-analysis` 相对 `0.23.0`(`b7be58ec`)的全部提交(`0c0ebce3` … `c2cefa9c`),即提案 [0072-cross-reference-analysis](../Documentations/Evolutions/0072-cross-reference-analysis.md) 的第一、二批。同一轮也审了 RuntimeViewer 的 `feature/cross-references`,那边的条目(编号 C 开头的大部分、D1、D4、D10–D13)记在 RuntimeViewer 的 `Documentations/KnownIssues/2026-10-17-cross-references-review-findings.md`。 + +**方式**:四个子代理按模块并行通读(只读),交回 47 条候选,去掉重复 43 条(两个仓库合计);每条都由本人回到代码复核,能造出复现的造复现。编号沿用审查时的分组:A 扫描与寄存器跟踪,B 分析器与预筛,C RuntimeViewer 引擎侧,D 测试与文档,N 公开接口的小毛病。 + +**四问的共同答案**:本模块是这个分支新写的,`0.23.0` / `main` 上没有;GitHub 上没有相关 PR 或 issue;[ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md) 在这一轮之前没有覆盖这些发现的条目。所以每条都是「本分支引入、以前没修过」,例外写在各条的「既往」里。 + +**状态**:用户 2026-10-17 批准按建议修。修了的每条都先写了修复前失败的测试(修前修后的实测写在各条),判为不修或误报的登记在 ReviewAdjudications A62–A67。A5(循环与跳转表)按约定先量数据给用户看,用户定为保持现状(登记 A68)。修复过程中机器死过一次(同时跑 release 全量构建与两套测试),之后重任务一次只跑一个。 + +## 总表 + +| # | 问题 | 严重度 | 处理 | 测试 | +|---|---|---|---|---| +| A1 | 带回写的读写、原子指令、寄存器对与 `casp` 的第二个寄存器、`umov` / `smov`、定点转换、SVE / SME、`sysl`、`svc` 写了寄存器却没作废 | 中 | 已修;SwiftThunkAnalysis 的同类两处一并修 | `RegisterFileTests`、`ThunkRegisterTrackerTests`、`ThunkTypeEvaluatorTests.aWriteBackPairMovesItsBase` | +| A4 | `XPAC` 的注释说保留寄存器,代码其实作废 | 低 | 已改注释 | —(行为不变) | +| A5 | 循环头与跳转表落点保留 `x19`–`x28` 的旧值 | 中 | 量了:错 0.02%–0.04% 的引用,精确修法多花 35%–60% 时间;用户定为不修,登记 A68 | 见该条 | +| A6 | 待到目标的排序插入、夹在代码里的数据线性查找 | 低(性能) | 量了,不修(A66) | — | +| A7 | 直接跳转型的桩不跟;槽位指向不认识的地址时不退回导入名 | 低 | 暂缓:本机无法复现(A64) | — | +| A8 | `bc.cond` 不解码;共用 selector 桩读字符串前不检查;`svc` 不作废 `x0` / `x1` | 低 | `svc` 并入 A1 修;其余不修(A65) | `RegisterFileTests` 的 `svc` 用例 | +| B1 | 被别的镜像改名再导出的 C 函数与类,跨库查调用者时漏掉按新名字导入的镜像 | 高 | 已修 | `RenamedReexportTests` | +| B2 | 类型查询里的 demangle 结果钉进进程级缓存,永不淘汰 | 中 | 已修 | `TypeNameRetentionTests` | +| B3 | 缓存外的镜像以安装名为路径:主程序与 bundle 是空串,框架是 `@rpath/…` | 高 | 已修 | `StandaloneImageTests` 新增三个 | +| B4 | `-bundle_loader` 的插件不算主程序的依赖方;同一安装名的两份拷贝只认第一份 | 低 | 随 B3 修 | `aBundleCountsAsLinkingTheMainExecutable` | +| B5 | 分析器存活期间缓存外镜像被卸载,会读到已释放的内存 | 低 | 不修,文档写明(A63) | — | +| B6 | `approximateByteCount` 不算字符串 | 低 | 补文档;RuntimeViewer 侧判为误报 | — | +| B7 | 按镜像的缓存用手写锁加字典,不用 `SharedCache` | — | 不修,有意设计(A62) | — | +| N1 | `swiftTypeDescriptorLocations` 承诺「一个或没有」,回退路径可能多个、顺序不定 | 低 | 已改文档 | — | +| N2 | `CodeReferenceTable.keys` 暴露 `Dictionary.Keys` | 低 | 改为 `some Collection` | 编译 | +| D2 | 类型名查询测试里四个标准库类型与被测代码同一套解开,等于没测 | 低 | 已改测试与模块文档的说法 | — | +| D3 | 与 Capstone 的对照只查「扫描没漏」,注释说「一处不多」 | 低 | 改成双向对照 | `callSitesMatchCapstone` | +| D5 | super 发送的类测试分辨不出类来自 `__objc_superrefs` 还是方法符号 | 低 | 补一个只有槽位能通过的测试(经变异验证) | `superSendsInBlocksNameTheClassOfTheirMethod` | +| D6 | 测试注释说「换系统版本不影响成立」,部分断言钉的是 macOS 27.2 的代码 | 低 | 改注释;不按系统版本门控(A67) | — | +| D8 | AGENTS.md 说「只为起名用元数据、从不用于扫描」「整个缓存约一秒扫完」,引用种类缺类与类型 | 中 | 已改 | — | +| D9、D14–D17 | 提案与模块文档的数字对不上、方案一节过时、内存说法缺了索引、镜像数差一 | 低 | 已改 | — | + +## A1 — 写了寄存器却没作废的指令 + +- **问题**:扫描器的规矩是「不建模的指令写了哪个寄存器就忘掉它」。`RegisterFile.forgetRegistersWritten(by:)` 漏了:前 / 后变址的单寄存器与寄存器对读写会把基址寄存器改掉(`ldr x9, [x8], #16` 之后 `x8` 加了 16);SIMD 与浮点的读写在入口就返回,连它们的基址回写也一起漏掉;不带内存序的原子指令(`ldadd`、`swp`,位 23–22 为 00)被当成存储;`ldxp` 的第二个寄存器、`casp` 的 `Rs+1`;从向量寄存器取值的 `umov` / `smov`;浮点转定点的 `fcvtzs xd, dn, #fbits`;SVE / SME 里写通用寄存器的几条(`cntd`、`addvl`、`rdvl`、`rdsvl`);`sysl`;系统调用 `svc`(结果在 `x0`、`x1`)。 +- **复现**:`RegisterFileTests.forgetsEveryRegisterAnInstructionWrites`,48 条汇编器编出的指令,每条给出架构写的寄存器。修复前 34 个用例失败(`svc` 后补,单独确认过失败)。`capstoneNamesNoOtherWrittenRegister` 用 Capstone 的寄存器访问表独立核对这张表没有漏项;Capstone 把 `cas` / `casp` 的基址也算成被写,架构上并不写,测试里列为已知偏差。`aPlainAccessForgetsOnlyWhatItLoads` 钉住普通读写只作废目标寄存器,不多忘。 +- **修法**:判断改写成纯函数 `RegisterFile.registersWritten(by:)`,返回位掩码(调用返回调用方保存的寄存器),`forgetRegistersWritten(by:)` 按掩码作废。按 A64 读写编码的分组(位 29–28)逐类判断,未分配或不常见的形态一律多忘。 +- **影响**:只会让扫描多忘,原本正确的结果不会丢。全缓存里这些形态多在 `memcpy` 一类循环和原子操作里,影响了多少结果没有单独量。 +- **横向排查**:SwiftThunkAnalysis 有自己的寄存器跟踪。`ThunkRegisterTracker` 对带回写的寄存器对不作废基址(`ObjCMethodThunkReferences` 用它找 thunk 引用的地址);`ThunkTypeEvaluator` 只在基址是 `sp` 时作废(经 `forgetStack()`)。两处都改为作废基址。修前 `ThunkRegisterTrackerTests.aWriteBackPairForgetsItsBase` 与 `aWriteBackPairMovesItsBase`(读与写两半各自确认过)失败。单寄存器的回写这边本来就对:Capstone 的写入表里带着基址。 +- **既往**:`forgetRegistersWritten` 出自 `0c0ebce3`,之后没改过;SwiftThunkAnalysis 的两处出自 `09c08453`(2026-09-12),thunk 里成对回写只用在 `sp` 上,所以一直没暴露。 + +## A4 — `XPAC` 的注释 + +- 注释说「PAC、AUT、XPAC 原样保留寄存器」,掩码 `0xFFFF_C000` 却只覆盖 opcode 位 13–10,`XPACI` / `XPACD`(位 14 置位)实际被作废。作废是保守的,只改注释:PAC 与 AUT 原地签名或认证、含义不变,保留;XPAC 作废。 + +## A5 — 循环头与跳转表落点保留 `x19`–`x28` + +- **问题**:分支跟踪(`00c5a040`)在循环头(向后分支的目标)与跳转表落点(无条件转移之后、没有向前分支指向的指令)只作废调用方保存的 `x0`–`x18`。`x19`–`x28` 留下的是文本上前一块末尾的值:循环体里改了 `x22`、跳回循环头,扫描器仍以为 `x22` 是进循环前的值;switch 的某个 case 改了 `x20` 后跳走,下一个 case 拿到的是它留下的值。 +- **当初为什么这样做**:提案给循环头的理由是「回边的状态此时还不知道」——这个理由对 `x19`–`x28` 同样成立,文档没有说为什么保留它们,判断是疏漏。 +- **测量方法**:一个临时的测量测试(量完已删,没有留在仓库里;要实现时照下面第 2 条的描述写),对同一批函数用几种做法各扫一遍,逐函数比较报出的引用。范围:六个大镜像(AppKit、Foundation、CoreFoundation、SwiftUICore、libobjc、Mac Catalyst 的 UIKitCore,共 3,317,645 条引用),以及缓存里每 16 个取 1 个(257 个镜像,7,105,278 条)。做法: + 1. 全部作废:循环头与没人指向的落点忘掉所有寄存器。 + 2. 精确:含循环的函数反复扫,循环头与上一遍回边带回的状态取交集,直到回边的状态不再变化(第一遍乐观;平均每个含循环的函数扫 2.1 遍,8 遍封顶,全部样本里只有 1 个函数没收敛)。按构造,它与现行做法的每一处差异都是现行做法在本模型下错了或漏了。 + 3. 精确,外加跳转表:跳转表的 `br` 之后、没人指向的落点取 `br` 那一刻的状态。 +- **结果**(release,单线程,扫描时间是这批镜像的合计): + + | 做法 | 六个大镜像:改变的引用 | 257 个镜像:改变的引用 | 扫描时间(六个 / 257 个) | + |---|---|---|---| + | 现行 | — | — | 1.15 s / 3.26 s | + | 全部作废 | 约 3.9 万:`self` 发送少 30,390,类引用少 4,425,类字面量发送少 3,062 | 约 1.5 万:`self` 发送少 7,666,类引用少 4,415 | 0.91 s / 2.52 s | + | 精确 | 1,203 条变了或没了、1,175 条新出现(0.04%):`self` 发送 −665 / +62,类字面量发送 −36 / +123,间接调用的表内偏移 −259 / +189 | 1,584 / 1,771(0.02%):间接调用 −1,080 / +1,196,类引用 −7 / +192,`self` 发送 −152 / +23 | 1.63 s / 5.26 s(+42% / +61%) | + | 精确外加跳转表 | 约 1,360 / 1,325 | 约 2,000 / 2,220 | 1.54 s / 5.01 s | + +- **抽查**:`-[NSMenuItem _titlePathForUserKeyEquivalents]` 是典型:`x22` 先是 `self`,循环体把它换成父菜单项(`ldr x22, [x8, x26, lsl #3]`)再跳回,循环头之后的 `_titleForUserKeyEquivalents` 发送现行做法说「发给 self」,精确做法说「接收者未知」。 +- **试过、弃用的近似**:只作废「循环区间里写过的寄存器」的几种写法(按合并后的区间、按循环头、排除不能回到回边的块、排除异常落点),每一版都还会丢掉正确的事实:`@synchronized` 的异常落点 `mov x19, x0` 写进了共享的解锁代码,循环前一次性 `adrp` 出的页地址被算进循环的写集合,等等。所以只留精确做法作为候选。 +- **值不值得修**:现行做法错的只占引用的 0.02%–0.04%,几乎都是循环里发送的接收者提示(「确定」与「按 selector」之间,极少数情况会把真实的调用者按类排除掉);精确做法要多花 35%–60% 的扫描时间。 +- **处理**:不修,作为已知局限(用户 2026-10-17 看过上面的数据后选定,登记 A68)。给用户的三个选项是:保持现状(建议)、精确做法、循环头全部作废。 + +## A6 — 待到目标的排序插入、夹在代码里的数据线性查找 + +- **问题**:`carry(to:)` 把向前分支的目标与约 640 字节的快照插进按地址排序的数组,近处的分支插在一长串远处目标前面时要整体搬动;`isInDataInCode` 对每条指令线性查一遍数据区间。 +- **测量**(release,同一个临时测量测试): + - 数据区间:抽样的 257 个缓存镜像里一条都没有(缓存镜像的 `LC_DATA_IN_CODE` 是空的),线性查找实际不发生。 + - 排序插入:向前目标最多的函数确实更慢。WebCore 平均每条指令 51 ns,`FormatConverter::convert`(5,529 个向前目标、9.3 万条指令)270 ns,扫一遍 25 ms;JavaScriptCore 平均 84 ns,`FTL::LowerDFGToB3::compileNode`(6,745 个目标)718 ns、61 ms;AppKit 里目标最多的函数只有一百多个,看不出差别。JavaScriptCore 目标最多的三个函数合计约 100 ms,占这个镜像扫描时间的 13% 左右;WebCore 的前三个约占 8%。 +- **值不值得修**:慢只在少数巨型函数上,每个几十毫秒,跨库查询是 27 个线程并发扫几千个镜像,这几个函数不在关键路径上。 +- **处理**:不修,登记 A66。若采用 A5 的精确做法(含循环的函数要扫两遍),或有用户在具体镜像上感到慢,再按审查建议的修法(排序数组只存 16 字节的「目标、快照序号」,快照另放一个只追加的数组)重议。 + +## A7 — 直接跳转型的桩、认不出目标的槽位 + +- **问题**:`ImageFunctionTable` 只收 `Stub.Branch.viaSlot` 的桩。MachOKit 把缓存构建器优化过的桩(单条 `b target`,或 `adrp x16; add x16; br x16`)读成 `.direct(target)`,这种桩的槽位为空,调用于是退回桩的导入名(`.importedSymbol`),拿不到目标函数。另外,槽位读出的指针落在所有镜像之外时,解析返回 `.unrecognized`,挡住了退回导入名。 +- **复现 / 是否误报**:本机复现不了。macOS 27.2 的缓存镜像已经没有桩(AppKit、libswiftCore、libsystem_c、Foundation、libobjc 的 `__auth_stubs` / `__stubs` 都是 0 字节),缓存外镜像的桩都经槽位,dyld 加载时就绑好;槽位指向镜像之外只发生在被 interpose 到非镜像内存之类的情况。`.direct` 桩真实存在于 macOS / iOS 26 及更早的缓存里——引擎在被查看的进程里扫,用户在这些系统上用时会遇到:调用按导入名报,按名字查调用者仍能找到,按位置的不行,改名再导出(B1)的别名也对不上。 +- **处理**:暂缓,登记 A64。规则要求修复带修复前失败的测试,本机造不出;等有 26.x 环境(另一台机器或经批准的模拟器)时补测试再修。 + +## A8 — 三处小缺口 + +- `bc.cond`(FEAT_HBC,位 4 置位)不解码:Apple 的核心没有实现这个扩展,编译器不会生成。不修。 +- 共用 selector 桩读字符串前只确认第一个字节可读,没有做 `selectorString(atRuntimeAddress:)` 那样的可打印与终止符检查:这种桩要严格匹配 `adrp x1; add x1; b ` 才认,而 `x1` 只会指向缓存的 selector 字符串区。造不出会读坏的输入,判为疑似误报,不修。 +- `svc` 写 `x0`、`x1`:并入 A1 修。 +- 登记 A65。 + +## B1 — 改名再导出 + +- **问题**:查一个 C 函数的跨库调用者时,预筛只拿函数在本镜像里的名字比对别的镜像的导入表。别的镜像若把它改名再导出,调用方导入的是新名字:libsystem_c 把 libsystem_platform 的 `__platform_strlen` 导出成 `_strlen`,CoreGraphics 把 SkyLight 的 `_SLSMainConnectionID` 导出成 `_CGSMainConnectionID`。按旧做法,这些调用方全被筛掉。 +- **规模**(`dyld_info -exports -all_dyld_cache`,macOS 27.2):12 个镜像里 1,438 条改名再导出——CoreGraphics 从 SkyLight 1,112 条、Metadata 从 MetadataUtilities 165 条、libHeimdalProxy 从 Heimdal 118 条、libsystem_c 从 libsystem_platform 22 条、UIFoundation 把 CoreText 的两个 ObjC 类改名,等等。AppKit 一个镜像就按 CoreGraphics 的名字导入了 273 个 SkyLight 函数。审查时只看了 libSystem 与十几个大框架,报的「23 个」低估了。 +- **复现**:`RenamedReexportTests`:`__platform_strlen` 与 `_SLSMainConnectionID` 的候选里要有 AppKit(同时确认 AppKit 确实调用它们),CoreText 的 `CTEmojiImageAsset` 的候选里要有按 `NSEmojiImageAsset` 导入它的 CharacterPicker。修复前三个都失败。 +- **修法**:新文件 `Scanning/RenamedReexportIndex.swift`:第一次需要时并发走一遍所有镜像的导出表,只记改名的再导出(名字只在命中时才拼出),按「被再导出的镜像与名字」归档;条目里的库序号经加载命令换成镜像。新公开接口 `reexportedNames(ofSymbolsNamed:inImageAt:)` 顺着改名再改名、以及经伞形框架整体再导出的情形(acfsSupport 从 CoreServices 再导出 Metadata 的 `_kMDConfigErase`)找全别名;`imageIndices(callingFunctionAt:symbolNames:among:)` 与类预筛把别名一并比对。 +- **既往**:`a5895b4c` 修过同一个预筛的 Swift 那一半(改按链接关系),C 名字这一半没动过,也没考虑改名再导出。 + +## B2 — demangle 结果永久驻留 + +- **问题**:`swiftTypeKeys(in:)` 与 `SwiftTypeIndex.key(ofDescriptorAt:)` 用 `demangleAsNode`,把整棵树钉进全局 `NodeCache`;`swiftTypeKeys(in:)` 的 mangled 名字一路用 `SymbolicDemangler.demangleType(for:in: InProcessContext.shared)`,结果进了进程级、永不淘汰的 memo。查询碰到的名字没有上限,长期运行的引擎服务里内存只涨不降。AGENTS.md 明令 Sources 不得在无界输入上用 `demangleAsNode`。 +- **复现**:`TypeNameRetentionTests`:用每次随机的标识符造一个访问器符号、一段内存里的 mangled 名字,再用测试包里一个只在这里出现的类型的 `…Mn` 符号,查询之后检查 `NodeCache` 是否已有这个标识符的叶子、进程级 memo 是否已有这个名字(新增的包内探针 `SymbolicDemangler.processScopedMemoHoldsType(for:)`,与既有的 `cacheExists(for:)` 同类)。修复前三个都失败,且都只在驻留断言上失败。 +- **修法**:改用 `demangleAsNodeTransient` 与 `demangleTypeUncached`。按镜像缓存的 `demangleContext(for:in: image.context)` 是仓库通行写法,可随镜像淘汰,不动。修前修后 `SwiftTypeReferenceTests` 的耗时没有变慢。 +- **横向排查**:Sources 里此外没有 `demangleAsNode` 调用。 + +## B3、B4 — 缓存外镜像的路径与链接关系 + +- **问题**:`imagePaths` 取 `MachOImage.path`,即 `LC_ID_DYLIB` 的安装名。主程序与插件 bundle 没有安装名,路径是空串;App 自带的框架是 `@rpath/…`。宿主(RuntimeViewer)用 dyld 给的真实路径查,对不上,报找不到镜像;在这些镜像里找到的调用者带着空串或 `@rpath` 路径。B4:用 `-bundle_loader` 链接宿主的插件经 `EXECUTABLE_ORDINAL` 绑定主程序,没有加载命令指向它,链接关系里不算依赖方;两份同安装名的框架拷贝,链接关系只认第一份。 +- **复现**:`StandaloneImageTests` 新增三个:SymbolTestsCore fixture 的路径是解析符号链接后与加载路径相同的绝对路径、能按它查回来、安装名也能查回来;测试包自己(`MH_BUNDLE`)的路径等于 `dladdr` 给的路径;测试包算作主程序的依赖方。修复前前两个各两处断言失败、第三个失败。 +- **修法**:缓存外的镜像取 `dladdr` 读到的加载路径(按头读,不按序号,免得中途有镜像加载或卸载时错位),缓存里的仍取安装名;另建「安装名 → 全部镜像」的表供加载命令解析,同名的拷贝都算;`imageIndex(forPath:)` 先按路径、再按安装名找。链接关系里每个 `MH_BUNDLE` 都算作每个 `MH_EXECUTE` 的依赖方(超集,预筛只是多扫几个镜像)。 + +## B5 — 分析器存活期间镜像被卸载 + +- 分析器持有缓存外镜像的 `MachOImage` 与映射区间,之后若有镜像被 `dlclose` 卸载,读它会读到已释放的内存。要求恰好在一次查询进行中卸载一个缓存外镜像,实际极少见;RuntimeViewer 的会话在镜像列表变化时换新的分析器。不修,在 `CrossReferenceAnalyzer` 的文档里写明,登记 A63。 + +## B6 — `approximateByteCount` 与字符串 + +- 估算只算引用、键与索引的定长部分。复核发现引用里的字符串几乎都共用存储:selector 与导入名在扫描器里按指针记忆、类名在类索引里按类记忆、访问器符号随调用目标的解析记忆,所以同一次扫描里重复的名字只占一份。审查说「实际占用可能到预算的两倍」不成立。只在文档里写明字符串不计、但同一次扫描里共用;RuntimeViewer 侧按误报登记。 + +## B7 — 手写锁加字典,不用 `SharedCache` + +- AGENTS.md 要求按镜像的缓存用 `SharedCache`。本模块的函数表、类索引、类型索引、链接关系、改名再导出表都属于一个 `CrossReferenceAnalyzer` 实例,随实例释放;`SharedCache` 管的是进程级、要靠注册表淘汰的缓存。不修,登记 A62。 + +## N1、N2 + +- N1:`swiftTypeDescriptorLocations(withKey:inImageAt:)` 的文档说「一个位置,或没有」,可只有找到 `…Mn` 符号时如此;退回逐个算 key 时返回全部同 key 的描述符,顺序不定。改文档如实说明(行为不变:目前见过的镜像里都只有一个)。 +- N2:`keys` 的类型 `Dictionary.Keys` 把实现暴露在公开接口上,改为 `some Collection`。还没发版,现在改不破坏任何调用方(RuntimeViewer 不用它)。 + +## D2、D3、D5、D6 — 测试的说法与鉴别力 + +- D2:`queriesKeepExactlyTheNamesThatMentionTheType` 里四个标准库类型,查询退回的正是测试拿来比对的同一套解开,它们只守着「符号引用不指错描述符」。改测试注释与模块文档的说法。 +- D3:`callSitesMatchCapstone` 原来只查 Capstone 找到的调用扫描都找到了。改成双向:扫描报的每一处调用或跳出函数的跳转,Capstone 也要认为是调用或跳转(`br` 例外:Capstone 分不出跳转表与尾调用);比对过的跳出函数的跳转要不止一处。改后在 macOS 27.2 上通过,即扫描没有多报。 +- D5:`superSendsNameTheClassOfTheirMethod` 的两个方法,槽位里的类与方法符号里的类相同,而扫描读不到槽位时正是退回方法符号,所以这个测试分辨不出。新增 `superSendsInBlocksNameTheClassOfTheirMethod`:Block 的符号不是方法名,只有槽位能给出类。临时去掉读槽位的那一行,新测试失败、旧测试照样通过,已恢复。 +- D6:`FallbackNamingTests` 的注释改为如实说明挑的镜像是 macOS 27.2 剥得最狠的那几个。不按系统版本门控(A67)。 + +## D8、D9、D14–D17 — 文档 + +- D8:AGENTS.md 两处:模块依赖那句改为「起名,以及认出扫描碰到的类与类型」;模块条目改为「两到三秒扫完」,补上类引用与类型引用、加载路径、分析器生命期里留着的索引、改名再导出。 +- D9:提案里 AppKit 的类引用数有两组(3,311 / 51,706 与 3,318 / 52,668),分别注明是设计阶段与实现阶段两次探针,口径差别没有记录。 +- D14:提案「方案」一节三处已被第二批修订的说法加注。 +- D15:模块文档「缓存、内存与生命周期」补上类索引、类型索引、链接关系、改名再导出表也随分析器留着;那里的 170 MB 是第二批之前测的,已注明。 +- D16:模块文档的 4,114 个镜像注明是缓存的 4,113 个加基准程序自己。 +- D17:提案说类型预筛「凡有 `__swift5_typeref` 节的镜像都算」,代码是任何非空的 `__swift5_*` 节,改提案。 diff --git a/Roadmaps/2026-10-21-pr135-review-findings.md b/Roadmaps/2026-10-21-pr135-review-findings.md new file mode 100644 index 000000000..e5cea31a7 --- /dev/null +++ b/Roadmaps/2026-10-21-pr135-review-findings.md @@ -0,0 +1,116 @@ +# PR #135 review findings(协议约束可选写在各自的关联类型上,2026-10-21) + +`/code-review high` 对 PR #135(`feature/protocol-requirement-placement` → `next`,PR 头 `07016c07`,基线 `7d181357`;提案 [0073-protocol-requirement-placement](../Documentations/Evolutions/0073-protocol-requirement-placement.md))给出 8 条发现。这份记录逐条按四问(能否复现 / 基线有没有 / 值不值得修 / 以前修过没有)裁决。 + +**结论**:没有会把输出印错的问题。只有第 1 条要改,而且只改文档措辞,另往 fixture 加了一个协议,用测试把文档说的规则固定下来;第 2–8 条是误报、有意设计或成本可以忽略,登记在 [ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md) A69–A75。已裁决清单 A1–A68 里没有覆盖这 8 条的条目,第 4、5、6 条各有同类先例(A26、A3、A45)。 + +**当前状态**:已落地(2026-10-21)。用户批准按这份结论修完后直接合并:第 1 条的修正是 `5c3da04b`,与这份记录、提案落地一起随 PR #135 合入 `next`。 + +## 总表 + +| # | 问题 | 从哪来 | 裁决 | +|---|---|---|---| +| 1 | 公开文档把约束归位的规则说宽了 | PR 引入 | 修(只改措辞,加测试) | +| 2 | 两个新套件进了 CI 名单,却只在 Xcode 27 上跑过 | PR 引入 | 误报(CI 的工具链上实跑通过),A69 | +| 3 | `SwiftDumpConformance` 被当普通文字印出 | 基线既有 | 误报(走不到),A70 | +| 4 | 默认写法下每个协议多读一次关联类型名 | PR 引入 | 不修(可以忽略),A71 | +| 5 | 开关打开时每条约束的主语 demangle 两次 | PR 引入 | 部分误报,不修,A72 | +| 6 | 现场编译 fixture 的辅助代码又复制了一份 | 基线既有 | 本 PR 不修,另做重构,A73 | +| 7 | 继承子句的拼写循环有三份 | 基线既有,PR 加一份 | 有意设计,不修,A74 | +| 8 | diff / evolution 的协议头手工传入「约束全留在协议上」 | PR 引入 | 有意设计,不修,A75 | + +## 1. 公开文档把约束归位的规则说宽了(修) + +`Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift:45-48`,`ProtocolRequirementPlacement.associatedTypes` 的文档注释。 + +- **能复现吗**:能,但只是文档与实现对不上,输出没错。原文说「any other requirement mentioning `Self.Item` goes into its `where` clause」,实现对 conformance、superclass、layout 约束只看主语(`ProtocolRequirementPartition.location(of:among:in:)`)。例如: + + ```swift + protocol SubjectOnlyRequirements: Sequence where Element: GenericBase { + associatedtype First + } + ``` + + `Self.Element: GenericBase` 提到了 `Self.First`,却留在协议的 `where` 子句,不挪到 `First` 上。 +- **基线有没有**:新代码,`next` 上没有。 +- **值不值得修**:修,只改措辞。实现本身是对的:提案的规则就是「只看主语,same-type 约束两边都看」,编译器自己也这么摆(`swift/lib/AST/ASTPrinter.cpp` 的 `bestRequirementPrintLocation`:conformance、superclass、layout 只看 `req.getFirstType()`,same-type 两边都看)。同样宽泛的说法还在 ProjectEvolutionLog 本节的「关键决策 ①」和 PR 描述里,三处一起改。CLI 的 `--help`、agent 插件的 skill、提案正文的说法没有问题。 +- **以前修过吗**:本 PR 新写,没有。 +- **横向排查**:说同一条规则的地方逐个看过:提案「摆放规则」、`ProtocolRequirementPartition` 的文档注释、fixture 与测试的注释、CLI 的 `--help`、agent 插件的 skill 都写的是「只看主语」或没有细到这一层,不用改。 + +**修法**: + +- 文档注释改成逐类说清:conformance、superclass、layout 约束只看主语,主语恰好是 `Self.Item` 进继承子句,主语是从 `Item` 起头的成员链进 `Item` 的 `where` 子句,主语与本协议的关联类型无关就留在协议上,即使父类提到了它;same-type 约束进任一边所关于的关联类型的 `where` 子句,恰好是 `Self.Item` 的那一边优先;inverse 与 same-shape 留在协议上。 +- ProjectEvolutionLog 本节「关键决策 ①」同样改写;PR 描述的「Where a requirement prints」一段同样改写。 +- `ProtocolRequirementPlacementFixture` 加 `SubjectOnlyRequirements`(就是上面的例子),`ProtocolRequirementPlacementInterfaceTests` 的 `placementCases` 加一条期望:`.associatedTypes` 写法下这条约束仍在协议头。参数化在 `protocolNames` 上的三个测试(默认写法不带约束、往返编译、diff 协议头)也自动覆盖了它。 + +这条修的是文档,不是代码,所以新测试在修前也是绿的。为证明它确实钉住了「只看主语」,在沙盒副本里临时把 superclass 约束改成也看右侧(文档原先的说法),新测试按预期变红,见文末「验证」。 + +## 2. 两个新套件进了 CI 名单,却只在 Xcode 27 上跑过(误报,A69) + +`.github/workflows/macOS.yml:123`。 + +- **能复现吗**:不能。PR 自己的验证只用了 Xcode 27.0(Swift 6.4):当天 github.com 连不上,依赖是拷来的一份只有 Swift 6.4 认的解析。这次在 `git archive` 出来的 PR 头副本里,用 `/Applications/Xcode.app`(Xcode 26.6,Swift 6.3.3,与 CI 相同)从远端重新解析依赖,跑两个新套件和 PR 改过的 `DumpAndInterfaceRequestTests`、`CommandRequestMappingTests`:4 个套件 45 个测试全部通过,原始退出码 0。只跑了 debug,CI 还会跑 release。 +- **基线有没有**:新加的套件。 +- **影响**:合进 `next` 的 PR 不跑 CI,真有问题也要到下次发版合进 `main` 时才暴露,所以值得在本机先用 CI 的工具链跑一遍。 +- **以前修过吗**:出过同类问题:`a2725835` 修的是换了工具链后一个现场编译 fixture 的测试全红,修法是固定语言模式。本 PR 的 fixture 从一开始就带 `-swift-version 5`。 + +## 3. `SwiftDumpConformance` 被当普通文字印出(误报,A70) + +`Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift:364`。 + +- **能复现吗**:构造不出来。这类内容只来自 SameConformance 约束(「两个 conformance 必须相同」),编译器的 IRGen 从不发出它,运行时遇到它也只是标着 `FIXME` 跳过(`ProtocolConformance.cpp:1906`、`:2062`)。就算出现,划分也把它留在协议的 `where` 子句,进不了 `associatedtype` 的继承子句,所以「这个 PR 让它变得可达」不成立。 +- **基线有没有**:有。协议的 `where` 子句一直经过这个函数,`next` 第 363 行就是这样。 +- **值不值得修**:不修。走不到的分支,不值得为它手工造一个二进制来写测试。 +- **以前修过吗**:`f223b210` 把旁边 `dumpContent` 的同一处改成了 `Error`,漏了这一处,只改了一半。 + +## 4. 默认写法下每个协议多读一次关联类型名(不修,A71) + +`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:377`。 + +- **能复现吗**:属实。默认写法用不到这份名单,打印 `associatedtype` 行时又读了一遍。 +- **基线有没有**:本 PR 新引入。 +- **值不值得修**:不修。多读的只是一个短字符串,比起打印整个协议可以忽略,也写不出修前会失败的测试。 +- **以前修过吗**:没有。同类先例 A26。 + +## 5. 开关打开时每条约束的主语 demangle 两次(部分误报,不修,A72) + +`Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift:74`。 + +- **能复现吗**:调用确实重复,但「两倍工作量」不对:第二次命中按镜像的记忆化缓存,只是从已驻留的 `NodeReference` 重建一棵很小的树。 +- **基线有没有**:本 PR 新引入,只在打开开关时发生。 +- **值不值得修**:不修,影响很小。 +- **以前修过吗**:没有。同类先例 A3:这类重建实测只占打印时间约 1%。 + +## 6. 现场编译 fixture 的辅助代码又复制了一份(本 PR 不修,A73) + +`Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift:153`。 + +- **能复现吗**:属实,而且比审查说的严重:`next` 上已有 41 份副本(审查说 6 份),这是第 42 份。 +- **基线有没有**:早就存在。 +- **值不值得修**:值得,但不在这个 PR 里:合并成一个共享函数要改 41 个测试文件。副本的代价有据可查:`d2cacc50`(先读完 stderr 再等进程退出,防死锁)和 `a2725835`(固定语言模式)当年都只修了一份,现在 41 份里还有 25 份没固定语言模式,只是因为它们都不生成 `.swiftinterface` 这类随语言模式变化的产物,暂时没出事。 +- **以前修过吗**:没人合并过。相关条目 A45。 + +## 7. 继承子句的拼写循环有三份(有意设计,不修,A74) + +`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift:238`。 + +- **能复现吗**:部分属实。新加的循环与协议头的循环形状相同,但两者调用不同的打印函数,后面还要接 `~Copyable`。PR 同时把 `where` 子句抽成了一个函数,打印器内部的重复其实变少了。 +- **基线有没有**:dump 与 interface 各有一份协议头,基线就有,而且是有意的。 +- **以前修过吗**:没有。分成两份是 `aa233bc0`(让 SwiftDump 成为叶子模块)有意做的,提交说明写着「the two paths intentionally diverge」。 + +## 8. diff / evolution 的协议头手工传入「约束全留在协议上」(有意设计,不修,A75) + +`Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift:76`。 + +- **能复现吗**:审查担心以后有人改成按配置走,约束会悄悄丢掉。不会悄悄发生:`diffHeaderKeepsEveryRequirement` 在开关打开时打印 diff 的协议头,与默认写法比较,那样改就会变红。 +- **基线有没有**:新代码。 +- **以前修过吗**:没有。提案的决策日志专门记了这个选择。 + +## 验证 + +- **环境**:PR 头的 `git archive` 副本 `/Volumes/DerivedData/Agents.noindex/claude/Scratch/MachOSwiftSection-PR135-CIToolchain`(SymbolTestsCore fixture 链接自主 checkout),构建目录 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Xcode26.6`,`DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`(Xcode 26.6,Swift 6.3.3),依赖从远端解析,不用本地兄弟仓库;机器 JHs-Mac-Studio(macOS 26.7)。日志在 `/Volumes/DerivedData/Agents.noindex/claude/Logs/`。 +- **第 2 条**:PR 头上,两个新套件加 `DumpAndInterfaceRequestTests`、`CommandRequestMappingTests` 共 4 个套件 45 个测试通过,退出码 0(`MachOSwiftSection-PR135-Xcode26.6.log`)。 +- **第 1 条修正之后**:同样 4 个套件 45 个测试通过,退出码 0;`SubjectOnlyRequirements` 在四个参数化测试里都通过,包括往返编译(`MachOSwiftSection-PR135-Xcode26.6-final.log`)。 +- **变异检查**:在沙盒里临时让 superclass 约束也看右侧(旧措辞的说法),`ProtocolRequirementPlacementInterfaceTests` 退出码 1,只有 `SubjectOnlyRequirements` 这一条放置用例失败:约束被挪进了 `associatedtype First where Self.Element: ProtocolRequirementPlacementFixture.GenericBase`。往返编译测试照样通过,因为这种摆法语义不变,所以「只看主语」只有这条用例在守。临时改动已撤回(`MachOSwiftSection-PR135-Xcode26.6-mutation.log`)。 +- **编译器对照**:Swift 6.3.3 对同一源码 `-emit-module-interface`,印出 `public protocol SubjectOnlyRequirements : Swift.Sequence where Self.Element : ProtocolRequirementPlacementFixture.GenericBase`,`associatedtype First` 不带约束,与测试的期望一致(`/Volumes/DerivedData/Agents.noindex/claude/Scratch/PR135-CompilerPlacementProbe/`)。 +- **没跑的**:release 配置;Xcode 27.0;全量测试。修正只动了测试和一段文档注释,全量测试在 PR 头 `07016c07` 上跑过,结果记在 ProjectEvolutionLog 本节。 diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Linkage.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Linkage.swift new file mode 100644 index 000000000..ffcd3ef82 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Linkage.swift @@ -0,0 +1,103 @@ +import Foundation +import MachOKit + +/// Which images link which: what tells the images that can bind to another +/// image's Swift symbols. +/// +/// Only 245 of the macOS 27.2 shared cache's 4,113 images keep any Swift +/// symbol among their undefined symbols. The rest bind Swift symbols with +/// nothing left to show: SharedWithYou keeps 314 undefined symbols, all C +/// functions and Objective-C classes, yet calls `URL`'s metadata accessor +/// through a GOT stub the cache builder bound; 44 images import `URL.path` +/// by name, and many more call it. A Swift symbol another image uses is told +/// by the linkage instead: an image binds only to the images it links and +/// the ones those re-export. +struct Linkage { + /// The images that link each image. + let dependents: [Int: [Int]] + /// The images that re-export each image. + let reexporters: [Int: [Int]] +} + +extension CrossReferenceAnalyzer { + /// The images among `candidates` that can bind to the symbols of the + /// image at `imageIndex`: the image itself, the images re-exporting it — + /// SwiftUI re-exports SwiftUICore — and every image linking one of those. + public func imageIndices(linkingImageAt imageIndex: Int, among candidates: some Sequence) -> [Int] { + let linkage = self.linkage() + let providers = Self.providers(of: imageIndex, in: linkage) + var linkers = providers + for provider in providers { + linkers.formUnion(linkage.dependents[provider] ?? []) + } + return candidates.filter(linkers.contains) + } + + /// The image at `imageIndex` and every image re-exporting it, directly or + /// through another re-exporter: the images its symbols can be bound + /// through under their own names. + private static func providers(of imageIndex: Int, in linkage: Linkage) -> Set { + var providers: Set = [imageIndex] + var pending = [imageIndex] + while let provider = pending.popLast() { + for reexporter in linkage.reexporters[provider] ?? [] where providers.insert(reexporter).inserted { + pending.append(reexporter) + } + } + return providers + } + + /// The names other images re-export the symbols `symbolNames` of the + /// image at `imageIndex` under, which is what the callers of those + /// symbols import: `_strlen`, `_index` … for libsystem_platform's + /// `__platform_strlen`, `_CGBeginDisplayConfiguration` for SkyLight's + /// `_SLBeginDisplayConfiguration`. + /// + /// Follows a re-export renamed again, and one made through an image that + /// re-exports this one whole. The first call walks every image's export + /// trie. + public func reexportedNames(ofSymbolsNamed symbolNames: [String], inImageAt imageIndex: Int) -> [String] { + let index = renamedReexports() + let linkage = self.linkage() + var names: [String] = [] + var visited = Set() + var pending = symbolNames.map { RenamedReexport(imageIndex: imageIndex, name: $0) } + while let symbol = pending.popLast() { + guard visited.insert(symbol).inserted else { continue } + for provider in Self.providers(of: symbol.imageIndex, in: linkage) { + for reexport in index.reexportsByProvider[provider]?[symbol.name] ?? [] { + if !symbolNames.contains(reexport.name), !names.contains(reexport.name) { names.append(reexport.name) } + pending.append(reexport) + } + } + } + return names + } + + /// The images among `candidates` that can call the function at + /// `location`, which its image names `symbolNames`: its own image; for a + /// C or Objective-C name, the images importing it, by that name or by + /// one another image re-exports it under; for a Swift name, which few + /// cache images keep among their undefined symbols, every image that can + /// bind to the function's image. + public func imageIndices(callingFunctionAt location: CodeLocation, symbolNames: [String], among candidates: some Sequence) -> [Int] { + let candidates = Array(candidates) + var result = Set() + if candidates.contains(location.imageIndex) { result.insert(location.imageIndex) } + let swiftNames = symbolNames.filter(Self.isSwiftSymbolName) + let otherNames = symbolNames.filter { !Self.isSwiftSymbolName($0) } + if !otherNames.isEmpty { + let importedNames = otherNames + reexportedNames(ofSymbolsNamed: otherNames, inImageAt: location.imageIndex) + result.formUnion(imageIndices(importingAnyOf: importedNames, among: candidates)) + } + if !swiftNames.isEmpty { + result.formUnion(imageIndices(linkingImageAt: location.imageIndex, among: candidates)) + } + return result.sorted() + } + + /// `_$s…`, or `$s…` without the C prefix. + static func isSwiftSymbolName(_ name: String) -> Bool { + name.hasPrefix("_$s") || name.hasPrefix("$s") + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Prefiltering.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Prefiltering.swift new file mode 100644 index 000000000..5d26dda35 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Prefiltering.swift @@ -0,0 +1,133 @@ +import Foundation +import MachOKit + +extension CrossReferenceAnalyzer { + /// The images among `candidates` whose symbol table imports + /// `symbolName` — for a C function or an Objective-C class, the ones that + /// reach it by that name: a shared cache image keeps those undefined + /// symbols even where the cache builder bound the calls directly. + /// + /// Not every image that can reach it. Another image may re-export it + /// under a name of its own, which its callers import instead + /// (`reexportedNames(ofSymbolsNamed:inImageAt:)`). And not for a Swift + /// symbol: only 245 of the macOS 27.2 cache's 4,113 images keep any among + /// their undefined symbols, so this finds a few of the images that use + /// one. `imageIndices(callingFunctionAt:symbolNames:among:)` covers both. + public func imageIndices(importing symbolName: String, among candidates: some Sequence) -> [Int] { + imageIndices(importingAnyOf: [symbolName], among: candidates) + } + + /// The images among `candidates` whose symbol table imports any of + /// `symbolNames`. + public func imageIndices(importingAnyOf symbolNames: [String], among candidates: some Sequence) -> [Int] { + guard !symbolNames.isEmpty else { return [] } + let wantedNames = symbolNames.map { strdup($0)! } + defer { wantedNames.forEach { free($0) } } + return candidates.filter { imageIndex in + guard let symbols = images[imageIndex].symbols64 else { return false } + var range = 0 ..< symbols.numberOfSymbols + if let dynamicSymbols = images[imageIndex].loadCommands.info(of: LoadCommand.dysymtab) { + let first = Int(dynamicSymbols.iundefsym) + let count = Int(dynamicSymbols.nundefsym) + if first + count <= symbols.numberOfSymbols { range = first ..< first + count } + } + for symbolIndex in range { + let entry = symbols.symbols[symbolIndex] + // An external, undefined symbol. + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0, entry.n_type & 0x01 != 0 else { continue } + let name = symbols.stringBase.advanced(by: Int(entry.n_un.n_strx)) + for wantedName in wantedNames where strcmp(name, wantedName) == 0 { return true } + } + return false + } + } + + /// The images among `candidates` whose `__objc_selrefs` reference + /// `selector` — the only ones that can send it. + public func imageIndices(referencingSelector selector: String, among candidates: some Sequence) -> [Int] { + selector.withCString { wantedSelector in + // The cache uniques selector strings; once one reference matched, + // the same pointer is compared before any string. + var matchedString: UInt? + return candidates.filter { imageIndex in + let image = images[imageIndex] + guard let slide = image.vmaddrSlide, + let section = image.sections64.first(where: { $0.sectionName == "__objc_selrefs" }), + section.size > 0, + let slots = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(section.address)) &+ slide) + else { return false } + for slotIndex in 0 ..< section.size / 8 { + let string = UInt(slots.loadUnaligned(fromByteOffset: slotIndex * 8, as: UInt64.self) & 0x0000_7FFF_FFFF_FFFF) + if string == matchedString { return true } + guard let pointer = UnsafePointer(bitPattern: string) else { continue } + if strcmp(pointer, wantedSelector) == 0 { + matchedString = string + return true + } + } + return false + } + } + } +} + +extension CrossReferenceAnalyzer { + /// Where the image at `imageIndex` defines a class named `name`: one + /// location, or none. The first query on an image reads the names of all + /// its classes. + public func objectiveCClassLocations(named name: String, inImageAt imageIndex: Int) -> [CodeLocation] { + objectiveCClassIndex(ofImageAt: imageIndex).classLocations(named: name) + } + + /// The images among `candidates` that can reference the Objective-C class + /// at `classLocation`: the image defining it, and the images importing a + /// symbol that names the class or its metaclass. + /// + /// Most images reach another image's class as `_OBJC_CLASS_$_`, but + /// not all: a block literal's `isa` is `__NSConcreteStackBlock`, an XPC + /// type is `__xpc_type_dictionary`. So every symbol the defining image + /// has at either address counts. A Swift class is reached through Swift + /// symbols as well, which the cache drops from its images' undefined + /// symbols, so every image that can bind to its image counts too. + public func imageIndices(referencingObjectiveCClassAt classLocation: CodeLocation, among candidates: some Sequence) -> [Int] { + imageIndices(referencingObjectiveCClassAt: classLocation, among: candidates, includingSwiftLinkage: true) + } + + /// `includingSwiftLinkage` false leaves out the images linking a Swift + /// class's image, for a class known to export no Swift symbol — see + /// `imageIndices(referencingSwiftType:among:)`. + func imageIndices(referencingObjectiveCClassAt classLocation: CodeLocation, among candidates: some Sequence, includingSwiftLinkage: Bool) -> [Int] { + let definer = classLocation.imageIndex + let image = images[definer] + let objectAddresses = Set(objectiveCClassIndex(ofImageAt: definer).objectAddresses(ofClassAt: classLocation)) + var names = Set() + if let symbols = image.symbols64 { + for symbolIndex in 0 ..< symbols.numberOfSymbols { + let entry = symbols.symbols[symbolIndex] + // A symbol defined in a section of this image. + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E, objectAddresses.contains(entry.n_value) else { continue } + names.insert(String(cString: symbols.stringBase.advanced(by: Int(entry.n_un.n_strx)))) + } + } + if let headerAddress = image.segments64.first(where: { $0.segmentName == "__TEXT" }).map({ UInt64($0.layout.vmaddr) }) { + for symbol in image.exportedSymbols { + guard let offset = symbol.offset, + objectAddresses.contains(UInt64(bitPattern: Int64(bitPattern: headerAddress) &+ Int64(offset))) + else { continue } + names.insert(symbol.name) + } + } + let candidates = Array(candidates) + // A class re-exported under another name is imported by that name: + // UIFoundation's `NSEmojiImageAsset` is CoreText's `CTEmojiImageAsset`. + let importedNames = names.sorted() + reexportedNames(ofSymbolsNamed: names.sorted(), inImageAt: definer) + var result = Set(imageIndices(importingAnyOf: importedNames, among: candidates)) + if candidates.contains(definer) { result.insert(definer) } + // Swift code reaches a Swift class through its metadata symbols, which + // few cache images keep among their undefined symbols. + if includingSwiftLinkage, objectiveCClassIndex(ofImageAt: definer).isSwiftClass(at: classLocation) { + result.formUnion(imageIndices(linkingImageAt: definer, among: candidates)) + } + return result.sorted() + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift new file mode 100644 index 000000000..22dc467e3 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift @@ -0,0 +1,349 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import Demangling + +/// A Swift type, as a type query looks for it. +public struct SwiftTypeIdentity: Hashable, Sendable { + /// The type's nominal mangling, without `$s` or a suffix: + /// `7SwiftUI4TextV`, `Sa`, `So6CGRectV`. + public let key: String + /// Where the type's context descriptor lies. + public let descriptorLocation: CodeLocation + /// For a Swift class: its class object's runtime name and where it lies. + /// Code reaches the class through its Objective-C class object as well. + public let objectiveCClassName: String? + public let objectiveCClassLocation: CodeLocation? +} + +extension CrossReferenceAnalyzer { + /// The type whose context descriptor lies at `location`. + public func swiftTypeIdentity(ofDescriptorAt location: CodeLocation) -> SwiftTypeIdentity? { + guard let slide = images[location.imageIndex].vmaddrSlide else { return nil } + let descriptor = UInt(bitPattern: Int(bitPattern: UInt(location.address)) &+ slide) + guard let key = swiftTypeIndex(ofImageAt: location.imageIndex).key(ofDescriptorAt: descriptor) else { return nil } + let classObject = objectiveCClassIndex(ofImageAt: location.imageIndex).swiftClassObject(describedBy: descriptor) + return SwiftTypeIdentity(key: key, descriptorLocation: location, objectiveCClassName: classObject?.name, objectiveCClassLocation: classObject?.location) + } + + /// Where the image at `imageIndex` defines a type whose key is `key`. The + /// type's `…Mn` symbol is looked for first, and settles it: one location. + /// Only when no symbol names the type are the keys of the types its + /// descriptors name alike built, and every descriptor with that key + /// returned, in no particular order — one in the images seen so far. + public func swiftTypeDescriptorLocations(withKey key: String, inImageAt imageIndex: Int) -> [CodeLocation] { + let image = images[imageIndex] + guard let slide = image.vmaddrSlide else { return [] } + let index = swiftTypeIndex(ofImageAt: imageIndex) + // The symbol settles it: a key spells the type the way its symbols do. + for address in addresses(ofSymbolsNamed: "_$s" + key + "Mn", inImageAt: imageIndex) { + let descriptor = UInt(bitPattern: Int(bitPattern: UInt(address)) &+ slide) + if index.describesType(descriptorAt: descriptor) { return [index.location(ofRuntimeAddress: descriptor)] } + } + return index.descriptorLocations(withKey: key) + } + + /// The references the image's functions make to the type: calls to its + /// metadata accessor and the accessor's address, the address of its + /// metadata or — for a class — of its class object, and the mangled + /// names that name it. + /// + /// A mangled name names a type through a symbolic reference to the type's + /// descriptor, which is compared directly. Only the types a name may also + /// spell out — the standard library's and the imported ones — take + /// demangling the names to find. + public func references(toSwiftType identity: SwiftTypeIdentity, inImageAt imageIndex: Int) -> [CodeReference] { + let table = existingFunctionTable(ofImageAt: imageIndex) ?? ImageFunctionTable(imageIndex: imageIndex, image: images[imageIndex]) + var scanner = ReferenceScanner(analyzer: self, table: table, matching: SwiftTypeQuery(identity: identity, analyzer: self)) + var references: [CodeReference] = [] + for index in table.starts.indices { + scanner.scanFunction(at: index, into: &references) + } + return references + } + + /// What ``references(toSwiftType:inImageAt:)`` finds, read from the + /// image's index instead of scanned: the type's descriptor, metadata and + /// class object are compared as the scan compares them, and the names + /// the index keeps are taken apart only as far as the scan would. + public func references(toSwiftType identity: SwiftTypeIdentity, in index: CodeReferenceIndex) -> [CodeReference] { + let query = SwiftTypeQuery(identity: identity, analyzer: self) + return index.references(toTypesMatching: { query.matches($0) }, objectiveCClassName: identity.objectiveCClassName) + } + + /// The images among `candidates` that can reference the type: its own + /// image; when that image exports the type, the images that can bind to + /// it — few cache images keep a Swift symbol among their undefined ones, + /// so the linkage is what tells (`imageIndices(linkingImageAt:among:)`); + /// for a class, the ones its class prefilter keeps; and, for a type every + /// image may name on its own — the standard library's and the imported + /// ones — every Swift image. + /// + /// Another image reaches a type through a symbol of it — its descriptor + /// (`…Mn`), its metadata accessor (`…Ma`), its metadata (`…N`) — so a type + /// its image exports none of, an internal one, is referenced from that + /// image alone. Most of a framework's types are internal, and the images + /// linking AppKit are most of the cache. + public func imageIndices(referencingSwiftType identity: SwiftTypeIdentity, among candidates: some Sequence) -> [Int] { + let candidates = Array(candidates) + let definer = identity.descriptorLocation.imageIndex + let isExported = isSwiftTypeExported(withKey: identity.key, fromImageAt: definer) + var result = Set() + if candidates.contains(definer) { + result.insert(definer) + } + if isExported { + result.formUnion(imageIndices(linkingImageAt: definer, among: candidates)) + } + if SwiftTypeQuery.mayBeSpelledOut(identity.key) { + result.formUnion(candidates.filter { imageIndex in + images[imageIndex].sections64.contains { $0.sectionName.hasPrefix("__swift5_") && $0.size > 0 } + }) + } + if let classLocation = identity.objectiveCClassLocation { + result.formUnion(imageIndices(referencingObjectiveCClassAt: classLocation, among: candidates, includingSwiftLinkage: isExported)) + } + return result.sorted() + } + + /// Whether the image exports a symbol of the type with this key: what + /// another image needs to reach it. + func isSwiftTypeExported(withKey key: String, fromImageAt imageIndex: Int) -> Bool { + ["Mn", "Ma", "N"].contains { exportsSymbol(named: "_$s" + key + $0, fromImageAt: imageIndex) } + } + + /// Whether the image's export trie lists `name`, spelled as the trie + /// spells it (`_$s…`, `_CFRelease`). Looked up in the trie: reading all of + /// it to look up three names took SwiftUICore's first type query 0.1 s in + /// a debug build, and keeping what was read 6 MiB. + func exportsSymbol(named name: String, fromImageAt imageIndex: Int) -> Bool { + images[imageIndex].exportTrie?.search(by: name) != nil + } + + /// The types a Swift type name names, by key, in the order the name + /// mentions them; demangles the name. + /// + /// The tree is demangled for this call alone — not interned in the + /// shared `NodeCache`, not memoized for the process — since nothing + /// bounds the names a query meets and neither cache is ever evicted. + public func swiftTypeKeys(in name: SwiftTypeName) -> [String] { + switch name { + case .accessorSymbol(let symbol): + guard let node = try? demangleAsNodeTransient(symbol) else { return [] } + return Self.nominalKeys(in: node) + case .mangledName(let location, _): + guard let slide = images[location.imageIndex].vmaddrSlide, + let pointer = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(location.address)) &+ slide), + let mangledName = try? MangledName.resolve(at: pointer, in: InProcessContext.shared), + let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledName, in: InProcessContext.shared) + else { return [] } + return Self.nominalKeys(in: node) + } + } + + // MARK: - Internals + + private static let nominalKinds: Set = [.structure, .class, .enum, .protocol, .typeAlias, .otherNominalType] + private static let boundGenericKinds: Set = [.boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias] + + /// Each nominal type a type node mentions, mangled on its own as a key. A + /// nested type names its parent only as its context: `Outer.Inner` + /// mentions `Inner` alone. A generic argument is a type of its own, + /// whether it binds the type or — `Regex.Match` — one of + /// its parents, which the demangled tree spells as a bound context. + static func nominalKeys(in node: Node) -> [String] { + var keys: [String] = [] + func walk(_ node: Node) { + if nominalKinds.contains(node.kind) { + var arguments: [Node] = [] + let unbound = unboundNominal(node, arguments: &arguments) + if let key = try? mangleAsString(NodeBuilder(kind: .type, children: [unbound]).node) { keys.append(key) } + arguments.forEach(walk) + return + } + node.children.forEach(walk) + } + walk(node) + return keys + } + + /// `node` with every bound context along its parents replaced by the + /// unbound type, and the arguments those contexts bound. + private static func unboundNominal(_ node: Node, arguments: inout [Node]) -> Node { + guard let context = node.children.first else { return node } + var unboundContext: Node? + if boundGenericKinds.contains(context.kind), let typeNode = context.children.first, let boundType = typeNode.children.first { + if context.children.count > 1 { arguments.append(context.children[1]) } + unboundContext = unboundNominal(boundType, arguments: &arguments) + } else if nominalKinds.contains(context.kind) { + let unbound = unboundNominal(context, arguments: &arguments) + if unbound !== context { unboundContext = unbound } + } else if context.kind == .extension, context.children.count > 1 { + // A constrained extension's extended type, bound in + // `Measurement.FormatStyle.UnitWidth`; the + // demangled tree holds it with or without a `Type` around it. + let isWrapped = context.children[1].kind == .type + guard let extendedType = isWrapped ? context.children[1].children.first : context.children[1] else { return node } + var unboundExtendedType: Node? + if boundGenericKinds.contains(extendedType.kind), let typeNode = extendedType.children.first, let boundType = typeNode.children.first { + if extendedType.children.count > 1 { arguments.append(extendedType.children[1]) } + unboundExtendedType = unboundNominal(boundType, arguments: &arguments) + } else if nominalKinds.contains(extendedType.kind) { + let unbound = unboundNominal(extendedType, arguments: &arguments) + if unbound !== extendedType { unboundExtendedType = unbound } + } + if let unboundExtendedType { + let replacement = isWrapped ? NodeBuilder(kind: .type, children: [unboundExtendedType]).node : unboundExtendedType + unboundContext = NodeBuilder(context).removeChild(at: 1).insertChild(replacement, at: 1).node + } + } + guard let unboundContext else { return node } + return NodeBuilder(node).removeChild(at: 0).insertChild(unboundContext, at: 0).node + } + + /// The unslid addresses the image's symbol table and export trie give + /// `name`. + private func addresses(ofSymbolsNamed name: String, inImageAt imageIndex: Int) -> [UInt64] { + let image = images[imageIndex] + var addresses: [UInt64] = [] + name.withCString { wantedName in + guard let symbols = image.symbols64 else { return } + for symbolIndex in 0 ..< symbols.numberOfSymbols { + let entry = symbols.symbols[symbolIndex] + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E, + strcmp(symbols.stringBase.advanced(by: Int(entry.n_un.n_strx)), wantedName) == 0 + else { continue } + addresses.append(entry.n_value) + } + } + if let headerAddress = image.segments64.first(where: { $0.segmentName == "__TEXT" }).map({ UInt64($0.layout.vmaddr) }), + let offset = image.exportTrie?.search(by: name)?.offset { + addresses.append(UInt64(bitPattern: Int64(bitPattern: headerAddress) &+ Int64(offset))) + } + return addresses + } +} + +/// What a type query keeps: the references to one Swift type, however the +/// code reaches it. One query serves one scan. +final class SwiftTypeQuery { + private let identity: SwiftTypeIdentity + private let analyzer: CrossReferenceAnalyzer + /// A type imported from C or Objective-C: every image that uses it holds + /// a descriptor of its own, so a descriptor is the type's when its key + /// is. + private let isImported: Bool + private let mayBeSpelledOut: Bool + /// The name the type's descriptor gives it — compared before any other + /// descriptor's key is built. + private let typeName: String? + private var descriptorMatches: [CodeLocation: Bool] = [:] + private var nameMatches: [SwiftTypeName: Bool] = [:] + + init(identity: SwiftTypeIdentity, analyzer: CrossReferenceAnalyzer) { + self.identity = identity + self.analyzer = analyzer + self.isImported = identity.key.hasPrefix("So") || identity.key.hasPrefix("SC") + self.mayBeSpelledOut = Self.mayBeSpelledOut(identity.key) + var typeName: String? + if let slide = analyzer.images[identity.descriptorLocation.imageIndex].vmaddrSlide, + let name = SwiftTypeIndex.name(ofDescriptorAt: UInt(bitPattern: Int(bitPattern: UInt(identity.descriptorLocation.address)) &+ slide)) { + typeName = String(cString: name) + } + self.typeName = typeName + } + + /// Whether mangled names may spell the type out rather than refer to its + /// descriptor: a type of the standard library (`Sa`, `s6UInt16V`), of + /// `_Concurrency` (`ScT`) or imported (`So6CGRectV`). Any other key starts + /// with its module's name, `7SwiftUI…`, and names refer to such a type + /// through a symbolic reference. + static func mayBeSpelledOut(_ key: String) -> Bool { + guard let first = key.utf8.first else { return false } + return first == UInt8(ascii: "s") || first == UInt8(ascii: "S") + } + + func matches(_ target: CodeReferenceTarget) -> Bool { + switch target { + case .swiftType(let descriptor): + return matchesDescriptor(at: descriptor) + case .swiftTypeName(let name): + if let known = nameMatches[name] { return known } + let result = matches(name) + nameMatches[name] = result + return result + case .objectiveCClass(_, let location): + return location == identity.objectiveCClassLocation + default: + return false + } + } + + private func matchesDescriptor(at location: CodeLocation) -> Bool { + if location == identity.descriptorLocation { return true } + guard isImported, let typeName else { return false } + if let known = descriptorMatches[location] { return known } + var result = false + if let slide = analyzer.images[location.imageIndex].vmaddrSlide { + let descriptor = UInt(bitPattern: Int(bitPattern: UInt(location.address)) &+ slide) + if let name = SwiftTypeIndex.name(ofDescriptorAt: descriptor), strcmp(name, typeName) == 0 { + result = analyzer.swiftTypeIndex(ofImageAt: location.imageIndex).key(ofDescriptorAt: descriptor) == identity.key + } + } + descriptorMatches[location] = result + return result + } + + private func matches(_ name: SwiftTypeName) -> Bool { + switch name { + case .accessorSymbol: + // A symbol spells every type out. + return analyzer.swiftTypeKeys(in: name).contains(identity.key) + case .mangledName(let location, let length): + guard let slide = analyzer.images[location.imageIndex].vmaddrSlide, + let bytes = UnsafePointer(bitPattern: Int(bitPattern: UInt(location.address)) &+ slide) + else { return false } + var index = 0 + while index < length { + let byte = bytes[index] + if byte == 0x01 || byte == 0x02, index + 5 <= length { + // A symbolic reference to a context descriptor, direct or + // through a pointer. + let field = UInt(bitPattern: bytes + index + 1) + let relative = UnsafeRawPointer(bytes + index + 1).loadUnaligned(as: Int32.self) + var descriptor = UInt(bitPattern: Int(bitPattern: field) &+ Int(relative)) + if byte == 0x02 { + guard analyzer.isMapped(runtimeAddress: descriptor, length: 8), let slot = UnsafeRawPointer(bitPattern: descriptor) else { + index += 5 + continue + } + descriptor = UInt(slot.loadUnaligned(as: UInt64.self) & SwiftTypeIndex.addressMask) + } + if let descriptorLocation = analyzer.location(ofDescriptorAtRuntimeAddress: descriptor), matchesDescriptor(at: descriptorLocation) { + return true + } + index += 5 + } else if byte >= 0x01, byte <= 0x17 { + index += 5 + } else if byte >= 0x18, byte <= 0x1F { + index += 9 + } else { + index += 1 + } + } + guard mayBeSpelledOut else { return false } + return analyzer.swiftTypeKeys(in: name).contains(identity.key) + } + } +} + +extension CrossReferenceAnalyzer { + /// Where the context descriptor at the runtime `address` lies, when it + /// lies in an image. + func location(ofDescriptorAtRuntimeAddress address: UInt) -> CodeLocation? { + guard let imageIndex = imageIndex(containingRuntimeAddress: address), let slide = images[imageIndex].vmaddrSlide else { return nil } + return CodeLocation(imageIndex: imageIndex, address: UInt64(bitPattern: Int64(bitPattern: UInt64(address)) &- Int64(slide))) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift new file mode 100644 index 000000000..29cbe1383 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift @@ -0,0 +1,662 @@ +import Foundation +import MachOKit + +/// Reads what each function of an image references, from its arm64 machine +/// code, inside the current process. +/// +/// An analyzer is a snapshot of the process's code: every image of the dyld +/// shared cache — loaded or not, the whole cache is mapped into every +/// process — plus every image loaded outside the cache when the analyzer was +/// made. Images loaded later need a new analyzer. +/// +/// An analyzer remembers the function table of every image it was asked to +/// name functions in (``functions(inImageAt:)``, ``function(containing:)``, +/// ``references(madeBy:)``) for its own lifetime; a whole-image scan builds +/// its table and drops it. It keeps no reference results either: +/// ``referenceTable(ofImageAt:)`` returns a value the host holds for as long +/// as it wants. Drop the analyzer to release the function tables. +/// +/// Only arm64 and arm64e are read. Evolution proposal +/// `cross-reference-analysis`. +public final class CrossReferenceAnalyzer: @unchecked Sendable { + /// Every image the analyzer knows, shared cache first. + public let images: [MachOImage] + /// Each image's path, by position in ``images``: where dyld loaded it — + /// for a shared cache image, its install name. + /// + /// Not the install name for an image outside the cache: an app's main + /// executable and its bundles have none, and its frameworks have an + /// `@rpath/…` one, which names no file. + public let imagePaths: [String] + + struct ImageAddressRange { + let start: UInt + let end: UInt + let imageIndex: Int + } + + /// Each image's `__TEXT` segment in memory, sorted by start. + let textRanges: [ImageAddressRange] + /// Each image's other segments in memory but `__LINKEDIT`, sorted by start: + /// where its class objects and its GOT slots lie. + let dataRanges: [ImageAddressRange] + /// The memory the shared cache maps executable — its images' code, and + /// the stubs and islands the cache builder put between them. + let executableRanges: [Range] + /// Every mapping of the shared cache and every segment of the images + /// outside it: what may be read without faulting. + let mappedRanges: [Range] + /// Where `objc_msgSend` lives, the original and the copies the cache + /// carries for its shared selector stubs. + let messageSendLocations: Set + let superMessageSendLocations: Set + /// The runtime libraries' helper functions; helpers the compiler emits + /// into each image are in that image's function table. + let runtimeHelperLocations: Set + /// `objc_opt_self`, `objc_opt_class` and `swift_getInitializedObjCClass`: + /// each returns the class it was handed, so `x0` keeps naming it. + let classReturningFunctionLocations: Set + /// The runtime's entry points that instantiate a type from its mangled + /// name, and the register each takes the name in: `x0`, or `x1` for the + /// `…InMetadataState` forms, whose first argument is the state. + let typeByMangledNameEntries: [CodeLocation: Int] + + private let indicesByPath: [String: Int] + /// Every image an install name names: the name load commands link an + /// image by. Two copies of one framework, loaded from two places, share + /// one. + private let indicesByInstallName: [String: [Int]] + private let lock = NSLock() + private var functionTables: [Int: ImageFunctionTable] = [:] + private var classIndexes: [Int: ObjectiveCClassIndex] = [:] + private var swiftTypeIndexes: [Int: SwiftTypeIndex] = [:] + private var linkageStorage: Linkage? + private var renamedReexportStorage: RenamedReexportIndex? + /// Held while the renamed re-exports are built, so they are built once. + private let renamedReexportBuildLock = NSLock() + private var renamedReexportBuildCountStorage = 0 + + /// The analyzer for the current process, or `nil` when it does not run + /// arm64 code. + public init?() { + #if arch(arm64) + var images: [MachOImage] = [] + var executableRanges: [Range] = [] + var mappedRanges: [Range] = [] + if let cache = DyldCacheLoaded.current, let slide = cache.slide { + images.append(contentsOf: cache.machOImages()) + func appendMappings(of subcache: DyldCacheLoaded) { + guard let mappings = subcache.mappingInfos else { return } + for mapping in mappings { + let start = UInt(bitPattern: Int(bitPattern: UInt(mapping.layout.address)) &+ slide) + let range = start ..< start + UInt(mapping.layout.size) + mappedRanges.append(range) + if mapping.maxProtection.contains(.execute) { executableRanges.append(range) } + } + } + appendMappings(of: cache) + if let subCaches = cache.subCaches { + for entry in subCaches { + if let subcache = try? entry.subcache(for: cache) { appendMappings(of: subcache) } + } + } + } + // Where dyld loaded each image outside the cache, read off the header + // itself so that an image loaded or unloaded meanwhile cannot shift + // it onto another. + var loadedPaths: [Int: String] = [:] + for imageIndex in 0 ..< _dyld_image_count() { + guard let header = _dyld_get_image_header(imageIndex) else { continue } + let image = MachOImage(ptr: header) + guard !image.header.isInDyldCache else { continue } + var information = Dl_info() + if dladdr(UnsafeRawPointer(header), &information) != 0, let fileName = information.dli_fname { + loadedPaths[images.count] = String(cString: fileName) + } + images.append(image) + } + + var imagePaths: [String] = [] + var indicesByPath: [String: Int] = [:] + var indicesByInstallName: [String: [Int]] = [:] + var textRanges: [ImageAddressRange] = [] + var dataRanges: [ImageAddressRange] = [] + for (imageIndex, image) in images.enumerated() { + let installName = image.path + let path = loadedPaths[imageIndex] ?? installName ?? "" + imagePaths.append(path) + if indicesByPath[path] == nil { indicesByPath[path] = imageIndex } + if let installName { indicesByInstallName[installName, default: []].append(imageIndex) } + guard let slide = image.vmaddrSlide, let text = image.segments64.first(where: { $0.segmentName == "__TEXT" }) else { continue } + let start = UInt(bitPattern: Int(bitPattern: UInt(text.layout.vmaddr)) &+ slide) + textRanges.append(ImageAddressRange(start: start, end: start + UInt(text.layout.vmsize), imageIndex: imageIndex)) + for segment in image.segments64 where segment.layout.vmsize > 0 && !["__TEXT", "__LINKEDIT", "__PAGEZERO"].contains(segment.segmentName) { + let segmentStart = UInt(bitPattern: Int(bitPattern: UInt(segment.layout.vmaddr)) &+ slide) + dataRanges.append(ImageAddressRange(start: segmentStart, end: segmentStart + UInt(segment.layout.vmsize), imageIndex: imageIndex)) + } + if !image.header.isInDyldCache { + executableRanges.append(start ..< start + UInt(text.layout.vmsize)) + for segment in image.segments64 where segment.layout.vmsize > 0 && segment.segmentName != "__PAGEZERO" { + let segmentStart = UInt(bitPattern: Int(bitPattern: UInt(segment.layout.vmaddr)) &+ slide) + mappedRanges.append(segmentStart ..< segmentStart + UInt(segment.layout.vmsize)) + } + } + } + textRanges.sort { $0.start < $1.start } + dataRanges.sort { $0.start < $1.start } + + self.images = images + self.imagePaths = imagePaths + self.indicesByPath = indicesByPath + self.indicesByInstallName = indicesByInstallName + self.textRanges = textRanges + self.dataRanges = dataRanges + self.executableRanges = executableRanges + self.mappedRanges = mappedRanges + + // The runtime's entry points, found by name in the runtime libraries. + var messageSendLocations = Set() + var superMessageSendLocations = Set() + var runtimeHelperLocations = Set() + var classReturningFunctionLocations = Set() + var typeByMangledNameEntries: [CodeLocation: Int] = [:] + for (imageIndex, path) in imagePaths.enumerated() where Self.isRuntimeLibrary(path) { + func classify(_ name: UnsafePointer, at location: CodeLocation) { + if strcmp(name, "_objc_msgSend") == 0 { + messageSendLocations.insert(location) + } else if strcmp(name, "_objc_msgSendSuper2") == 0 { + superMessageSendLocations.insert(location) + } else if strcmp(name, "_objc_opt_self") == 0 || strcmp(name, "_objc_opt_class") == 0 || strcmp(name, "_swift_getInitializedObjCClass") == 0 { + classReturningFunctionLocations.insert(location) + } else if strncmp(name, "_swift_getTypeByMangledNameIn", 29) == 0 { + typeByMangledNameEntries[location] = strstr(name, "InMetadataState") == nil ? 0 : 1 + } else if RuntimeHelperNames.isRuntimeHelper(name) { + runtimeHelperLocations.insert(location) + } + } + if let symbols = images[imageIndex].symbols64 { + for symbolIndex in 0 ..< symbols.numberOfSymbols { + let entry = symbols.symbols[symbolIndex] + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E else { continue } + classify(symbols.stringBase.advanced(by: Int(entry.n_un.n_strx)), at: CodeLocation(imageIndex: imageIndex, address: entry.n_value)) + } + } + // A cache image's symbol table need not hold its exported + // symbols; the export trie always does. + guard let headerAddress = images[imageIndex].segments64.first(where: { $0.segmentName == "__TEXT" }).map({ UInt64($0.layout.vmaddr) }) else { continue } + for symbol in images[imageIndex].exportedSymbols { + guard let offset = symbol.offset else { continue } + symbol.name.withCString { classify($0, at: CodeLocation(imageIndex: imageIndex, address: UInt64(bitPattern: Int64(bitPattern: headerAddress) &+ Int64(offset)))) } + } + } + self.messageSendLocations = messageSendLocations + self.superMessageSendLocations = superMessageSendLocations + self.runtimeHelperLocations = runtimeHelperLocations + self.classReturningFunctionLocations = classReturningFunctionLocations + self.typeByMangledNameEntries = typeByMangledNameEntries + #else + return nil + #endif + } + + /// The libraries whose exported helpers a scan recognizes, and whose + /// `objc_msgSend` copies the shared selector stubs branch to. + private static func isRuntimeLibrary(_ path: String) -> Bool { + path.hasSuffix("/libobjc.A.dylib") + || path.hasSuffix("/libswiftCore.dylib") + || path.hasSuffix("/libswift_Concurrency.dylib") + || path.contains("/libobjcMsgSend") + } + + // MARK: - Images and functions + + /// The position in ``images`` of the image at `path`: where dyld loaded + /// it, which for a shared cache image is its install name. An install + /// name finds an image outside the cache too. + public func imageIndex(forPath path: String) -> Int? { + indicesByPath[path] ?? indicesByInstallName[path]?.first + } + + /// The image whose `__TEXT` segment holds the runtime address `address`, + /// and the unslid address there. + public func location(ofRuntimeAddress address: UInt) -> CodeLocation? { + guard let imageIndex = imageIndex(containingRuntimeAddress: address), + let slide = images[imageIndex].vmaddrSlide + else { return nil } + return CodeLocation(imageIndex: imageIndex, address: UInt64(bitPattern: Int64(Int(bitPattern: address) &- slide))) + } + + /// Every function of the image, sorted by address. + public func functions(inImageAt imageIndex: Int) -> [CodeFunction] { + let table = functionTable(ofImageAt: imageIndex) + return table.starts.indices.map { table.codeFunction(at: $0) } + } + + /// The function whose code holds `location`. + public func function(containing location: CodeLocation) -> CodeFunction? { + let table = functionTable(ofImageAt: location.imageIndex) + guard let index = table.functionIndex(containing: location.address) else { return nil } + return table.codeFunction(at: index) + } + + /// The functions holding each of `locations`, keyed by the location + /// asked about — for naming the results of a query that touched many + /// images. Each image's table is built for the lookup and dropped, + /// unless the analyzer already holds it; a location in no function is + /// left out. + public func functions(containing locations: some Sequence) -> [CodeLocation: CodeFunction] { + var functions: [CodeLocation: CodeFunction] = [:] + for (imageIndex, imageLocations) in Dictionary(grouping: locations, by: \.imageIndex) { + let table = existingFunctionTable(ofImageAt: imageIndex) ?? ImageFunctionTable(imageIndex: imageIndex, image: images[imageIndex]) + for location in imageLocations { + guard let index = table.functionIndex(containing: location.address) else { continue } + functions[location] = table.codeFunction(at: index) + } + } + return functions + } + + /// The symbol at exactly `location`, when one is there. + public func symbolName(at location: CodeLocation) -> String? { + guard let function = function(containing: location), function.location == location, + case .symbol(let name)? = function.name + else { return nil } + return name + } + + // MARK: - References + + /// What `function` references, in instruction order. + public func references(madeBy function: CodeFunction) -> [CodeReference] { + let table = functionTable(ofImageAt: function.location.imageIndex) + guard let index = table.functionIndex(containing: function.location.address) else { return [] } + var scanner = ReferenceScanner(analyzer: self, table: table) + var references: [CodeReference] = [] + scanner.scanFunction(at: index, into: &references) + return references + } + + /// What every function of the image references, grouped by what it + /// references. + /// + /// The image's function table is built for the scan and dropped after + /// it, unless the analyzer already holds it: a cross-image query scans + /// thousands of images, and keeping every table it touched held 1.5 GB + /// after a scan of a macOS 27.2 cache. + public func referenceTable(ofImageAt imageIndex: Int) -> CodeReferenceTable { + let table = existingFunctionTable(ofImageAt: imageIndex) ?? ImageFunctionTable(imageIndex: imageIndex, image: images[imageIndex]) + var scanner = ReferenceScanner(analyzer: self, table: table) + var references: [CodeReference] = [] + for index in table.starts.indices { + scanner.scanFunction(at: index, into: &references) + } + return CodeReferenceTable(imageIndex: imageIndex, references: references) + } + + /// Scans every function of the image once and files what a query for + /// callers or for a type's references reads in a ``CodeReferenceIndex``: + /// a quarter to a third of the memory of a ``CodeReferenceTable`` — + /// AppKit's is 21 MiB against 67 MiB on macOS 27.2 — so a host can keep + /// one for each image it has open and answer later queries without + /// scanning again. + /// + /// Keeps the image's function table, which naming what the index answers + /// needs: build indexes for the images a host means to keep, not for + /// every image a cross-image query touches. + public func referenceIndex(ofImageAt imageIndex: Int) -> CodeReferenceIndex { + // Never stopped: the progress closure is absent. + referenceIndex(ofImageAt: imageIndex, reportingProgress: nil)! + } + + /// ``referenceIndex(ofImageAt:)``, telling `reportProgress` how many of + /// the image's functions are scanned every so often, the last time when + /// all are; it returns whether to go on, and the index is `nil` when it + /// said not to. + public func referenceIndex( + ofImageAt imageIndex: Int, + reportingProgress reportProgress: ((_ scannedFunctionCount: Int, _ functionCount: Int) -> Bool)? + ) -> CodeReferenceIndex? { + let table = functionTable(ofImageAt: imageIndex) + var scanner = ReferenceScanner(analyzer: self, table: table) + var builder = CodeReferenceIndex.Builder(imageIndex: imageIndex, codeStart: table.textStart) + var functionReferences: [CodeReference] = [] + let functionCount = table.starts.count + for index in table.starts.indices { + if let reportProgress, index % Self.referenceIndexProgressStride == 0, !reportProgress(index, functionCount) { + return nil + } + functionReferences.removeAll(keepingCapacity: true) + scanner.scanFunction(at: index, into: &functionReferences) + for reference in functionReferences { + builder.add(reference) + } + } + if let reportProgress, !reportProgress(functionCount, functionCount) { + return nil + } + return builder.index() + } + + /// How many functions an index's scan gets through between progress + /// reports: a few dozen reports for a large image. + static let referenceIndexProgressStride = 2048 + + /// Builds the image's function table now, unless the analyzer holds it, + /// and keeps it for the analyzer's lifetime — for a host about to name the + /// functions a ``CodeReferenceIndex`` answers with, again and again, with + /// an analyzer other than the one that built the index. + public func keepFunctionTable(ofImageAt imageIndex: Int) { + _ = functionTable(ofImageAt: imageIndex) + } + + /// Reads now every name a query reads the first time it names a function + /// of the image or looks up a class or a Swift type it defines, and keeps + /// them for the analyzer's lifetime: the function table, with the names + /// its symbol table does not give — from the export trie, the Objective-C + /// method lists and the Swift metadata — the names of the image's + /// classes, and the symbols of its Swift types. + /// + /// For a host keeping a ``CodeReferenceIndex`` of the image, so that the + /// first query about it is answered as fast as the next: AppKit's take + /// 0.3 s in a debug build, and hold about 14 MiB with the function table + /// (``approximateByteCount(ofImageDataAt:)``). + public func prepareNames(inImageAt imageIndex: Int) { + functionTable(ofImageAt: imageIndex).fallbackNames.readEverySource() + objectiveCClassIndex(ofImageAt: imageIndex).readEveryName() + swiftTypeIndex(ofImageAt: imageIndex).readDescriptorSymbols() + } + + /// The memory of what the analyzer keeps for the image now — its function + /// table with the names read for it, its class and Swift type indexes — + /// estimated from the collections' capacities: for a host counting a + /// prepared image against a budget along with its ``CodeReferenceIndex``. + public func approximateByteCount(ofImageDataAt imageIndex: Int) -> Int { + lock.lock() + let kept = (functionTables[imageIndex], classIndexes[imageIndex], swiftTypeIndexes[imageIndex]) + lock.unlock() + return (kept.0?.approximateByteCount ?? 0) + (kept.1?.approximateByteCount ?? 0) + (kept.2?.approximateByteCount ?? 0) + } + + /// Reads now what filtering the images that can reference a function or + /// a type reads across every image the first time, and keeps it for the + /// analyzer's lifetime: which images link which — every image's load + /// commands — and the symbols images re-export under other names — every + /// image's export trie, 3.9 s in a debug build. + /// + /// On the calling thread alone, for work in the background: reading the + /// export tries on every core, as a query that needs them first does, is + /// barely faster in a debug build (3.4 s on 28). A query that needs them + /// meanwhile waits for this to finish instead of reading them again. + public func preparePrefilters() { + _ = linkage() + _ = renamedReexports(concurrently: false) + } + + /// Drops what the analyzer keeps for every image but `keptImageIndices`: + /// function tables with the names read for them, class and Swift type + /// indexes. A later query reads them again. What the analyzer keeps + /// across all images — the linkage and the renamed re-exports — stays. + /// + /// What replacing the analyzer releases, for a host that keeps a few + /// images prepared (``prepareNames(inImageAt:)``) and would otherwise + /// read them all again. + public func releaseImageData(exceptForImagesAt keptImageIndices: Set) { + lock.lock() + let released = (functionTables, classIndexes, swiftTypeIndexes) + functionTables = functionTables.filter { keptImageIndices.contains($0.key) } + classIndexes = classIndexes.filter { keptImageIndices.contains($0.key) } + swiftTypeIndexes = swiftTypeIndexes.filter { keptImageIndices.contains($0.key) } + lock.unlock() + // What goes is freed here, outside the lock. + withExtendedLifetime(released) {} + } + + /// The references the image's functions make to any of `keys`, in table + /// order — what a query for callers needs, without the image's whole + /// table. + /// + /// A whole table of a large image runs to a hundred megabytes, and a + /// cross-image query scans thousands of images at once; building them all + /// is what sets the scan's peak memory. + public func references(to keys: Set, inImageAt imageIndex: Int) -> [CodeReference] { + let table = existingFunctionTable(ofImageAt: imageIndex) ?? ImageFunctionTable(imageIndex: imageIndex, image: images[imageIndex]) + var scanner = ReferenceScanner(analyzer: self, table: table, keeping: keys) + var references: [CodeReference] = [] + for index in table.starts.indices { + scanner.scanFunction(at: index, into: &references) + } + return references + } + + // MARK: - Internals + + func existingFunctionTable(ofImageAt imageIndex: Int) -> ImageFunctionTable? { + lock.lock() + defer { lock.unlock() } + return functionTables[imageIndex] + } + + /// The class and Swift type indexes the analyzer keeps for the image now, + /// without building either; for tests. + func existingIndexes(ofImageAt imageIndex: Int) -> (classIndex: ObjectiveCClassIndex?, swiftTypeIndex: SwiftTypeIndex?) { + lock.lock() + defer { lock.unlock() } + return (classIndexes[imageIndex], swiftTypeIndexes[imageIndex]) + } + + /// Whether the linkage and the renamed re-exports are read; for tests. + var hasPreparedPrefilters: Bool { + lock.lock() + defer { lock.unlock() } + return linkageStorage != nil && renamedReexportStorage != nil + } + + /// The image's function table, built on first use and then kept for the + /// analyzer's lifetime — what naming functions needs. + func functionTable(ofImageAt imageIndex: Int) -> ImageFunctionTable { + lock.lock() + if let table = functionTables[imageIndex] { + lock.unlock() + return table + } + lock.unlock() + // Built outside the lock: two threads may build the same table once + // each, and the first one stored wins. + let table = ImageFunctionTable(imageIndex: imageIndex, image: images[imageIndex]) + lock.lock() + defer { lock.unlock() } + if let stored = functionTables[imageIndex] { return stored } + functionTables[imageIndex] = table + return table + } + + func imageIndex(containingRuntimeAddress address: UInt) -> Int? { + var lower = 0 + var upper = textRanges.count + while lower < upper { + let middle = (lower + upper) / 2 + if textRanges[middle].start <= address { lower = middle + 1 } else { upper = middle } + } + guard lower > 0 else { return nil } + let candidate = textRanges[lower - 1] + return address < candidate.end ? candidate.imageIndex : nil + } + + /// The image whose segments other than `__TEXT` hold the runtime + /// `address`. + func imageIndex(containingDataAddress address: UInt) -> Int? { + var lower = 0 + var upper = dataRanges.count + while lower < upper { + let middle = (lower + upper) / 2 + if dataRanges[middle].start <= address { lower = middle + 1 } else { upper = middle } + } + guard lower > 0 else { return nil } + let candidate = dataRanges[lower - 1] + return address < candidate.end ? candidate.imageIndex : nil + } + + /// The class object at the runtime `address`, when an image lists one + /// there; a metaclass is reported as its class. + func objectiveCClass(atRuntimeAddress address: UInt) -> ObjectiveCClassObject? { + guard let imageIndex = imageIndex(containingDataAddress: address) else { return nil } + return objectiveCClassIndex(ofImageAt: imageIndex).classObject(atRuntimeAddress: address) + } + + /// The image's class index, built on first use and then kept for the + /// analyzer's lifetime: a scan meets the same few hundred classes again + /// and again. + func objectiveCClassIndex(ofImageAt imageIndex: Int) -> ObjectiveCClassIndex { + lock.lock() + if let index = classIndexes[imageIndex] { + lock.unlock() + return index + } + lock.unlock() + let index = ObjectiveCClassIndex(image: images[imageIndex], imageIndex: imageIndex) + lock.lock() + defer { lock.unlock() } + if let stored = classIndexes[imageIndex] { return stored } + classIndexes[imageIndex] = index + return index + } + + /// Built on first use and kept: reading every image's load commands takes + /// a few tens of milliseconds. + func linkage() -> Linkage { + lock.lock() + if let linkageStorage { + lock.unlock() + return linkageStorage + } + lock.unlock() + var dependents: [Int: [Int]] = [:] + var reexporters: [Int: [Int]] = [:] + var executables: [Int] = [] + var bundles: [Int] = [] + for (imageIndex, image) in images.enumerated() { + switch image.header.fileType { + case .execute?: executables.append(imageIndex) + case .bundle?: bundles.append(imageIndex) + default: break + } + for (command, isReexport) in dylibCommands(ofImageAt: imageIndex) { + for dependency in imageIndices(linkedAs: command.dylib(cmdsStart: image.cmdsStartPtr).name) where dependency != imageIndex { + dependents[dependency, default: []].append(imageIndex) + if isReexport { reexporters[dependency, default: []].append(imageIndex) } + } + } + } + // A bundle linked with `-bundle_loader` binds to the main executable, + // which no load command names; every bundle counts as linking it. + for executable in executables { + dependents[executable, default: []].append(contentsOf: bundles) + } + let linkage = Linkage(dependents: dependents, reexporters: reexporters) + lock.lock() + defer { lock.unlock() } + if let linkageStorage { return linkageStorage } + linkageStorage = linkage + return linkage + } + + /// The image's dylib load commands, in order — the order a bind's or a + /// re-export's library ordinal counts, from 1 — and whether each + /// re-exports the dylib. + private func dylibCommands(ofImageAt imageIndex: Int) -> [(command: DylibCommand, isReexport: Bool)] { + images[imageIndex].loadCommands.compactMap { command in + switch command { + case .loadDylib(let command), .loadWeakDylib(let command), .loadUpwardDylib(let command), .lazyLoadDylib(let command): + return (command, false) + case .reexportDylib(let command): + return (command, true) + default: + return nil + } + } + } + + /// The images a load command's dylib name stands for: every image with + /// that install name, or the image loaded from that path. + private func imageIndices(linkedAs name: String) -> [Int] { + indicesByInstallName[name] ?? indicesByPath[name].map { [$0] } ?? [] + } + + /// The images the image at `imageIndex` links, by library ordinal: the + /// first element for ordinal 1. An element is empty when no image the + /// analyzer knows is that dylib. + func dependencyImageIndices(ofImageAt imageIndex: Int) -> [[Int]] { + dylibCommands(ofImageAt: imageIndex).map { imageIndices(linkedAs: $0.command.dylib(cmdsStart: images[imageIndex].cmdsStartPtr).name) } + } + + /// Built on first use and kept: every image's export trie is walked once, + /// and what is kept is small. Built once: a caller that asks while it is + /// being built waits for it. + func renamedReexports(concurrently: Bool = true) -> RenamedReexportIndex { + lock.lock() + if let renamedReexportStorage { + lock.unlock() + return renamedReexportStorage + } + lock.unlock() + renamedReexportBuildLock.lock() + defer { renamedReexportBuildLock.unlock() } + lock.lock() + if let renamedReexportStorage { + lock.unlock() + return renamedReexportStorage + } + lock.unlock() + let index = RenamedReexportIndex(analyzer: self, concurrently: concurrently) + lock.lock() + renamedReexportStorage = index + renamedReexportBuildCountStorage += 1 + lock.unlock() + return index + } + + /// How many times the renamed re-exports were built; for tests. + var renamedReexportBuildCount: Int { + lock.lock() + defer { lock.unlock() } + return renamedReexportBuildCountStorage + } + + /// The image's Swift type index, built on first use and then kept for the + /// analyzer's lifetime, like the class index. + func swiftTypeIndex(ofImageAt imageIndex: Int) -> SwiftTypeIndex { + lock.lock() + if let index = swiftTypeIndexes[imageIndex] { + lock.unlock() + return index + } + lock.unlock() + let index = SwiftTypeIndex(image: images[imageIndex], imageIndex: imageIndex) + lock.lock() + defer { lock.unlock() } + if let stored = swiftTypeIndexes[imageIndex] { return stored } + swiftTypeIndexes[imageIndex] = index + return index + } + + /// Whether `length` bytes at the runtime `address` are mapped executable. + func isExecutable(runtimeAddress address: UInt, length: UInt) -> Bool { + let (end, overflow) = address.addingReportingOverflow(length) + guard !overflow else { return false } + return executableRanges.contains { $0.lowerBound <= address && end <= $0.upperBound } + } + + /// Whether `length` bytes at the runtime `address` are mapped at all. + func isMapped(runtimeAddress address: UInt, length: UInt) -> Bool { + let (end, overflow) = address.addingReportingOverflow(length) + guard !overflow else { return false } + return mappedRanges.contains { $0.lowerBound <= address && end <= $0.upperBound } + } + + /// How many bytes from the runtime `address` on may be read: up to the + /// end of the mapping that holds it, or none. + func mappedLength(fromRuntimeAddress address: UInt) -> UInt { + guard let range = mappedRanges.first(where: { $0.contains(address) }) else { return 0 } + return range.upperBound - address + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeFunction.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeFunction.swift new file mode 100644 index 000000000..b8601fe02 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeFunction.swift @@ -0,0 +1,47 @@ +/// A function of an image, bounded by `LC_FUNCTION_STARTS` and the symbol +/// table. +/// +/// Every function is scanned, named or not: half of the functions in a +/// macOS 27.2 dyld shared cache carry no symbol, and the calls they make are +/// half of all calls. +public struct CodeFunction: Hashable, Sendable { + /// Where a function's name came from, in the order they are tried. + public enum Name: Hashable, Sendable { + /// From the symbol table or the export trie, as they spell it: a + /// mangled Swift name, a C name, or `-[Class selector]`. + case symbol(String) + /// From an Objective-C method list, when no symbol names the + /// function. The method lists do not record categories, so a + /// category method reads as `-[NSTextView draggingUpdated:]` where + /// the symbol would say `-[NSTextView(NSDragging) draggingUpdated:]`. + case objectiveCMethod(className: String, selector: String, isClassMethod: Bool) + /// A Swift mangled name rebuilt from metadata, when no symbol names + /// the function: a type's metadata accessor (`…Ma`) or singleton + /// completion function (`…Mr`), or a method whose descriptor's + /// `…Tq` symbol spells it. Demangles like a symbol. + case swiftMetadata(mangledName: String) + } + + /// The first instruction. + public let location: CodeLocation + /// Bytes up to the next function start, or to the end of `__text`. + public let size: Int + /// `nil` when neither a symbol nor metadata names the function. An + /// iOS device's shared cache keeps its images' local symbol entries but + /// names every one ``; those count as unnamed. + public let name: Name? + /// Other symbols at the same address, left there by identical code + /// folding. + public let foldedSymbolNames: [String] + /// A function that only manages memory or values — a retain, an + /// outlined copy — and is hidden from results by default. + public let isRuntimeHelper: Bool + + public init(location: CodeLocation, size: Int, name: Name?, foldedSymbolNames: [String], isRuntimeHelper: Bool) { + self.location = location + self.size = size + self.name = name + self.foldedSymbolNames = foldedSymbolNames + self.isRuntimeHelper = isRuntimeHelper + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeLocation.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeLocation.swift new file mode 100644 index 000000000..90b51ed15 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeLocation.swift @@ -0,0 +1,21 @@ +/// An address in the code of one image a ``CrossReferenceAnalyzer`` knows. +/// +/// The address is the image's own, unslid — the one `dyld_info`, a +/// disassembler or a crash report's binary image list prints. Unslid +/// addresses of two images outside the dyld shared cache can coincide, so a +/// location carries its image. +public struct CodeLocation: Hashable, Comparable, Sendable { + /// The image's position in ``CrossReferenceAnalyzer/images``. + public let imageIndex: Int + /// The unslid address. + public let address: UInt64 + + public init(imageIndex: Int, address: UInt64) { + self.imageIndex = imageIndex + self.address = address + } + + public static func < (lhs: CodeLocation, rhs: CodeLocation) -> Bool { + (lhs.imageIndex, lhs.address) < (rhs.imageIndex, rhs.address) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift new file mode 100644 index 000000000..aa0599123 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift @@ -0,0 +1,123 @@ +/// What an Objective-C send's receiver is known to be. +public enum ReceiverClassHint: Hashable, Sendable { + /// The sending method's own receiver, still in `x0` where it arrived, or a + /// copy of it. + case methodReceiver + /// Loaded from a class reference: `[NSWindow alloc]`. + case classLiteral(String) + case unknown +} + +/// Evidence for where an indirect call may go. +public struct IndirectCallEvidence: Hashable, Sendable { + /// The table the callee was loaded from. + public enum Table: Hashable, Sendable { + case classVirtualTable + case protocolWitnessTable + case valueWitnessTable + /// A function value, or a table the analysis cannot identify. + case none + } + + public let table: Table + /// The displacement of the load that produced the callee, when it came + /// from memory. + public let tableOffset: Int64? + /// The 16-bit arm64e discriminator constant, when there is one. + public let pointerAuthenticationConstant: UInt16? + /// Whether the constant was blended into an address (`movk xN, #imm, + /// lsl #48`) or used alone (`mov x17, #imm`). + public let isAddressBlended: Bool + + public init(table: Table, tableOffset: Int64?, pointerAuthenticationConstant: UInt16?, isAddressBlended: Bool) { + self.table = table + self.tableOffset = tableOffset + self.pointerAuthenticationConstant = pointerAuthenticationConstant + self.isAddressBlended = isAddressBlended + } +} + +/// What one instruction references. +public enum CodeReferenceTarget: Hashable, Sendable { + /// A function: in the same image, in another, or wherever a stub, a GOT + /// slot or a stub island led. + case function(CodeLocation) + /// A stub whose slot could not be followed; the name its indirect symbol + /// carries. + case importedSymbol(name: String) + /// An Objective-C message send whose selector is known. + case messageSend(selector: String, receiver: ReceiverClassHint) + /// A send through `objc_msgSendSuper2` whose selector is known, and the + /// class the lookup starts above: the one the sending method loads from + /// `__objc_superrefs`, or the class its symbol names. `nil` for Swift + /// code, which builds its `objc_super` from a class known only at run + /// time. + case superMessageSend(selector: String, className: String?) + /// A Swift type, by where its context descriptor lies: a call to its + /// metadata accessor, or the address of the accessor or of the type's + /// metadata. A Swift class is also reached as an Objective-C class. + case swiftType(descriptor: CodeLocation) + /// Swift types named by a mangled name, which the scan does not take + /// apart: see ``SwiftTypeName``. + case swiftTypeName(SwiftTypeName) + /// An Objective-C class reference: the class's runtime name (`NSWindow`, + /// `_TtC7SwiftUI20FilePresenterWrapper`) and where the class object lies. + /// A name alone can be ambiguous — a shared cache carries the macOS and the + /// Mac Catalyst variant of a framework, and both define its classes. A + /// reference to a metaclass is reported as one to its class. + case objectiveCClass(name: String, location: CodeLocation) + case indirect(IndirectCallEvidence) + /// Code that lies in no image and in no recognized trampoline — or data + /// in `__text` that decoded as a branch. + case unrecognized(address: UInt64) +} + +/// One instruction's reference. +public struct CodeReference: Hashable, Sendable { + public enum Kind: Hashable, Sendable { + case call + /// A branch out of the function that does not return to it. + case tailCall + /// A reference to a type: an instruction that takes the address of a + /// class object, a type's metadata or its metadata accessor — a load + /// from a GOT slot or class reference, or `adrp` / `add` of the object + /// itself — or a call to a metadata accessor or a mangled-name + /// instantiation, which is reported as the call it is as well. + case reference + } + + /// The first instruction of the function the referencing instruction + /// belongs to. + public let function: CodeLocation + /// The referencing instruction's unslid address, in the same image as + /// ``function``. + public let instructionAddress: UInt64 + public let kind: Kind + public let target: CodeReferenceTarget + /// A retain or release, an outlined value operation or another runtime + /// helper; the target says which function. + public let isRuntimeHelperCall: Bool + + public init(function: CodeLocation, instructionAddress: UInt64, kind: Kind, target: CodeReferenceTarget, isRuntimeHelperCall: Bool) { + self.function = function + self.instructionAddress = instructionAddress + self.kind = kind + self.target = target + self.isRuntimeHelperCall = isRuntimeHelperCall + } +} + +/// A mangled name that names Swift types. Which types it names takes +/// demangling to tell, so a scan records where the name is and leaves that +/// to whoever asks (`CrossReferenceAnalyzer.swiftTypeKeys(in:)`). +public enum SwiftTypeName: Hashable, Sendable { + /// The name a call to `__swift_instantiateConcreteTypeFromMangledName` + /// (or the runtime's `swift_getTypeByMangledNameInContext`) instantiates: + /// where its bytes start and how many there are. It may hold symbolic + /// references to context descriptors. + case mangledName(location: CodeLocation, length: Int) + /// The symbol of a metadata accessor no type context descriptor stands + /// for — a generic instance (`$sSNy10Foundation4DateVGMa`) or an + /// existential — without the leading underscore. + case accessorSymbol(String) +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift new file mode 100644 index 000000000..b1156a549 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift @@ -0,0 +1,344 @@ +import Foundation + +/// One image's references, filed by what they reference and stored small +/// enough for a host to keep for every image it has open: a name is stored +/// once however many references carry it, and the referencing function and +/// instruction as 32-bit offsets into the image's `__text`. +/// +/// It holds what a query for callers or for a type's references reads — +/// calls and tail calls, sends, imported names, class and Swift type +/// references — and leaves out indirect calls and branches into no image. +/// Read from it, ``references(to:)`` answers exactly what +/// ``CrossReferenceAnalyzer/references(to:inImageAt:)`` scans for, and +/// ``CrossReferenceAnalyzer/references(toSwiftType:in:)`` what +/// ``CrossReferenceAnalyzer/references(toSwiftType:inImageAt:)`` does. +/// +/// A value that holds no analyzer: any analyzer over the same images reads +/// it, so a host may replace its analyzer and keep its indexes, as long as +/// the image keeps its position. Built by +/// ``CrossReferenceAnalyzer/referenceIndex(ofImageAt:)``. +public struct CodeReferenceIndex: Sendable { + /// One reference, without what it references: its group says that. + struct Entry { + let functionOffset: UInt32 + let instructionOffset: UInt32 + /// For a send, the class-literal receiver; for a super send, the + /// class the lookup starts above: a position in `classNames`, plus + /// one. Zero for none. + let className: UInt32 + /// Bits 0–1 the kind, bit 2 a runtime helper call, bits 3–4 how a + /// send's receiver is known. + let flags: UInt8 + } + + /// What every reference of a group references, but a send's receiver, + /// which its entry carries. + enum Target: Hashable { + case function(CodeLocation) + case importedSymbol(name: String) + case messageSend(selector: String) + case superMessageSend(selector: String) + case objectiveCClass(name: String, location: CodeLocation) + case swiftType(descriptor: CodeLocation) + case swiftTypeName(SwiftTypeName) + } + + struct Group { + let target: Target + let entryStart: Int32 + let entryEnd: Int32 + } + + /// The image's position in the analyzer's + /// ``CrossReferenceAnalyzer/images``. + public let imageIndex: Int + + /// A rough measure of the memory the index holds, the heap storage of its + /// names included. + public let approximateByteCount: Int + + /// Where the offsets count from: the start of the image's `__text`. + private let codeStart: UInt64 + /// Every group's entries, one group after another, each in scan order. + private let entries: [Entry] + /// Groups sharing a table key lie next to each other — a selector's sends + /// and super sends, a class name's classes — and the Swift type and type + /// name groups, which a type query reads through, last. + private let groups: [Group] + private let groupRangesByKey: [CodeReferenceTable.Key: Range] + private let swiftTypeGroupRange: Range + private let swiftTypeNameGroupRange: Range + private let classNames: [String] + + /// How many references the index holds. + public var referenceCount: Int { + entries.count + } + + /// The references filed under any of `keys`, in instruction order — what + /// ``CrossReferenceAnalyzer/references(to:inImageAt:)`` finds for them. + public func references(to keys: Set) -> [CodeReference] { + var groupIndices: [Int32] = [] + for key in keys { + guard let range = groupRangesByKey[key] else { continue } + groupIndices.append(contentsOf: range) + } + return references(inGroupsAt: groupIndices) + } + + /// The references in the groups a type query reads — every Swift type and + /// type name, and the classes named `objectiveCClassName` — whose target + /// `matches`. + func references(toTypesMatching matches: (CodeReferenceTarget) -> Bool, objectiveCClassName: String?) -> [CodeReference] { + var candidateGroups = Array(swiftTypeGroupRange) + Array(swiftTypeNameGroupRange) + if let objectiveCClassName, let range = groupRangesByKey[.objectiveCClass(objectiveCClassName)] { + candidateGroups.append(contentsOf: range) + } + return references(inGroupsAt: candidateGroups.filter { matches(Self.target(of: groups[Int($0)].target, receiver: .unknown, className: nil)) }) + } + + /// The references of the groups, in instruction order: a call before the + /// type reference it also makes, as a scan records them. + private func references(inGroupsAt groupIndices: [Int32]) -> [CodeReference] { + var positions: [(entryIndex: Int32, groupIndex: Int32)] = [] + for groupIndex in groupIndices { + let group = groups[Int(groupIndex)] + for entryIndex in group.entryStart ..< group.entryEnd { + positions.append((entryIndex, groupIndex)) + } + } + positions.sort { left, right in + let leftEntry = entries[Int(left.entryIndex)] + let rightEntry = entries[Int(right.entryIndex)] + if leftEntry.instructionOffset != rightEntry.instructionOffset { return leftEntry.instructionOffset < rightEntry.instructionOffset } + let leftRank = Self.kindRank(leftEntry.flags) + let rightRank = Self.kindRank(rightEntry.flags) + if leftRank != rightRank { return leftRank < rightRank } + if left.groupIndex != right.groupIndex { return left.groupIndex < right.groupIndex } + return left.entryIndex < right.entryIndex + } + return positions.map { reference(at: Int($0.entryIndex), in: groups[Int($0.groupIndex)]) } + } + + private func reference(at entryIndex: Int, in group: Group) -> CodeReference { + let entry = entries[entryIndex] + let className = entry.className == 0 ? nil : classNames[Int(entry.className - 1)] + let receiver: ReceiverClassHint + switch (entry.flags >> 3) & 0b11 { + case 1: + receiver = .methodReceiver + case 2: + receiver = .classLiteral(className ?? "") + default: + receiver = .unknown + } + return CodeReference( + function: CodeLocation(imageIndex: imageIndex, address: codeStart + UInt64(entry.functionOffset)), + instructionAddress: codeStart + UInt64(entry.instructionOffset), + kind: Self.kind(entry.flags), + target: Self.target(of: group.target, receiver: receiver, className: className), + isRuntimeHelperCall: entry.flags & 0b100 != 0 + ) + } + + private static func target(of target: Target, receiver: ReceiverClassHint, className: String?) -> CodeReferenceTarget { + switch target { + case .function(let location): + return .function(location) + case .importedSymbol(let name): + return .importedSymbol(name: name) + case .messageSend(let selector): + return .messageSend(selector: selector, receiver: receiver) + case .superMessageSend(let selector): + return .superMessageSend(selector: selector, className: className) + case .objectiveCClass(let name, let location): + return .objectiveCClass(name: name, location: location) + case .swiftType(let descriptor): + return .swiftType(descriptor: descriptor) + case .swiftTypeName(let name): + return .swiftTypeName(name) + } + } + + private static func kind(_ flags: UInt8) -> CodeReference.Kind { + switch flags & 0b11 { + case 1: .tailCall + case 2: .reference + default: .call + } + } + + /// A call or tail call comes before the type reference the same + /// instruction makes. + private static func kindRank(_ flags: UInt8) -> UInt8 { + flags & 0b11 == 2 ? 1 : 0 + } + + // MARK: - Building + + /// Files a scan's references as they come, function by function. + struct Builder { + private let imageIndex: Int + private let codeStart: UInt64 + private var entriesByTarget: [Target: [Entry]] = [:] + private var classNamePositions: [String: UInt32] = [:] + private var classNames: [String] = [] + + init(imageIndex: Int, codeStart: UInt64) { + self.imageIndex = imageIndex + self.codeStart = codeStart + } + + mutating func add(_ reference: CodeReference) { + let target: Target + var className: String? + var receiverBits: UInt8 = 0 + switch reference.target { + case .function(let location): + target = .function(location) + case .importedSymbol(let name): + target = .importedSymbol(name: name) + case .messageSend(let selector, let receiver): + target = .messageSend(selector: selector) + switch receiver { + case .methodReceiver: + receiverBits = 1 + case .classLiteral(let name): + receiverBits = 2 + className = name + case .unknown: + receiverBits = 0 + } + case .superMessageSend(let selector, let superclassName): + target = .superMessageSend(selector: selector) + className = superclassName + case .objectiveCClass(let name, let location): + target = .objectiveCClass(name: name, location: location) + case .swiftType(let descriptor): + target = .swiftType(descriptor: descriptor) + case .swiftTypeName(let name): + target = .swiftTypeName(name) + case .indirect, .unrecognized: + // No query for callers or for a type reads them. + return + } + let kindBits: UInt8 + switch reference.kind { + case .call: kindBits = 0 + case .tailCall: kindBits = 1 + case .reference: kindBits = 2 + } + assert( + reference.function.address >= codeStart && reference.instructionAddress >= codeStart && reference.instructionAddress - codeStart <= UInt64(UInt32.max), + "a reference outside the image's __text" + ) + var classNamePosition: UInt32 = 0 + if let className { + classNamePosition = position(ofClassName: className) + } + let entry = Entry( + functionOffset: UInt32(truncatingIfNeeded: reference.function.address &- codeStart), + instructionOffset: UInt32(truncatingIfNeeded: reference.instructionAddress &- codeStart), + className: classNamePosition, + flags: kindBits | (reference.isRuntimeHelperCall ? 0b100 : 0) | (receiverBits << 3) + ) + entriesByTarget[target, default: []].append(entry) + } + + private mutating func position(ofClassName name: String) -> UInt32 { + if let position = classNamePositions[name] { return position } + classNames.append(name) + let position = UInt32(classNames.count) + classNamePositions[name] = position + return position + } + + /// Lays the groups out — those sharing a key next to each other, the + /// Swift type and type name groups last — and files them by key. + func index() -> CodeReferenceIndex { + var keyedTargets: [CodeReferenceTable.Key: [Target]] = [:] + var swiftTypeTargets: [Target] = [] + var swiftTypeNameTargets: [Target] = [] + for target in entriesByTarget.keys { + switch target { + case .function(let location): + keyedTargets[.function(location), default: []].append(target) + case .importedSymbol(let name): + keyedTargets[.importedSymbol(name), default: []].append(target) + case .messageSend(let selector), .superMessageSend(let selector): + keyedTargets[.selector(selector), default: []].append(target) + case .objectiveCClass(let name, _): + keyedTargets[.objectiveCClass(name), default: []].append(target) + case .swiftType: + swiftTypeTargets.append(target) + case .swiftTypeName: + swiftTypeNameTargets.append(target) + } + } + var entries: [Entry] = [] + entries.reserveCapacity(entriesByTarget.values.reduce(0) { $0 + $1.count }) + var groups: [Group] = [] + var nameBytes = 0 + func appendGroup(_ target: Target) { + let targetEntries = entriesByTarget[target] ?? [] + let start = Int32(entries.count) + entries.append(contentsOf: targetEntries) + groups.append(Group(target: target, entryStart: start, entryEnd: Int32(entries.count))) + nameBytes += Self.heapByteCount(of: target) + } + var groupRangesByKey: [CodeReferenceTable.Key: Range] = [:] + groupRangesByKey.reserveCapacity(keyedTargets.count + swiftTypeTargets.count) + for (key, targets) in keyedTargets { + let start = Int32(groups.count) + targets.forEach(appendGroup) + groupRangesByKey[key] = start ..< Int32(groups.count) + } + let swiftTypeStart = Int32(groups.count) + for target in swiftTypeTargets { + guard case .swiftType(let descriptor) = target else { continue } + let start = Int32(groups.count) + appendGroup(target) + groupRangesByKey[.swiftTypeDescriptor(descriptor)] = start ..< Int32(groups.count) + } + let swiftTypeNameStart = Int32(groups.count) + swiftTypeNameTargets.forEach(appendGroup) + nameBytes += classNames.reduce(0) { $0 + Self.heapByteCount(of: $1) } + + let dictionaryBucketByteCount = MemoryLayout.stride + MemoryLayout>.stride + let approximateByteCount = entries.count * MemoryLayout.stride + + groups.count * MemoryLayout.stride + + groupRangesByKey.capacity * dictionaryBucketByteCount + + classNames.count * MemoryLayout.stride + + nameBytes + return CodeReferenceIndex( + imageIndex: imageIndex, + approximateByteCount: approximateByteCount, + codeStart: codeStart, + entries: entries, + groups: groups, + groupRangesByKey: groupRangesByKey, + swiftTypeGroupRange: swiftTypeStart ..< swiftTypeNameStart, + swiftTypeNameGroupRange: swiftTypeNameStart ..< Int32(groups.count), + classNames: classNames + ) + } + + /// The heap a name holds beyond the string value itself: none for one + /// short enough to be stored inline. + private static func heapByteCount(of name: String) -> Int { + let byteCount = name.utf8.count + return byteCount > 15 ? byteCount + 32 : 0 + } + + private static func heapByteCount(of target: Target) -> Int { + switch target { + case .importedSymbol(let name), .messageSend(let name), .superMessageSend(let name), .objectiveCClass(let name, _): + return heapByteCount(of: name) + case .swiftTypeName(.accessorSymbol(let symbol)): + return heapByteCount(of: symbol) + case .function, .swiftType, .swiftTypeName(.mangledName): + return 0 + } + } + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift new file mode 100644 index 000000000..0bd53220b --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift @@ -0,0 +1,79 @@ +/// Every reference the functions of one image make, grouped by what they +/// reference. +/// +/// A table is a plain value: the analyzer does not keep it, so a host holds +/// it for as long as it is useful — ``approximateByteCount`` is what to +/// budget it by. +public struct CodeReferenceTable: Sendable { + /// What references are grouped by. + public enum Key: Hashable, Sendable { + case function(CodeLocation) + /// Every send of the selector, `super` sends included. + case selector(String) + case importedSymbol(String) + /// Every reference to the class, by its runtime name. + case objectiveCClass(String) + /// Every reference to the Swift type whose context descriptor lies + /// there. Names a mangled name holds are not filed: telling them takes + /// demangling (`CrossReferenceAnalyzer.references(toSwiftType:inImageAt:)`). + case swiftTypeDescriptor(CodeLocation) + } + + public let imageIndex: Int + /// In instruction order within each function, functions in address order. + public let references: [CodeReference] + private let referenceIndicesByKey: [Key: [Int32]] + + init(imageIndex: Int, references: [CodeReference]) { + self.imageIndex = imageIndex + self.references = references + var referenceIndicesByKey: [Key: [Int32]] = [:] + for (index, reference) in references.enumerated() { + guard let key = reference.target.tableKey else { continue } + referenceIndicesByKey[key, default: []].append(Int32(index)) + } + self.referenceIndicesByKey = referenceIndicesByKey + } + + /// The references to `key`, in table order. + public func references(to key: Key) -> [CodeReference] { + referenceIndicesByKey[key]?.map { references[Int($0)] } ?? [] + } + + /// Every key some reference in the table has, in no particular order. + public var keys: some Collection { + referenceIndicesByKey.keys + } + + /// A rough measure of the memory the table holds: the references, their + /// keys and the index — not the heap storage of the strings they carry. + /// A selector, class or imported name longer than 15 bytes holds a + /// buffer of its own, which every reference to that name from one scan + /// shares. + public var approximateByteCount: Int { + references.count * MemoryLayout.stride + + referenceIndicesByKey.count * (MemoryLayout.stride + 48) + + references.count * MemoryLayout.stride + } +} + +extension CodeReferenceTarget { + /// The key a ``CodeReferenceTable`` files this target under; `nil` for an + /// indirect call, an unrecognized target or a Swift type name. + public var tableKey: CodeReferenceTable.Key? { + switch self { + case .function(let location): + return .function(location) + case .messageSend(let selector, _), .superMessageSend(let selector, _): + return .selector(selector) + case .importedSymbol(let name): + return .importedSymbol(name) + case .objectiveCClass(let name, _): + return .objectiveCClass(name) + case .swiftType(let descriptor): + return .swiftTypeDescriptor(descriptor) + case .swiftTypeName, .indirect, .unrecognized: + return nil + } + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/ApproximateSize.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ApproximateSize.swift new file mode 100644 index 000000000..76c888fc4 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ApproximateSize.swift @@ -0,0 +1,37 @@ +/// How much memory the collections and strings the analyzer keeps take, +/// estimated from their capacities and element strides: what a host counts +/// against its memory budget. Allocator rounding is left out; a heap object's +/// header is counted as 32 bytes. +enum ApproximateSize { + private static let heapObjectHeaderByteCount = 32 + + static func of(_ array: [Element]) -> Int { + array.capacity == 0 ? 0 : heapObjectHeaderByteCount + array.capacity * MemoryLayout.stride + } + + static func of(_ set: Set) -> Int { + hashTableByteCount(capacity: set.capacity, bucketStride: MemoryLayout.stride) + } + + static func of(_ dictionary: [Key: Value]) -> Int { + hashTableByteCount(capacity: dictionary.capacity, bucketStride: MemoryLayout.stride + MemoryLayout.stride) + } + + /// A string's own storage: none for one of up to 15 UTF-8 bytes, which + /// is stored inline. + static func of(_ string: String) -> Int { + let byteCount = string.utf8.count + return byteCount <= 15 ? 0 : heapObjectHeaderByteCount + byteCount + 1 + } + + /// A native hash table: a power of two of buckets, at most three quarters + /// full, and a bit per bucket saying which are. + private static func hashTableByteCount(capacity: Int, bucketStride: Int) -> Int { + guard capacity > 0 else { return 0 } + var bucketCount = 1 + while bucketCount * 3 / 4 < capacity { + bucketCount <<= 1 + } + return heapObjectHeaderByteCount + bucketCount * bucketStride + bucketCount / 8 + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFallbackNames.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFallbackNames.swift new file mode 100644 index 000000000..cb6191733 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFallbackNames.swift @@ -0,0 +1,352 @@ +import Foundation +import MachOKit +import MachOObjCSection +import MachOFoundation +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import Demangling + +/// Names for the functions an image's symbol table leaves unnamed: from the +/// export trie, the Objective-C method lists, and the Swift metadata — tried +/// in that order, each read only when a function is still unnamed after the +/// ones before it. +/// +/// Read when a function is named, never during a scan. A scan needs no names, +/// and reading an image's method lists and metadata costs about as much as +/// scanning it (AppKit's method lists alone take 42–86 ms). Evolution proposal +/// `cross-reference-analysis`, batch two. +final class ImageFallbackNames: @unchecked Sendable { + struct ObjectiveCMethod { + let className: String + let selector: String + let isClassMethod: Bool + } + + /// Where a Swift function's name comes from. + private enum SwiftSource { + /// A type's metadata accessor (`Ma`) or singleton completion function + /// (`Mr`): the type's descriptor, and the suffix the name ends in. + case typeFunction(descriptor: TypeContextDescriptorWrapper, suffix: String) + /// A method whose descriptor's `…Tq` symbol spells its name. + case method(descriptorAddress: UInt64) + } + + private let image: MachOImage + private let headerAddress: UInt64 + private let slide: Int + private let textRange: Range + + private let lock = NSLock() + private var exportedNamesStorage: [UInt64: [String]]? + private var objectiveCMethodsStorage: [UInt64: ObjectiveCMethod]? + private var swiftSourcesStorage: [UInt64: SwiftSource]? + /// The `Mn` / `Tq` symbol at each descriptor the Swift sources name. + private var descriptorSymbolsStorage: [UInt64: String]? + private var swiftNames: [UInt64: String?] = [:] + /// What the sources read so far take, counted as each is read. + private var sourceByteCount = 0 + + init(image: MachOImage, headerAddress: UInt64, slide: Int, textRange: Range) { + self.image = image + self.headerAddress = headerAddress + self.slide = slide + self.textRange = textRange + } + + /// The name of the function at the unslid `address`, and the other names + /// at the same address, when one of the sources has one. + func name(at address: UInt64) -> (name: CodeFunction.Name, foldedSymbolNames: [String])? { + if let names = exportedNames()[address], let first = names.first { + return (.symbol(first), Array(names.dropFirst())) + } + if let method = objectiveCMethods()[address] { + return (.objectiveCMethod(className: method.className, selector: method.selector, isClassMethod: method.isClassMethod), []) + } + if let mangledName = swiftName(at: address) { + return (.swiftMetadata(mangledName: mangledName), []) + } + return nil + } + + /// Reads every source now — for a host that will name functions of the + /// image and wants none of it read while it waits. Each function's Swift + /// name is still rebuilt the first time it is asked for. + func readEverySource() { + _ = objectiveCMethods() + // Reads the export trie and the Swift metadata on its way. + _ = descriptorSymbols() + } + + /// Whether every source has been read; for tests. + var hasReadEverySource: Bool { + lock.lock() + defer { lock.unlock() } + return exportedNamesStorage != nil && objectiveCMethodsStorage != nil && swiftSourcesStorage != nil && descriptorSymbolsStorage != nil + } + + /// The memory the sources read so far and the Swift names rebuilt take; + /// see `ApproximateSize`. + var approximateByteCount: Int { + lock.lock() + defer { lock.unlock() } + return swiftNames.values.reduce(sourceByteCount + ApproximateSize.of(swiftNames)) { $0 + ($1.map(ApproximateSize.of) ?? 0) } + } + + // MARK: - Export trie + + /// What the export trie names, by address: functions in `__text`, and the + /// descriptors in `__TEXT,__const` whose symbols name Swift functions. A + /// shared cache image's symbol table may hold its local symbols alone + /// (SiriAppIntents' holds two entries; its export trie names 76,318 + /// functions), and an iOS device's cache redacts the local ones while the + /// export trie survives. + private func exportedNames() -> [UInt64: [String]] { + lock.lock() + defer { lock.unlock() } + if let exportedNamesStorage { return exportedNamesStorage } + var names: [UInt64: [String]] = [:] + var byteCount = 0 + for symbol in image.exportedSymbols { + guard let offset = symbol.offset else { continue } + names[address(atOffset: offset), default: []].append(symbol.name) + byteCount += ApproximateSize.of(symbol.name) + } + exportedNamesStorage = names + sourceByteCount += names.values.reduce(byteCount + ApproximateSize.of(names)) { $0 + ApproximateSize.of($1) } + return names + } + + // MARK: - Objective-C + + /// Every method implementation the image's own class and category lists + /// name. A shared cache attaches other images' category lists to a + /// class's list of lists; those are skipped, because the image that holds + /// them lists the same methods in its own `__objc_catlist`. + func objectiveCMethods() -> [UInt64: ObjectiveCMethod] { + lock.lock() + defer { lock.unlock() } + if let objectiveCMethodsStorage { return objectiveCMethodsStorage } + var methods: [UInt64: ObjectiveCMethod] = [:] + // A class's methods share its name's storage. + var stringByteCount = 0 + + func record(_ methodList: ObjCMethodList, in listImage: MachOImage, className: String, isClassMethod: Bool) { + guard !methodList.isListOfLists else { return } + for method in methodList.methods(in: listImage) where method.imp != 0 { + let address = unslidAddress(ofRuntime: method.imp) + guard textRange.contains(address), methods[address] == nil else { continue } + methods[address] = ObjectiveCMethod(className: className, selector: method.name, isClassMethod: isClassMethod) + stringByteCount += ApproximateSize.of(method.name) + } + } + + func ownLists(of readOnlyData: ObjCClassROData64, in owner: MachOImage) -> [(MachOImage, ObjCMethodList)] { + if let methodList = readOnlyData.methodList(in: owner) { return [(owner, methodList)] } + guard let listOfLists = readOnlyData.methodRelativeListList(in: owner) else { return [] } + return listOfLists.lists(in: owner).filter { $0.0.ptr == image.ptr } + } + + for classObject in image.objc.classes64 ?? [] { + guard let readOnlyData = ObjectiveCClassIndex.readOnlyData(of: classObject, in: image), + let className = readOnlyData.name(in: image) + else { continue } + stringByteCount += ApproximateSize.of(className) + for (listImage, methodList) in ownLists(of: readOnlyData, in: image) { + record(methodList, in: listImage, className: className, isClassMethod: false) + } + if let (metaImage, metaClass) = classObject.metaClass(in: image), + let metaReadOnlyData = ObjectiveCClassIndex.readOnlyData(of: metaClass, in: metaImage) { + for (listImage, methodList) in ownLists(of: metaReadOnlyData, in: metaImage) { + record(methodList, in: listImage, className: className, isClassMethod: true) + } + } + } + for category in (image.objc.categories64 ?? []) + (image.objc.categories2_64 ?? []) { + guard let className = category.className(in: image), !className.isEmpty else { continue } + stringByteCount += ApproximateSize.of(className) + if let methodList = category.instanceMethodList(in: image) { + record(methodList, in: image, className: className, isClassMethod: false) + } + if let methodList = category.classMethodList(in: image) { + record(methodList, in: image, className: className, isClassMethod: true) + } + } + objectiveCMethodsStorage = methods + sourceByteCount += stringByteCount + ApproximateSize.of(methods) + return methods + } + + // MARK: - Swift + + /// The Swift name of the function at `address`, rebuilt from the + /// metadata that points at it — remembered, since rebuilding a type's + /// name without its `Mn` symbol takes a demangle and a remangle. + func swiftName(at address: UInt64) -> String? { + guard let source = swiftSources()[address] else { return nil } + lock.lock() + if let known = swiftNames[address] { + lock.unlock() + return known + } + lock.unlock() + let name = buildSwiftName(from: source) + lock.lock() + defer { lock.unlock() } + swiftNames[address] = name + return name + } + + private func buildSwiftName(from source: SwiftSource) -> String? { + let descriptorSymbols = self.descriptorSymbols() + switch source { + case .typeFunction(let descriptor, let suffix): + let descriptorAddress = address(atOffset: descriptor.typeContextDescriptor.offset) + if let symbol = descriptorSymbols[descriptorAddress], let typeMangling = Self.mangling(ofSymbol: symbol, suffix: "Mn") { + return "$s" + typeMangling + suffix + } + guard let typeMangling = typeMangling(of: descriptor) else { return nil } + return "$s" + typeMangling + suffix + case .method(let descriptorAddress): + guard let symbol = descriptorSymbols[descriptorAddress], let methodMangling = Self.mangling(ofSymbol: symbol, suffix: "Tq") else { return nil } + return "$s" + methodMangling + } + } + + /// `_$s7SwiftUI4TextVMn` with suffix `Mn` → `7SwiftUI4TextV`. + private static func mangling(ofSymbol symbol: String, suffix: String) -> String? { + var mangling = Substring(symbol) + if mangling.hasPrefix("_") { mangling = mangling.dropFirst() } + guard mangling.hasPrefix("$s"), mangling.hasSuffix(suffix) else { return nil } + mangling = mangling.dropFirst(2).dropLast(suffix.count) + return mangling.isEmpty ? nil : String(mangling) + } + + /// A type's mangling built from its descriptor, for a type no `Mn` + /// symbol spells. + private func typeMangling(of descriptor: TypeContextDescriptorWrapper) -> String? { + guard let contextNode = try? SymbolicDemangler.demangleContext(for: descriptor.asContextDescriptorWrapper, in: image.context) else { return nil } + return try? mangleAsString(NodeBuilder(kind: .type, children: [contextNode]).node) + } + + /// Which functions the metadata names, by address: every type's + /// metadata accessor and singleton completion function, and every + /// vtable implementation. + private func swiftSources() -> [UInt64: SwiftSource] { + lock.lock() + defer { lock.unlock() } + if let swiftSourcesStorage { return swiftSourcesStorage } + var sources: [UInt64: SwiftSource] = [:] + let context = image.context + for wrapper in (try? image.swift.typeContextDescriptors) ?? [] { + let descriptorOffset = wrapper.typeContextDescriptor.offset + // Every type context descriptor holds its metadata accessor as a + // relative direct pointer at +12. + let accessorField = address(atOffset: descriptorOffset) &+ 12 + if let accessor = relativeTarget(ofFieldAt: accessorField), textRange.contains(accessor) { + sources[accessor] = .typeFunction(descriptor: wrapper, suffix: "Ma") + } + guard let typeWrapper = try? TypeContextWrapper.forTypeContextDescriptorWrapper(wrapper, in: context) else { continue } + var completionOffset: Int? + switch typeWrapper { + case .class(let classType): + completionOffset = classType.singletonMetadataInitialization?.resolvedDirectOffset(from: \.completionFunction) + for method in classType.methodDescriptors { + guard let implementationOffset = method.implementationOffset, + let implementation = codeAddress(ofImplementationAtOffset: implementationOffset), + sources[implementation] == nil + else { continue } + sources[implementation] = .method(descriptorAddress: address(atOffset: method.offset)) + } + case .struct(let structType): + completionOffset = structType.singletonMetadataInitialization?.resolvedDirectOffset(from: \.completionFunction) + case .enum(let enumType): + completionOffset = enumType.singletonMetadataInitialization?.resolvedDirectOffset(from: \.completionFunction) + } + if let completionOffset { + let completion = address(atOffset: completionOffset) + if textRange.contains(completion) { + sources[completion] = .typeFunction(descriptor: wrapper, suffix: "Mr") + } + } + } + swiftSourcesStorage = sources + sourceByteCount += ApproximateSize.of(sources) + return sources + } + + /// An implementation's code: the offset itself when it lies in `__text`, + /// or — for an async function — the function an async function pointer + /// record (`{ rel32 function, u32 context size }`) leads to. + private func codeAddress(ofImplementationAtOffset offset: Int) -> UInt64? { + let implementation = address(atOffset: offset) + if textRange.contains(implementation) { return implementation } + guard let followed = relativeTarget(ofFieldAt: implementation), textRange.contains(followed) else { return nil } + return followed + } + + /// The target of a 32-bit relative pointer stored at the unslid `field`, + /// or `nil` when it is zero. + private func relativeTarget(ofFieldAt field: UInt64) -> UInt64? { + guard let pointer = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(field)) &+ slide) else { return nil } + let relative = pointer.loadUnaligned(as: Int32.self) + guard relative != 0 else { return nil } + return UInt64(bitPattern: Int64(bitPattern: field) &+ Int64(relative)) + } + + /// The `Mn` and `Tq` symbols at the descriptors the Swift sources name, + /// from the symbol table and the export trie. + private func descriptorSymbols() -> [UInt64: String] { + let sources = swiftSources() + let exportedNames = self.exportedNames() + lock.lock() + defer { lock.unlock() } + if let descriptorSymbolsStorage { return descriptorSymbolsStorage } + var wanted = Set() + for source in sources.values { + switch source { + case .typeFunction(let descriptor, _): + wanted.insert(address(atOffset: descriptor.typeContextDescriptor.offset)) + case .method(let descriptorAddress): + wanted.insert(descriptorAddress) + } + } + var symbols: [UInt64: String] = [:] + // The names the export trie gives share their storage with it. + var stringByteCount = 0 + func consider(_ name: String, at address: UInt64) -> Bool { + guard symbols[address] == nil, name.hasSuffix("Mn") || name.hasSuffix("Tq") else { return false } + symbols[address] = name + return true + } + if let symbolTable = image.symbols64 { + for symbolIndex in 0 ..< symbolTable.numberOfSymbols { + let entry = symbolTable.symbols[symbolIndex] + // Defined in a section, not a debugging entry. + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E, wanted.contains(entry.n_value) else { continue } + let name = String(cString: symbolTable.stringBase.advanced(by: Int(entry.n_un.n_strx))) + if consider(name, at: entry.n_value) { stringByteCount += ApproximateSize.of(name) } + } + } + for address in wanted { + for name in exportedNames[address] ?? [] { _ = consider(name, at: address) } + } + descriptorSymbolsStorage = symbols + sourceByteCount += stringByteCount + ApproximateSize.of(symbols) + return symbols + } + + private func unslidAddress(ofRuntime runtimeAddress: UInt64) -> UInt64 { + // Strip the pointer-authentication bits; user addresses fit in 47. + let address = runtimeAddress & 0x0000_7FFF_FFFF_FFFF + return UInt64(bitPattern: Int64(bitPattern: address) &- Int64(slide)) + } +} + +extension ImageFallbackNames { + /// The unslid address `offset` bytes from the Mach header. Offsets may be + /// negative: in a shared cache, an export or an implementation can lie + /// below the image's own header. + fileprivate func address(atOffset offset: Int) -> UInt64 { + UInt64(bitPattern: Int64(bitPattern: headerAddress) &+ Int64(offset)) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFunctionTable.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFunctionTable.swift new file mode 100644 index 000000000..600ae3afb --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFunctionTable.swift @@ -0,0 +1,305 @@ +import Foundation +import MachOKit + +/// One image's functions and the sections a scan reads, collected in one pass +/// over its load commands and symbol table. +/// +/// Symbol and selector names are kept as pointers into the image's mapped +/// `__LINKEDIT` and the cache's selector strings, which stay valid for the +/// life of the process; that is what makes the unchecked `Sendable` sound. +final class ImageFunctionTable: @unchecked Sendable { + /// One entry of the image's `__stubs` / `__auth_stubs`. + struct SymbolStub { + /// The GOT slot the stub loads its target from, unslid. + let slotAddress: UInt64? + /// The imported symbol its indirect symbol entry names. + let name: UnsafePointer? + } + + let imageIndex: Int + let image: MachOImage + /// What to add to an unslid address to reach memory. + let slide: Int + let textStart: UInt64 + let textEnd: UInt64 + /// Every function start, sorted: `LC_FUNCTION_STARTS` and the symbols in + /// `__text`. + let starts: [UInt64] + /// For each start, the index of its primary name in `primaryNames`, or -1. + let primaryNameIndices: [Int32] + let primaryNames: [UnsafePointer] + /// The other names at an address, left by identical code folding. + let foldedNames: [UInt64: [UnsafePointer]] + let runtimeHelperStarts: Set + let objectiveCStubRange: Range? + let objectiveCStubSelectors: [UInt64: UnsafePointer] + let symbolStubRanges: [Range] + let symbolStubs: [UInt64: SymbolStub] + let selectorReferenceRange: Range? + /// The sections whose slots may hold a reference to a class or a Swift + /// type: `__got`, `__auth_got`, `__objc_classrefs`. Other slots that point + /// at a class — a constant string's `isa` — are no reference to it. + let referenceSlotRanges: [Range] + /// `__objc_superrefs`: the class a super send in one of its methods starts + /// above. + let superclassReferenceRange: Range? + /// The image's segments other than `__TEXT` and `__LINKEDIT`, unslid: where + /// its own class objects lie. + let dataSegmentRanges: [Range] + /// Every segment of the image, unslid. + let segmentRanges: [Range] + let dataInCodeRanges: [Range] + /// The unslid address of the Mach header — `__TEXT`'s vmaddr. + let headerAddress: UInt64 + + private let fallbackNamesLock = NSLock() + private var fallbackNamesStorage: ImageFallbackNames? + + init(imageIndex: Int, image: MachOImage) { + self.imageIndex = imageIndex + self.image = image + let slide = image.vmaddrSlide ?? 0 + self.slide = slide + let headerAddress = image.segments64.first { $0.segmentName == "__TEXT" }.map { UInt64($0.layout.vmaddr) } ?? 0 + self.headerAddress = headerAddress + + var textStart: UInt64 = 0 + var textEnd: UInt64 = 0 + var textSectionOrdinal = 0 + var objectiveCStubRange: Range? + var objectiveCStubSelectors: [UInt64: UnsafePointer] = [:] + var symbolStubRanges: [Range] = [] + var symbolStubs: [UInt64: SymbolStub] = [:] + var selectorReferenceRange: Range? + var referenceSlotRanges: [Range] = [] + var superclassReferenceRange: Range? + let symbols = image.symbols64 + let indirectSymbols = image.indirectSymbols.map { Array($0) } ?? [] + + var ordinal = 0 + for section in image.sections64 { + ordinal += 1 + let sectionStart = UInt64(section.address) + let sectionRange = sectionStart ..< sectionStart + UInt64(section.size) + let sectionName = section.sectionName + if section.segmentName == "__TEXT", sectionName == "__text" { + textStart = sectionRange.lowerBound + textEnd = sectionRange.upperBound + textSectionOrdinal = ordinal + } else if sectionName == "__objc_stubs", !sectionRange.isEmpty, let stubs = section.objcStubs(in: image) { + objectiveCStubRange = sectionRange + for objectiveCStub in stubs { + guard let selectorReference = objectiveCStub.selectorReference, + let selector = Self.selectorString(inSlotAt: selectorReference, slide: slide) + else { continue } + objectiveCStubSelectors[objectiveCStub.stub.address] = selector + } + } else if section.flags.type == .symbol_stubs, !sectionRange.isEmpty, let stubs = section.stubs(in: image) { + symbolStubRanges.append(sectionRange) + for stub in stubs { + var slotAddress: UInt64? + if case .viaSlot(let address) = stub.branch { slotAddress = address } + var name: UnsafePointer? + if let indirectIndex = stub.indirectSymbolIndex, indirectIndex < indirectSymbols.count, + let symbolIndex = indirectSymbols[indirectIndex].index, + let symbols, symbolIndex < symbols.numberOfSymbols { + name = symbols.stringBase.advanced(by: Int(symbols.symbols[symbolIndex].n_un.n_strx)) + } + symbolStubs[stub.address] = SymbolStub(slotAddress: slotAddress, name: name) + } + } else if sectionName == "__objc_selrefs", !sectionRange.isEmpty { + selectorReferenceRange = sectionRange + } else if sectionName == "__objc_superrefs", !sectionRange.isEmpty { + superclassReferenceRange = sectionRange + } else if !sectionRange.isEmpty, ["__got", "__auth_got", "__objc_classrefs"].contains(sectionName) { + referenceSlotRanges.append(sectionRange) + } + } + self.textStart = textStart + self.textEnd = textEnd + self.objectiveCStubRange = objectiveCStubRange + self.objectiveCStubSelectors = objectiveCStubSelectors + self.symbolStubRanges = symbolStubRanges + self.symbolStubs = symbolStubs + self.selectorReferenceRange = selectorReferenceRange + self.referenceSlotRanges = referenceSlotRanges + self.superclassReferenceRange = superclassReferenceRange + var dataSegmentRanges: [Range] = [] + var segmentRanges: [Range] = [] + for segment in image.segments64 where segment.layout.vmsize > 0 && segment.segmentName != "__PAGEZERO" { + let range = UInt64(segment.layout.vmaddr) ..< UInt64(segment.layout.vmaddr) + UInt64(segment.layout.vmsize) + segmentRanges.append(range) + if segment.segmentName != "__TEXT", segment.segmentName != "__LINKEDIT" { dataSegmentRanges.append(range) } + } + self.dataSegmentRanges = dataSegmentRanges + self.segmentRanges = segmentRanges + + // Symbols in __text, external ones first at each address. + var namedAddresses: [(address: UInt64, isExternal: Bool, name: UnsafePointer?)] = [] + if let symbols, textSectionOrdinal > 0 { + namedAddresses.reserveCapacity(symbols.numberOfSymbols / 2) + for symbolIndex in 0 ..< symbols.numberOfSymbols { + let entry = symbols.symbols[symbolIndex] + // Not a debugging entry, defined in a section, and that section is __text. + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E, Int(entry.n_sect) == textSectionOrdinal else { continue } + let name = symbols.stringBase.advanced(by: Int(entry.n_un.n_strx)) + let isRedacted = strcmp(name, "") == 0 + namedAddresses.append((entry.n_value, entry.n_type & 0x01 != 0, isRedacted ? nil : name)) + } + } + namedAddresses.sort { lhs, rhs in + lhs.address != rhs.address ? lhs.address < rhs.address : (lhs.isExternal && !rhs.isExternal) + } + + var functionStarts: [UInt64] = [] + if let starts = image.functionStarts { + // `MachOImage.FunctionStarts` seeds its running offset with + // __TEXT's vmaddr, so `offset` is already the unslid address, + // whatever its documentation says. The trailing padding of the + // encoding repeats the last start. + for functionStart in starts { + let address = UInt64(functionStart.offset) + if address >= textStart, address < textEnd, functionStarts.last != address { functionStarts.append(address) } + } + functionStarts.sort() + } + + var mergedStarts: [UInt64] = [] + var primaryNameIndices: [Int32] = [] + var primaryNames: [UnsafePointer] = [] + var foldedNames: [UInt64: [UnsafePointer]] = [:] + var runtimeHelperStarts = Set() + mergedStarts.reserveCapacity(max(functionStarts.count, namedAddresses.count)) + primaryNameIndices.reserveCapacity(mergedStarts.capacity) + + var namedCursor = 0 + var startCursor = 0 + while namedCursor < namedAddresses.count || startCursor < functionStarts.count { + let namedAddress = namedCursor < namedAddresses.count ? namedAddresses[namedCursor].address : .max + let startAddress = startCursor < functionStarts.count ? functionStarts[startCursor] : .max + let address = min(namedAddress, startAddress) + if startAddress == address { startCursor += 1 } + var names: [UnsafePointer] = [] + while namedCursor < namedAddresses.count, namedAddresses[namedCursor].address == address { + if let name = namedAddresses[namedCursor].name { names.append(name) } + namedCursor += 1 + } + mergedStarts.append(address) + if let primaryName = names.first { + primaryNameIndices.append(Int32(primaryNames.count)) + primaryNames.append(primaryName) + if names.count > 1 { foldedNames[address] = Array(names.dropFirst()) } + if names.contains(where: { RuntimeHelperNames.isRuntimeHelper($0) }) { runtimeHelperStarts.insert(address) } + } else { + primaryNameIndices.append(-1) + } + } + self.starts = mergedStarts + self.primaryNameIndices = primaryNameIndices + self.primaryNames = primaryNames + self.foldedNames = foldedNames + self.runtimeHelperStarts = runtimeHelperStarts + + var dataInCodeRanges: [Range] = [] + if let entries = image.dataInCode { + for entry in entries { + let start = headerAddress + UInt64(entry.layout.offset) + dataInCodeRanges.append(start ..< start + UInt64(entry.layout.length)) + } + dataInCodeRanges.sort { $0.lowerBound < $1.lowerBound } + } + self.dataInCodeRanges = dataInCodeRanges + } + + /// The selector string a selector reference slot points at, read from + /// memory — the cache builder and dyld have already bound it. + static func selectorString(inSlotAt slotAddress: UInt64, slide: Int) -> UnsafePointer? { + guard let slot = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(slotAddress)) &+ slide) else { return nil } + let value = slot.loadUnaligned(as: UInt64.self) & 0x0000_7FFF_FFFF_FFFF + return UnsafePointer(bitPattern: UInt(value)) + } + + /// The index in `starts` of the function containing `address`. + func functionIndex(containing address: UInt64) -> Int? { + guard address >= textStart, address < textEnd, let first = starts.first, address >= first else { return nil } + var lower = 0 + var upper = starts.count + while lower < upper { + let middle = (lower + upper) / 2 + if starts[middle] <= address { lower = middle + 1 } else { upper = middle } + } + return lower - 1 + } + + func end(ofFunctionAt index: Int) -> UInt64 { + index + 1 < starts.count ? starts[index + 1] : textEnd + } + + func primaryName(ofFunctionAt index: Int) -> UnsafePointer? { + let nameIndex = primaryNameIndices[index] + return nameIndex < 0 ? nil : primaryNames[Int(nameIndex)] + } + + /// Whether the function at `index` is an Objective-C method, whose `x0` + /// on entry is its receiver. + func isObjectiveCMethod(at index: Int) -> Bool { + guard let name = primaryName(ofFunctionAt: index) else { return false } + return (name[0] == 0x2D || name[0] == 0x2B) && name[1] == 0x5B + } + + /// The memory holding the instruction at the unslid `address`. + func instructionPointer(at address: UInt64) -> UnsafePointer { + UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(address)) &+ slide)!.assumingMemoryBound(to: UInt32.self) + } + + func isInDataInCode(_ address: UInt64) -> Bool { + guard !dataInCodeRanges.isEmpty else { return false } + return dataInCodeRanges.contains { $0.contains(address) } + } + + func codeFunction(at index: Int) -> CodeFunction { + let start = starts[index] + var name: CodeFunction.Name? = primaryName(ofFunctionAt: index).map { .symbol(String(cString: $0)) } + var foldedSymbolNames = foldedNames[start]?.map { String(cString: $0) } ?? [] + if name == nil, let fallback = fallbackNames.name(at: start) { + name = fallback.name + foldedSymbolNames = fallback.foldedSymbolNames + } + return CodeFunction( + location: CodeLocation(imageIndex: imageIndex, address: start), + size: Int(end(ofFunctionAt: index) - start), + name: name, + foldedSymbolNames: foldedSymbolNames, + isRuntimeHelper: runtimeHelperStarts.contains(start) + ) + } + + /// The names the symbol table does not give, read on first use: naming a + /// function needs them, scanning never does. + var fallbackNames: ImageFallbackNames { + fallbackNamesLock.lock() + defer { fallbackNamesLock.unlock() } + if let fallbackNamesStorage { return fallbackNamesStorage } + let fallbackNames = ImageFallbackNames(image: image, headerAddress: headerAddress, slide: slide, textRange: textStart ..< textEnd) + fallbackNamesStorage = fallbackNames + return fallbackNames + } + + /// The fallback names, when something has asked for them. + var existingFallbackNames: ImageFallbackNames? { + fallbackNamesLock.lock() + defer { fallbackNamesLock.unlock() } + return fallbackNamesStorage + } + + /// The memory the table takes, with the fallback names read for it; see + /// `ApproximateSize`. The names it points at belong to the image. + var approximateByteCount: Int { + var byteCount = ApproximateSize.of(starts) + ApproximateSize.of(primaryNameIndices) + ApproximateSize.of(primaryNames) + byteCount += foldedNames.values.reduce(ApproximateSize.of(foldedNames)) { $0 + ApproximateSize.of($1) } + byteCount += ApproximateSize.of(runtimeHelperStarts) + ApproximateSize.of(objectiveCStubSelectors) + ApproximateSize.of(symbolStubs) + byteCount += ApproximateSize.of(symbolStubRanges) + ApproximateSize.of(referenceSlotRanges) + ApproximateSize.of(dataSegmentRanges) + byteCount += ApproximateSize.of(segmentRanges) + ApproximateSize.of(dataInCodeRanges) + return byteCount + (existingFallbackNames?.approximateByteCount ?? 0) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/ObjectiveCClassIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ObjectiveCClassIndex.swift new file mode 100644 index 000000000..e98169cd7 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ObjectiveCClassIndex.swift @@ -0,0 +1,165 @@ +import Foundation +import MachOKit +@_spi(Core) import MachOObjCSection + +/// A class object a scan met: its class's runtime name, and where the class +/// lies. A metaclass is met as its class. +struct ObjectiveCClassObject: Hashable { + let name: String + let location: CodeLocation +} + +/// The class objects one image defines, by address: every class of its +/// `__objc_classlist` and its metaclass. +/// +/// How a scan tells a class reference from any other pointer. A class object +/// cannot be recognized by the section it lies in — 92,000 Swift classes and +/// metaclasses of the macOS 27.2 cache sit in `__data`, not `__objc_data` — +/// so a value counts as a class only when its image lists it. Built per image +/// on first use, straight from the class list: going through +/// `MachOImage.objc.classes64` looks up the image's load commands again for +/// every class, which made a scan of the whole cache twice as slow. A +/// class's name is read only once a reference to it is reported. +final class ObjectiveCClassIndex: @unchecked Sendable { + private struct Entry { + /// The class's own runtime address; a metaclass's entry holds its + /// class's. + let classAddress: UInt + let isMetaclass: Bool + } + + /// User-space addresses fit in 47 bits; above them are pointer + /// authentication bits. + private static let addressMask: UInt64 = 0x0000_7FFF_FFFF_FFFF + + private let image: MachOImage + private let imageIndex: Int + private let slide: Int + private let entriesByRuntimeAddress: [UInt: Entry] + private let lock = NSLock() + private var namesByClassAddress: [UInt: String?] = [:] + + init(image: MachOImage, imageIndex: Int) { + self.image = image + self.imageIndex = imageIndex + self.slide = image.vmaddrSlide ?? 0 + var entries: [UInt: Entry] = [:] + for section in image.sections64 where section.sectionName == "__objc_classlist" { + guard let list = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(section.address)) &+ slide) else { continue } + for position in 0 ..< section.size / 8 { + let classAddress = UInt(list.loadUnaligned(fromByteOffset: position * 8, as: UInt64.self) & Self.addressMask) + guard let classObject = UnsafeRawPointer(bitPattern: classAddress) else { continue } + entries[classAddress] = Entry(classAddress: classAddress, isMetaclass: false) + // A class's `isa` is its metaclass. + let metaclassAddress = UInt(classObject.loadUnaligned(as: UInt64.self) & Self.addressMask) + if metaclassAddress != 0, entries[metaclassAddress] == nil { + entries[metaclassAddress] = Entry(classAddress: classAddress, isMetaclass: true) + } + } + } + self.entriesByRuntimeAddress = entries + } + + /// The class object at the runtime `address`, a metaclass as its class. + func classObject(atRuntimeAddress address: UInt) -> ObjectiveCClassObject? { + guard let entry = entriesByRuntimeAddress[address], let name = name(ofClassAt: entry.classAddress) else { return nil } + return ObjectiveCClassObject(name: name, location: location(ofRuntimeAddress: entry.classAddress)) + } + + /// Where the classes named `name` lie; reads every class's name once. + func classLocations(named name: String) -> [CodeLocation] { + entriesByRuntimeAddress.compactMap { address, entry in + !entry.isMetaclass && self.name(ofClassAt: address) == name ? location(ofRuntimeAddress: address) : nil + } + } + + /// Reads every class's name now, which the first ``classLocations(named:)`` + /// would. + func readEveryName() { + for (address, entry) in entriesByRuntimeAddress where !entry.isMetaclass { + _ = name(ofClassAt: address) + } + } + + /// Whether every class's name has been read; for tests. + var hasReadEveryName: Bool { + let classCount = entriesByRuntimeAddress.values.count { !$0.isMetaclass } + lock.lock() + defer { lock.unlock() } + return namesByClassAddress.count >= classCount + } + + /// The memory the index takes, with the names read; see `ApproximateSize`. + var approximateByteCount: Int { + lock.lock() + defer { lock.unlock() } + return namesByClassAddress.values.reduce(ApproximateSize.of(entriesByRuntimeAddress) + ApproximateSize.of(namesByClassAddress)) { $0 + ($1.map(ApproximateSize.of) ?? 0) } + } + + /// The unslid addresses of the class at `classLocation` and of its + /// metaclass. + func objectAddresses(ofClassAt classLocation: CodeLocation) -> [UInt64] { + let classAddress = UInt(bitPattern: Int(bitPattern: UInt(classLocation.address)) &+ slide) + return entriesByRuntimeAddress.compactMap { address, entry in + entry.classAddress == classAddress ? location(ofRuntimeAddress: address).address : nil + } + } + + /// Whether the class at `classLocation` is a Swift class: one of the two + /// low bits of its data word (+0x20) is set. + func isSwiftClass(at classLocation: CodeLocation) -> Bool { + let classAddress = UInt(bitPattern: Int(bitPattern: UInt(classLocation.address)) &+ slide) + guard entriesByRuntimeAddress[classAddress] != nil, let classObject = UnsafeRawPointer(bitPattern: classAddress) else { return false } + return classObject.loadUnaligned(fromByteOffset: 0x20, as: UInt64.self) & 0x3 != 0 + } + + /// The Swift class whose type context descriptor lies at the runtime + /// `descriptor`: a Swift class object holds its descriptor at +0x40, and + /// sets one of the two low bits of its data word (+0x20). + func swiftClassObject(describedBy descriptor: UInt) -> ObjectiveCClassObject? { + for (address, entry) in entriesByRuntimeAddress where !entry.isMetaclass { + guard let classObject = UnsafeRawPointer(bitPattern: address), + classObject.loadUnaligned(fromByteOffset: 0x20, as: UInt64.self) & 0x3 != 0, + UInt(classObject.loadUnaligned(fromByteOffset: 0x40, as: UInt64.self) & Self.addressMask) == descriptor, + let name = name(ofClassAt: address) + else { continue } + return ObjectiveCClassObject(name: name, location: location(ofRuntimeAddress: address)) + } + return nil + } + + private func location(ofRuntimeAddress address: UInt) -> CodeLocation { + CodeLocation(imageIndex: imageIndex, address: UInt64(bitPattern: Int64(bitPattern: UInt64(address)) &- Int64(slide))) + } + + private func name(ofClassAt classAddress: UInt) -> String? { + lock.lock() + if let known = namesByClassAddress[classAddress] { + lock.unlock() + return known + } + lock.unlock() + var name: String? + if let pointer = UnsafeRawPointer(bitPattern: classAddress) { + let classObject = ObjCClass64( + layout: pointer.assumingMemoryBound(to: ObjCClass64.Layout.self).pointee, + offset: Int(bitPattern: classAddress &- UInt(bitPattern: image.ptr)) + ) + name = Self.readOnlyData(of: classObject, in: image)?.name(in: image) + } + lock.lock() + namesByClassAddress[classAddress] = name + lock.unlock() + return name + } + + /// A class's read-only data, through its read-write data once the + /// runtime has realized it — as for every class an image loaded in this + /// process has used. + static func readOnlyData(of classObject: ObjCClass64, in image: MachOImage) -> ObjCClassROData64? { + if let readOnlyData = classObject.classROData(in: image) { return readOnlyData } + guard let readWriteData = classObject.classRWData(in: image) else { return nil } + if let readOnlyData = readWriteData.classROData(in: image) { return readOnlyData } + return readWriteData.ext(in: image)?.classROData(in: image) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/ReferenceScanner.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ReferenceScanner.swift new file mode 100644 index 000000000..97298caeb --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/ReferenceScanner.swift @@ -0,0 +1,808 @@ +import Foundation +import MachOKit +import ARM64InstructionDecoding + +/// Decodes the functions of one image into ``CodeReference``s. +/// +/// Only the instructions that call, branch out, or build an address are +/// decoded; every other instruction merely forgets what its destination +/// register held. Register tracking records only what is certain — an +/// address `adrp` / `add` built, a slot that address was loaded from, the +/// receiver an Objective-C method arrived with, a pointer-authentication +/// constant — and nothing is guessed. +/// +/// A scanner memoizes how each call target resolves, so one scanner should +/// serve a whole image. +struct ReferenceScanner { + private let analyzer: CrossReferenceAnalyzer + private let table: ImageFunctionTable + /// When set, only references filed under one of these keys are kept. + private let keptKeys: Set? + /// Whether register state follows the branches inside a function: a + /// forward branch carries what the registers hold to its target, an + /// instruction after an unconditional transfer starts from what the + /// branches to it carried, and a loop header forgets the caller-saved + /// registers. Off, the scan reads straight down, as the first batch did — + /// only to measure what following them changes. + let followsBranches: Bool + private let registers = RegisterFile() + /// The current function's forward branch targets not yet reached, + /// ascending from `pendingCursor`, and the state the branches to each + /// carried, met over every branch to the same target. Sorted lists with a + /// cursor rather than hash tables: the scan only moves forward, so each + /// instruction compares against one entry. + private var pendingTargets: [UInt64] = [] + private var pendingSnapshots: [RegisterFile.Snapshot] = [] + private var pendingCursor = 0 + /// The targets of the current function's backward branches, ascending. + private var loopHeaders: [UInt64] = [] + private var loopHeaderCursor = 0 + private var resolvedTargets: [UInt64: ResolvedTarget] = [:] + private var selectorNames: [UInt: String] = [:] + private var importedNames: [UInt: String] = [:] + /// Whether the call being decoded is to a function that returns the class + /// it was handed (`objc_opt_self` …), so `x0` survives it. + private var callReturnsArgument = false + /// The function being scanned, and the class its last load from + /// `__objc_superrefs` yielded: a super send in it starts above that class. + private var currentFunctionIndex = 0 + private var superclassReferenceClassName: String? + /// What the call being decoded stands for besides the call itself: a + /// metadata accessor, a mangled-name instantiation. + private var calledTypeFunction: TypeFunction? + /// What each slot and address holds, remembered: an image loads the same + /// few hundred classes and types again and again. + private var slotReferences: [UInt64: AddressReference?] = [:] + private var addressReferences: [UInt64: AddressReference?] = [:] + /// The class and type indexes this scan asked for, kept here so that a + /// lookup does not contend for the analyzer's lock — a whole-cache scan + /// spent most of its time waiting on it. A reference, so that resolving + /// a call target, which does not mutate the scanner, uses it too. + private let indexes: ScanIndexes + /// When set, the references to one Swift type are kept besides the + /// ones `keptKeys` names. + private let swiftTypeQuery: SwiftTypeQuery? + /// Whether the scan looks for class and type references at all. A query + /// for the callers of a selector or a function keeps none, and skipping + /// them keeps it as fast as before they existed; a send's class-literal + /// receiver is still told, at the send. + private let findsTypeReferences: Bool + + /// How many stubs and islands are followed from one call before giving + /// up; a hop per subcache crossed is the worst case described. + private static let maximumTrampolineHops = 8 + + init(analyzer: CrossReferenceAnalyzer, table: ImageFunctionTable, keeping keptKeys: Set? = nil, matching swiftTypeQuery: SwiftTypeQuery? = nil, followsBranches: Bool = true) { + self.analyzer = analyzer + self.table = table + self.keptKeys = keptKeys ?? (swiftTypeQuery == nil ? nil : []) + self.swiftTypeQuery = swiftTypeQuery + self.followsBranches = followsBranches + self.indexes = ScanIndexes(analyzer: analyzer) + self.findsTypeReferences = swiftTypeQuery != nil || keptKeys.map { keys in + keys.contains { key in + switch key { + case .objectiveCClass, .swiftTypeDescriptor: return true + case .function, .selector, .importedSymbol: return false + } + } + } ?? true + } + + /// Takes the reference ready-made: a reference built in the call's + /// argument list would mutate the scanner while this non-mutating call + /// holds it, and Swift copies the whole scanner — its memo dictionaries + /// included — to keep the two apart, which made a scan of the cache + /// forty times slower. + private func keep(_ reference: CodeReference, in references: inout [CodeReference]) { + if let keptKeys { + let isFiled = reference.target.tableKey.map(keptKeys.contains) ?? false + guard isFiled || swiftTypeQuery?.matches(reference.target) == true else { return } + } + references.append(reference) + } + + // MARK: - Scanning + + mutating func scanFunction(at index: Int, into references: inout [CodeReference]) { + let start = table.starts[index] + let end = table.end(ofFunctionAt: index) + guard end > start else { return } + let function = CodeLocation(imageIndex: table.imageIndex, address: start) + let words = table.instructionPointer(at: start) + let instructionCount = Int((end - start) / 4) + let isObjectiveCMethod = table.isObjectiveCMethod(at: index) + + registers.reset() + if isObjectiveCMethod { registers.setMethodReceiver(0) } + currentFunctionIndex = index + superclassReferenceClassName = nil + + pendingTargets.removeAll(keepingCapacity: true) + pendingSnapshots.removeAll(keepingCapacity: true) + pendingCursor = 0 + loopHeaders.removeAll(keepingCapacity: true) + loopHeaderCursor = 0 + if followsBranches { findLoopHeaders(start: start, end: end, words: words, instructionCount: instructionCount) } + + var previousInstructionTransfers = false + for instructionIndex in 0 ..< instructionCount { + let pc = start &+ UInt64(instructionIndex * 4) + if table.isInDataInCode(pc) { continue } + let word = UInt32(littleEndian: words[instructionIndex]) + if followsBranches { enter(pc, afterTransfer: previousInstructionTransfers) } + previousInstructionTransfers = false + + if let target = ARM64InstructionWord.callTarget(word, at: pc) { + callReturnsArgument = false + let callReference = reference(to: target, at: pc, in: function, kind: .call, isObjectiveCMethod: isObjectiveCMethod) + keep(callReference, in: &references) + if let typeReference = typeReferenceOfCalledFunction(at: pc, in: function) { keep(typeReference, in: &references) } + if callReturnsArgument { + registers.clobberCallerSavedRegisters(keeping: 0) + } else { + registers.clobberCallerSavedRegisters() + } + } else if let target = ARM64InstructionWord.branchTarget(word, at: pc) { + previousInstructionTransfers = true + if target < start || target >= end { + let tailCallReference = reference(to: target, at: pc, in: function, kind: .tailCall, isObjectiveCMethod: isObjectiveCMethod) + keep(tailCallReference, in: &references) + if let typeReference = typeReferenceOfCalledFunction(at: pc, in: function) { keep(typeReference, in: &references) } + } else if target > pc { + carry(to: target) + } + } else if let materialization = ARM64InstructionWord.addressMaterialization(word, at: pc) { + registers.setAddress(materialization.address, of: materialization.destination) + } else if let arithmetic = ARM64InstructionWord.addImmediate(word) { + registers.add(arithmetic.addend, to: arithmetic.source, into: arithmetic.destination) + if findsTypeReferences, let address = registers.builtAddress(of: arithmetic.destination), let addressReference = addressReference(atAddress: address) { + let typeReference = reference(to: addressReference, at: pc, in: function) + keep(typeReference, in: &references) + } + } else if let load = ARM64InstructionWord.load(word) { + let slot = registers.builtAddress(of: load.base).map { ARM64InstructionWord.adding(load.displacement, to: $0) } + registers.load(into: load.destination, base: load.base, displacement: load.displacement, writesBack: load.writesBack) + if load.destination != 31, let slot { + if let range = table.superclassReferenceRange, range.contains(slot) { + superclassReferenceClassName = classObject(storedAt: runtimeAddress(ofUnslid: slot, slide: table.slide))?.name + } else if findsTypeReferences, let slotReference = slotReference(fromSlot: slot) { + let typeReference = reference(to: slotReference, at: pc, in: function) + keep(typeReference, in: &references) + } + } + } else if let move = ARM64InstructionWord.moveRegister(word) { + registers.copy(move.source, to: move.destination) + } else if let wide = ARM64InstructionWord.moveWide(word) { + registers.moveWide(into: wide.destination, immediate: wide.immediate, shift: wide.shift, keepsOtherBits: wide.keepsOtherBits) + } else if let branch = ARM64InstructionWord.registerBranch(word) { + if branch.isCall { + let indirectCall = indirectReference(through: branch, at: pc, in: function, kind: .call) + keep(indirectCall, in: &references) + registers.clobberCallerSavedRegisters() + } else { + previousInstructionTransfers = true + // A computed `br` is a jump table; a pointer loaded from + // memory, or an authenticated one, is a tail call. + if branch.isAuthenticated || registers.wasLoadedFromMemory(branch.target) { + let indirectTailCall = indirectReference(through: branch, at: pc, in: function, kind: .tailCall) + keep(indirectTailCall, in: &references) + } + } + } else if let target = ARM64InstructionWord.conditionalBranchTarget(word, at: pc) { + if target < start || target >= end { + let tailCallReference = reference(to: target, at: pc, in: function, kind: .tailCall, isObjectiveCMethod: isObjectiveCMethod) + keep(tailCallReference, in: &references) + if let typeReference = typeReferenceOfCalledFunction(at: pc, in: function) { keep(typeReference, in: &references) } + } else if target > pc { + carry(to: target) + } + } else if ARM64InstructionWord.isReturn(word) { + previousInstructionTransfers = true + } else { + registers.forgetRegistersWritten(by: word) + } + } + } + + // MARK: - Branches + + /// The targets of the function's backward branches: what reaches them + /// from below is not known when the scan gets there. + private mutating func findLoopHeaders(start: UInt64, end: UInt64, words: UnsafePointer, instructionCount: Int) { + for instructionIndex in 0 ..< instructionCount { + let pc = start &+ UInt64(instructionIndex * 4) + let word = UInt32(littleEndian: words[instructionIndex]) + guard let target = ARM64InstructionWord.branchTarget(word, at: pc) ?? ARM64InstructionWord.conditionalBranchTarget(word, at: pc), + target >= start, target <= pc + else { continue } + loopHeaders.append(target) + } + loopHeaders.sort() + } + + /// Carries what the registers hold to a forward branch's target. + private mutating func carry(to target: UInt64) { + let snapshot = registers.snapshot() + var lower = pendingCursor + var upper = pendingTargets.count + while lower < upper { + let middle = (lower + upper) / 2 + if pendingTargets[middle] < target { lower = middle + 1 } else { upper = middle } + } + if lower < pendingTargets.count, pendingTargets[lower] == target { + pendingSnapshots[lower].meet(snapshot) + } else { + pendingTargets.insert(target, at: lower) + pendingSnapshots.insert(snapshot, at: lower) + } + } + + /// Sets the registers up for the instruction at `pc` from the paths that + /// reach it: the branches that carried state here, falling through unless + /// the instruction before was an unconditional transfer, and nothing + /// known about a loop's back edge. An instruction after a transfer that + /// no branch here targets is reached some way the scan does not see — a + /// jump table — so the caller-saved registers are unknown there. + private mutating func enter(_ pc: UInt64, afterTransfer: Bool) { + // Targets the scan stepped over (data in code) are dropped. + while pendingCursor < pendingTargets.count, pendingTargets[pendingCursor] < pc { pendingCursor += 1 } + if pendingCursor < pendingTargets.count, pendingTargets[pendingCursor] == pc { + if afterTransfer { + registers.restore(pendingSnapshots[pendingCursor]) + } else { + registers.meet(pendingSnapshots[pendingCursor]) + } + pendingCursor += 1 + } else if afterTransfer { + registers.clobberCallerSavedRegisters() + } + while loopHeaderCursor < loopHeaders.count, loopHeaders[loopHeaderCursor] < pc { loopHeaderCursor += 1 } + if loopHeaderCursor < loopHeaders.count, loopHeaders[loopHeaderCursor] == pc { + registers.clobberCallerSavedRegisters() + } + } + + // MARK: - References + + private mutating func reference(to target: UInt64, at pc: UInt64, in function: CodeLocation, kind: CodeReference.Kind, isObjectiveCMethod: Bool) -> CodeReference { + let referenceTarget: CodeReferenceTarget + var isRuntimeHelperCall = false + calledTypeFunction = nil + switch resolve(target) { + case .selector(let selector): + referenceTarget = .messageSend(selector: selectorName(selector), receiver: receiverHint(isObjectiveCMethod: isObjectiveCMethod)) + case .function(let functionTarget): + switch functionTarget.messageSendKind { + case .classic?: + if let selector = selectorInSelectorRegister() { + referenceTarget = .messageSend(selector: selector, receiver: receiverHint(isObjectiveCMethod: isObjectiveCMethod)) + } else { + referenceTarget = .function(functionTarget.location) + } + case .superclass?: + if let selector = selectorInSelectorRegister() { + referenceTarget = .superMessageSend(selector: selector, className: superclassSendClassName()) + } else { + referenceTarget = .function(functionTarget.location) + } + case nil: + referenceTarget = .function(functionTarget.location) + isRuntimeHelperCall = functionTarget.isRuntimeHelper + callReturnsArgument = functionTarget.returnsItsClassArgument + calledTypeFunction = functionTarget.typeFunction + } + case .importedSymbol(let name): + let importedName = importedSymbolName(name) + referenceTarget = .importedSymbol(name: importedName) + isRuntimeHelperCall = RuntimeHelperNames.isRuntimeHelper(name) + callReturnsArgument = Self.returnsItsClassArgument(name) + if let accessorSymbol = Self.accessorSymbol(name) { calledTypeFunction = .accessorSymbol(accessorSymbol) } + case .unrecognized: + referenceTarget = .unrecognized(address: target) + } + return CodeReference(function: function, instructionAddress: pc, kind: kind, target: referenceTarget, isRuntimeHelperCall: isRuntimeHelperCall) + } + + private func indirectReference(through branch: ARM64InstructionWord.RegisterBranch, at pc: UInt64, in function: CodeLocation, kind: CodeReference.Kind) -> CodeReference { + var constant: UInt16? + var isAddressBlended = false + if let modifier = branch.modifier, let modifierConstant = registers.constant(of: modifier) { + constant = modifierConstant.value + isAddressBlended = modifierConstant.isBlended + } + let evidence = IndirectCallEvidence( + table: .none, + tableOffset: registers.loadDisplacement(of: branch.target), + pointerAuthenticationConstant: constant, + isAddressBlended: isAddressBlended + ) + return CodeReference(function: function, instructionAddress: pc, kind: kind, target: .indirect(evidence), isRuntimeHelperCall: false) + } + + private mutating func receiverHint(isObjectiveCMethod: Bool) -> ReceiverClassHint { + if isObjectiveCMethod, registers.holdsMethodReceiver(0) { return .methodReceiver } + if case .objectiveCClass(let classObject)? = reference(inRegister: 0) { return .classLiteral(classObject.name) } + return .unknown + } + + // MARK: - Classes and types + + /// A class or a Swift type an address or a slot leads to. + private enum AddressReference { + case objectiveCClass(ObjectiveCClassObject) + /// The type's context descriptor. + case swiftType(CodeLocation) + } + + private func reference(to addressReference: AddressReference, at pc: UInt64, in function: CodeLocation) -> CodeReference { + let target: CodeReferenceTarget + switch addressReference { + case .objectiveCClass(let classObject): + target = .objectiveCClass(name: classObject.name, location: classObject.location) + case .swiftType(let descriptor): + target = .swiftType(descriptor: descriptor) + } + return CodeReference(function: function, instructionAddress: pc, kind: .reference, target: target, isRuntimeHelperCall: false) + } + + /// What a register holds: an `adrp` / `add` of a class object or type + /// metadata, or a load from a slot holding one. + private mutating func reference(inRegister register: Int) -> AddressReference? { + if let address = registers.builtAddress(of: register) { return addressReference(atAddress: address) } + if let slot = registers.slotAddress(of: register) { return slotReference(fromSlot: slot) } + return nil + } + + /// The class object, type metadata or metadata accessor at the unslid + /// `address`. Most addresses code builds lie in its own image outside + /// these — strings, selectors, constants — and are turned away before any + /// lookup. + private mutating func addressReference(atAddress address: UInt64) -> AddressReference? { + let isCode = address >= table.textStart && address < table.textEnd + if !isCode, !table.dataSegmentRanges.contains(where: { $0.contains(address) }), table.segmentRanges.contains(where: { $0.contains(address) }) { return nil } + if let known = addressReferences[address] { return known } + let runtimeAddress = runtimeAddress(ofUnslid: address, slide: table.slide) + let addressReference = isCode ? accessorReference(atRuntimeAddress: runtimeAddress) : self.addressReference(atRuntimeAddress: runtimeAddress) + addressReferences[address] = addressReference + return addressReference + } + + /// What a load from the slot at the unslid `slot` yields. Only a slot of + /// this image's GOT or class references counts, or one of the GOT pool the + /// shared cache keeps outside every image: a constant string's `isa` also + /// points at a class, and is no reference to it. + private mutating func slotReference(fromSlot slot: UInt64) -> AddressReference? { + let isOwnReferenceSlot = table.referenceSlotRanges.contains { $0.contains(slot) } + // Any other slot of the image's own holds no reference. + if !isOwnReferenceSlot, table.segmentRanges.contains(where: { $0.contains(slot) }) { return nil } + if let known = slotReferences[slot] { return known } + var slotReference: AddressReference? + let runtimeSlot = runtimeAddress(ofUnslid: slot, slide: table.slide) + let isReferenceSlot = isOwnReferenceSlot + || (analyzer.imageIndex(containingDataAddress: runtimeSlot) == nil + && analyzer.imageIndex(containingRuntimeAddress: runtimeSlot) == nil + && analyzer.isMapped(runtimeAddress: runtimeSlot, length: 8)) + if isReferenceSlot, let pointer = UnsafeRawPointer(bitPattern: runtimeSlot) { + // Strip the pointer-authentication bits; user addresses fit in 47. + let value = UInt(pointer.loadUnaligned(as: UInt64.self) & SwiftTypeIndex.addressMask) + slotReference = addressReference(atRuntimeAddress: value) ?? accessorReference(atRuntimeAddress: value) + } + slotReferences[slot] = slotReference + return slotReference + } + + /// A class object, or the metadata of a struct, an enum or an imported + /// type, at the runtime `address`. A Swift class's metadata is its + /// Objective-C class object. + private mutating func addressReference(atRuntimeAddress address: UInt) -> AddressReference? { + if let classObject = classObject(atRuntimeAddress: address) { return .objectiveCClass(classObject) } + if let descriptor = valueMetadataDescriptor(atRuntimeAddress: address) { return .swiftType(descriptor) } + return nil + } + + /// The class a slot at the runtime `slot` points at. + private mutating func classObject(storedAt runtimeSlot: UInt) -> ObjectiveCClassObject? { + guard let pointer = UnsafeRawPointer(bitPattern: runtimeSlot) else { return nil } + // Strip the pointer-authentication bits; user addresses fit in 47. + return classObject(atRuntimeAddress: UInt(pointer.loadUnaligned(as: UInt64.self) & SwiftTypeIndex.addressMask)) + } + + private func classObject(atRuntimeAddress address: UInt) -> ObjectiveCClassObject? { + guard let imageIndex = analyzer.imageIndex(containingDataAddress: address) else { return nil } + return indexes.classIndex(ofImageAt: imageIndex).classObject(atRuntimeAddress: address) + } + + /// The type whose metadata accessor starts at the runtime `address`. + private mutating func accessorReference(atRuntimeAddress address: UInt) -> AddressReference? { + guard let imageIndex = analyzer.imageIndex(containingRuntimeAddress: address) else { return nil } + return swiftTypeIndex(ofImageAt: imageIndex).descriptorLocation(ofAccessorAt: address).map { .swiftType($0) } + } + + /// The descriptor of the type whose metadata lies at the runtime + /// `address`: a struct, an enum, an optional or an imported type, whose + /// metadata holds its kind first and its descriptor next. + private mutating func valueMetadataDescriptor(atRuntimeAddress address: UInt) -> CodeLocation? { + guard analyzer.isMapped(runtimeAddress: address, length: 16), let metadata = UnsafeRawPointer(bitPattern: address) else { return nil } + // MetadataKind: struct 0x200, enum 0x201, optional 0x202, foreign + // class 0x203, foreign reference type 0x204. + let kind = metadata.loadUnaligned(as: UInt64.self) + guard kind >= 0x200, kind <= 0x204 else { return nil } + let descriptor = UInt(metadata.loadUnaligned(fromByteOffset: 8, as: UInt64.self) & SwiftTypeIndex.addressMask) + guard let imageIndex = analyzer.imageIndex(containingRuntimeAddress: descriptor) else { return nil } + let index = swiftTypeIndex(ofImageAt: imageIndex) + return index.describesType(descriptorAt: descriptor) ? index.location(ofRuntimeAddress: descriptor) : nil + } + + private func swiftTypeIndex(ofImageAt imageIndex: Int) -> SwiftTypeIndex { + indexes.swiftTypeIndex(ofImageAt: imageIndex) + } + + /// The type reference a call makes besides the call itself: to the type + /// whose metadata accessor it calls, or to the types the mangled name it + /// instantiates names. + private mutating func typeReferenceOfCalledFunction(at pc: UInt64, in function: CodeLocation) -> CodeReference? { + guard let typeFunction = calledTypeFunction else { return nil } + let target: CodeReferenceTarget + switch typeFunction { + case .accessor(let descriptor): + target = .swiftType(descriptor: descriptor) + case .accessorSymbol(let symbol): + target = .swiftTypeName(.accessorSymbol(symbol)) + case .instantiationHelper(let takesRecord): + guard let name = takesRecord ? mangledNameInRecord(inRegister: 1) : mangledNameInCacheVariable(inRegister: 0) else { return nil } + target = .swiftTypeName(name) + case .runtimeEntry(let nameRegister): + guard let name = mangledName(inRegister: nameRegister) else { return nil } + target = .swiftTypeName(name) + } + return CodeReference(function: function, instructionAddress: pc, kind: .reference, target: target, isRuntimeHelperCall: false) + } + + /// The longest mangled name read; a longer one is taken for something + /// else. + private static let maximumMangledNameLength = 4096 + + /// `__swift_instantiateConcreteTypeFromMangledNameV2`'s second argument: + /// `{ int32 offset from the record to the name, int32 length }`. + private func mangledNameInRecord(inRegister register: Int) -> SwiftTypeName? { + guard let record = registers.builtAddress(of: register) else { return nil } + let runtimeRecord = runtimeAddress(ofUnslid: record, slide: table.slide) + guard analyzer.isMapped(runtimeAddress: runtimeRecord, length: 8), let pointer = UnsafeRawPointer(bitPattern: runtimeRecord) else { return nil } + let offset = pointer.loadUnaligned(as: Int32.self) + let length = Int(pointer.loadUnaligned(fromByteOffset: 4, as: Int32.self)) + return mangledName(at: ARM64InstructionWord.adding(Int64(offset), to: record), length: length) + } + + /// The first argument of the older helper: a cache variable that holds + /// `{ int32 offset from the variable to the name, int32 negated length }` + /// until the type is instantiated, and its metadata afterwards — then the + /// name is gone, and nothing is reported. + private func mangledNameInCacheVariable(inRegister register: Int) -> SwiftTypeName? { + guard let cache = registers.builtAddress(of: register) else { return nil } + let runtimeCache = runtimeAddress(ofUnslid: cache, slide: table.slide) + guard analyzer.isMapped(runtimeAddress: runtimeCache, length: 8), let pointer = UnsafeRawPointer(bitPattern: runtimeCache) else { return nil } + let value = pointer.loadUnaligned(as: Int64.self) + guard value < 0 else { return nil } + return mangledName(at: ARM64InstructionWord.adding(Int64(Int32(truncatingIfNeeded: value)), to: cache), length: -Int(Int32(truncatingIfNeeded: value >> 32))) + } + + /// The name a runtime entry point is handed, which runs to its + /// terminator: a symbolic reference's payload is skipped, since it may + /// hold zero bytes. + private func mangledName(inRegister register: Int) -> SwiftTypeName? { + guard let name = registers.builtAddress(of: register) else { return nil } + let runtimeName = runtimeAddress(ofUnslid: name, slide: table.slide) + let readableLength = Int(min(analyzer.mappedLength(fromRuntimeAddress: runtimeName), UInt(Self.maximumMangledNameLength))) + guard readableLength > 0, let bytes = UnsafePointer(bitPattern: runtimeName) else { return nil } + var length = 0 + while length < readableLength { + let byte = bytes[length] + if byte == 0 { return mangledName(at: name, length: length) } + length += byte >= 0x01 && byte <= 0x17 ? 5 : (byte >= 0x18 && byte <= 0x1F ? 9 : 1) + } + return nil + } + + private func mangledName(at name: UInt64, length: Int) -> SwiftTypeName? { + guard length > 0, length <= Self.maximumMangledNameLength, + analyzer.isMapped(runtimeAddress: runtimeAddress(ofUnslid: name, slide: table.slide), length: UInt(length)) + else { return nil } + return .mangledName(location: CodeLocation(imageIndex: table.imageIndex, address: name), length: length) + } + + /// `_$s…Ma` without its leading underscore, for a metadata accessor's + /// symbol. + private static func accessorSymbol(_ name: UnsafePointer) -> String? { + guard name[0] == 0x5F, name[1] == 0x24, name[2] == 0x73 else { return nil } + let length = strlen(name) + guard length > 5, name[length - 2] == 0x4D, name[length - 1] == 0x61 else { return nil } + return String(cString: name + 1) + } + + /// The class a super send in the current function starts above: the one + /// its `__objc_superrefs` slot holds — a category method's class too — + /// or, when no such load was seen, the class its symbol names. + private func superclassSendClassName() -> String? { + superclassReferenceClassName ?? table.primaryName(ofFunctionAt: currentFunctionIndex).flatMap(Self.className(ofMethodSymbol:)) + } + + /// `objc_opt_self`, `objc_opt_class`, `swift_getInitializedObjCClass`: + /// the class they are handed is what they return. + private static func returnsItsClassArgument(_ name: UnsafePointer) -> Bool { + strcmp(name, "_objc_opt_self") == 0 || strcmp(name, "_objc_opt_class") == 0 || strcmp(name, "_swift_getInitializedObjCClass") == 0 + } + + /// `-[NSView(NSLayout) frame]` → `NSView`. + private static func className(ofMethodSymbol symbol: UnsafePointer) -> String? { + guard symbol[0] == 0x2D || symbol[0] == 0x2B, symbol[1] == 0x5B else { return nil } + var length = 0 + while symbol[2 + length] != 0, symbol[2 + length] != 0x20, symbol[2 + length] != 0x28 { length += 1 } + guard length > 0 else { return nil } + return String(decoding: UnsafeRawBufferPointer(start: symbol + 2, count: length), as: UTF8.self) + } + + /// The selector a classic send passes in `x1`: loaded from this image's + /// selector references, or the selector string's own address. + /// + /// The second is what a classic send looks like inside the shared cache. + /// The cache builder rewrites the `adrp` / `ldr` of a selector reference + /// into an `adrp` / `add` of the string it points at, so the instructions + /// carry only the string's address — macOS 27.2 compiles + /// `-[NSObject debugDescription]` to `adrp x8; add x1, x8; b _objc_msgSend`. + private mutating func selectorInSelectorRegister() -> String? { + if let slotAddress = registers.slotAddress(of: 1) { + guard let range = table.selectorReferenceRange, range.contains(slotAddress), + let selector = ImageFunctionTable.selectorString(inSlotAt: slotAddress, slide: table.slide) + else { return nil } + return selectorName(selector) + } + if let stringAddress = registers.builtAddress(of: 1), + let selector = selectorString(atRuntimeAddress: runtimeAddress(ofUnslid: stringAddress, slide: table.slide)) { + return selectorName(selector) + } + return nil + } + + /// The longest selector read; longer ones are taken for something else. + private static let maximumSelectorLength = 1024 + + /// A selector string at `address`: mapped, and printable up to its + /// terminator. Checked rather than assumed — `x1` holds the selector by + /// convention only, and a string runs to wherever its terminator is. + private func selectorString(atRuntimeAddress address: UInt) -> UnsafePointer? { + let readableLength = min(analyzer.mappedLength(fromRuntimeAddress: address), UInt(Self.maximumSelectorLength)) + guard readableLength > 0, let bytes = UnsafePointer(bitPattern: address) else { return nil } + for index in 0 ..< Int(readableLength) { + let byte = bytes[index] + if byte == 0 { + return index > 0 ? UnsafeRawPointer(bytes).assumingMemoryBound(to: CChar.self) : nil + } + // Selectors are identifiers and colons: printable, never a space. + guard byte > 0x20, byte < 0x7F else { return nil } + } + return nil + } + + private mutating func selectorName(_ pointer: UnsafePointer) -> String { + let key = UInt(bitPattern: pointer) + if let known = selectorNames[key] { return known } + let name = String(cString: pointer) + selectorNames[key] = name + return name + } + + private mutating func importedSymbolName(_ pointer: UnsafePointer) -> String { + let key = UInt(bitPattern: pointer) + if let known = importedNames[key] { return known } + let name = String(cString: pointer) + importedNames[key] = name + return name + } + + // MARK: - Resolving call targets + + private enum MessageSendKind { + case classic + case superclass + } + + /// What calling a function stands for besides the call. + private enum TypeFunction { + /// A type's metadata accessor: the type's descriptor. + case accessor(descriptor: CodeLocation) + /// A metadata accessor no descriptor stands for: its symbol, without + /// the leading underscore. + case accessorSymbol(String) + /// `__swift_instantiateConcreteTypeFromMangledName…`: the V2 helpers + /// take the name's `{ offset, length }` record in `x1`, the older ones + /// a cache variable in `x0`. + case instantiationHelper(takesRecord: Bool) + /// `swift_getTypeByMangledName…`: the name in this register. + case runtimeEntry(nameRegister: Int) + } + + private struct FunctionTarget { + let location: CodeLocation + var isRuntimeHelper = false + var messageSendKind: MessageSendKind? + /// `objc_opt_self`, `objc_opt_class`, `swift_getInitializedObjCClass`. + var returnsItsClassArgument = false + var typeFunction: TypeFunction? + } + + private enum ResolvedTarget { + case function(FunctionTarget) + /// A stub that names its selector. + case selector(UnsafePointer) + case importedSymbol(UnsafePointer) + case unrecognized + } + + /// Where an unslid address in this image's address space leads. + private mutating func resolve(_ target: UInt64) -> ResolvedTarget { + if let known = resolvedTargets[target] { return known } + let resolved = computeResolution(of: target) + resolvedTargets[target] = resolved + return resolved + } + + /// `detectsTypeFunctions`: whether to tell metadata accessors and + /// mangled-name helpers apart, which looks into the helper candidates' + /// own calls — not while looking into one. + private func computeResolution(of target: UInt64, detectsTypeFunctions: Bool = true) -> ResolvedTarget { + if let range = table.objectiveCStubRange, range.contains(target) { + guard let selector = table.objectiveCStubSelectors[target] else { return .unrecognized } + return .selector(selector) + } + if let stub = table.symbolStubs[target] { + // dyld binds every slot when it loads the image, lazy pointers + // included (macOS 27.2, `LazyBindingTests`), so the slot is read + // as it stands. + if let slotAddress = stub.slotAddress, + let resolved = resolveSlot(atRuntimeAddress: runtimeAddress(ofUnslid: slotAddress, slide: table.slide), hops: 0, detectsTypeFunctions: detectsTypeFunctions) { + return resolved + } + if let name = stub.name { return .importedSymbol(name) } + return .unrecognized + } + if target >= table.textStart, target < table.textEnd { + return functionTarget(CodeLocation(imageIndex: table.imageIndex, address: target), detectsTypeFunctions: detectsTypeFunctions) + } + return resolve(runtimeAddress: runtimeAddress(ofUnslid: target, slide: table.slide), hops: 0, detectsTypeFunctions: detectsTypeFunctions) + } + + private func resolve(runtimeAddress address: UInt, hops: Int, detectsTypeFunctions: Bool) -> ResolvedTarget { + if let location = analyzer.location(ofRuntimeAddress: address) { + return functionTarget(location, detectsTypeFunctions: detectsTypeFunctions) + } + // Between images: a stub or island the cache builder put there. + guard hops < Self.maximumTrampolineHops, + analyzer.isExecutable(runtimeAddress: address, length: UInt(ARM64Trampoline.maximumInstructionCount * 4)), + let pointer = UnsafeRawPointer(bitPattern: address), + let trampoline = ARM64Trampoline(readingAt: pointer, address: UInt64(address)) + else { return .unrecognized } + switch trampoline { + case .selectorStub(let selectorAddress, _): + guard analyzer.isMapped(runtimeAddress: UInt(selectorAddress), length: 1), + let selector = UnsafePointer(bitPattern: UInt(selectorAddress)) + else { return .unrecognized } + return .selector(selector) + case .slotLoad(let slotAddress): + return resolveSlot(atRuntimeAddress: UInt(slotAddress), hops: hops + 1, detectsTypeFunctions: detectsTypeFunctions) ?? .unrecognized + case .computed(let computedTarget): + return resolve(runtimeAddress: UInt(computedTarget), hops: hops + 1, detectsTypeFunctions: detectsTypeFunctions) + } + } + + /// Follows the pointer a GOT slot holds — dyld or the cache builder bound + /// it already. + private func resolveSlot(atRuntimeAddress slotAddress: UInt, hops: Int, detectsTypeFunctions: Bool) -> ResolvedTarget? { + guard analyzer.isMapped(runtimeAddress: slotAddress, length: 8), + let slot = UnsafeRawPointer(bitPattern: slotAddress) + else { return nil } + // Strip the pointer-authentication bits; user addresses fit in 47. + let target = UInt(slot.loadUnaligned(as: UInt64.self) & 0x0000_7FFF_FFFF_FFFF) + guard target != 0 else { return nil } + return resolve(runtimeAddress: target, hops: hops, detectsTypeFunctions: detectsTypeFunctions) + } + + private func functionTarget(_ location: CodeLocation, detectsTypeFunctions: Bool) -> ResolvedTarget { + var functionTarget = FunctionTarget(location: location) + if analyzer.messageSendLocations.contains(location) { + functionTarget.messageSendKind = .classic + return .function(functionTarget) + } + if analyzer.superMessageSendLocations.contains(location) { + functionTarget.messageSendKind = .superclass + return .function(functionTarget) + } + functionTarget.isRuntimeHelper = analyzer.runtimeHelperLocations.contains(location) + || (location.imageIndex == table.imageIndex && table.runtimeHelperStarts.contains(location.address)) + functionTarget.returnsItsClassArgument = analyzer.classReturningFunctionLocations.contains(location) + if detectsTypeFunctions { functionTarget.typeFunction = typeFunction(at: location) } + return .function(functionTarget) + } + + /// What a function stands for besides a call: a type's metadata + /// accessor — by its descriptor, or by its symbol when no descriptor + /// stands for it — a mangled-name instantiation helper, or one of the + /// runtime's entry points that instantiate a type from its mangled name. + private func typeFunction(at location: CodeLocation) -> TypeFunction? { + guard findsTypeReferences else { return nil } + if let nameRegister = analyzer.typeByMangledNameEntries[location] { return .runtimeEntry(nameRegister: nameRegister) } + if let slide = analyzer.images[location.imageIndex].vmaddrSlide, + let descriptor = swiftTypeIndex(ofImageAt: location.imageIndex).descriptorLocation(ofAccessorAt: runtimeAddress(ofUnslid: location.address, slide: slide)) { + return .accessor(descriptor: descriptor) + } + // Accessors of generic instances and mangled-name helpers are emitted + // into each image that uses them. + guard location.imageIndex == table.imageIndex, + let functionIndex = table.functionIndex(containing: location.address), + table.starts[functionIndex] == location.address + else { return nil } + if let name = table.primaryName(ofFunctionAt: functionIndex) { + if let accessorSymbol = Self.accessorSymbol(name) { return .accessorSymbol(accessorSymbol) } + guard strstr(name, "instantiateConcreteTypeFromMangledName") != nil else { return nil } + let length = strlen(name) + return .instantiationHelper(takesRecord: length > 2 && name[length - 2] == 0x56 && name[length - 1] == 0x32) + } + return instantiationHelperByShape(ofFunctionAt: functionIndex) + } + + /// A mangled-name helper without a symbol, told by what it does: a short + /// function that calls the runtime's `swift_getTypeByMangledName…`. The V2 + /// helpers read their record through `x1` (`ldr x9, [x1]`); the older + /// ones take nothing in `x1`. + private func instantiationHelperByShape(ofFunctionAt functionIndex: Int) -> TypeFunction? { + let start = table.starts[functionIndex] + let end = table.end(ofFunctionAt: functionIndex) + guard end > start, end - start <= 0x90 else { return nil } + let words = table.instructionPointer(at: start) + var readsRecord = false + var callsRuntime = false + for instructionIndex in 0 ..< Int((end - start) / 4) { + let pc = start &+ UInt64(instructionIndex * 4) + let word = UInt32(littleEndian: words[instructionIndex]) + if let load = ARM64InstructionWord.load(word), load.base == 1, load.displacement == 0 { + readsRecord = true + } else if let callee = ARM64InstructionWord.callTarget(word, at: pc) ?? ARM64InstructionWord.branchTarget(word, at: pc), + callee < start || callee >= end, + case .function(let calleeTarget) = computeResolution(of: callee, detectsTypeFunctions: false), + analyzer.typeByMangledNameEntries[calleeTarget.location] != nil { + callsRuntime = true + } + } + return callsRuntime ? .instantiationHelper(takesRecord: readsRecord) : nil + } + + private func runtimeAddress(ofUnslid address: UInt64, slide: Int) -> UInt { + UInt(bitPattern: Int(bitPattern: UInt(address)) &+ slide) + } +} + +/// The class and Swift type indexes one scan has asked the analyzer for. +/// A scan runs on one thread, so the dictionaries need no lock. +private final class ScanIndexes { + private let analyzer: CrossReferenceAnalyzer + private var classIndexes: [Int: ObjectiveCClassIndex] = [:] + private var swiftTypeIndexes: [Int: SwiftTypeIndex] = [:] + + init(analyzer: CrossReferenceAnalyzer) { + self.analyzer = analyzer + } + + func classIndex(ofImageAt imageIndex: Int) -> ObjectiveCClassIndex { + if let index = classIndexes[imageIndex] { return index } + let index = analyzer.objectiveCClassIndex(ofImageAt: imageIndex) + classIndexes[imageIndex] = index + return index + } + + func swiftTypeIndex(ofImageAt imageIndex: Int) -> SwiftTypeIndex { + if let index = swiftTypeIndexes[imageIndex] { return index } + let index = analyzer.swiftTypeIndex(ofImageAt: imageIndex) + swiftTypeIndexes[imageIndex] = index + return index + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/RegisterFile.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RegisterFile.swift new file mode 100644 index 000000000..1657114d5 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RegisterFile.swift @@ -0,0 +1,357 @@ +import Foundation +import ARM64InstructionDecoding + +/// What the scanner knows about each general-purpose register — only what +/// is certain. +/// +/// Register 31 is the zero register or the stack pointer, neither of which +/// is tracked: writing it changes nothing and reading it yields nothing. +final class RegisterFile { + private enum State: UInt8 { + case unknown = 0 + /// Holds an address `adrp` / `adr` / `add` built. + case address + /// Holds what was loaded from the slot at a known address. + case loadedFromSlot + /// Holds the receiver an Objective-C method arrived with. + case methodReceiver + } + + private static let registerCount = 32 + + /// `x0`–`x18` and the link register: what a call may change. + private static let callerSavedMask: UInt32 = 0x0007_FFFF | (1 << 30) + + /// Everything the file knows at one instruction. A value of fixed size, + /// so a forward branch carries it to its target as a plain copy — the + /// scan takes one at every forward branch, and arrays would allocate. + struct Snapshot { + fileprivate var states = SIMD32(repeating: 0) + fileprivate var values = SIMD32(repeating: 0) + fileprivate var loadDisplacements = SIMD32(repeating: 0) + fileprivate var constants = SIMD32(repeating: 0) + /// Registers holding a value loaded from memory, by bit. + fileprivate var loadedMask: UInt32 = 0 + /// Registers holding a pointer-authentication constant, by bit. + fileprivate var constantMask: UInt32 = 0 + /// Of those, the ones whose constant was blended into an address. + fileprivate var blendedMask: UInt32 = 0 + + /// Keeps only what `other` agrees on: two paths that reach one + /// instruction leave a register known there only when both put the + /// same thing in it. + mutating func meet(_ other: Snapshot) { + for register in 0 ..< RegisterFile.registerCount where !agrees(with: other, on: register) { + let bit: UInt32 = 1 << UInt32(register) + states[register] = State.unknown.rawValue + loadedMask &= ~bit + constantMask &= ~bit + blendedMask &= ~bit + } + } + + private func agrees(with other: Snapshot, on register: Int) -> Bool { + let bit: UInt32 = 1 << UInt32(register) + return states[register] == other.states[register] + && (states[register] == State.unknown.rawValue || values[register] == other.values[register]) + && loadedMask & bit == other.loadedMask & bit + && (loadedMask & bit == 0 || loadDisplacements[register] == other.loadDisplacements[register]) + && constantMask & bit == other.constantMask & bit + && blendedMask & bit == other.blendedMask & bit + && (constantMask & bit == 0 || constants[register] == other.constants[register]) + } + } + + private var contents = Snapshot() + + func reset() { + contents.states = SIMD32(repeating: 0) + contents.loadedMask = 0 + contents.constantMask = 0 + contents.blendedMask = 0 + } + + // MARK: - Writes + + func setMethodReceiver(_ register: Int) { + overwrite(register, state: .methodReceiver, value: 0) + } + + func setAddress(_ address: UInt64, of register: Int) { + overwrite(register, state: .address, value: address) + } + + func add(_ addend: Int64, to source: Int, into destination: Int) { + guard destination != 31 else { return } + if source != 31, contents.states[source] == State.address.rawValue { + overwrite(destination, state: .address, value: UInt64(bitPattern: Int64(bitPattern: contents.values[source]) &+ addend)) + } else { + overwrite(destination, state: .unknown, value: 0) + } + } + + func load(into destination: Int, base: Int, displacement: Int64, writesBack: Bool) { + let slotIsKnown = base != 31 && contents.states[base] == State.address.rawValue + let slotAddress = UInt64(bitPattern: Int64(bitPattern: contents.values[base & 31]) &+ displacement) + if writesBack, base != 31 { overwrite(base, state: .unknown, value: 0) } + guard destination != 31 else { return } + overwrite(destination, state: slotIsKnown ? .loadedFromSlot : .unknown, value: slotIsKnown ? slotAddress : 0) + contents.loadedMask |= 1 << UInt32(destination) + contents.loadDisplacements[destination] = displacement + } + + func copy(_ source: Int, to destination: Int) { + guard destination != 31 else { return } + guard source != 31 else { + overwrite(destination, state: .unknown, value: 0) + return + } + contents.states[destination] = contents.states[source] + contents.values[destination] = contents.values[source] + contents.loadDisplacements[destination] = contents.loadDisplacements[source] + contents.constants[destination] = contents.constants[source] + copyBit(from: source, to: destination, in: &contents.loadedMask) + copyBit(from: source, to: destination, in: &contents.constantMask) + copyBit(from: source, to: destination, in: &contents.blendedMask) + } + + /// `movz` / `movk`: a pointer-authentication constant is `movk xN, #imm, + /// lsl #48` blended into an address, or `mov x17, #imm` on its own. + func moveWide(into destination: Int, immediate: UInt16, shift: Int, keepsOtherBits: Bool) { + guard destination != 31 else { return } + let isConstant = keepsOtherBits ? shift == 48 : shift == 0 + overwrite(destination, state: .unknown, value: 0) + guard isConstant else { return } + contents.constants[destination] = immediate + contents.constantMask |= 1 << UInt32(destination) + if keepsOtherBits { contents.blendedMask |= 1 << UInt32(destination) } + } + + func clobberCallerSavedRegisters() { + for register in 0 ... 18 { contents.states[register] = State.unknown.rawValue } + contents.states[30] = State.unknown.rawValue + contents.loadedMask &= ~Self.callerSavedMask + contents.constantMask &= ~Self.callerSavedMask + contents.blendedMask &= ~Self.callerSavedMask + } + + /// What a call to a function that returns its argument leaves: the + /// caller-saved registers forgotten except `kept`, which still holds what + /// it was handed. + func clobberCallerSavedRegisters(keeping kept: Int) { + let keptContents = contents + clobberCallerSavedRegisters() + let bit: UInt32 = 1 << UInt32(kept) + contents.states[kept] = keptContents.states[kept] + contents.values[kept] = keptContents.values[kept] + contents.loadDisplacements[kept] = keptContents.loadDisplacements[kept] + contents.constants[kept] = keptContents.constants[kept] + contents.loadedMask = (contents.loadedMask & ~bit) | (keptContents.loadedMask & bit) + contents.constantMask = (contents.constantMask & ~bit) | (keptContents.constantMask & bit) + contents.blendedMask = (contents.blendedMask & ~bit) | (keptContents.blendedMask & bit) + } + + /// Forgets the registers an instruction the scanner does not model + /// writes. Erring toward forgetting only loses facts; never forgetting a + /// write would keep a stale one. + func forgetRegistersWritten(by word: UInt32) { + forget(mask: Self.registersWritten(by: word)) + } + + /// The general-purpose registers `word` writes, by bit: every one it may + /// write, never one it does not — except a pointer signed or + /// authenticated in place, which keeps what it means. A call writes the + /// caller-saved registers. + static func registersWritten(by word: UInt32) -> UInt32 { + let destination = word & 0x1F + let base = (word >> 5) & 0x1F + // Calls: `bl`, and `blr` and its authenticating forms. + if word & 0xFC00_0000 == 0x9400_0000 || ARM64InstructionWord.registerBranch(word)?.isCall == true { + return callerSavedMask + } + // Loads and stores. A write-back moves the base whether the + // register transferred is a general one or a vector one. + if word & 0x0A00_0000 == 0x0800_0000 { + return registersWritten(byLoadOrStore: word, destination: destination, base: base) + } + // Data processing, immediate or register. + if word & 0x1C00_0000 == 0x1000_0000 || word & 0x0E00_0000 == 0x0A00_0000 { + // PAC and AUT sign or authenticate the register in place, which + // keeps what it holds; XPAC, which strips it, is forgotten. + if word & 0xFFFF_C000 == 0xDAC1_0000 { return 0 } + return bit(destination) + } + // Floating point to a general register: moves and conversions, to an + // integer or to fixed point. + if word & 0x5F20_FC00 == 0x1E20_0000 || word & 0x5F20_0000 == 0x1E00_0000 { + return bit(destination) + } + // `umov` / `smov`: a vector element to a general register. + if word & 0xBFE0_EC00 == 0x0E00_2C00 { + return bit(destination) + } + // SVE and SME: the few that yield a general register (`cntd`, + // `addvl`, `rdsvl` …) write it here. + if word & 0x1E00_0000 == 0x0400_0000 || word & 0x9E00_0000 == 0x8000_0000 { + return bit(destination) + } + // System register reads, and `sysl`. + if word & 0xFFE0_0000 == 0xD520_0000 { + return bit(destination) + } + // `svc`: a system call returns in `x0` and `x1`. + if word & 0xFFE0_001F == 0xD400_0001 { + return 0b11 + } + return 0 + } + + private static func registersWritten(byLoadOrStore word: UInt32, destination: UInt32, base: UInt32) -> UInt32 { + let isVector = word & 0x0400_0000 != 0 + let secondRegister = (word >> 10) & 0x1F + let statusRegister = (word >> 16) & 0x1F + var written: UInt32 = 0 + switch (word >> 28) & 0x3 { + case 0b11: + // Single register. Bit 24 clear and bit 21 clear: bit 10 marks + // the pre- and post-indexed forms. Bit 21 set: bits 11–10 are 00 + // for an atomic, x1 for a pointer-authenticated load, whose bit + // 11 writes back. + if word & 0x0100_0000 == 0, word & 0x0020_0000 == 0 { + if word & 0x0400 != 0 { written |= bit(base) } + } else if word & 0x0100_0000 == 0, word & 0x0400 != 0 { + if word & 0x0800 != 0 { written |= bit(base) } + return written | bit(destination) + } else if word & 0x0100_0000 == 0, word & 0x0C00 == 0 { + // An atomic returns the old value whatever its ordering, + // which takes the bits a load's opc would. + return isVector ? written : written | bit(destination) + } + // opc 00 is a store; everything else loads. + if !isVector, (word >> 22) & 0x3 != 0 { written |= bit(destination) } + case 0b10: + // Register pair: bit 23 marks the pre- and post-indexed forms, + // bit 22 a load. + if word & 0x0080_0000 != 0 { written |= bit(base) } + if !isVector, word & 0x0040_0000 != 0 { written |= bit(destination) | bit(secondRegister) } + case 0b01: + if word & 0x0100_0000 == 0 { + // Load literal. + if !isVector { written |= bit(destination) } + } else if word & 0x0020_0C00 == 0 { + // Load-acquire and store-release, unscaled: opc 00 stores. + if !isVector, (word >> 22) & 0x3 != 0 { written |= bit(destination) } + } else { + // Memory copy and set, which move all three of their + // registers along, memory tags, and the write-back forms of + // load-acquire and store-release. + written |= bit(destination) | bit(base) | bit(statusRegister) + } + default: + if isVector { + // Structure loads and stores: bit 23 marks the + // post-indexed forms. + if word & 0x0080_0000 != 0 { written |= bit(base) } + return written + } + // Exclusives, ordered accesses, compare and swap: the register + // transferred, the status or compared one, and with bit 23 clear + // and bit 21 set a pair — a pair's second register, or for + // `casp` (bit 31 clear) the register after the compared one. + written |= bit(destination) | bit(statusRegister) + if word & 0x00A0_0000 == 0x0020_0000 { + written |= bit(secondRegister) + if word & 0x8000_0000 == 0, statusRegister != 31 { written |= bit(statusRegister + 1) } + } + } + return written + } + + /// Register `register`'s bit; none for register 31, which is not tracked. + private static func bit(_ register: UInt32) -> UInt32 { + register == 31 ? 0 : 1 << register + } + + // MARK: - Branches + + func snapshot() -> Snapshot { + contents + } + + /// Becomes `snapshot`: the instruction is reached only by the branches + /// it was taken at. + func restore(_ snapshot: Snapshot) { + contents = snapshot + } + + /// Keeps only what `snapshot` agrees on: the instruction is reached both + /// by falling through and by the branches `snapshot` was taken at. + func meet(_ snapshot: Snapshot) { + contents.meet(snapshot) + } + + // MARK: - Reads + + func wasLoadedFromMemory(_ register: Int) -> Bool { + register != 31 && contents.loadedMask & (1 << UInt32(register)) != 0 + } + + func loadDisplacement(of register: Int) -> Int64? { + wasLoadedFromMemory(register) ? contents.loadDisplacements[register] : nil + } + + func constant(of register: Int) -> (value: UInt16, isBlended: Bool)? { + guard register != 31, contents.constantMask & (1 << UInt32(register)) != 0 else { return nil } + return (contents.constants[register], contents.blendedMask & (1 << UInt32(register)) != 0) + } + + func holdsMethodReceiver(_ register: Int) -> Bool { + register != 31 && contents.states[register] == State.methodReceiver.rawValue + } + + /// The address a register holds, when `adrp` / `adr` / `add` built it. + func builtAddress(of register: Int) -> UInt64? { + guard register != 31, contents.states[register] == State.address.rawValue else { return nil } + return contents.values[register] + } + + /// The slot a register's value was loaded from, when that is known. + func slotAddress(of register: Int) -> UInt64? { + guard register != 31, contents.states[register] == State.loadedFromSlot.rawValue else { return nil } + return contents.values[register] + } + + // MARK: - Helpers + + private func overwrite(_ register: Int, state: State, value: UInt64) { + guard register != 31 else { return } + contents.states[register] = state.rawValue + contents.values[register] = value + let bit: UInt32 = 1 << UInt32(register) + contents.loadedMask &= ~bit + contents.constantMask &= ~bit + contents.blendedMask &= ~bit + } + + private func forget(_ register: Int) { + overwrite(register, state: .unknown, value: 0) + } + + /// Forgets every register `mask` has a bit for. + func forget(mask: UInt32) { + var remaining = mask & 0x7FFF_FFFF + while remaining != 0 { + let register = remaining.trailingZeroBitCount + forget(register) + remaining &= remaining - 1 + } + } + + private func copyBit(from source: Int, to destination: Int, in mask: inout UInt32) { + if mask & (1 << UInt32(source)) != 0 { + mask |= 1 << UInt32(destination) + } else { + mask &= ~(1 << UInt32(destination)) + } + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/RenamedReexportIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RenamedReexportIndex.swift new file mode 100644 index 000000000..157e8841d --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RenamedReexportIndex.swift @@ -0,0 +1,138 @@ +import Foundation +import MachOKit + +/// A symbol one image re-exports under a name of its own. +struct RenamedReexport: Hashable { + /// The re-exporting image. + let imageIndex: Int + /// The name it exports the symbol under. + let name: String +} + +/// Every symbol an image re-exports under another name, by the image it +/// re-exports from and the symbol's name there. +/// +/// An image calling such a function imports it by the re-exporting image's +/// name: libsystem_c exports libsystem_platform's `__platform_strlen` as +/// `_strlen`, CoreGraphics exports SkyLight's `_SLBeginDisplayConfiguration` +/// as `_CGBeginDisplayConfiguration`, and every caller imports the latter. A +/// prefilter by imports has to look for those names too. The macOS 27.2 cache +/// holds 1,438 such re-exports in 12 images, 1,112 of them CoreGraphics'. +/// +/// Read from every image's export trie, once; only the renamed re-exports +/// are kept. +struct RenamedReexportIndex { + /// By the image re-exported from, then by the symbol's name there. + let reexportsByProvider: [Int: [String: [RenamedReexport]]] + + /// `concurrently` reads the tries on every core; otherwise on the calling + /// thread alone, which a debug build finishes about as soon (3.9 s against + /// 3.4 on 28 cores for the macOS 27.2 cache's 144 MiB of tries). + init(analyzer: CrossReferenceAnalyzer, concurrently: Bool = true) { + let images = analyzer.images + let entriesByImage = UnsafeMutableBufferPointer<[TrieEntry]>.allocate(capacity: images.count) + entriesByImage.initialize(repeating: []) + defer { + _ = entriesByImage.deinitialize() + entriesByImage.deallocate() + } + nonisolated(unsafe) let entries = entriesByImage.baseAddress! + let readTrie: @Sendable (Int) -> Void = { imageIndex in + guard let trie = images[imageIndex].exportTrie, trie.exportSize > 0 else { return } + (entries + imageIndex).pointee = Self.renamedReexports(inTrieAt: trie.basePointer.assumingMemoryBound(to: UInt8.self), size: trie.exportSize) + } + if concurrently { + DispatchQueue.concurrentPerform(iterations: images.count, execute: readTrie) + } else { + images.indices.forEach(readTrie) + } + var reexportsByProvider: [Int: [String: [RenamedReexport]]] = [:] + for imageIndex in images.indices where !entriesByImage[imageIndex].isEmpty { + // An entry names the image it re-exports from by its ordinal + // among the image's dylib load commands, from 1. + let dependencies = analyzer.dependencyImageIndices(ofImageAt: imageIndex) + for entry in entriesByImage[imageIndex] { + guard entry.ordinal >= 1, entry.ordinal <= UInt64(dependencies.count) else { continue } + let reexport = RenamedReexport(imageIndex: imageIndex, name: entry.name) + for provider in dependencies[Int(entry.ordinal) - 1] { + reexportsByProvider[provider, default: [:]][entry.importedName, default: []].append(reexport) + } + } + } + self.reexportsByProvider = reexportsByProvider + } + + struct TrieEntry { + let name: String + let ordinal: UInt64 + let importedName: String + } + + /// `EXPORT_SYMBOL_FLAGS_REEXPORT`. + private static let reexportFlag: UInt64 = 0x08 + + /// The renamed re-exports among the entries of the export trie at + /// `base`: walks every node, and spells out the names of those alone. + static func renamedReexports(inTrieAt base: UnsafePointer, size: Int) -> [TrieEntry] { + var result: [TrieEntry] = [] + var name: [UInt8] = [] + // A node still to visit, with how long its parent's name is and the + // edge label that leads to it. + var pending: [(offset: Int, parentNameLength: Int, labelStart: Int, labelLength: Int)] = [(0, 0, 0, 0)] + // A well-formed trie has fewer nodes than bytes; a malformed one may + // loop. + var remainingNodes = size + while let node = pending.popLast(), remainingNodes > 0 { + remainingNodes -= 1 + name.removeLast(name.count - node.parentNameLength) + name.append(contentsOf: UnsafeBufferPointer(start: base + node.labelStart, count: node.labelLength)) + var cursor = node.offset + guard let terminalSize = readULEB128(base, size: size, at: &cursor) else { continue } + let childrenOffset = cursor + Int(clamping: terminalSize) + if terminalSize > 0, + let flags = readULEB128(base, size: size, at: &cursor), flags & reexportFlag != 0, + let ordinal = readULEB128(base, size: size, at: &cursor), + let importedName = readCString(base, size: size, at: cursor), + !importedName.isEmpty { + let exportedName = String(decoding: name, as: UTF8.self) + if importedName != exportedName { + result.append(TrieEntry(name: exportedName, ordinal: ordinal, importedName: importedName)) + } + } + guard childrenOffset < size else { continue } + cursor = childrenOffset + let childCount = Int(base[cursor]) + cursor += 1 + for _ in 0 ..< childCount { + let labelStart = cursor + while cursor < size, base[cursor] != 0 { cursor += 1 } + guard cursor < size else { break } + let labelLength = cursor - labelStart + cursor += 1 + guard let childOffset = readULEB128(base, size: size, at: &cursor), childOffset < UInt64(size) else { break } + pending.append((Int(childOffset), name.count, labelStart, labelLength)) + } + } + return result + } + + private static func readULEB128(_ base: UnsafePointer, size: Int, at cursor: inout Int) -> UInt64? { + var value: UInt64 = 0 + var shift: UInt64 = 0 + while cursor < size, shift < 64 { + let byte = base[cursor] + cursor += 1 + value |= UInt64(byte & 0x7F) << shift + if byte & 0x80 == 0 { return value } + shift += 7 + } + return nil + } + + private static func readCString(_ base: UnsafePointer, size: Int, at offset: Int) -> String? { + var end = offset + while end < size, base[end] != 0 { end += 1 } + guard end < size else { return nil } + return String(decoding: UnsafeBufferPointer(start: base + offset, count: end - offset), as: UTF8.self) + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/RuntimeHelperNames.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RuntimeHelperNames.swift new file mode 100644 index 000000000..121c9b55e --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/RuntimeHelperNames.swift @@ -0,0 +1,67 @@ +import Foundation + +/// The functions a scan marks as runtime helpers: memory management and +/// value operations, which outnumber everything else a function calls — in +/// a macOS 27.2 shared cache, 26.5% of all direct call targets. +enum RuntimeHelperNames { + /// Symbol-name prefixes of helpers exported by libobjc and the Swift + /// runtime, and of the helpers the Swift compiler emits into each image. + private static let prefixes: [StaticString] = [ + "_objc_retain", + "_objc_release", + "_objc_autorelease", + "_objc_storeStrong", + "_objc_loadWeak", + "_objc_storeWeak", + "_objc_initWeak", + "_objc_destroyWeak", + "_objc_copyWeak", + "_objc_moveWeak", + "_objc_claimAutoreleasedReturnValue", + "_objc_unsafeClaimAutoreleasedReturnValue", + "_swift_retain", + "_swift_release", + "_swift_bridgeObjectRetain", + "_swift_bridgeObjectRelease", + "_swift_unknownObjectRetain", + "_swift_unknownObjectRelease", + "_swift_unknownObjectWeak", + "_swift_unknownObjectUnowned", + "_swift_unowned", + "_swift_weak", + "_swift_nonatomic_", + "_swift_beginAccess", + "_swift_endAccess", + "___swift_destroy_boxed_opaque_existential", + "___swift_allocate_boxed_opaque_existential", + "___swift_project_boxed_opaque_existential", + "___swift_memcpy", + "___swift_noop", + ] + + /// Whether the symbol named `name` is a runtime helper. + static func isRuntimeHelper(_ name: UnsafePointer) -> Bool { + guard name[0] == 0x5F else { return false } + if name[1] == 0x24 { + return isOutlinedValueOperation(name) + } + guard name[1] == 0x6F || name[1] == 0x73 || name[1] == 0x5F else { return false } + for prefix in prefixes { + let matches = prefix.withUTF8Buffer { buffer in + buffer.withMemoryRebound(to: CChar.self) { strncmp(name, $0.baseAddress!, buffer.count) == 0 } + } + if matches { return true } + } + return false + } + + /// An outlined copy, destroy, retain or release: a mangled name ending in + /// `WO` and a lowercase letter, perhaps merged (`Tm`). + private static func isOutlinedValueOperation(_ name: UnsafePointer) -> Bool { + var length = strlen(name) + if length > 2, name[length - 2] == 0x54, name[length - 1] == 0x6D { length -= 2 } + guard length > 6 else { return false } + let operation = name[length - 1] + return name[length - 3] == 0x57 && name[length - 2] == 0x4F && operation >= 0x61 && operation <= 0x7A + } +} diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift new file mode 100644 index 000000000..95134ed01 --- /dev/null +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift @@ -0,0 +1,240 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import Demangling + +/// The Swift types one image defines, by the addresses code reaches them +/// through: every type context descriptor its `__swift5_types` lists, and +/// each descriptor's metadata accessor. +/// +/// Built per image on first use. A type's key — its nominal mangling, +/// `7SwiftUI4TextV` — is built only when someone asks for it: it takes +/// demangling the descriptor's context, tens of microseconds a type. +final class SwiftTypeIndex: @unchecked Sendable { + /// User-space addresses fit in 47 bits; above them are pointer + /// authentication bits. + static let addressMask: UInt64 = 0x0000_7FFF_FFFF_FFFF + + private let image: MachOImage + private let imageIndex: Int + private let slide: Int + private let descriptorsByRuntimeAddress: [UInt: TypeContextDescriptorWrapper] + private let descriptorsByAccessor: [UInt: UInt] + private let lock = NSLock() + private var keysByDescriptor: [UInt: String?] = [:] + private var descriptorSymbolsStorage: [UInt: String]? + + init(image: MachOImage, imageIndex: Int) { + self.image = image + self.imageIndex = imageIndex + self.slide = image.vmaddrSlide ?? 0 + var descriptors: [UInt: TypeContextDescriptorWrapper] = [:] + var accessors: [UInt: UInt] = [:] + let base = UInt(bitPattern: image.ptr) + for wrapper in (try? image.swift.typeContextDescriptors) ?? [] { + let descriptor = base &+ UInt(bitPattern: wrapper.typeContextDescriptor.offset) + descriptors[descriptor] = wrapper + // Every type context descriptor holds its metadata accessor as a + // relative direct pointer at +12. + guard let field = UnsafeRawPointer(bitPattern: descriptor &+ 12) else { continue } + let relative = field.loadUnaligned(as: Int32.self) + guard relative != 0 else { continue } + accessors[UInt(bitPattern: Int(bitPattern: descriptor &+ 12) &+ Int(relative))] = descriptor + } + self.descriptorsByRuntimeAddress = descriptors + self.descriptorsByAccessor = accessors + } + + /// The descriptor of the type whose metadata accessor starts at the + /// runtime `address`. + func descriptorLocation(ofAccessorAt address: UInt) -> CodeLocation? { + descriptorsByAccessor[address].map(location(ofRuntimeAddress:)) + } + + /// Whether a type context descriptor of this image lies at the runtime + /// `address`. + func describesType(descriptorAt address: UInt) -> Bool { + descriptorsByRuntimeAddress[address] != nil + } + + /// The runtime address of the metadata accessor of the type whose + /// descriptor lies at the runtime `descriptor`. + func accessorAddress(ofDescriptorAt descriptor: UInt) -> UInt? { + guard descriptorsByRuntimeAddress[descriptor] != nil, let field = UnsafeRawPointer(bitPattern: descriptor &+ 12) else { return nil } + let relative = field.loadUnaligned(as: Int32.self) + return relative == 0 ? nil : UInt(bitPattern: Int(bitPattern: descriptor &+ 12) &+ Int(relative)) + } + + /// The key of the type whose descriptor lies at the runtime `address`, + /// `7SwiftUI4TextV`: the type its `…Mn` symbol names, demangled and + /// mangled again, so that it is spelled as the keys of demangled names + /// and symbols are. Without a symbol, the descriptor's context is + /// demangled instead, which spells a type in a constrained extension with + /// the extension's requirements (`7SwiftUI7ForEachVAASkRzSHR_rlE16PlaceholderViewsV` + /// for the symbol's `7SwiftUI7ForEachVAAE16PlaceholderViewsV`, 58 of + /// SwiftUICore's accessor calls) and loses a private type an extension of + /// another module's type holds — Foundation's + /// `Mutex<…>.LockResult` comes out as `15Synchronization5MutexV`. + func key(ofDescriptorAt address: UInt) -> String? { + guard let wrapper = descriptorsByRuntimeAddress[address] else { return nil } + lock.lock() + if let known = keysByDescriptor[address] { + lock.unlock() + return known + } + lock.unlock() + var key: String? + // Demangled for the key alone: the shared `NodeCache` would keep + // every type's tree for the life of the process. + if let symbol = descriptorSymbols()[address], let node = try? demangleAsNodeTransient(symbol) { + key = CrossReferenceAnalyzer.nominalKeys(in: node).first + } + if key == nil, let contextNode = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: image.context) { + key = try? mangleAsString(NodeBuilder(kind: .type, children: [contextNode]).node) + } + lock.lock() + keysByDescriptor[address] = key + lock.unlock() + return key + } + + /// The `$s…Mn` symbol at each descriptor, from the symbol table and the + /// export trie, without the leading underscore; read on first use. + private func descriptorSymbols() -> [UInt: String] { + lock.lock() + defer { lock.unlock() } + if let descriptorSymbolsStorage { return descriptorSymbolsStorage } + var symbols: [UInt: String] = [:] + func consider(_ name: UnsafePointer, at address: UInt) { + guard symbols[address] == nil, descriptorsByRuntimeAddress[address] != nil, name[0] == 0x5F, name[1] == 0x24 else { return } + let length = strlen(name) + guard length > 4, name[length - 2] == 0x4D, name[length - 1] == 0x6E else { return } + symbols[address] = String(cString: name + 1) + } + if let symbolTable = image.symbols64 { + for symbolIndex in 0 ..< symbolTable.numberOfSymbols { + let entry = symbolTable.symbols[symbolIndex] + // Defined in a section, not a debugging entry. + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E else { continue } + consider(symbolTable.stringBase.advanced(by: Int(entry.n_un.n_strx)), at: UInt(bitPattern: Int(bitPattern: UInt(entry.n_value)) &+ slide)) + } + } + let base = UInt(bitPattern: image.ptr) + for exported in image.exportedSymbols { + guard let offset = exported.offset, exported.name.hasSuffix("Mn") else { continue } + exported.name.withCString { consider($0, at: base &+ UInt(bitPattern: offset)) } + } + descriptorSymbolsStorage = symbols + return symbols + } + + /// Where the types whose key is `key` lie. Only the types whose + /// descriptors give them the name the key ends in — `Text` for + /// `7SwiftUI4TextV` — have their keys built and compared: building every + /// type's key, a demangle each, took AppKit's first lookup 0.7 s in a + /// debug build. A key whose name cannot be read is compared with every + /// type's. + func descriptorLocations(withKey key: String) -> [CodeLocation] { + var candidates = Array(descriptorsByRuntimeAddress.keys) + if let typeName = Self.typeName(inKey: key) { + candidates = typeName.withCString { wantedName in + candidates.filter { Self.descriptor(at: $0, isNamed: wantedName) } + } + } + return candidates.compactMap { address in + self.key(ofDescriptorAt: address) == key ? location(ofRuntimeAddress: address) : nil + } + } + + /// Whether the descriptor at the runtime `address` gives its type the + /// name `wantedName`: the name it is declared with, or — for a type + /// imported from C or Objective-C under another Swift name — the name it + /// has there, which a key spells and the descriptor's import info keeps + /// after the name: `ResponseDisposition`, then + /// `NNSURLSessionResponseDisposition`. + static func descriptor(at address: UInt, isNamed wantedName: UnsafePointer) -> Bool { + guard let name = name(ofDescriptorAt: address) else { return false } + if strcmp(name, wantedName) == 0 { return true } + guard hasImportInfo(descriptorAt: address) else { return false } + // Null-terminated strings, each starting with a tag, until an empty one. + var component = name + strlen(name) + 1 + while component[0] != 0 { + if component[0] == 0x4E /* N: the ABI name */, strcmp(component + 1, wantedName) == 0 { return true } + component += strlen(component) + 1 + } + return false + } + + /// `TypeContextDescriptorFlags::HasImportInfo`: the third of the + /// kind-specific flags, the upper half of the descriptor's first word. + private static func hasImportInfo(descriptorAt address: UInt) -> Bool { + guard let descriptor = UnsafeRawPointer(bitPattern: address) else { return false } + return descriptor.loadUnaligned(as: UInt32.self) & (1 << 18) != 0 + } + + /// The name the key's type is declared with — `Text` for + /// `7SwiftUI4TextV`, `Storage` for a private or a local `Storage` — which + /// is the name its descriptor gives it. Demangled for this call alone. + static func typeName(inKey key: String) -> String? { + // Global › TypeMetadata › Type › the nominal type: context, name. + guard let node = try? demangleAsNodeTransient("$s" + key + "N"), + let nominal = node.children.first?.children.first?.children.first, + nominal.children.count >= 2 + else { return nil } + let nameNode = nominal.children[1] + switch nameNode.kind { + case .identifier: + return nameNode.text + case .privateDeclName, .localDeclName: + return nameNode.children.last?.text + default: + return nil + } + } + + /// Reads the descriptors' symbols now, which the first key built would. + func readDescriptorSymbols() { + _ = descriptorSymbols() + } + + /// Where every type's descriptor lies; for tests. + var descriptorAddresses: [UInt] { + Array(descriptorsByRuntimeAddress.keys) + } + + /// Whether the descriptors' symbols have been read, and how many keys + /// are built; for tests. + var builtState: (hasReadDescriptorSymbols: Bool, keyCount: Int, typeCount: Int) { + lock.lock() + defer { lock.unlock() } + return (descriptorSymbolsStorage != nil, keysByDescriptor.count, descriptorsByRuntimeAddress.count) + } + + /// The memory the index takes, with the symbols read and the keys built; + /// see `ApproximateSize`. + var approximateByteCount: Int { + lock.lock() + defer { lock.unlock() } + var byteCount = ApproximateSize.of(descriptorsByRuntimeAddress) + ApproximateSize.of(descriptorsByAccessor) + ApproximateSize.of(keysByDescriptor) + byteCount = keysByDescriptor.values.reduce(byteCount) { $0 + ($1.map(ApproximateSize.of) ?? 0) } + if let descriptorSymbolsStorage { + byteCount = descriptorSymbolsStorage.values.reduce(byteCount + ApproximateSize.of(descriptorSymbolsStorage)) { $0 + ApproximateSize.of($1) } + } + return byteCount + } + + /// The name a descriptor gives its type, `Text` — for a type declared in + /// Swift, the last component of its key — read without demangling. + static func name(ofDescriptorAt address: UInt) -> UnsafePointer? { + guard let field = UnsafeRawPointer(bitPattern: address &+ 8) else { return nil } + let relative = field.loadUnaligned(as: Int32.self) + guard relative != 0 else { return nil } + return UnsafePointer(bitPattern: UInt(bitPattern: Int(bitPattern: address &+ 8) &+ Int(relative))) + } + + func location(ofRuntimeAddress address: UInt) -> CodeLocation { + CodeLocation(imageIndex: imageIndex, address: UInt64(bitPattern: Int64(bitPattern: UInt64(address)) &- Int64(slide))) + } +} diff --git a/Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift b/Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift index 008cd7d3b..c0db1594b 100644 --- a/Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift +++ b/Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift @@ -12,16 +12,20 @@ import MachOSwiftSection /// once, here, instead of every index spelling the `MachOFile` / /// `MachOImage` split itself. Passing the existential to a `some`-typed /// build opens it (SE-0352), so the builds stay generic. +/// +/// A host's `MachOReaderWrapper` is re-typed as the reader beneath it where +/// it cannot answer itself: `ObjCImplementationClassReading` is this +/// module's own, so no wrapper outside it can conform. extension MachORepresentableWithCache { - /// `self` as a Swift-section reader, or `nil` for a reader of another - /// kind. + /// `self` as a Swift-section reader — or the reader beneath its wrappers + /// when `self` is not one — or `nil` for a reader of another kind. var swiftSectionReader: (any MachOSwiftSectionRepresentableWithCache)? { - self as? any MachOSwiftSectionRepresentableWithCache + (self as? any MachOSwiftSectionRepresentableWithCache) ?? (underlyingReader as? any MachOSwiftSectionRepresentableWithCache) } - /// `self` as the reader the ObjC-side indexes build from, or `nil` for - /// a reader of another kind. + /// The reader the ObjC-side indexes build from — `self`, or the reader + /// beneath its wrappers — or `nil` for a reader of another kind. var objcImplementationClassReader: (any ObjCImplementationClassReading & MachOSwiftSectionRepresentableWithCache)? { - self as? any ObjCImplementationClassReading & MachOSwiftSectionRepresentableWithCache + underlyingReader as? any ObjCImplementationClassReading & MachOSwiftSectionRepresentableWithCache } } diff --git a/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift b/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift index 74563b2f8..6b456300a 100644 --- a/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift +++ b/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift @@ -195,16 +195,16 @@ public final class ObjCAncestorResolverStore: @unchecked Sendable { ?? ObjCAncestorResolver(inProcessRoot: machOImage) } - /// The resolver for whichever reader kind `machO` is; `nil` for a reader - /// of another kind. (Named apart from ``resolver(for:)`` on purpose — a - /// same-labelled generic overload resolved to itself from inside the - /// cast and recursed.) + /// The resolver for whichever reader kind `machO` reads through — itself, + /// or the reader beneath its wrappers; `nil` for a reader of another kind. + /// (Named apart from ``resolver(for:)`` on purpose — a same-labelled + /// generic overload resolved to itself from inside the cast and recursed.) func resolver(forImage machO: some MachORepresentableWithCache) -> ObjCAncestorResolver? { - if let machOFile = machO as? MachOFile { + if let machOFile = machO.asMachOFile { let fileResolver: ObjCAncestorResolver = resolver(for: machOFile) return fileResolver } - if let machOImage = machO as? MachOImage { + if let machOImage = machO.asMachOImage { let imageResolver: ObjCAncestorResolver = resolver(for: machOImage) return imageResolver } diff --git a/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift b/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift index 2986b1da0..d260578bc 100644 --- a/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift +++ b/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift @@ -158,9 +158,9 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { /// it — or `nil` when there is neither, or no ObjC method of its own /// (nothing to attribute — the ancestor walk is skipped). package func hierarchy(forRuntimeName runtimeName: String, in machO: some MachORepresentableWithCache) -> ObjCClassHierarchy? { - if let machOFile = machO as? MachOFile { + if let machOFile = machO.asMachOFile { return hierarchy(forRuntimeName: runtimeName, reader: machOFile) - } else if let machOImage = machO as? MachOImage { + } else if let machOImage = machO.asMachOImage { return hierarchy(forRuntimeName: runtimeName, reader: machOImage) } return nil @@ -393,10 +393,10 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { } private func folding(for machO: some MachORepresentableWithCache, resolver: ObjCAncestorResolver?) -> AncestorCategoryFolding? { - if let machOFile = machO as? MachOFile, let storage = storage(in: machOFile) { + if let machOFile = machO.asMachOFile, let storage = storage(in: machOFile) { return AncestorCategoryFolding(rootReader: machOFile, rootStorage: storage, resolver: resolver) } - if let machOImage = machO as? MachOImage, let storage = storage(in: machOImage) { + if let machOImage = machO.asMachOImage, let storage = storage(in: machOImage) { return AncestorCategoryFolding(rootReader: machOImage, rootStorage: storage, resolver: resolver) } return nil diff --git a/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift b/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift new file mode 100644 index 000000000..a81c0c00f --- /dev/null +++ b/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift @@ -0,0 +1,139 @@ +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import MachOSymbols + +/// Which of a protocol's own associated types are declared `~Copyable` or +/// `~Escapable` (SE-0503), inferred from the image's extensions of the +/// protocol (evolution proposal `borrow-accessors-and-suppressed-associated-types`). +/// +/// The binary does not record the declaration itself. IRGen encodes an +/// inverted-protocols requirement only for a generic parameter and drops the +/// one `associatedtype Element: ~Copyable` states (`addGenericRequirements` +/// skips a subject that does not reduce to a generic parameter), and the +/// protocol's requirement symbols do not mangle it either — the descriptor of +/// `protocol P { associatedtype Element: ~Copyable }` reads exactly like the +/// one without the suppression. +/// +/// What survives is an extension that suppresses the default an extension of +/// the protocol would otherwise get: `extension P where Element: ~Copyable` +/// mangles `Self.Element: ~Swift.Copyable` into every member's context. SE-0503 +/// rejects that inverse unless the protocol declares `Element` suppressible, so +/// one such signature proves the declaration. The inference therefore has +/// positive evidence only — an associated type no extension suppresses keeps +/// the default reading, which can be wrong, but nothing reads as `~Copyable` +/// that is not. +/// +/// Only a PRIMARY associated type (`protocol P`) can leave that +/// evidence: SE-0503 gives an extension the default `Element: Copyable` for +/// primary associated types alone, so `where Strategy: ~Copyable` on an +/// ordinary one suppresses nothing and mangles to nothing. +package enum SuppressedAssociatedTypeInference { + /// The member kinds an extension of a protocol can hold. + private static let extensionMemberKinds: [SymbolIndexStore.MemberKind] = SymbolIndexStore.MemberKind.allCases.filter(\.isInExtension) + + /// The suppressed invertible protocols of `descriptor`'s own associated + /// types, by associated type name; an associated type without evidence + /// has no entry. Empty when the protocol declares no associated types or + /// its context does not demangle. + package static func suppressedInvertibleProtocolsByAssociatedTypeName( + of descriptor: ProtocolDescriptor, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> [String: InvertibleProtocolSet] { + guard let associatedTypeNames = try? descriptor.associatedTypes(in: machO.context), !associatedTypeNames.isEmpty, + let protocolNode = try? SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: machO.context) + else { return [:] } + return suppressedInvertibleProtocolsByAssociatedTypeName( + ofAssociatedTypesNamed: Set(associatedTypeNames), + protocolNode: protocolNode, + in: machO + ) + } + + /// The same, for a caller already holding the protocol's context node + /// (`type(protocol(…))`, as `SymbolicDemangler.demangleContext` returns + /// it) and its associated type names. + package static func suppressedInvertibleProtocolsByAssociatedTypeName( + ofAssociatedTypesNamed associatedTypeNames: Set, + protocolNode: Node, + in machO: some MachORepresentableWithCache + ) -> [String: InvertibleProtocolSet] { + guard !associatedTypeNames.isEmpty else { return [:] } + let typeNode = protocolNode.kind == .type ? protocolNode : Node.createTransient(kind: .type, child: protocolNode) + let protocolName = typeNode.print(using: .interfaceTypeBuilderOnly) + var result: [String: InvertibleProtocolSet] = [:] + for kind in extensionMemberKinds { + for memberSymbol in SymbolIndexStore.shared.memberSymbols(of: kind, for: protocolName, node: typeNode, in: machO) { + // The member's context is the first `extension` in preorder: + // its own entity's first child, ahead of every type the + // signature or the member's type mentions. + guard let extensionNode = memberSymbol.demangledNode.first(of: .extension), + let genericSignature = extensionNode.children.at(2), genericSignature.kind == .dependentGenericSignature + else { continue } + for requirement in genericSignature.children where requirement.kind == .dependentGenericInverseConformanceRequirement { + guard let suppressed = suppressedProtocol(of: requirement), + let associatedTypeName = selfAssociatedTypeName(of: requirement, protocolName: protocolName), + associatedTypeNames.contains(associatedTypeName) + else { continue } + result[associatedTypeName, default: []].insert(suppressed) + } + } + } + return result + } + + /// `Swift.Copyable` is inverse index 0, `Swift.Escapable` index 1 — the + /// order the demangler prints them in. + private static func suppressedProtocol(of requirement: some DemanglingNode) -> InvertibleProtocolSet? { + switch requirement.children.at(1)?.index { + case 0: .copyable + case 1: .escapable + default: nil + } + } + + /// `X` when the requirement's subject is `Self.X` — the protocol's own + /// generic parameter, depth 0 index 0, one member deep — and the + /// associated type reference, if it names a protocol at all, names this + /// one. A deeper path (`Self.X.Y`) says nothing about the protocol's own + /// declarations. + private static func selfAssociatedTypeName(of requirement: some DemanglingNode, protocolName: String) -> String? { + guard var subject = requirement.children.first else { return nil } + if subject.kind == .type, let unwrapped = subject.children.first { + subject = unwrapped + } + guard subject.kind == .dependentMemberType, + var base = subject.children.first, + let associatedTypeReference = subject.children.at(1), associatedTypeReference.kind == .dependentAssociatedTypeRef + else { return nil } + if base.kind == .type, let unwrapped = base.children.first { + base = unwrapped + } + guard base.kind == .dependentGenericParamType, + base.children.at(0)?.index == 0, + base.children.at(1)?.index == 0 + else { return nil } + // `type(protocol(…))` prints the same name with or without its + // `type` wrapper, so the comparison needs no normalizing. + if let referencedProtocol = associatedTypeReference.children.at(1), + referencedProtocol.print(using: .interfaceTypeBuilderOnly) != protocolName { + return nil + } + return associatedTypeReference.children.first?.text + } +} + +extension SymbolIndexStore.MemberKind { + fileprivate var isInExtension: Bool { + switch self { + case .allocator(let inExtension), + .constructor(let inExtension), + .subscript(let inExtension, _), + .variable(let inExtension, _, _), + .function(let inExtension, _): + inExtension + case .deallocator, + .destructor: + false + } + } +} diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index a2c7bd3a6..ab44634e4 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -74,6 +74,14 @@ extension SymbolicDemangler { package static func cacheExists(for machO: some MachOSwiftSectionRepresentableWithCache) -> Bool { SymbolicDemanglerCache.shared.contains(in: machO) } + + /// Non-creating membership probe for the process-wide memo that + /// `demangleType(for:in:)` fills for an in-process context, which is + /// never evicted — test-support surface for the callers that must not + /// leave a tree in it (`CrossReferenceAnalyzer.swiftTypeKeys(in:)`). + package static func processScopedMemoHoldsType(for mangledName: MangledName) -> Bool { + SymbolicDemanglerCache.shared.processScopedMemoHoldsType(for: mangledName) + } } extension SymbolicDemangler { @@ -415,6 +423,30 @@ extension SymbolicDemangler { } } + /// The `Node.index` an `opaqueTypeDescriptorSymbolicReference` carries for + /// the descriptor at `offset`. + /// + /// Wherever `context` is mapped into this process — `InProcessContext`, an + /// in-process `MachOImage`, or a reader wrapping one — the index is the + /// descriptor's absolute address, the Swift runtime's own scheme + /// (`(ContextDescriptor *)demangleNode->getIndex()`, + /// `stdlib/public/runtime/MetadataLookup.cpp`): a descriptor in another + /// loaded image is then the same kind of value, and the rewriter reads the + /// whole opaque-type chain through `InProcessContext`. Off-process the index + /// is the offset itself. Whoever reads the index back tells the two apart by + /// asking its reader the question `MachOContext.runtimePointer(at:)` is built + /// on, `asMachOImage`. + /// + /// `nil` when the offset can be no index: a negative one, which only a + /// reader of this process's memory that never says so produces — the + /// reference is left unresolved rather than trapping. + private static func opaqueTypeDescriptorReferenceIndex(forDescriptorAt offset: Int, in context: some ReadingContext) throws -> UInt64? { + if let runtimePointer = try context.runtimePointer(at: context.addressFromOffset(offset)) { + return UInt64(UInt(bitPattern: runtimePointer)) + } + return UInt64(exactly: offset) + } + private static func demangle(for mangledName: MangledName, kind: MangledNameKind, in context: some ReadingContext) throws -> Node { let stringValue = switch kind { case .type: @@ -433,27 +465,11 @@ extension SymbolicDemangler { switch kind { case .context: switch directness { - // ABI convention for `opaqueTypeDescriptorSymbolicReference` Node.index: - // * MachOContext path: ALWAYS the descriptor's *absolute* - // in-process pointer bit pattern (`machO.ptr + opaqueTypeDescriptor.offset`). - // This unifies in-image and cross-image refs at the Node level so the - // downstream rewriter can drive the entire opaque-type chain through - // `InProcessContext`, matching the Swift runtime's own scheme of - // `(ContextDescriptor *)demangleNode->getIndex()` (see - // swift/stdlib/public/runtime/MetadataLookup.cpp). Cross-image refs - // (e.g. an indirect cell whose pointer lands in another loaded image) - // work transparently because the InProcess pipeline only ever - // dereferences pointers — there is no per-image "file offset" scale. - // * MachOFile / other contexts: keep the legacy file-offset semantic. case .direct: if let contextWrapper = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(at: baseAddress, in: context) { if let opaqueTypeDescriptor = contextWrapper.opaqueTypeDescriptor { - if let machOImageContext = context as? MachOContext { - let absoluteAddress = machOImageContext.machO.ptr.bitPattern.int + opaqueTypeDescriptor.offset - result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: UInt64(absoluteAddress)) - } else { - result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: opaqueTypeDescriptor.offset.cast()) - } + guard let referenceIndex = try opaqueTypeDescriptorReferenceIndex(forDescriptorAt: opaqueTypeDescriptor.offset, in: context) else { return nil } + result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: referenceIndex) } else { result = try buildContextMangling(context: .element(contextWrapper), in: context) } @@ -462,12 +478,8 @@ extension SymbolicDemangler { let relativePointer = RelativeIndirectSymbolOrElementPointer(relativeOffset: relativeOffset) if let resolvableElement = try relativePointer.resolve(at: baseAddress, in: context).asOptional { if case .element(let element) = resolvableElement, let opaqueTypeDescriptor = element.opaqueTypeDescriptor { - if let machOImageContext = context as? MachOContext { - let absoluteAddress = machOImageContext.machO.ptr.bitPattern.int + opaqueTypeDescriptor.offset - result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: UInt64(absoluteAddress)) - } else { - result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: opaqueTypeDescriptor.offset.cast()) - } + guard let referenceIndex = try opaqueTypeDescriptorReferenceIndex(forDescriptorAt: opaqueTypeDescriptor.offset, in: context) else { return nil } + result = .createTransient(kind: .opaqueTypeDescriptorSymbolicReference, index: referenceIndex) } else { result = try buildContextMangling(context: resolvableElement, in: context) } @@ -477,7 +489,8 @@ extension SymbolicDemangler { // The symbolic reference points at a resolver function, but we can't // execute code in the target process to resolve it from here. let rawPointerOffset = try RelativeDirectRawPointer(relativeOffset: relativeOffset).resolveDirectAddress(at: context.addressFromOffset(offset), in: context) - result = try .createTransient(kind: .accessorFunctionReference, index: context.offsetFromAddress(rawPointerOffset).cast()) + guard let referenceIndex = try UInt64(exactly: context.offsetFromAddress(rawPointerOffset)) else { return nil } + result = .createTransient(kind: .accessorFunctionReference, index: referenceIndex) case .uniqueExtendedExistentialTypeShape: let extendedExistentialTypeShape = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(at: baseAddress, in: context) let existentialType = try extendedExistentialTypeShape.existentialType(in: context) @@ -1149,6 +1162,10 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { cache.contains(in: machO) } + fileprivate func processScopedMemoHoldsType(for mangledName: MangledName) -> Bool { + Self.processScopedStorage.nodeReferenceForMangledNameBox[MangledNameBox(mangledName)] != nil + } + /// `InProcessContext`'s discriminator lookup, memoized as text. Only an /// `identifier` — what the lookup returns for every discriminator it /// finds — is memoized; a hit rebuilds the same node. diff --git a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift index 451ce46aa..88f4a9aee 100644 --- a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift +++ b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift @@ -4,8 +4,9 @@ import Demangling /// A per-image index of the `__swift5_builtin` section's `BuiltinTypeDescriptor` /// records, keyed by the type's fully-qualified name (e.g. `"__C.CGRect"`, -/// `"SymbolTestsCore.Enums.MultiPayloadEnumTests"`), each carrying the statically -/// embedded `(size, stride, alignment, extra inhabitants)`. +/// `"SymbolTestsCore.Enums.MultiPayloadEnumTests"`) — or, for a builtin leaf +/// type, by the builtin's own name (`"Builtin.Int1"`) — each carrying the +/// statically embedded `(size, stride, alignment, extra inhabitants)`. /// /// The compiler emits a builtin descriptor for a type whose layout the /// reflection reader cannot derive structurally — imported C value types and @@ -16,6 +17,14 @@ import Demangling /// whole-type layout for those types, which the resolver consults before its /// structural paths. /// +/// libswiftCore additionally records the compiler's builtin leaf types +/// (`Builtin.Int1`, `Builtin.BridgeObject`, `Builtin.FPIEEE16`, …), the +/// layouts every standard library type bottoms out in: IRGen collects the +/// builtin types a field mentions only while compiling the standard library +/// (`GenReflection.cpp`, `addBuiltinTypeRefs`). Every other image declaring +/// builtin-typed fields (`_Concurrency`) carries none of them; the resolver +/// answers those from its own fallback. +/// /// A **generic** multi-payload enum gets a record exactly when its layout is /// argument-independent (statically fixed — every payload's layout resolves /// without an argument), in which case the record's quintuple holds for the @@ -24,12 +33,14 @@ import Demangling /// fixed-vs-runtime-tagged verdict, and the generic-argument-free key below is /// safe for instantiated lookups. /// -/// The descriptor's `typeName` is a **symbolic reference** (a relative pointer -/// to the type's context descriptor), so its raw string is empty; the name is -/// recovered by demangling, then keyed with the same `nominalQualifiedName` -/// formatting the resolver looks types up by. +/// A nominal type's descriptor `typeName` is a **symbolic reference** (a +/// relative pointer to the type's context descriptor), so its raw string is +/// empty; the name is recovered by demangling, then keyed with the same +/// `nominalQualifiedName` formatting the resolver looks types up by. A builtin +/// leaf's is a plain mangling (`Bi1_`), keyed by the name it demangles to — +/// the spelling the resolver looks a `.builtinTypeName` node up by. public struct BuiltinTypeLayoutIndex: Sendable { - private let layoutsByQualifiedName: [String: StaticTypeLayout] + private let layoutsByTypeName: [String: StaticTypeLayout] public init(machO: some MachOSwiftSectionRepresentableWithCache) throws { var index: [String: StaticTypeLayout] = [:] @@ -55,14 +66,16 @@ public struct BuiltinTypeLayoutIndex: Sendable { // plain nominal references and enter the map under the // generic-argument-free name the resolver looks types up by. if let demangledNode, Self.isConcreteBoundGenericReference(demangledNode) { continue } - let qualifiedName: String + let typeName: String if let demangledNode, let nominalQualifiedName = NodeTypeNaming.nominalQualifiedName(of: demangledNode) { - qualifiedName = nominalQualifiedName + typeName = nominalQualifiedName + } else if let demangledNode, let builtinTypeName = Self.builtinTypeName(of: demangledNode) { + typeName = builtinTypeName } else { // Fall back to the raw string for any plain-named entry. let rawName = mangledTypeName.typeString guard !rawName.isEmpty else { continue } - qualifiedName = rawName + typeName = rawName } let layout = StaticTypeLayout( size: Int(descriptor.layout.size), @@ -73,11 +86,19 @@ public struct BuiltinTypeLayoutIndex: Sendable { ) // First writer wins: qualified names are unique per declaration // (instantiation-specific records are skipped above). - if index[qualifiedName] == nil { - index[qualifiedName] = layout + if index[typeName] == nil { + index[typeName] = layout } } - self.layoutsByQualifiedName = index + self.layoutsByTypeName = index + } + + /// The name of a builtin type reference (`Builtin.Int1` for `Bi1_`), or + /// `nil` for any other type. + private static func builtinTypeName(of node: Node) -> String? { + let typeNode = node.kind == .type ? node.firstChild : node + guard let typeNode, typeNode.kind == .builtinTypeName else { return nil } + return typeNode.text } /// Whether a demangled type reference is a concrete bound-generic @@ -95,9 +116,10 @@ public struct BuiltinTypeLayoutIndex: Sendable { return node.first(where: { $0.kind == .dependentGenericParamType }) == nil } - /// Returns the embedded whole-type layout for a fully-qualified type name, or - /// `nil` if this image emits no builtin descriptor for it. + /// Returns the embedded whole-type layout for a fully-qualified type name or + /// a builtin type name (`"Builtin.Int1"`), or `nil` if this image emits no + /// builtin descriptor for it. public func layout(forTypeName qualifiedTypeName: String) -> StaticTypeLayout? { - layoutsByQualifiedName[qualifiedTypeName] + layoutsByTypeName[qualifiedTypeName] } } diff --git a/Sources/Analysis/SwiftLayout/ImageReference.swift b/Sources/Analysis/SwiftLayout/ImageReference.swift index 3caee7a7b..3606fb25d 100644 --- a/Sources/Analysis/SwiftLayout/ImageReference.swift +++ b/Sources/Analysis/SwiftLayout/ImageReference.swift @@ -145,40 +145,40 @@ public final class ImageReference [String: (instanceSize: Int, alignmentMask: Int)] { - if let inProcessImage = machO as? MachOImage { + if let inProcessImage = machO.asMachOImage { return ObjCClassIndex.instanceSizesByBareName(in: inProcessImage) } - if let fileImage = machO as? MachOFile { + if let fileImage = machO.asMachOFile { return ObjCClassIndex.instanceSizesByBareName(in: fileImage) } return [:] } /// Builds the Swift-qualified-name → own-`instanceStart` index for the - /// image's statically-emitted Swift classes, dispatching to the concrete - /// `MachOImage` / `MachOFile` ObjC reader. + /// image's statically-emitted Swift classes, dispatching to the + /// `MachOImage` / `MachOFile` ObjC reader the reader reads through. private static func swiftClassInstanceStarts(in machO: MachO) -> [String: Int] { - if let inProcessImage = machO as? MachOImage { + if let inProcessImage = machO.asMachOImage { return ObjCClassIndex.swiftClassInstanceStartsByQualifiedName(in: inProcessImage) } - if let fileImage = machO as? MachOFile { + if let fileImage = machO.asMachOFile { return ObjCClassIndex.swiftClassInstanceStartsByQualifiedName(in: fileImage) } return [:] } /// Builds the Swift-qualified-name index of the image's `@objc` protocol - /// declarations, dispatching to the concrete `MachOImage` / `MachOFile` - /// ObjC reader. A reader the engine does not recognize (or an image with - /// no ObjC protocols) contributes nothing. + /// declarations, dispatching to the `MachOImage` / `MachOFile` ObjC reader + /// the reader reads through. Any other reader (or an image with no ObjC + /// protocols) contributes nothing. private static func objCProtocolQualifiedNames(in machO: MachO) -> Set { - if let inProcessImage = machO as? MachOImage { + if let inProcessImage = machO.asMachOImage { return ObjCProtocolIndex.qualifiedNames(in: inProcessImage) } - if let fileImage = machO as? MachOFile { + if let fileImage = machO.asMachOFile { return ObjCProtocolIndex.qualifiedNames(in: fileImage) } return [] diff --git a/Sources/Analysis/SwiftLayout/KnownLayoutTable.swift b/Sources/Analysis/SwiftLayout/KnownLayoutTable.swift index 0c825d0df..1b3262ed6 100644 --- a/Sources/Analysis/SwiftLayout/KnownLayoutTable.swift +++ b/Sources/Analysis/SwiftLayout/KnownLayoutTable.swift @@ -15,6 +15,12 @@ /// none. Exactness matters beyond display — a single-payload enum's size /// depends on whether its empty cases fit the payload's extra inhabitants, so /// an under- or over-estimate here moves real field offsets. +/// +/// The table is a fast path, not a second source of truth: every entry is what +/// libswiftCore's own metadata computes — its field records laid out down to +/// its builtin leaf records — and `StandardLibraryLeafLayoutTests` requires +/// exactly that. It stays in front of the structural path because it answers +/// without reaching libswiftCore, which a single-image scope cannot do. public enum KnownLayoutTable { /// Returns the frozen layout for a fully-qualified type name such as /// `"Swift.Int"`, or `nil` if the type is not a known fixed-layout diff --git a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift index 1fa2f44e2..724768631 100644 --- a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift +++ b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift @@ -329,8 +329,15 @@ final class StaticTypeLayoutResolver StaticTypeLayout? { switch builtinName { case "Builtin.NativeObject", @@ -338,17 +345,37 @@ final class StaticTypeLayoutResolver [ThunkInstruction] { - let capstone = try Capstone(arch: .aarch64, mode: [Mode.endian.little]) - try capstone.set(option: .detail(value: true)) - let decodedInstructions: [AArch64Instruction] = try capstone.disassemble( - code: machineCode, - address: startAddress, - count: maximumInstructionCount - ) - return decodedInstructions.map(thunkInstruction(from:)) + // Each instruction is converted while the disassembler lends it, so + // nothing of Capstone's outlives this call. + let disassembler = try Disassembler() + var thunkInstructions: [ThunkInstruction] = [] + disassembler.forEachInstruction(in: machineCode, address: startAddress, limit: maximumInstructionCount) { instruction in + thunkInstructions.append(thunkInstruction(from: instruction)) + } + return thunkInstructions } - private static func thunkInstruction(from instruction: AArch64Instruction) -> ThunkInstruction { + private static func thunkInstruction(from instruction: borrowing InstructionView) -> ThunkInstruction { ThunkInstruction( address: instruction.address, operation: operation(from: instruction), @@ -130,7 +130,7 @@ public enum CapstoneThunkDecoder { ) } - private static func operation(from instruction: AArch64Instruction) -> ThunkOperation { + private static func operation(from instruction: borrowing InstructionView) -> ThunkOperation { let operation = modelledOperation(from: instruction) if case .unmodelled = operation { return .unmodelled(writtenRegisters: writtenRegisters(of: instruction)) @@ -140,16 +140,16 @@ public enum CapstoneThunkDecoder { /// The general-purpose registers an instruction writes, per the /// disassembler's register-access list (explicit and implicit). - private static func writtenRegisters(of instruction: AArch64Instruction) -> [ThunkRegister] { + private static func writtenRegisters(of instruction: borrowing InstructionView) -> [ThunkRegister] { var registers: [ThunkRegister] = [] - for register in instruction.registersAccessed.written + instruction.registersAccessedImplicitly.written { + for register in instruction.registersAccessed().written + instruction.implicitRegistersWritten { guard let thunkRegister = thunkRegister(from: register), !registers.contains(thunkRegister) else { continue } registers.append(thunkRegister) } return registers } - private static func modelledOperation(from instruction: AArch64Instruction) -> ThunkOperation { + private static func modelledOperation(from instruction: borrowing InstructionView) -> ThunkOperation { let operands = instruction.operands switch semanticInstruction(of: instruction) { case .adrp: @@ -297,25 +297,26 @@ public enum CapstoneThunkDecoder { } } - private static func semanticInstruction(of instruction: AArch64Instruction) -> AArch64Ins? { - // v6 combines an underlying opcode with the displayed alias's operands. - // Match both before interpreting a shortened move or comparison list. - switch (instruction.instruction, instruction.mnemonic) { - case (.orr, "mov"), (.add, "mov"), (.movz, "mov"), (.movn, "mov"): + private static func semanticInstruction(of instruction: borrowing InstructionView) -> AArch64Ins? { + // v6 reports an alias's real opcode with the displayed alias's operands: + // `mov x0, x1` is `orr` with two operands. The alias decides how those + // operands read, for the moves and comparisons this analysis models. + switch instruction.alias { + case .aliasMov: return .mov - case (.subs, "cmp"): + case .aliasCmp: return .aliasCmp default: - return instruction.instruction + return instruction.identifier } } - private static func writesBack(_ instruction: AArch64Instruction) -> Bool { - // v6 exposes post-indexing but no general write-back flag. Pre-indexed - // memory operands retain the `!` marker in Capstone's printed syntax. - // A written base register alone is insufficient: `ldr x0, [x0]` also - // writes its base, through the load destination rather than write-back. - instruction.isPostIndex == true || instruction.operandsString.contains("]!") + private static func writesBack(_ instruction: borrowing InstructionView) -> Bool { + // Capstone's own write-back flag is set for any tied operand (`movk`, + // `cas`); this property is set only when the base register is updated. + // A written base register alone would not do either: `ldr x0, [x0]` + // writes its base through the load destination, not by write-back. + instruction.writesBackBaseRegister } private static func condition(from conditionCode: AArch64CondCode?) -> ThunkCondition { @@ -326,12 +327,12 @@ public enum CapstoneThunkDecoder { } } - private static func register(at index: Int, of operands: [AArch64Instruction.Operand]) -> ThunkRegister? { + private static func register(at index: Int, of operands: [AArch64.Operand]) -> ThunkRegister? { guard index < operands.count, let register = operands[index].register else { return nil } return thunkRegister(from: register) } - private static func immediateValue(at index: Int, of operands: [AArch64Instruction.Operand]) -> Int64? { + private static func immediateValue(at index: Int, of operands: [AArch64.Operand]) -> Int64? { guard index < operands.count, let value = operands[index].immediateValue else { return nil } guard let shift = operands[index].shift else { return value } guard shift.type == .lsl, shift.value < 64 else { return nil } @@ -340,7 +341,7 @@ public enum CapstoneThunkDecoder { private static func memoryOperand( at index: Int, - of instruction: AArch64Instruction + of instruction: borrowing InstructionView ) -> (base: ThunkRegister, displacement: Int64)? { let operands = instruction.operands guard index < operands.count, let memory = operands[index].memory else { return nil } @@ -349,7 +350,7 @@ public enum CapstoneThunkDecoder { guard memory.index == nil, let base = thunkRegister(from: memory.base) else { return nil } // v6 places the post-index update in mem.disp; the access itself still // reads the old base. The evaluator separately refuses write-back. - return (base: base, displacement: instruction.isPostIndex == true ? 0 : memory.displacement) + return (base: base, displacement: instruction.isPostIndex ? 0 : memory.displacement) } /// Folds Capstone's separate 32-bit and 64-bit register spellings onto one diff --git a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift index e439d074b..19de64aa7 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift @@ -29,9 +29,9 @@ package enum ObjCMethodThunkReferences { /// The names of the Swift symbols the IMP at `implementationOffset` /// references, in first-reference order. package static func referencedSwiftSymbolNames(atImplementationOffset implementationOffset: Int, in machO: some MachORepresentableWithCache) -> [String] { - if let machOFile = machO as? MachOFile { + if let machOFile = machO.asMachOFile { return referencedSwiftSymbolNames(atImplementationOffset: implementationOffset, in: machOFile) - } else if let machOImage = machO as? MachOImage { + } else if let machOImage = machO.asMachOImage { return referencedSwiftSymbolNames(atImplementationOffset: implementationOffset, in: machOImage) } return [] diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift index 29c04cf22..8a5b404ff 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import Demangling +import ARM64InstructionDecoding @_spi(Internals) import SwiftInspection @Loggable(.fileprivate, subsystem: "com.machoswiftsection.swift-thunk-analysis", category: "MachOThunkEnvironment") @@ -299,43 +300,28 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun /// has an island's shape: the target computed into a register by /// `adrp` / `add` alone — no load, no call — and a register jump. private func stubIslandTarget(at address: UInt64) -> UInt64? { - guard let offset = addressSpace.offset(forAddress: address), - let bytes: [UInt8] = try? machO.readElements(offset: offset, numberOfElements: 16), - let instructions = try? CapstoneThunkDecoder.decode(machineCode: Data(bytes), startAddress: address, maximumInstructionCount: 4) - else { return nil } - var tracker = ThunkRegisterTracker() - for instruction in instructions { - switch instruction.operation { - case .materializePageAddress, .addImmediate: - tracker.apply(instruction.operation) - case .indirectBranch(let register): - return tracker.address(of: register) - default: - return nil - } - } - return nil + guard case .computed(let target)? = trampoline(at: address) else { return nil } + return target } /// The GOT slot a stub at `address` loads its target from. private func stubSlotAddress(at address: UInt64) -> UInt64? { + guard case .slotLoad(let slotAddress)? = trampoline(at: address) else { return nil } + return slotAddress + } + + /// The trampoline at `address`, read from the file. The shapes are + /// recognized by `ARM64Trampoline`, which `CrossReferenceAnalysis` + /// shares (evolution proposal `cross-reference-analysis`). + private func trampoline(at address: UInt64) -> ARM64Trampoline? { + let byteCount = ARM64Trampoline.maximumInstructionCount * 4 guard let offset = addressSpace.offset(forAddress: address), - let bytes: [UInt8] = try? machO.readElements(offset: offset, numberOfElements: 16), - let instructions = try? CapstoneThunkDecoder.decode(machineCode: Data(bytes), startAddress: address, maximumInstructionCount: 4) + let bytes: [UInt8] = try? machO.readElements(offset: offset, numberOfElements: byteCount), + bytes.count == byteCount else { return nil } - var tracker = ThunkRegisterTracker() - for instruction in instructions { - switch instruction.operation { - case .loadFromMemory(_, let base, let displacement): - guard let baseAddress = tracker.address(of: base) else { return nil } - return baseAddress &+ UInt64(bitPattern: displacement) - case .indirectBranch, .returnFromFunction, .call, .branch: - return nil - default: - tracker.apply(instruction.operation) - } + return bytes.withUnsafeBytes { buffer in + ARM64Trampoline(readingAt: buffer.baseAddress!, address: address) } - return nil } /// The symbol at `offset` when it is a lazily specialized metadata diff --git a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift index a1c09ef7d..e92764d82 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift @@ -9,6 +9,7 @@ import OutputTransformer import SwiftOutputTransformer import SwiftDeclarationRendering import SwiftPrinting +@_spi(Support) import SwiftIndexing import Semantic /// A part of a binary's Swift metadata that `dump` can print. @@ -75,6 +76,14 @@ public struct DumpRequest: Sendable, Equatable { /// A `not exported` comment on member lines whose symbol has no /// export-trie entry. public var emitsExportStatus: Bool + /// A comment above every declaration whose name brings a private + /// discriminator the declaration it is printed inside does not carry, + /// naming the source file the discriminator was derived from — or saying + /// it could not be recovered (evolution proposal + /// `private-declaration-source-files`). Indexes the image and searches + /// every discriminator it declares once, before the first declaration + /// prints: seconds to minutes for a framework the size of SwiftUI. + public var emitsPrivateDeclarationSourceFiles: Bool /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool @@ -96,6 +105,7 @@ public struct DumpRequest: Sendable, Equatable { emitsTypeLayout: Bool = false, emitsEnumLayout: Bool = false, emitsExportStatus: Bool = false, + emitsPrivateDeclarationSourceFiles: Bool = false, emitsHeader: Bool = false, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output @@ -112,6 +122,7 @@ public struct DumpRequest: Sendable, Equatable { self.emitsTypeLayout = emitsTypeLayout self.emitsEnumLayout = emitsEnumLayout self.emitsExportStatus = emitsExportStatus + self.emitsPrivateDeclarationSourceFiles = emitsPrivateDeclarationSourceFiles self.emitsHeader = emitsHeader self.commentTransformers = commentTransformers self.destination = destination @@ -165,6 +176,24 @@ public struct DumpRequest: Sendable, Equatable { ) } + // The index reads its candidates from an indexer, which `dump` does + // without otherwise. It has to live until the dump is done: its last + // release evicts the caches its `prepare()` built, the symbol index + // every member line is read from among them. + var privateDeclarationIndexer: SwiftDeclarationIndexer? + if emitsPrivateDeclarationSourceFiles { + session.output.reportProgress(PrivateDeclarationSourceFileRecovery.progressMessage) + let indexer = SwiftDeclarationIndexer( + configuration: .init(dependencySearchPaths: dependencySearchPaths.indexingSearchPaths), + eventHandlers: session.output.indexEventHandlers(forInputLabeled: nil), + in: machOFile + ) + try await indexer.prepare() + configuration.privateDeclarationSourceFileProvider = PrivateDeclarationSourceFileRecovery.index(searchingEveryDeclarationOf: indexer) + privateDeclarationIndexer = indexer + } + defer { withExtendedLifetime(privateDeclarationIndexer) {} } + if emitsHeader { let headerInfo = InterfaceHeaderInfo( machO: machOFile, diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index af63329c8..7e34ed0f1 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -4,8 +4,8 @@ import MachOFoundation import MachOSwiftSection import SwiftDeclaration import SwiftIndexing -import SwiftPrinting -import SwiftInterface +@_spi(Support) import SwiftPrinting +@_spi(Support) import SwiftInterface import SwiftDeclarationRendering import OutputTransformer import SwiftOutputTransformer @@ -47,6 +47,14 @@ public struct InterfaceRequest: Sendable, Equatable { /// A `not exported` comment on members none of whose symbols has an /// export-trie entry. public var emitsExportStatus: Bool + /// A comment above every declaration whose name brings a private + /// discriminator the declaration it is printed inside does not carry, + /// naming the source file the discriminator was derived from — or saying + /// it could not be recovered (evolution proposal + /// `private-declaration-source-files`). Searches every discriminator the + /// image declares once, after indexing: seconds to minutes for a + /// framework the size of SwiftUI. + public var emitsPrivateDeclarationSourceFiles: Bool /// Only the declarations the image exports: types and protocols whose /// descriptor symbol has an export-trie entry, extensions targeting them, /// and members with at least one exported symbol. `override` / `@objc` @@ -60,6 +68,11 @@ public struct InterfaceRequest: Sendable, Equatable { /// Names qualified with SE-0491 module selectors (`Swift::Int`), as a /// Swift 6.4 `.swiftinterface` spells them. public var usesModuleSelectors: Bool + /// Where a requirement about one of a protocol's own associated types + /// prints: in the protocol's `where` clause, or on that `associatedtype` + /// (`associatedtype Body: SwiftUI.View`). The requirements are the same + /// either way; the binary does not record where the source wrote them. + public var protocolRequirementPlacement: ProtocolRequirementPlacement /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool @@ -78,10 +91,12 @@ public struct InterfaceRequest: Sendable, Equatable { emitsTypeLayout: Bool = false, emitsEnumLayout: Bool = false, emitsExportStatus: Bool = false, + emitsPrivateDeclarationSourceFiles: Bool = false, printsExportedDeclarationsOnly: Bool = false, memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory, infersObjCOverridesFromSelectorNames: Bool = false, usesModuleSelectors: Bool = false, + protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause, emitsHeader: Bool = false, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output @@ -97,10 +112,12 @@ public struct InterfaceRequest: Sendable, Equatable { self.emitsTypeLayout = emitsTypeLayout self.emitsEnumLayout = emitsEnumLayout self.emitsExportStatus = emitsExportStatus + self.emitsPrivateDeclarationSourceFiles = emitsPrivateDeclarationSourceFiles self.printsExportedDeclarationsOnly = printsExportedDeclarationsOnly self.memberSortOrder = memberSortOrder self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames self.usesModuleSelectors = usesModuleSelectors + self.protocolRequirementPlacement = protocolRequirementPlacement self.emitsHeader = emitsHeader self.commentTransformers = commentTransformers self.destination = destination @@ -137,6 +154,7 @@ public struct InterfaceRequest: Sendable, Equatable { // whether it prints as `@objc override`. printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames printConfiguration.usesModuleSelectors = usesModuleSelectors + printConfiguration.protocolRequirementPlacement = protocolRequirementPlacement var configuration = SwiftInterfaceBuilderConfiguration( indexConfiguration: .init( @@ -179,6 +197,11 @@ public struct InterfaceRequest: Sendable, Equatable { try await builder.prepare() + if emitsPrivateDeclarationSourceFiles { + output.reportProgress(PrivateDeclarationSourceFileRecovery.progressMessage) + builder.printer.setPrivateDeclarationSourceFileProvider(PrivateDeclarationSourceFileRecovery.index(searchingEveryDeclarationOf: builder.indexer)) + } + output.reportProgress("Building Swift interface...") let interfaceString = try await builder.printRoot() diff --git a/Sources/Commands/SwiftSectionKit/Swift/PrivateDeclarationSourceFileRecovery.swift b/Sources/Commands/SwiftSectionKit/Swift/PrivateDeclarationSourceFileRecovery.swift new file mode 100644 index 000000000..b551d5b2e --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/PrivateDeclarationSourceFileRecovery.swift @@ -0,0 +1,21 @@ +import MachOKit +@_spi(Support) import SwiftIndexing +@_spi(Support) import SwiftPrivateDiscriminators + +/// What `dump` and `interface` share to name the source files of an image's +/// private declarations (evolution proposal +/// `private-declaration-source-files`). +enum PrivateDeclarationSourceFileRecovery { + /// Said before the search, which is what keeps a large framework silent + /// for a while before its first declaration. + static let progressMessage = "Recovering the source files of private declarations..." + + /// The index of `indexer`'s image, every discriminator the image declares + /// something with already searched for: printing then asks for each + /// declaration's, and every answer is a lookup. + static func index(searchingEveryDeclarationOf indexer: SwiftDeclarationIndexer) -> PrivateDiscriminatorSourceFileIndex { + let index = PrivateDiscriminatorSourceFileIndex(indexer: indexer) + index.recoverSourceFiles(ofEveryDeclarationIn: indexer) + return index + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift index 381450b79..fa6ae9b29 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift @@ -57,7 +57,9 @@ package enum DefinitionBuilder { continue } let nodes = accessors.map(\.symbol.demangledNode) - guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) || !$0.memberSubtree.hasAccessor }) else { continue } + // The declaration prints from a read accessor's node: a getter, or + // the SE-0507 `borrow` that a property declaring it has instead. + guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) || $0.memberSubtree.contains(.borrowAccessor) || !$0.memberSubtree.hasAccessor }) else { continue } var variableDefinition = VariableDefinition(node: node, name: name, accessors: accessors, isGlobalOrStatic: isGlobalOrStatic) if accessors.contains(where: { $0.methodDescriptor?.method?.layout.flags.isDynamic ?? false }) { variableDefinition.attributes.append(.dynamic) @@ -99,7 +101,7 @@ package enum DefinitionBuilder { for (_, accessors) in accessorsByNode { let nodes = accessors.map(\.symbol.demangledNode) - guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) }) else { continue } + guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) || $0.memberSubtree.contains(.borrowAccessor) }) else { continue } var subscriptDefinition = SubscriptDefinition(node: node, accessors: accessors, isStatic: isStatic) if accessors.contains(where: { $0.methodDescriptor?.method?.layout.flags.isDynamic ?? false }) { subscriptDefinition.attributes.append(.dynamic) diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift index 8f6d93d42..adff18ef3 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift @@ -57,7 +57,7 @@ package enum WrappedPropertyRecovery { let skipsFirst = first.kind == .asyncFunctionPointer || first.kind == .asyncSuspendResumePartialFunction || first.kind == .mergedFunction guard let next = skipsFirst ? node.children.dropFirst().first : first else { return nil } node = next - case .static, .getter, .setter, .modifyAccessor, .methodDescriptor: + case .static, .getter, .setter, .modifyAccessor, .borrowAccessor, .mutateAccessor, .methodDescriptor: guard let next = node.firstChild else { return nil } node = next case .protocolWitness: diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift index dec5ebd92..f36cd6154 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift @@ -37,6 +37,11 @@ extension ProtocolDefinition: OnceIndexedDefinition { return nil } associatedTypes = try protocolDescriptor.associatedTypes(in: machO.context) + suppressedInvertibleProtocolsByAssociatedTypeName = SuppressedAssociatedTypeInference.suppressedInvertibleProtocolsByAssociatedTypeName( + ofAssociatedTypesNamed: Set(associatedTypes), + protocolNode: protocolName.node.materialize(), + in: machO + ) var requirementMemberSymbolsByKind: OrderedDictionary = [:] var defaultImplementationMemberSymbolsByKind: OrderedDictionary = [:] diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift index d0d1c4de7..608444e6f 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift @@ -51,6 +51,13 @@ public final class ProtocolDefinition: Definition, MutableDefinition, @unchecked public package(set) var associatedTypes: [String] = [] + /// The invertible protocols each associated type is declared to suppress + /// (`associatedtype Element: ~Copyable`, SE-0503), by name. The binary + /// does not record the declaration, so this holds only what the image's + /// extensions of the protocol prove (`SuppressedAssociatedTypeInference`): + /// an associated type without an entry may still be suppressible. + public package(set) var suppressedInvertibleProtocolsByAssociatedTypeName: [String: InvertibleProtocolSet] = [:] + public package(set) var allocators: [FunctionDefinition] = [] public package(set) var constructors: [FunctionDefinition] = [] diff --git a/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift index 7128014f1..a93ba29df 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift @@ -3,6 +3,12 @@ public enum AccessorKind: Sendable, Codable { case setter case modifyAccessor case readAccessor + /// SE-0507: a `borrow` accessor, which returns a borrow of the stored + /// value instead of a copy (symbol suffix `vb`). + case borrowAccessor + /// SE-0507: a `mutate` accessor, which returns an `inout` projection of + /// the stored value (symbol suffix `vz`). + case mutateAccessor case none /// Label used in address comments. Returns `nil` for stored properties (`.none`). @@ -12,6 +18,8 @@ public enum AccessorKind: Sendable, Codable { case .setter: "setter" case .modifyAccessor: "modify" case .readAccessor: "read" + case .borrowAccessor: "borrow" + case .mutateAccessor: "mutate" case .none: nil } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift b/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift index 74cb94552..3f8c8e4c8 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift @@ -28,6 +28,11 @@ extension AccessorRepresentable { } public var hasSetter: Bool { accessors.contains { $0.kind == .setter } } public var hasModifyAccessor: Bool { accessors.contains { $0.kind == .modifyAccessor } } + /// SE-0507. A `borrow` accessor excludes a declared `get` and a `mutate` + /// requires a `borrow`, so the two decide the accessor block on their + /// own; a getter or setter beside them is one the compiler synthesized. + public var hasBorrowAccessor: Bool { accessors.contains { $0.kind == .borrowAccessor } } + public var hasMutateAccessor: Bool { accessors.contains { $0.kind == .mutateAccessor } } public var hasVTableAccessor: Bool { accessors.contains { $0.methodDescriptor != nil } } } diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift index 3ec37a4db..05ce2080c 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift @@ -11,12 +11,14 @@ extension DemanglingNode where Self: Sequence { /// storage symbol, and the property printed as a computed one (evolution /// proposal `local-type-context-names`). package var accessorKind: AccessorKind { - guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor, .variable, .subscript) else { return .none } + guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor, .borrowAccessor, .mutateAccessor, .variable, .subscript) else { return .none } switch node.kind { case .getter: return .getter case .setter: return .setter case .modifyAccessor: return .modifyAccessor case .readAccessor: return .readAccessor + case .borrowAccessor: return .borrowAccessor + case .mutateAccessor: return .mutateAccessor default: return .none } } diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift index fda686668..44daae8ec 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift @@ -385,12 +385,12 @@ public final class SwiftDeclarationIndexer) -> [String: PrivateDiscriminatorSourceFiles.SourceFile] { let requestedDiscriminators = Set(discriminators) - // Read outside the lock and on a large stack: reading the names - // prints every one of them, and the request may come from a - // cooperative thread's 512 KB stack. One hop for the whole batch; - // a thread that already has the stack reads them where it is. - let readCandidates = imageNamesToRead(forDiscriminators: requestedDiscriminators).map { imageNames in - PrivateDiscriminatorSourceFiles.Candidates(imagePath: imagePath, imageNames: StackSafeExecutor.withLargeStack { imageNames() }) - } + let readCandidates = imageNamesToRead(unlessAnswering: requestedDiscriminators).map(candidates(readingNamesWith:)) lock.lock() defer { lock.unlock() } - // Another first request may have built them meanwhile: those stay, - // and these are dropped. - if candidates == nil, let readCandidates { - candidates = readCandidates - imageNames = nil - } - let unansweredDiscriminators = requestedDiscriminators.filter { answerByDiscriminator[$0] == nil } - if !unansweredDiscriminators.isEmpty, let candidates { - numberOfSearches += 1 - let search = PrivateDiscriminatorSourceFiles(recovering: unansweredDiscriminators, candidates: candidates, knownFileNames: knownFileNames) - // A search also finds the file a synthesized one was made for. - for (discriminator, sourceFile) in search.sourceFileByDiscriminator { - answerByDiscriminator[discriminator] = .recovered(sourceFile) - } - for discriminator in unansweredDiscriminators where answerByDiscriminator[discriminator] == nil { - answerByDiscriminator[discriminator] = .unrecovered - } - } + install(readCandidates) + searchUnanswered(requestedDiscriminators) var sourceFileByDiscriminator: [String: PrivateDiscriminatorSourceFiles.SourceFile] = [:] for discriminator in requestedDiscriminators { if case .recovered(let sourceFile) = answerByDiscriminator[discriminator] { @@ -137,15 +118,96 @@ public final class PrivateDiscriminatorSourceFileIndex: @unchecked Sendable { return sourceFileByDiscriminator } - /// What reads the image's names, when a request for `discriminators` - /// brings one not answered before and the candidates are not built yet. - private func imageNamesToRead(forDiscriminators discriminators: Set) -> (@Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName])? { + /// Searches once for the source file of every discriminator `indexer`'s + /// image declares something with — its types', protocols' and extensions' + /// names, which the index reads anyway, and its members' and globals' — so + /// that asking for any of them afterwards costs a lookup (evolution + /// proposal `private-declaration-source-files`). + /// + /// A printer that names the file of every private declaration it shows + /// calls this first. Asked one declaration at a time, each discriminator + /// nothing recovers would run through every candidate on its own; asked + /// together, they share one pass. The candidates are the same either way. + @_spi(Support) + public func recoverSourceFiles(ofEveryDeclarationIn indexer: SwiftDeclarationIndexer) { + // Outside the lock and on a large stack, like the names: a member + // symbol's node may still have to be demangled. + let declarationDiscriminators = StackSafeExecutor.withLargeStack { Self.memberAndGlobalDiscriminators(in: indexer) } + let readCandidates = imageNamesToRead(unlessAnswering: nil).map(candidates(readingNamesWith:)) lock.lock() defer { lock.unlock() } - guard candidates == nil, discriminators.contains(where: { answerByDiscriminator[$0] == nil }) else { return nil } + install(readCandidates) + let nameDiscriminators = candidates.map { Set($0.identifiersByDiscriminator.keys) } ?? [] + searchUnanswered(nameDiscriminators.union(declarationDiscriminators)) + } + + /// What reads the image's names, when the candidates are not built yet + /// and — for `discriminators` — one of them is not answered either. + private func imageNamesToRead(unlessAnswering discriminators: Set?) -> (@Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName])? { + lock.lock() + defer { lock.unlock() } + guard candidates == nil else { return nil } + if let discriminators, !discriminators.contains(where: { answerByDiscriminator[$0] == nil }) { + return nil + } return imageNames } + /// The candidates the image's names make. Called outside the lock; the + /// names are read on a large stack: reading them prints every one of + /// them, and the request may come from a cooperative thread's 512 KB + /// stack. One hop for the whole batch; a thread that already has the + /// stack reads them where it is. + private func candidates(readingNamesWith imageNames: @escaping @Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName]) -> PrivateDiscriminatorSourceFiles.Candidates { + PrivateDiscriminatorSourceFiles.Candidates(imagePath: imagePath, imageNames: StackSafeExecutor.withLargeStack { imageNames() }) + } + + /// Keeps `readCandidates` unless another first request built them + /// meanwhile: those stay, and these are dropped. Called under the lock. + private func install(_ readCandidates: PrivateDiscriminatorSourceFiles.Candidates?) { + if candidates == nil, let readCandidates { + candidates = readCandidates + imageNames = nil + } + } + + /// Searches for those of `discriminators` not answered before, in one + /// search, and remembers every answer. Called under the lock. + private func searchUnanswered(_ discriminators: Set) { + let unansweredDiscriminators = discriminators.filter { answerByDiscriminator[$0] == nil } + guard !unansweredDiscriminators.isEmpty, let candidates else { return } + numberOfSearches += 1 + let search = PrivateDiscriminatorSourceFiles(recovering: unansweredDiscriminators, candidates: candidates, knownFileNames: knownFileNames) + // A search also finds the file a synthesized one was made for. + for (discriminator, sourceFile) in search.sourceFileByDiscriminator { + answerByDiscriminator[discriminator] = .recovered(sourceFile) + } + for discriminator in unansweredDiscriminators where answerByDiscriminator[discriminator] == nil { + answerByDiscriminator[discriminator] = .unrecovered + } + } + + /// The discriminators of the members and globals `indexer`'s image + /// declares, which no name the index reads has to carry: a file holding + /// only `extension View { private func … }` shows up nowhere else. + private static func memberAndGlobalDiscriminators(in indexer: SwiftDeclarationIndexer) -> Set { + @Dependency(\.symbolIndexStore) + var symbolIndexStore + var discriminators: Set = [] + for memberKind in SymbolIndexStore.MemberKind.allCases { + for memberSymbol in symbolIndexStore.memberSymbols(of: memberKind, in: indexer.machO) { + discriminators.formUnion(memberSymbol.demangledNode.privateDeclarations.map(\.discriminator)) + } + } + for globalVariable in indexer.globalVariableDefinitions { + discriminators.formUnion(globalVariable.node.privateDeclarations.map(\.discriminator)) + } + for globalFunction in indexer.globalFunctionDefinitions { + discriminators.formUnion(globalFunction.node.privateDeclarations.map(\.discriminator)) + } + return discriminators + } + // MARK: - Names of the Image /// The names of every Swift type, protocol and extension `indexer` @@ -203,3 +265,15 @@ public final class PrivateDiscriminatorSourceFileIndex: @unchecked Sendable { names.filter { !$0.isEmpty && !$0.hasPrefix("_Tt") }.map { .init(printedName: $0) } } } + +/// What dump and interface ask for the file a private declaration comes from +/// (evolution proposal `private-declaration-source-files`). A host searches +/// the whole image first — `recoverSourceFiles(ofEveryDeclarationIn:)` — so +/// that each answer is a lookup. +extension PrivateDiscriminatorSourceFileIndex: PrivateDeclarationSourceFileProviding { + public func sourceFile(forPrivateDiscriminator discriminator: String) -> PrivateDeclarationSourceFile? { + sourceFiles(forDiscriminators: CollectionOfOne(discriminator))[discriminator].map { + PrivateDeclarationSourceFile(fileName: $0.fileName, moduleName: $0.moduleName, isSynthesized: $0.isSynthesized) + } + } +} diff --git a/Sources/Executables/swift-section/Commands/DumpCommand.swift b/Sources/Executables/swift-section/Commands/DumpCommand.swift index ef12e0d5c..716b8ec43 100644 --- a/Sources/Executables/swift-section/Commands/DumpCommand.swift +++ b/Sources/Executables/swift-section/Commands/DumpCommand.swift @@ -56,6 +56,9 @@ struct DumpCommand: AsyncParsableCommand, Sendable { @Flag(help: "Annotate member-symbol lines whose symbol has no export-trie entry with a `not exported` comment") var emitExportStatus: Bool = false + @Flag(help: "Comment each declaration whose name carries a private discriminator with the source file the discriminator was derived from (recovered by hashing candidate file names), or say it could not be recovered. Indexes the image and searches every discriminator once before the first declaration prints, which takes a while for a framework the size of SwiftUI") + var emitPrivateSourceFiles: Bool = false + /// The library request these flags describe. func makeRequest() throws -> DumpRequest { DumpRequest( @@ -71,6 +74,7 @@ struct DumpCommand: AsyncParsableCommand, Sendable { emitsTypeLayout: emitTypeLayout, emitsEnumLayout: emitEnumLayout, emitsExportStatus: emitExportStatus, + emitsPrivateDeclarationSourceFiles: emitPrivateSourceFiles, emitsHeader: emitHeader, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 942018a69..904a99c47 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -59,12 +59,18 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Annotate members none of whose symbols have an export-trie entry with a `not exported` comment") var emitExportStatus: Bool = false + @Flag(help: "Comment each declaration whose name carries a private discriminator with the source file the discriminator was derived from (recovered by hashing candidate file names), or say it could not be recovered, with the discriminator. Searches every discriminator of the image once after indexing, which takes a while for a framework the size of SwiftUI") + var emitPrivateSourceFiles: Bool = false + @Flag(name: .customLong("exported-only"), help: "Print only the declarations the image exports: types and protocols whose descriptor symbol has an export-trie entry, extensions targeting them, and members with at least one exported symbol (dispatch-thunk and other derived forms included). `override` / `@objc` members and anything without export evidence are kept.") var exportedOnly: Bool = false @Flag(name: .customLong("module-selectors"), help: "Qualify names with SE-0491 module selectors (Swift::Int instead of Swift.Int), the way the Swift 6.4 compiler writes a .swiftinterface. Every type level carries the module that declared it (Swift::Duration.Foundation::TimeFormatStyle).") var moduleSelectors: Bool = false + @Flag(name: .customLong("requirements-on-associated-types"), help: "Print each protocol requirement about one of the protocol's own associated types on that associatedtype (associatedtype Element: Hashable, associatedtype Nested: Sequence where Self.Nested.Element: Hashable) instead of in the protocol's where clause, the way the compiler writes a .swiftinterface. The requirements are the same either way: the binary records the canonical requirement signature, not where the source wrote each one.") + var requirementsOnAssociatedTypes: Bool = false + @Option(name: .shortAndLong, help: "The color scheme for the output.") var colorScheme: SemanticColorScheme = .none @@ -82,10 +88,12 @@ struct InterfaceCommand: AsyncParsableCommand { emitsTypeLayout: emitTypeLayout, emitsEnumLayout: emitEnumLayout, emitsExportStatus: emitExportStatus, + emitsPrivateDeclarationSourceFiles: emitPrivateSourceFiles, printsExportedDeclarationsOnly: exportedOnly, memberSortOrder: sortMembersByOffset ? .byOffset : .byCategory, infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, usesModuleSelectors: moduleSelectors, + protocolRequirementPlacement: requirementsOnAssociatedTypes ? .associatedTypes : .protocolWhereClause, emitsHeader: emitHeader, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output diff --git a/Sources/Executables/swift-section/Version.swift b/Sources/Executables/swift-section/Version.swift index 0d9f1af2e..98c70d337 100644 --- a/Sources/Executables/swift-section/Version.swift +++ b/Sources/Executables/swift-section/Version.swift @@ -4,5 +4,5 @@ // release with the same string. // Verified by .github/workflows/version-check.yml (PR) and .github/workflows/release.yml (tag). enum BundledVersion { - static let value = "0.23.0" + static let value = "0.24.0" } diff --git a/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift b/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift index 254d0fefd..72db86837 100644 --- a/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift +++ b/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift @@ -86,13 +86,14 @@ public struct MachOContext: Readi address } - /// Vends the underlying MachO object as a bind/rebase resolver when it - /// conforms to `MachOBindRebaseResolving`. The runtime cast keeps the - /// generic parameter `MachO` unconstrained, so wrapper types (e.g. - /// UI-layer projections that compose a `MachOFile`) can opt in by - /// declaring conformance themselves without changing this site. + /// Vends the reader as a bind/rebase resolver when it conforms to + /// `MachOBindRebaseResolving` — or, for a `MachOReaderWrapper` that does + /// not, the reader beneath it. The runtime cast keeps the generic parameter + /// `MachO` unconstrained, so a wrapper type (a UI-layer projection that + /// composes a `MachOFile`) resolves through the file it wraps whether or + /// not it forwards the conformance itself. public var bindRebaseResolver: (any MachOBindRebaseResolving)? { - machO as? any MachOBindRebaseResolving + (machO as? any MachOBindRebaseResolving) ?? (machO.underlyingReader as? any MachOBindRebaseResolving) } /// Offsets are per image, so memo entries belong to this image: keyed on @@ -129,14 +130,13 @@ extension MachORepresentableWithCache where Self: Readable { // MARK: - Runtime Pointer Support extension MachOContext { - /// Returns the runtime pointer for the given file offset when the - /// underlying reader is a `MachOImage` mapped into the current process. - /// Returns `nil` for `MachOFile` and other non-resident readers. + /// Returns the runtime pointer for the given offset when the reader reads + /// through a `MachOImage` mapped into the current process — the image + /// itself, or a `MachOReaderWrapper` of one. Returns `nil` for a + /// `MachOFile` and every other reader not resident here. public func runtimePointer(at address: Int) throws -> UnsafeRawPointer? { - if let machOImage = machO as? MachOImage { - return machOImage.ptr + UnsafeRawPointer.Stride(address) - } - return nil + guard let machOImage = machO.asMachOImage else { return nil } + return machOImage.ptr + UnsafeRawPointer.Stride(address) } } diff --git a/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift b/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift index b455566c1..0a46b2b79 100644 --- a/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift +++ b/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift @@ -255,7 +255,9 @@ public protocol ReadingContext: Sendable { /// when this context is mapped into the current process. /// /// - `InProcessContext`: returns the address itself (already a pointer). - /// - `MachOContext`: returns `machO.ptr + address`. + /// - `MachOContext` over a reader whose `asMachOImage` answers — a + /// `MachOImage`, or a `MachOReaderWrapper` of one: returns + /// `image.ptr + address`. /// - `MachOContext` / other readers: returns `nil`. /// /// Declared as a protocol requirement (with a default `nil` implementation diff --git a/Sources/MachO/MachOSymbols/MachO+Symbol.swift b/Sources/MachO/MachOSymbols/MachO+Symbol.swift index 42c189e5a..90b93e420 100644 --- a/Sources/MachO/MachOSymbols/MachO+Symbol.swift +++ b/Sources/MachO/MachOSymbols/MachO+Symbol.swift @@ -16,7 +16,7 @@ extension MachORepresentable { /// it under (see `SymbolValueOffsetConverter`). Debug-map entries are /// left out. public var swiftSymbols: [MachOResolving.Symbol] { - let symbolValueOffsetConverter = (self as? MachOFile).map { SymbolValueOffsetConverter(for: $0) } + let symbolValueOffsetConverter = asMachOFile.map { SymbolValueOffsetConverter(for: $0) } return symbols.filter { $0.name.isSwiftSymbol && !$0.nlist.isDebuggingEntry }.map { .init(offset: symbolValueOffsetConverter?.offset(forSymbolValue: $0.offset) ?? $0.offset, name: $0.name) } diff --git a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift index 3e13805bf..7bc1b1187 100644 --- a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift @@ -617,7 +617,7 @@ public final class SymbolIndexStore: @unchecked Sendable { // whose names are decoded per entry from the file) collects through // the generic leg below, whose Swift names are appended once into // the table's private byte buffer. - let machOImage = machO as? MachOImage + let machOImage = machO.asMachOImage let mappedSymbols64 = machOImage?.symbols64 let mappedSymbols32 = machOImage?.symbols32 let mappedStringTableBase = mappedSymbols64.map { UnsafeRawPointer($0.stringBase) } ?? mappedSymbols32.map { UnsafeRawPointer($0.stringBase) } @@ -773,6 +773,10 @@ public final class SymbolIndexStore: @unchecked Sendable { } exportFacts.exportedRowBitmap[wordIndex] |= 1 << UInt64(Int(row) & 63) } + // A trie offset counts from the image's header; a file's index offsets + // count from its start offset (a dyld cache image's, from the shared + // region). Asked once — the reader is the same for every entry. + let exportedSymbolOffsetBase = machO.asMachOFile == nil ? 0 : machO.startOffset for exportedSymbol in machO.exportedSymbols { sawAnyExportedSymbol = true let name = exportedSymbol.name @@ -780,10 +784,7 @@ public final class SymbolIndexStore: @unchecked Sendable { if let existingRow = tableBuilder.existingRow(forName: name) { recordExportedRow(existingRow) } else if let rawOffset = exportedSymbol.offset { - var canonicalOffset = rawOffset - if machO is MachOFile { - canonicalOffset += machO.startOffset - } + let canonicalOffset = rawOffset + exportedSymbolOffsetBase // The `existingRow` guard above means this name has no row // yet, so `canonicalRow` always mints one and the duplicate // check is never needed here. Export-trie names are decoded @@ -957,8 +958,13 @@ public final class SymbolIndexStore: @unchecked Sendable { if let first { return processMemberSymbol(symbolTableRow, node: first, memberKind: .variable(inExtension: traits.contains(.inExtension), isStatic: traits.contains(.isStatic), isStorage: traits.contains(.isStorage)), builder: &builder) } + // A SE-0507 `borrow` / `mutate` accessor is the property's read / + // write accessor when it declares one: such a property has no getter + // or setter symbol of its own, so skipping them dropped it whole. case .getter, - .setter: + .setter, + .borrowAccessor, + .mutateAccessor: if let variableNode = node.children.first, variableNode.kind == .variable, var first = variableNode.children.first { if first.kind == .extension, let type = first.children.at(1) { traits.insert(.inExtension) @@ -1071,7 +1077,9 @@ public final class SymbolIndexStore: @unchecked Sendable { // this is a stored variable declaration return .init(kind: .variable(isStorage: true), symbolTableRow: symbolTableRow) case .getter, - .setter: + .setter, + .borrowAccessor, + .mutateAccessor: if let variableNode = node.children.first, variableNode.kind == .variable { return processGlobalSymbol(symbolTableRow, node: variableNode) } @@ -1489,6 +1497,8 @@ extension Node.Kind { .function, .getter, .setter, + .borrowAccessor, + .mutateAccessor, .methodDescriptor, .protocolWitness, .variable: @@ -1533,8 +1543,8 @@ extension DependencyValues { extension DemanglingNode { package var isGlobal: Bool { guard let first = children.first else { return false } - guard first.isKind(of: .getter, .setter, .function, .variable) else { return false } - if first.isKind(of: .getter, .setter), let variable = first.children.first, variable.isKind(of: .variable) { + guard first.isKind(of: .getter, .setter, .borrowAccessor, .mutateAccessor, .function, .variable) else { return false } + if first.isKind(of: .getter, .setter, .borrowAccessor, .mutateAccessor), let variable = first.children.first, variable.isKind(of: .variable) { return variable.children.first?.isKind(of: .module) ?? false } else { return first.children.first?.isKind(of: .module) ?? false @@ -1542,7 +1552,7 @@ extension DemanglingNode { } package var isAccessor: Bool { - return isKind(of: .getter, .setter, .modifyAccessor, .readAccessor) + return isKind(of: .getter, .setter, .modifyAccessor, .readAccessor, .borrowAccessor, .mutateAccessor) } } diff --git a/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift b/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift index b320f358b..f623d6838 100644 --- a/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift +++ b/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift @@ -34,7 +34,7 @@ struct SymbolValueOffsetConverter { private let accounting: Accounting init(for machO: some MachORepresentableWithCache) { - guard let machOFile = machO as? MachOFile else { + guard let machOFile = machO.asMachOFile else { accounting = .unchanged return } diff --git a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift index 4037fe35c..1205b28dc 100644 --- a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift +++ b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift @@ -96,6 +96,13 @@ public struct DeclarationRenderConfiguration: Sendable { /// option with a `VisibilityRegion`, whatever the `print…` flags say. public var marksOptionalContent: Bool = false + /// Where the dump learns the source file of each private discriminator + /// (evolution proposal `private-declaration-source-files`). With one, a + /// declaration whose name reads a discriminator the declaration it is + /// printed inside does not carry is printed under a comment naming the + /// file; `nil` prints none and reads no name for it. + public var privateDeclarationSourceFileProvider: (any PrivateDeclarationSourceFileProviding)? = nil + public static func demangleOptions(_ demangleOptions: DemangleOptions) -> Self { .init(demangleResolver: .options(demangleOptions)) } @@ -163,6 +170,30 @@ extension DeclarationRenderConfiguration { BreakLine() } + /// The comment lines naming the source files of the private declarations + /// `nodes` read that `enclosingNodes` do not (evolution proposal + /// `private-declaration-source-files`; see + /// `PrivateDeclarationSourceFileComments`). Nothing without a + /// `privateDeclarationSourceFileProvider`, and the nodes are only worked + /// out with one. + /// + /// Each line is indented to `indentationLevel` and followed by a line + /// break. + @SemanticStringBuilder + package func privateDeclarationSourceFileComments( + for nodes: @autoclosure () -> [any DemanglingNode], + enclosedBy enclosingNodes: @autoclosure () -> [any DemanglingNode] = [], + indentationLevel: Int + ) -> SemanticString { + if let privateDeclarationSourceFileProvider { + for line in PrivateDeclarationSourceFileComments.lines(for: nodes(), enclosedBy: enclosingNodes(), provider: privateDeclarationSourceFileProvider) { + Indent(level: indentationLevel) + Comment(line) + BreakLine() + } + } + } + /// Builds a `not exported` comment line (evolution proposal 0008), /// emitted by the dumpers next to a member-symbol line whose symbol /// provably has no export-trie entry. diff --git a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift index ede6dbbac..e737b840e 100644 --- a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift +++ b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift @@ -79,44 +79,51 @@ package enum DependentMemberProjection { return searchPaths + [.systemDyldSharedCache] } + /// A projection made in the universe of the reader `machO` reads through. + /// + /// `image` is that universe's reader — a `MachOFile` or a `MachOImage` — + /// and not necessarily the caller's reader type: the record can sit in + /// another image of the closure, and a wrapper's universe is built from the + /// reader beneath it. + package struct Projection { + /// The witness type with the base's generic arguments substituted; + /// demangled in `image`. + package let witnessNode: Node + /// The image whose `__swift5_assocty` record answered. + package let image: any MachOSwiftSectionRepresentableWithCache + package let conformingQualifiedName: String + package let protocolQualifiedName: String + + init(_ projection: ImageUniverse.ProjectedAssociatedTypeWitness) { + self.witnessNode = projection.witnessNode + self.image = projection.image + self.conformingQualifiedName = projection.conformingQualifiedName + self.protocolQualifiedName = projection.protocolQualifiedName + } + } + /// Projects `base.Name` through the conformance records reachable from - /// `machO`, or answers `nil` when the reader is neither a file nor an - /// in-process image, the universe cannot be built, or the record is not - /// there. See ``ImageUniverse/projectedAssociatedTypeWitness(base:associatedTypeReference:)``. - package static func project( + /// `machO`, or answers `nil` when the reader reads through neither a file + /// nor an in-process image, the universe cannot be built, or the record is + /// not there. See ``ImageUniverse/projectedAssociatedTypeWitness(base:associatedTypeReference:)``. + package static func project( base baseTypeNode: Node, associatedTypeReference: Node, - in machO: MachO - ) -> ImageUniverse.ProjectedAssociatedTypeWitness? { - if let machOFile = machO as? MachOFile { + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> Projection? { + if let machOFile = machO.asMachOFile { let registry = fileRegistries.storage(in: machOFile) { FileRegistry(root: $0) } ?? FileRegistry(root: machOFile) guard let entry = registry.entry(for: searchPaths(for: machOFile)) else { return nil } let projection = entry.withUniverse { $0.projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference) } - return projection.flatMap { Self.cast($0) } + return projection.map(Projection.init) } - if let machOImage = machO as? MachOImage { + if let machOImage = machO.asMachOImage { guard let entry = imageEntries.storage(in: machOImage, buildUsing: { (try? ImageUniverse.dependencyClosure(root: $0)).map { Entry(universe: $0) } }) else { return nil } let projection = entry.withUniverse { $0.projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference) } - return projection.flatMap { Self.cast($0) } + return projection.map(Projection.init) } return nil } - - /// The generic-parameter cast the `as?` dispatch above cannot express - /// directly: a projection made in a `MachOFile` universe is a projection - /// for `MachO` exactly when `MachO` is `MachOFile`, which the dispatch - /// established. - private static func cast( - _ projection: ImageUniverse.ProjectedAssociatedTypeWitness - ) -> ImageUniverse.ProjectedAssociatedTypeWitness? { - guard let image = projection.image as? MachO else { return nil } - return ImageUniverse.ProjectedAssociatedTypeWitness( - witnessNode: projection.witnessNode, - image: image, - conformingQualifiedName: projection.conformingQualifiedName, - protocolQualifiedName: projection.protocolQualifiedName - ) - } } // MARK: - Projecting every concrete member of a type @@ -126,19 +133,19 @@ extension DependentMemberProjection { /// the type its conformance's witness record names, through the universe /// of `machO`'s dependency closure — see /// ``ImageUniverse/projectingConcreteMembers(in:)``. `node` unchanged when - /// the reader is neither a file nor an in-process image, or the universe - /// cannot be built. + /// the reader reads through neither a file nor an in-process image, or the + /// universe cannot be built. package static func projectingConcreteMembers(in node: Node, in machO: MachO) -> Node { // Nothing to project, so nothing to look up: no search-path inference // (it lists directories), no lock, no dependency closure built — the // first call used to build one even for a plain `Swift.Int`. guard node.contains(.dependentMemberType) else { return node } - if let machOFile = machO as? MachOFile { + if let machOFile = machO.asMachOFile { let registry = fileRegistries.storage(in: machOFile) { FileRegistry(root: $0) } ?? FileRegistry(root: machOFile) guard let entry = registry.entry(for: searchPaths(for: machOFile)) else { return node } return entry.withUniverse { $0.projectingConcreteMembers(in: node) } } - if let machOImage = machO as? MachOImage { + if let machOImage = machO.asMachOImage { guard let entry = imageEntries.storage(in: machOImage, buildUsing: { (try? ImageUniverse.dependencyClosure(root: $0)).map { Entry(universe: $0) } }) else { return node } return entry.withUniverse { $0.projectingConcreteMembers(in: node) } } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift index 375e8c72d..bed7dbc68 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift @@ -138,15 +138,6 @@ extension TargetGenericContext { } } -extension Node { - fileprivate static let firstGenericParamType: Node = .create(kind: .type) { - Node.create(kind: .dependentGenericParamType) { - Node.create(kind: .index, index: 0) - Node.create(kind: .index, index: 0) - } - } -} - extension GenericRequirementDescriptor { @SemanticStringBuilder package func dump(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { @@ -301,29 +292,39 @@ extension GenericRequirementDescriptor { try await dumpProtocolMangledName(paramMangledName(in: context), in: context, builder: builder) } + /// A type of the protocol's requirement signature. A type parameter — + /// `Self` or a chain of its members, `Self.Second.Leaf` — is spelled here, + /// without the protocol qualifiers its mangling may carry. Any other type + /// prints as itself through `builder`, with the protocol's generic + /// parameter spelled `Self`: the right-hand side of a same-type or + /// superclass requirement can be any type (`[Self.First]`, + /// `(Self.First, [Self.First])`, `GenericBase`), and reading + /// only the member names out of it printed a different requirement + /// (`Self.Second == Self.First`). @SemanticStringBuilder private func dumpProtocolMangledName(_ mangledName: MangledName, in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { let node = try SymbolicDemangler.demangleType(for: mangledName, in: context) - let params = node.filter(of: .dependentAssociatedTypeRef).compactMap { $0.first(of: .identifier)?.text } - - if params.isEmpty { - if node == .firstGenericParamType { - Keyword(.Self) - } else { - try await builder(node) + if let memberNames = node.protocolSelfMemberNames { + Keyword(.Self) + for memberName in memberNames { + Standard(".") + Standard(memberName) } } else { - for (offset, param) in params.offsetEnumerated() { - if offset.isStart { - Keyword(.Self) - Standard(".") - } - Standard(param) - if !offset.isEnd { - Standard(".") - } - } + try await builder(node.spellingProtocolSelfParameter()) + } + } + + /// The right-hand side alone — what an `associatedtype` inheritance clause + /// spells for its requirement (`associatedtype Body: SwiftUI.View`). + @SemanticStringBuilder + package func dumpProtocolContent(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { + switch resolver { + case .options(let demangleOptions): + try await dumpProtocolContent(in: context) { $0.printSemantic(using: demangleOptions) } + case .builder(let builder): + try await dumpProtocolContent(in: context, builder: builder) } } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift index a07fa5e3b..1b9753da6 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift @@ -278,7 +278,7 @@ extension Node { /// ``AccessorThunkResolving`` vends to a host that wants to show them. private func resolvingAccessorFunctionReferences(in node: Node, ownerLayout: AccessorThunkOwnerLayout) -> Node? { guard node.contains(Node.Kind.accessorFunctionReference) else { return nil } - guard let machOFile = machO as? MachOFile else { return nil } + guard let machOFile = machO.asMachOFile else { return nil } let rewriter = AccessorFunctionReferenceRewriter( resolver: AccessorThunkResolution.effectiveResolver, @@ -343,8 +343,9 @@ extension Node { /// produces for it. /// /// **By pointer** (`opaqueTypeDescriptorSymbolicReference`): the - /// node carries the descriptor's offset — or, in any `MachOImage` - /// environment, its absolute in-process pointer bit pattern, which + /// node carries the descriptor's offset — or, whenever the reader reads + /// through a `MachOImage` (`asMachOImage`, wrappers included), its + /// absolute in-process pointer bit pattern, which /// `SymbolicDemangler` stashes in `Node.index` regardless of whether /// the descriptor lives in this image or a sibling loaded one /// (cross-image refs from `View.searchFieldStyle`-style helpers, @@ -362,7 +363,7 @@ extension Node { /// resolves here; one it does not is ``foreignOpaqueType(referencedBy:)``'s. private func opaqueType(referencedBy reference: Node) throws -> ReadOpaqueType? { if reference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let offset: Int = reference.index?.cast() { - if machO is MachOImage, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { + if machO.asMachOImage != nil, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { let opaqueTypeDescriptor: OpaqueTypeDescriptor = try absolutePointer.readWrapperElement() return try ReadOpaqueType(OpaqueType(descriptor: opaqueTypeDescriptor, in: .inProcess), in: .inProcess) } @@ -396,7 +397,7 @@ extension Node { /// list, printed the conformer itself as the witness (`typealias Body /// = SidebarListBody.CollectionViewBody`), a real, wrong type. private func foreignOpaqueType(referencedBy reference: Node) throws -> (image: MachOFile, opaqueType: ReadOpaqueType)? { - guard reference.isKind(of: .opaqueReturnTypeOf), let machOFile = machO as? MachOFile else { return nil } + guard reference.isKind(of: .opaqueReturnTypeOf), let machOFile = machO.asMachOFile else { return nil } let descriptorSymbolNode = Node.create(kind: .global, children: [Node.create(kind: .opaqueTypeDescriptor, children: [reference.copy()])]) let descriptorSymbolName = try mangleAsString(descriptorSymbolNode) let searchPaths = (AccessorThunkResolution.effectiveResolver as? DisassemblingAccessorThunkResolver)?.searchPaths @@ -440,7 +441,7 @@ extension Node { let allTypeList = Node.opaqueTypeGenericArgumentsByDepth(of: node, depthLayout: readOpaqueType.depthLayout) guard let underlyingTypeArgumentMangledName = opaqueType.underlyingTypeArgumentMangledNames[safe: ordinal] else { return nil } let underlyingTypeArgumentNode: Node? - if machO is MachOImage { + if machO.asMachOImage != nil { underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: .inProcess) } else { underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO.context) @@ -497,18 +498,25 @@ extension Node { )) // The witness is that image's tree: its references are resolved // there, one nesting level down. - let rewritten = OpaqueTypeRewriter( - machO: projection.image, + let rewritten = rewriteOneLevelDown(projection.witnessNode, in: projection.image) + // Unwrapped so the result composes where a type belongs, the + // way `expansion(of:forNode:)`'s does. + if rewritten.kind == .type, let content = rewritten.firstChild { return content } + return rewritten + } + + /// `node` rewritten one nesting level down by a rewriter over `image`, + /// whatever reader type `image` is — passing the projection's + /// existential opens it (SE-0352). + private func rewriteOneLevelDown(_ node: Node, in image: Image) -> Node { + OpaqueTypeRewriter( + machO: image, reportDegradation: reportDegradation, expansionDepth: expansionDepth + 1, branchSelection: branchSelection, candidateLedger: candidateLedger, projectionLedger: projectionLedger - ).rewrite(projection.witnessNode) - // Unwrapped so the result composes where a type belongs, the - // way `expansion(of:forNode:)`'s does. - if rewritten.kind == .type, let content = rewritten.firstChild { return content } - return rewritten + ).rewrite(node) } override func visit(_ node: Node) -> Node { @@ -602,7 +610,7 @@ extension Node { ownerLayout: AccessorThunkOwnerLayout ) -> Node { guard contains(Node.Kind.accessorFunctionReference), - let machOFile = machO as? MachOFile + let machOFile = machO.asMachOFile else { return self } let rewriter = AccessorFunctionReferenceRewriter(resolver: AccessorThunkResolution.effectiveResolver, machO: machOFile, ownerLayout: ownerLayout) let rewritten = rewriter.rewrite(copy()) diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+ProtocolSelf.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+ProtocolSelf.swift new file mode 100644 index 000000000..18a3ef756 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+ProtocolSelf.swift @@ -0,0 +1,84 @@ +import Demangling + +/// Reading the types of a protocol's requirement signature, where the +/// protocol's `Self` is the one generic parameter (`τ_0_0`). +extension Node { + /// The associated type names of a type that is the protocol's `Self` or a + /// chain of members rooted at it, root first: `["Second", "Leaf"]` for + /// `Self.Second.Leaf`, `[]` for `Self` itself. `nil` for any other type, + /// including a composite type that only mentions `Self` (`[Self.First]`). + /// + /// A member's protocol qualifier (`Self.Seventh.[Sequence]Element`) is not + /// part of its name: Swift source cannot spell it, and the associated + /// types of one name in a protocol and the protocols it refines are one + /// type. + package var protocolSelfMemberNames: [String]? { + var memberNames: [String] = [] + var currentNode = self + while true { + switch currentNode.kind { + case .type: + guard currentNode.children.count == 1, let wrappedNode = currentNode.children.first else { return nil } + currentNode = wrappedNode + case .dependentMemberType: + guard currentNode.children.count == 2, + let baseNode = currentNode.children.first, + let associatedTypeReference = currentNode.children.at(1), + associatedTypeReference.isKind(of: .dependentAssociatedTypeRef), + let memberName = associatedTypeReference.children.first?.text + else { return nil } + memberNames.append(memberName) + currentNode = baseNode + case .dependentGenericParamType: + return currentNode.isProtocolSelfParameter ? memberNames.reversed() : nil + default: + return nil + } + } + } + + /// The root of the first member chain in this type, in preorder, whose + /// root is one of `associatedTypeNames`: `Second` for `Self.Second.Leaf`, + /// for `[Self.Second]`, and for `(Self.Element, Self.Second)` when + /// `Element` is not one of them. A chain's own subtree is not searched + /// again: every inner chain has the same root. + package func firstProtocolSelfMemberRoot(among associatedTypeNames: Set) -> String? { + var pendingNodes: [Node] = [self] + while let node = pendingNodes.popLast() { + if let memberNames = node.protocolSelfMemberNames { + if let rootName = memberNames.first, associatedTypeNames.contains(rootName) { + return rootName + } + continue + } + pendingNodes.append(contentsOf: node.children.reversed()) + } + return nil + } + + /// The same tree printable as Swift source inside the protocol: the + /// protocol's generic parameter spelled `Self` rather than by its position + /// (`A`), and every member's protocol qualifier dropped + /// (`strippingAssociatedTypeProtocolQualifiers()`), which the upstream + /// `NodePrinter` would otherwise spell out (`Self.Seventh.Swift.Sequence.Element`). + package func spellingProtocolSelfParameter() -> Node { + ProtocolSelfParameterSpeller().rewrite(strippingAssociatedTypeProtocolQualifiers()) + } + + fileprivate var isProtocolSelfParameter: Bool { + isKind(of: .dependentGenericParamType) + && children.count == 2 + && children.first?.index == 0 + && children.at(1)?.index == 0 + } +} + +/// Puts `.constrainedExistentialSelf` where the protocol's generic parameter +/// was: the one node kind both printers spell `Self` — swift-demangling's +/// `NodePrinter` as text, SwiftPrinting's type printer as the keyword. The +/// replacement is `NodeFactory`'s shared leaf, which outlives every print. +private final class ProtocolSelfParameterSpeller: Node.Rewriter { + override func visit(_ node: Node) -> Node { + node.isProtocolSelfParameter ? NodeFactory.constrainedExistentialSelf : node + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderable+MachOReaderWrapper.swift b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderable+MachOReaderWrapper.swift new file mode 100644 index 000000000..6ccf72e25 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderable+MachOReaderWrapper.swift @@ -0,0 +1,39 @@ +import Semantic +import MachOKitExtensions +import MachOSwiftSection +import SwiftLayout +@_spi(Internals) import SwiftInspection + +/// A wrapper renders its field-layout comments the way the reader it wraps +/// does: a host's `MachOReaderWrapper` declares `FieldLayoutRenderable` with an +/// empty body and renders through `Base`'s backend — from live metadata when it +/// wraps a `MachOImage`, statically when it wraps a `MachOFile`. +extension FieldLayoutRenderable where Self: MachOReaderWrapper, Base: FieldLayoutRenderable { + public static func makeStaticFieldLayoutProvider(machO: Self, resolution: StaticLayoutDependencyResolution) -> (any StaticFieldLayoutProvider)? { + Base.makeStaticFieldLayoutProvider(machO: machO.base, resolution: resolution) + } + + public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, genericArgumentBinding: GenericArgumentBinding?, machO: Self, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { + Base.precomputedStaticAggregateFieldLayout(for: type, genericArgumentBinding: genericArgumentBinding, machO: machO.base, configuration: configuration) + } + + public static func renderFieldOffsets(_ state: FieldLayoutRenderState, machO: Self) -> [Int]? { + Base.renderFieldOffsets(state, machO: machO.base) + } + + public static func renderStoredFieldComments(_ state: FieldLayoutRenderState, machO: Self, forFieldAtIndex index: Int, mangledTypeName: MangledName, fieldOffsets: [Int]?) async throws -> SemanticString { + try await Base.renderStoredFieldComments(state, machO: machO.base, forFieldAtIndex: index, mangledTypeName: mangledTypeName, fieldOffsets: fieldOffsets) + } + + public static func renderEnumLayout(_ state: FieldLayoutRenderState, machO: Self) async -> EnumLayoutCalculator.LayoutResult? { + await Base.renderEnumLayout(state, machO: machO.base) + } + + public static func renderEnumPrefixComments(_ state: FieldLayoutRenderState, machO: Self, enumLayout: EnumLayoutCalculator.LayoutResult?) async -> SemanticString { + await Base.renderEnumPrefixComments(state, machO: machO.base, enumLayout: enumLayout) + } + + public static func renderEnumCaseComments(_ state: FieldLayoutRenderState, machO: Self, forCaseAtIndex index: Int, mangledTypeName: MangledName, enumLayout: EnumLayoutCalculator.LayoutResult?) async throws -> SemanticString { + try await Base.renderEnumCaseComments(state, machO: machO.base, forCaseAtIndex: index, mangledTypeName: mangledTypeName, enumLayout: enumLayout) + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift b/Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift index f8b927e77..6445dff5e 100644 --- a/Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift +++ b/Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift @@ -70,7 +70,7 @@ package enum InProcessAccessorFunctionResolution { conformingTypeName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache ) -> Node { - guard let machOImage = machO as? MachOImage, resolved.contains(Node.Kind.accessorFunctionReference) else { return resolved } + guard let machOImage = machO.asMachOImage, resolved.contains(Node.Kind.accessorFunctionReference) else { return resolved } return witnessNode(witnessMangledName: witnessMangledName, conformingTypeName: conformingTypeName, in: machOImage) ?? resolved } } diff --git a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift index 377ed69c9..f519433af 100644 --- a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift +++ b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift @@ -71,7 +71,7 @@ extension Node { if let ownerDeclaration = ownerDeclarationNode(of: reference) { return ownerDeclaration } guard reference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let offset: Int = reference.index?.cast() else { return nil } var contextNode: Node? - if machO is MachOImage, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { + if machO.asMachOImage != nil, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { if let descriptor: OpaqueTypeDescriptor = try? absolutePointer.readWrapperElement() { contextNode = try? SymbolicDemangler.demangleContext(for: .opaqueType(descriptor), in: .inProcess) } diff --git a/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift b/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift new file mode 100644 index 000000000..5502625a7 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift @@ -0,0 +1,104 @@ +import Demangling +import SwiftInspection + +/// The source file a private discriminator was derived from, as dump and +/// interface name it (evolution proposal `private-declaration-source-files`). +public struct PrivateDeclarationSourceFile: Hashable, Sendable { + /// The file's name, `Enabled.swift`. + public let fileName: String + + /// The module name that went into the discriminator: a framework's own + /// name (`SwiftUICore`), which is not always the module its declarations + /// print under (`SwiftUI`). + public let moduleName: String + + /// Whether the discriminator belongs to the file the compiler synthesizes + /// for `fileName`, not to `fileName` itself. + public let isSynthesized: Bool + + public init(fileName: String, moduleName: String, isSynthesized: Bool) { + self.fileName = fileName + self.moduleName = moduleName + self.isSynthesized = isSynthesized + } +} + +/// What tells dump and interface the source file of a private discriminator +/// (evolution proposal `private-declaration-source-files`). The library's own +/// is `SwiftPrivateDiscriminators`' `PrivateDiscriminatorSourceFileIndex`, +/// which sits above this module. +/// +/// It is asked once for every private declaration printed, from the printing +/// thread, so an answer should cost a lookup: search for the whole image +/// before printing. +public protocol PrivateDeclarationSourceFileProviding: Sendable { + /// The source file `discriminator` was derived from; `nil` when it could + /// not be recovered. + func sourceFile(forPrivateDiscriminator discriminator: String) -> PrivateDeclarationSourceFile? +} + +/// The comments above a printed declaration that name the source files its +/// private declarations come from (evolution proposal +/// `private-declaration-source-files`). Dump and interface print the same +/// lines. +package enum PrivateDeclarationSourceFileComments { + /// One line for each discriminator the names in `nodes` read that + /// `enclosingNodes` — the names of the declaration they are printed inside, + /// a conformance's type and protocol — do not, in the order the names read + /// them. + /// + /// A type nested in a private type, or a member of one, is necessarily + /// declared in that type's file, so it repeats nothing; a private member of + /// a public type says where it is. A line names the last declaration read + /// with its discriminator: the private type `B` in `(A in _X).(B in _X)`. + package static func lines( + for nodes: [any DemanglingNode], + enclosedBy enclosingNodes: [any DemanglingNode], + provider: any PrivateDeclarationSourceFileProviding + ) -> [String] { + let enclosingDiscriminators = Set(enclosingNodes.flatMap { $0.privateDeclarations.map(\.discriminator) }) + var discriminators: [String] = [] + var lastDeclarationByDiscriminator: [String: (declaration: PrivateDeclaration, moduleName: String?)] = [:] + for node in nodes { + let moduleName = declaringModuleName(of: node) + for privateDeclaration in node.privateDeclarations where !enclosingDiscriminators.contains(privateDeclaration.discriminator) { + if lastDeclarationByDiscriminator[privateDeclaration.discriminator] == nil { + discriminators.append(privateDeclaration.discriminator) + } + lastDeclarationByDiscriminator[privateDeclaration.discriminator] = (privateDeclaration, moduleName) + } + } + return discriminators.compactMap { discriminator in + lastDeclarationByDiscriminator[discriminator].map { line(for: $0.declaration, sourceFile: provider.sourceFile(forPrivateDiscriminator: discriminator), printedModuleName: $0.moduleName) } + } + } + + /// The line saying where `privateDeclaration` is declared: + /// `EnabledKey is declared in Enabled.swift of module SwiftUICore`, the + /// module named only when it is not the one the declaration prints under. + /// One nothing recovered says so, with its discriminator: the interface + /// prints none anywhere else. + package static func line(for privateDeclaration: PrivateDeclaration, sourceFile: PrivateDeclarationSourceFile?, printedModuleName: String?) -> String { + let subject = privateDeclaration.name.map { "\($0) is declared in" } ?? "Declared in" + guard let sourceFile else { + return "\(subject) a source file whose name could not be recovered (private discriminator \(privateDeclaration.discriminator))" + } + let file = sourceFile.isSynthesized ? "the file the compiler synthesized for \(sourceFile.fileName)" : sourceFile.fileName + let module = sourceFile.moduleName == printedModuleName ? "" : " of module \(sourceFile.moduleName)" + return "\(subject) \(file)\(module)" + } + + /// The module a name is declared in: the end of its chain of contexts, + /// each the first child of the one before — an extension's own module + /// rather than the extended type's. + private static func declaringModuleName(of node: DeclarationNode) -> String? { + var context: DeclarationNode? = node + while let currentContext = context { + if currentContext.kind == .module { + return currentContext.text + } + context = currentContext.children.first + } + return nil + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift index 18ad413e6..c072b7c5e 100644 --- a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift +++ b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift @@ -22,7 +22,8 @@ public struct PropertyWrapperEvidence: Sendable { } /// The accessor forms a `wrappedValue` symbol takes, read off its demangled -/// tree (`global → getter | setter | modifyAccessor → variable → type`). +/// tree (`global → getter | setter | modifyAccessor → variable → type`; +/// SE-0507's `borrow` reads like a getter, its `mutate` writes like a setter). public enum WrappedValueAccessorSymbol { public struct Shape: Sendable { public let isSetter: Bool @@ -39,10 +40,10 @@ public enum WrappedValueAccessorSymbol { case .global: guard let next = node.firstChild else { return nil } node = next - case .getter, .static: + case .getter, .borrowAccessor, .static: guard let next = node.firstChild else { return nil } node = next - case .setter, .modifyAccessor: + case .setter, .modifyAccessor, .mutateAccessor: isSetter = true guard let next = node.firstChild else { return nil } node = next @@ -100,15 +101,16 @@ public final class PropertyWrapperTypeCatalog: @unchecked Sendable { /// A catalog over `root`'s export trie and, on demand, its dependency /// closure — resolved through `searchPaths` for a file, through the - /// loaded images for an in-process image. The reader kinds are a closed - /// set of two; any other reader gets a catalog that answers nothing. + /// loaded images for an in-process image — whichever of the two `root` + /// reads through, wrappers included. Any other reader gets a catalog that + /// answers nothing. public static func make(root: some MachORepresentableWithCache, searchPaths: [DependencySearchPath]) -> PropertyWrapperTypeCatalog { - if let machOFile = root as? MachOFile { + if let machOFile = root.asMachOFile { return PropertyWrapperTypeCatalog(rootLookup: lookup(for: machOFile)) { DependencyClosure(root: machOFile, searchPaths: searchPaths).images.map(lookup(for:)) } } - if let machOImage = root as? MachOImage { + if let machOImage = root.asMachOImage { return PropertyWrapperTypeCatalog(rootLookup: lookup(for: machOImage)) { DependencyClosure(root: machOImage).images.map(lookup(for:)) } diff --git a/Sources/Output/SwiftDiffing/MemberRecord.swift b/Sources/Output/SwiftDiffing/MemberRecord.swift index 420e71963..7f144dbf3 100644 --- a/Sources/Output/SwiftDiffing/MemberRecord.swift +++ b/Sources/Output/SwiftDiffing/MemberRecord.swift @@ -274,6 +274,8 @@ extension MemberRecord { case .setter: return "set" case .modifyAccessor: return "modify" case .readAccessor: return "read" + case .borrowAccessor: return "borrow" + case .mutateAccessor: return "mutate" case .none: return "none" } } diff --git a/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift b/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift index cae8ed47a..3dbfded98 100644 --- a/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift @@ -95,6 +95,17 @@ package struct AssociatedTypeDumper: Conforme package var body: SemanticString { get async throws { + // The associated types of a conformance of a private type, or to + // a private protocol, are declared in that type's or protocol's + // file (evolution proposal `private-declaration-source-files`). + configuration.privateDeclarationSourceFileComments( + for: [ + try? SymbolicDemangler.demangleType(for: dumped.conformingTypeName, in: machO.context), + try? SymbolicDemangler.demangleType(for: dumped.protocolTypeName, in: machO.context), + ].compactMap { $0 }, + indentationLevel: 0 + ) + try await declaration Space() diff --git a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift index 60c18fe44..af49e387e 100644 --- a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift @@ -219,6 +219,18 @@ package struct ClassDumper: TypedDumper { package var body: SemanticString { get async throws { + // Same-named private types share the stripped name bucket; the + // context node picks this type's own sub-bucket (issue #115). + // A context that cannot be demangled falls back to the name-only + // (merged) lookup rather than dropping members. It is also the + // name whose private declarations the class's source-file comment + // names, and its members' leave out (evolution proposal + // `private-declaration-source-files`). + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) + let contextNodes: [Node] = contextNode.map { [$0] } ?? [] + + configuration.privateDeclarationSourceFileComments(for: contextNodes, indentationLevel: 0) + // The ObjC runtime name the source chose (evolution proposal // `objc-custom-class-name`), as the attribute the interface prints. if let customObjCClassName = SwiftClassObjectIndex.shared.customObjCClassName(forClassDescriptorOffset: dumped.descriptor.offset, in: machO) { @@ -252,21 +264,14 @@ package struct ClassDumper: TypedDumper { for (offset, descriptor) in dumped.methodDescriptors.offsetEnumerated() { BreakLine() - if configuration.printVTableOffset, let vtableBaseOffset { - configuration.vtableOffsetComment(slotOffset: vtableBaseOffset + offset.index) - } - - if configuration.printMemberAddress, let implementationOffset = descriptor.implementationOffset { - configuration.memberAddressComment(offset: implementationOffset, addressString: machO.addressString(forOffset: implementationOffset)) - } - // Attribution, in order of evidence: the descriptor's own `Tq` // symbol (one per member, at the descriptor's own address, so // identical code folding cannot reach it), then the symbols at // the implementation address (not invertible under folding — // the fallback, not the source of truth). Pre-resolved before // any keyword is emitted because the distributed check reads - // the node. + // the node, and before the comments because the source-file + // one leads them. let implementationSymbols = descriptor.implementationSymbols(in: machO) let attributedMethodNode = descriptor.attributedMemberNode(in: machO) var resolvedMethodNode = attributedMethodNode @@ -274,6 +279,16 @@ package struct ClassDumper: TypedDumper { resolvedMethodNode = try? await validNode(for: implementationSymbols, visitedNodes: methodVisitedNodes) } + configuration.privateDeclarationSourceFileComments(for: resolvedMethodNode.map { [$0] } ?? [], enclosedBy: contextNodes, indentationLevel: configuration.indentation) + + if configuration.printVTableOffset, let vtableBaseOffset { + configuration.vtableOffsetComment(slotOffset: vtableBaseOffset + offset.index) + } + + if configuration.printMemberAddress, let implementationOffset = descriptor.implementationOffset { + configuration.memberAddressComment(offset: implementationOffset, addressString: machO.addressString(forOffset: implementationOffset)) + } + if descriptor.implementation.isNull { configuration.deletedMethodSlotComment() } else if attributedMethodNode == nil, let implementationSymbols, implementationSymbols.count > 1 { @@ -398,12 +413,6 @@ package struct ClassDumper: TypedDumper { // which identifies it without demangling. let overrideImplementationSymbolNames = configuration.printExportStatus ? collectOverrideImplementationSymbolNames() : [] - // Same-named private types share the stripped name bucket; the - // context node picks this type's own sub-bucket (issue #115). - // A context that cannot be demangled falls back to the name-only - // (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) - // `override` of ObjC-inherited members (evolution proposal // `objc-ancestor-override-recovery`): the class's own ObjC method // table against its ancestors'. Nil for a class with no static @@ -437,6 +446,8 @@ package struct ClassDumper: TypedDumper { BreakLine() + configuration.privateDeclarationSourceFileComments(for: [symbol.demangledNode], enclosedBy: contextNodes, indentationLevel: configuration.indentation) + if configuration.printMemberAddress { configuration.memberAddressComment(offset: symbol.offset, addressString: machO.addressString(forOffset: symbol.offset)) } @@ -483,6 +494,8 @@ package struct ClassDumper: TypedDumper { BreakLine() + configuration.privateDeclarationSourceFileComments(for: [symbol.demangledNode], enclosedBy: contextNodes, indentationLevel: configuration.indentation) + if configuration.printMemberAddress { configuration.memberAddressComment(offset: symbol.offset, addressString: machO.addressString(forOffset: symbol.offset)) } diff --git a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift index a54047563..731b6e95d 100644 --- a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift @@ -141,6 +141,18 @@ package struct EnumDumper: TypedDumper { package var body: SemanticString { get async throws { + // Same-named private types share the stripped name bucket; the + // context node picks this type's own sub-bucket (issue #115). + // A context that cannot be demangled falls back to the name-only + // (merged) lookup rather than dropping members. It is also the + // name whose private declarations the type's source-file comment + // names, and its members' leave out (evolution proposal + // `private-declaration-source-files`). + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.enum(dumped.descriptor)), in: machO.context) + let contextNodes: [Node] = contextNode.map { [$0] } ?? [] + + configuration.privateDeclarationSourceFileComments(for: contextNodes, indentationLevel: 0) + try await declaration Space() @@ -151,12 +163,6 @@ package struct EnumDumper: TypedDumper { let interfaceNameString = try await interfaceName.string - // Same-named private types share the stripped name bucket; the - // context node picks this type's own sub-bucket (issue #115). - // A context that cannot be demangled falls back to the name-only - // (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.enum(dumped.descriptor)), in: machO.context) - for kind in SymbolIndexStore.MemberKind.allCases { let memberSymbols = if let contextNode { symbolIndexStore.memberSymbols(of: kind, for: interfaceNameString, node: contextNode, in: machO) @@ -174,6 +180,8 @@ package struct EnumDumper: TypedDumper { BreakLine() + configuration.privateDeclarationSourceFileComments(for: [symbol.demangledNode], enclosedBy: contextNodes, indentationLevel: configuration.indentation) + if configuration.printMemberAddress { configuration.memberAddressComment(offset: symbol.offset, addressString: machO.addressString(forOffset: symbol.offset)) } diff --git a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift index 687b22e3f..d7683cad3 100644 --- a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift @@ -284,6 +284,10 @@ package struct ObjCImplementationClassDumper: InlineComment("Swift " + kind.description) } BreakLine() + // An Objective-C class reads no discriminator, so a private + // member of its `@implementation` names its own file + // (evolution proposal `private-declaration-source-files`). + configuration.privateDeclarationSourceFileComments(for: [symbol.demangledNode], indentationLevel: configuration.indentation) if configuration.printMemberAddress { configuration.memberAddressComment(offset: symbol.offset, addressString: machO.addressString(forOffset: symbol.offset)) } diff --git a/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift index 694a7fa41..3dafbe663 100644 --- a/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift @@ -60,6 +60,17 @@ package struct ProtocolConformanceDumper: Con package var body: SemanticString { get async throws { + // A conformance of a private type, or to a private protocol, is + // declared in that type's or protocol's file (evolution proposal + // `private-declaration-source-files`). + configuration.privateDeclarationSourceFileComments( + for: [ + (try? dumped.typeNode(in: machO.context)) ?? nil, + (try? dumped.protocolNode(in: machO.context)) ?? nil, + ].compactMap { $0 }, + indentationLevel: 0 + ) + try await declaration let typeNameString = try await typeName.string diff --git a/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift index b3a480ce9..ee00ca296 100644 --- a/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift @@ -62,18 +62,26 @@ package struct ProtocolDumper: NamedDumper { } } + /// The `associatedtype` lines. `: ~Swift.Copyable` follows a name the + /// image's extensions of the protocol prove suppressible (SE-0503) — the + /// binary records the declaration nowhere else, so a name without such + /// an extension prints bare even when it is suppressible. @SemanticStringBuilder package var associatedTypes: SemanticString { get async throws { let associatedTypes = try dumped.descriptor.associatedTypes(in: machO.context) if !associatedTypes.isEmpty { + let suppressedInvertibleProtocolsByAssociatedTypeName = SuppressedAssociatedTypeInference.suppressedInvertibleProtocolsByAssociatedTypeName(of: dumped.descriptor, in: machO) for (offset, associatedType) in associatedTypes.offsetEnumerated() { BreakLine() Indent(level: configuration.indentation) Keyword(.associatedtype) Space() TypeDeclaration(kind: .other, associatedType) + if let suppressedInvertibleProtocols = suppressedInvertibleProtocolsByAssociatedTypeName[associatedType] { + try await suppressedInvertibleProtocols.dumpInvertedProtocolsInheritance(resolver: demangleResolver) + } if offset.isEnd { BreakLine() } @@ -84,6 +92,13 @@ package struct ProtocolDumper: NamedDumper { package var body: SemanticString { get async throws { + // The name whose private declarations the protocol's source-file + // comment names, and its default implementations' leave out + // (evolution proposal `private-declaration-source-files`). + let contextNodes: [Node] = (try? SymbolicDemangler.demangleContext(for: .protocol(dumped.descriptor), in: machO.context)).map { [$0] } ?? [] + + configuration.privateDeclarationSourceFileComments(for: contextNodes, indentationLevel: 0) + try await declaration Space() @@ -120,6 +135,7 @@ package struct ProtocolDumper: NamedDumper { } BreakLine() + configuration.privateDeclarationSourceFileComments(for: [defaultImplementation.reference], enclosedBy: contextNodes, indentationLevel: configuration.indentation) Indent(level: configuration.indentation) try await demangleResolver.resolve(for: defaultImplementation.reference) diff --git a/Sources/Output/SwiftDump/Dumper/StructDumper.swift b/Sources/Output/SwiftDump/Dumper/StructDumper.swift index 35d0bf843..50af67116 100644 --- a/Sources/Output/SwiftDump/Dumper/StructDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/StructDumper.swift @@ -128,6 +128,19 @@ package struct StructDumper: TypedDumper { package var body: SemanticString { get async throws { + // The interface-printed name strips private discriminators, so + // same-named private types from different files share one name + // bucket; the context node picks this type's own sub-bucket + // (issue #115). A context that cannot be demangled falls back to + // the name-only (merged) lookup rather than dropping members. It + // is also the name whose private declarations the type's + // source-file comment names, and its members' leave out + // (evolution proposal `private-declaration-source-files`). + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.struct(dumped.descriptor)), in: machO.context) + let contextNodes: [Node] = contextNode.map { [$0] } ?? [] + + configuration.privateDeclarationSourceFileComments(for: contextNodes, indentationLevel: 0) + try await declaration Space() @@ -138,13 +151,6 @@ package struct StructDumper: TypedDumper { let interfaceNameString = try await interfaceName.string - // The interface-printed name strips private discriminators, so - // same-named private types from different files share one name - // bucket; the context node picks this type's own sub-bucket - // (issue #115). A context that cannot be demangled falls back to - // the name-only (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.struct(dumped.descriptor)), in: machO.context) - for kind in SymbolIndexStore.MemberKind.allCases { let memberSymbols = if let contextNode { symbolIndexStore.memberSymbols(of: kind, for: interfaceNameString, node: contextNode, in: machO) @@ -162,6 +168,8 @@ package struct StructDumper: TypedDumper { BreakLine() + configuration.privateDeclarationSourceFileComments(for: [symbol.demangledNode], enclosedBy: contextNodes, indentationLevel: configuration.indentation) + if configuration.printMemberAddress { configuration.memberAddressComment(offset: symbol.offset, addressString: machO.addressString(forOffset: symbol.offset)) } diff --git a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index 009a09295..864e6ea41 100644 --- a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -59,14 +59,26 @@ package extension SwiftDeclarationPrinter { /// Renders a protocol's declaration header (`protocol Foo : Bar where …`) with /// no opening brace, body, or trailing newline. Mirrors the header portion of /// `printProtocolDefinition`; keep in sync. + /// + /// Every requirement stays in the header whatever + /// `protocolRequirementPlacement` says: the diff compares a protocol's + /// `associatedtype` lines by name alone (`printAssociatedType`), so a + /// requirement moved onto one would print nowhere. @SemanticStringBuilder func printProtocolHeader(_ protocolDefinition: ProtocolDefinition, level: Int, displayParentName: Bool = false) async throws -> SemanticString { try protocolDefinition.index(in: machO) // This header-print operation's single wrapper materialization // (proposal 0002). + let dumpedProtocol = try protocolDefinition.materializedProtocol(in: machO.context) try await renderProtocolDeclarationHeader( - for: protocolDefinition.materializedProtocol(in: machO.context), + for: dumpedProtocol, + requirementPartition: ProtocolRequirementPartition( + requirements: dumpedProtocol.requirementInSignatures, + associatedTypeNames: [], + placement: .protocolWhereClause, + in: machO.context + ), displayParentName: displayParentName, leafNameNode: leafNameNode(of: protocolDefinition.protocolName.node.materialize()) ) diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift index f3151ef8f..680869049 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift @@ -173,6 +173,11 @@ public final class SwiftInterfaceBuilder: Sen await printCatchedThrowing(dispatchingTo: eventDispatcher, degradationSource: .definitionBlock) { await BlockList { for variable in indexer.globalVariableDefinitions where !printer.isExcludedByExportFilter(globalSymbolNames: variable.accessors.map(\.symbol.name)) { + // One item per line: the list breaks before each + // (evolution proposal `private-declaration-source-files`). + for line in printer.privateDeclarationSourceFileLines(for: [variable.node]) { + Comment(line) + } printer.globalExportStatusComment(forSymbolNames: variable.accessors.map(\.symbol.name)) await printer.printVariable(variable, level: 0) } @@ -182,6 +187,9 @@ public final class SwiftInterfaceBuilder: Sen await printCatchedThrowing(dispatchingTo: eventDispatcher, degradationSource: .definitionBlock) { await BlockList { for function in indexer.globalFunctionDefinitions where !printer.isExcludedByExportFilter(globalSymbolNames: [function.symbol.name]) { + for line in printer.privateDeclarationSourceFileLines(for: [function.node]) { + Comment(line) + } printer.globalExportStatusComment(forSymbolNames: [function.symbol.name]) await printer.printFunction(function, level: 0) } diff --git a/Sources/Output/SwiftPrinting/InterfaceHeader.swift b/Sources/Output/SwiftPrinting/InterfaceHeader.swift index e6e1b11b0..d6b53543f 100644 --- a/Sources/Output/SwiftPrinting/InterfaceHeader.swift +++ b/Sources/Output/SwiftPrinting/InterfaceHeader.swift @@ -95,10 +95,12 @@ extension InterfaceHeaderInfo { @Dependency(\.symbolIndexStore) var symbolIndexStore - let imagePath: String? = switch machO { - case let machOFile as MachOFile: machOFile.imagePath - case let machOImage as MachOImage: machOImage.path - default: nil + let imagePath: String? = if let machOFile = machO.asMachOFile { + machOFile.imagePath + } else if let machOImage = machO.asMachOImage { + machOImage.path + } else { + nil } var uuid: UUID? diff --git a/Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift index 665fdd037..d388135d3 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift @@ -58,6 +58,24 @@ extension MemberDeclarationNodePrintable { ] } + /// Wrappers whose first child is the entity: a method descriptor, and the + /// accessor a member symbol names — SE-0507's `borrow` / `mutate` alike, + /// since a property declaring them has no getter symbol to print from. + /// A `switch`, not a `Set` literal: the walk asks once per wrapper of + /// every printed member, and a computed `Set` would be rebuilt each time. + static func isSkippedAccessorWrapper(_ kind: Node.Kind) -> Bool { + switch kind { + case .methodDescriptor, + .getter, + .setter, + .borrowAccessor, + .mutateAccessor: + true + default: + false + } + } + mutating func printRoot(_ node: Node) async throws -> Target { if isFinal { target.write("final", context: .context(state: .printKeyword)) @@ -88,7 +106,7 @@ extension MemberDeclarationNodePrintable { target.write(isClassMember ? "class" : "static", context: .context(state: .printKeyword)) target.writeSpace() try await unwrapAndPrintDeclaration(first, isStatic: true) - } else if node.kind == .methodDescriptor || node.kind == .getter || node.kind == .setter, let first = node.children.first { + } else if Self.isSkippedAccessorWrapper(node.kind), let first = node.children.first { try await unwrapAndPrintDeclaration(first, isStatic: isStatic) } else if node.kind == .protocolWitness, let second = node.children.second { try await unwrapAndPrintDeclaration(second, isStatic: isStatic) @@ -144,16 +162,17 @@ extension MemberDeclarationNodePrintable { } /// The `{ get }` / `{ get set }` block of a computed variable or a - /// subscript, indented one level deeper than the declaration. - mutating func printAccessorBlock(hasSetter: Bool, indentation: Int) { + /// subscript — `{ borrow }` / `{ borrow mutate }` for SE-0507 accessors — + /// indented one level deeper than the declaration. + mutating func printAccessorBlock(_ keywords: AccessorBlockKeywords, indentation: Int) { target.write(" {") target.write("\n") target.write(String(repeating: " ", count: (indentation + 1) * 4)) - target.write("get", context: .context(state: .printKeyword)) - if hasSetter { + target.write(keywords.read, context: .context(state: .printKeyword)) + if let write = keywords.write { target.write("\n") target.write(String(repeating: " ", count: (indentation + 1) * 4)) - target.write("set", context: .context(state: .printKeyword)) + target.write(write, context: .context(state: .printKeyword)) } target.write("\n") target.write(String(repeating: " ", count: indentation * 4)) diff --git a/Sources/Output/SwiftPrinting/NodePrinter/AccessorBlockKeywords.swift b/Sources/Output/SwiftPrinting/NodePrinter/AccessorBlockKeywords.swift new file mode 100644 index 000000000..458b9bda2 --- /dev/null +++ b/Sources/Output/SwiftPrinting/NodePrinter/AccessorBlockKeywords.swift @@ -0,0 +1,36 @@ +import SwiftDeclaration + +/// The keywords of a computed member's accessor block: `{ get }` and +/// `{ get set }`, or SE-0507's `{ borrow }` and `{ borrow mutate }`. +/// +/// A declared `borrow` excludes a `get` and a `mutate` requires a `borrow` +/// (SE-0507), so the SE-0507 accessors decide the block whenever the member +/// has them: a getter or setter beside them is one the compiler synthesized, +/// for instance to satisfy a protocol requirement. +struct AccessorBlockKeywords: Equatable, Sendable { + let read: String + + let write: String? + + var hasWriteAccessor: Bool { write != nil } + + static func getter(hasSetter: Bool) -> AccessorBlockKeywords { + AccessorBlockKeywords(read: "get", write: hasSetter ? "set" : nil) + } + + init(read: String, write: String?) { + self.read = read + self.write = write + } + + init(of member: some AccessorRepresentable) { + read = member.hasBorrowAccessor ? "borrow" : "get" + write = if member.hasMutateAccessor { + "mutate" + } else if member.hasSetter { + "set" + } else { + nil + } + } +} diff --git a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift index ef1afe9c3..67915f31f 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift @@ -26,22 +26,26 @@ struct SubscriptNodePrinter: MemberDeclarationNodePri let isClassMember: Bool - private let hasSetter: Bool + private let accessorKeywords: AccessorBlockKeywords private let indentation: Int static var declarationNodeKinds: Set { subscriptDeclarationNodeKinds } - init(isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { + init(isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, accessorKeywords: AccessorBlockKeywords, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { self.isOverride = isOverride self.isClassMember = isClassMember self.isFinal = isFinal - self.hasSetter = hasSetter + self.accessorKeywords = accessorKeywords self.indentation = indentation self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false } + init(isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { + self.init(isOverride: isOverride, isClassMember: isClassMember, isFinal: isFinal, accessorKeywords: .getter(hasSetter: hasSetter), indentation: indentation, delegate: delegate) + } + mutating func printDeclaration(_ node: Node) async throws { target.write("subscript", context: .context(state: .printKeyword)) @@ -55,6 +59,6 @@ struct SubscriptNodePrinter: MemberDeclarationNodePri } await printWhereClause(of: subscriptNode) - printAccessorBlock(hasSetter: hasSetter, indentation: indentation) + printAccessorBlock(accessorKeywords, indentation: indentation) } } diff --git a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift index 4a22f34a5..a8a3f42b7 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift @@ -28,23 +28,27 @@ struct VariableNodePrinter: MemberDeclarationNodePrin private let isStored: Bool - private let hasSetter: Bool + private let accessorKeywords: AccessorBlockKeywords private let indentation: Int static var declarationNodeKinds: Set { variableDeclarationNodeKinds } - init(isStored: Bool, isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { + init(isStored: Bool, isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, accessorKeywords: AccessorBlockKeywords, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { self.isStored = isStored self.isOverride = isOverride self.isClassMember = isClassMember self.isFinal = isFinal - self.hasSetter = hasSetter + self.accessorKeywords = accessorKeywords self.indentation = indentation self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false } + init(isStored: Bool, isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { + self.init(isStored: isStored, isOverride: isOverride, isClassMember: isClassMember, isFinal: isFinal, accessorKeywords: .getter(hasSetter: hasSetter), indentation: indentation, delegate: delegate) + } + mutating func printDeclaration(_ node: Node) async throws { let identifier: Node? = if let identifier = node.children.first(of: .identifier) { identifier @@ -57,7 +61,7 @@ struct VariableNodePrinter: MemberDeclarationNodePrin throw MemberDeclarationPrintError.missingIdentifier(node) } - target.write(isStored && !hasSetter ? "let" : "var", context: .context(state: .printKeyword)) + target.write(isStored && !accessorKeywords.hasWriteAccessor ? "let" : "var", context: .context(state: .printKeyword)) target.writeSpace() target.write(identifier.text ?? "", context: .context(for: identifier, parentKind: .variable, state: .printIdentifier)) target.write(": ") @@ -68,6 +72,6 @@ struct VariableNodePrinter: MemberDeclarationNodePrin guard !isStored else { return } - printAccessorBlock(hasSetter: hasSetter, indentation: indentation) + printAccessorBlock(accessorKeywords, indentation: indentation) } } diff --git a/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift new file mode 100644 index 000000000..0d17ef2fe --- /dev/null +++ b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift @@ -0,0 +1,101 @@ +import MachOSwiftSection +import Demangling +import SwiftDeclarationRendering +@_spi(Internals) import SwiftInspection + +/// A protocol's requirement signature split by where each requirement prints +/// (evolution proposal `protocol-requirement-placement`). +/// +/// Every requirement lands in exactly one list, each list keeps the +/// signature's order, and a requirement prints the same words wherever it +/// lands — an inheritance clause only leaves out the `Self.Item:` it is +/// attached to. So both placements state the same requirements by +/// construction; where one lands is the only thing that differs. +package struct ProtocolRequirementPartition { + /// The protocol's inheritance clause: requirements on `Self` itself. + package private(set) var protocolInheritanceClause: [GenericRequirement] = [] + + /// The protocol's `where` clause. + package private(set) var protocolWhereClause: [GenericRequirement] = [] + + /// Each associated type's inheritance clause, by associated type name. + package private(set) var associatedTypeInheritanceClauses: [String: [GenericRequirement]] = [:] + + /// Each associated type's `where` clause, by associated type name. + package private(set) var associatedTypeWhereClauses: [String: [GenericRequirement]] = [:] + + /// `associatedTypeNames` are the protocol's own associated types, the + /// ones its descriptor lists; `.protocolWhereClause` never reads them. + package init(requirements: [GenericRequirement], associatedTypeNames: [String], placement: ProtocolRequirementPlacement, in context: some ReadingContext) { + let ownAssociatedTypeNames = Set(associatedTypeNames) + for requirement in requirements { + if requirement.isProtocolInherited { + protocolInheritanceClause.append(requirement) + continue + } + switch placement { + case .protocolWhereClause: + protocolWhereClause.append(requirement) + case .associatedTypes: + switch Self.location(of: requirement, among: ownAssociatedTypeNames, in: context) { + case .associatedTypeInheritanceClause(let associatedTypeName): + associatedTypeInheritanceClauses[associatedTypeName, default: []].append(requirement) + case .associatedTypeWhereClause(let associatedTypeName): + associatedTypeWhereClauses[associatedTypeName, default: []].append(requirement) + case nil: + protocolWhereClause.append(requirement) + } + } + } + } + + private enum Location { + case associatedTypeInheritanceClause(String) + case associatedTypeWhereClause(String) + } + + /// Where `requirement` prints under `.associatedTypes`; `nil` is the + /// protocol's `where` clause. + /// + /// Only a conformance, superclass or layout requirement on exactly + /// `Self.Item` goes into `Item`'s inheritance clause — the one placement + /// that would change the meaning if it took the wrong associated type. + /// The compiler's own printer does take the wrong one for a member of a + /// member: `Self.Child.Leaf: Hashable` of a recursive protocol reads + /// `associatedtype Leaf: Hashable` in its `.swiftinterface`, a stronger + /// requirement on `Self.Leaf`. Any other requirement goes into the + /// `where` clause of the associated type its member chain starts from + /// (`Self.Child.Leaf` starts from `Child`); a same-type requirement takes + /// a side that is exactly `Self.Item` first, then the left side's chain, + /// then the right's. Inverse and same-shape requirements stay where they + /// were. A `where` clause takes any requirement about `Self`, so none of + /// this can change what the requirements say. + private static func location(of requirement: GenericRequirement, among associatedTypeNames: Set, in context: some ReadingContext) -> Location? { + guard let subject = try? SymbolicDemangler.demangleType(for: requirement.paramManagledName, in: context) else { return nil } + switch requirement.descriptor.flags.kind { + case .protocol, .baseClass, .layout: + if let associatedTypeName = directAssociatedTypeName(of: subject, among: associatedTypeNames) { + return .associatedTypeInheritanceClause(associatedTypeName) + } + return subject.firstProtocolSelfMemberRoot(among: associatedTypeNames).map(Location.associatedTypeWhereClause) + case .sameType: + var sides = [subject] + if case .type(let mangledName) = requirement.content, let rightHandSide = try? SymbolicDemangler.demangleType(for: mangledName, in: context) { + sides.append(rightHandSide) + } + if let associatedTypeName = sides.lazy.compactMap({ directAssociatedTypeName(of: $0, among: associatedTypeNames) }).first { + return .associatedTypeWhereClause(associatedTypeName) + } + return sides.lazy.compactMap { $0.firstProtocolSelfMemberRoot(among: associatedTypeNames) }.first.map(Location.associatedTypeWhereClause) + default: + return nil + } + } + + /// `Item` when `type` is exactly `Self.Item` and `Item` is one of + /// `associatedTypeNames`. + private static func directAssociatedTypeName(of type: Node, among associatedTypeNames: Set) -> String? { + guard let memberNames = type.protocolSelfMemberNames, memberNames.count == 1, let associatedTypeName = memberNames.first, associatedTypeNames.contains(associatedTypeName) else { return nil } + return associatedTypeName + } +} diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index c0c454a5e..58b8b8b6b 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -13,6 +13,48 @@ public enum SwiftDeclarationMemberSortOrder: Hashable, Codable, Sendable, CaseIt case byOffset } +/// Where the interface writes a protocol requirement about one of the +/// protocol's own associated types (evolution proposal +/// `protocol-requirement-placement`). +/// +/// The binary records only the canonical requirement signature, never where +/// the source wrote a requirement, and the two placements state exactly the +/// same requirements: each one once, in the same words, only somewhere else. +/// A requirement on `Self` itself — a refined protocol, `AnyObject`, a +/// superclass — stays in the protocol's inheritance clause under both. +public enum ProtocolRequirementPlacement: Hashable, Codable, Sendable, CaseIterable { + /// Every requirement in the protocol's `where` clause: + /// + /// ```swift + /// protocol Menu where Self.Item: Swift.Sequence, Self.Item.Element: Swift.Hashable { + /// associatedtype Item + /// } + /// ``` + case protocolWhereClause + + /// Each requirement on the associated type it is about, the way the + /// compiler writes a `.swiftinterface`: + /// + /// ```swift + /// protocol Menu { + /// associatedtype Item: Swift.Sequence where Self.Item.Element: Swift.Hashable + /// } + /// ``` + /// + /// A conformance, superclass or layout requirement goes by its subject + /// alone: on exactly `Self.Item` into `Item`'s inheritance clause, on a + /// member chain starting from `Item` (`Self.Item.Element`) into `Item`'s + /// `where` clause, as written in the protocol's. One whose subject is not + /// about the protocol's own associated types stays in the protocol's + /// `where` clause, even when its superclass names one + /// (`Self.Element: Base` on a `Sequence` refinement). A + /// same-type requirement goes into the `where` clause of an associated + /// type either side is about, a side that is exactly `Self.Item` first. + /// Inverse and same-shape requirements stay in the protocol's `where` + /// clause. + case associatedTypes +} + @MemberwiseInit(.public) public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { public var printStrippedSymbolicItem: Bool = true @@ -68,6 +110,17 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// Off by default, and off the output is unchanged byte for byte. public var usesModuleSelectors: Bool = false + /// Where a requirement about one of a protocol's own associated types + /// prints: in the protocol's `where` clause (the default, unchanged byte + /// for byte), or on that `associatedtype` (evolution proposal + /// `protocol-requirement-placement`). The requirements are the same + /// either way. + /// + /// The diff and evolution interfaces always print `.protocolWhereClause`: + /// they compare a protocol's `associatedtype` lines by name alone and + /// print no requirement on them. + public var protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause + public var memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory public var printTypeLayout: Bool = false public var printEnumLayout: Bool = false diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index f75937841..db1c9ac46 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -191,9 +191,11 @@ extension SwiftDeclarationPrinter { // MARK: - Protocol header /// Renders a protocol's declaration header (`protocol Foo : Bar where …`), - /// mirroring `ProtocolDumper.declaration`. + /// mirroring `ProtocolDumper.declaration`. The header carries the + /// requirements `requirementPartition` leaves on the protocol; the rest + /// print on the `associatedtype` lines (`renderProtocolAssociatedTypes`). @SemanticStringBuilder - package func renderProtocolDeclarationHeader(for dumped: MachOSwiftSection.`Protocol`, displayParentName: Bool, leafNameNode: Node? = nil) async throws -> SemanticString { + package func renderProtocolDeclarationHeader(for dumped: MachOSwiftSection.`Protocol`, requirementPartition: ProtocolRequirementPartition, displayParentName: Bool, leafNameNode: Node? = nil) async throws -> SemanticString { let resolver = typeDemangleResolver Keyword(.protocol) Space() @@ -203,37 +205,28 @@ extension SwiftDeclarationPrinter { renderLeafName(kind: .protocol, bareName: try dumped.descriptor.name(in: machO.context), leafNameNode: leafNameNode) } - if dumped.numberOfRequirementsInSignature > 0 { - var requirementInSignatures = dumped.requirementInSignatures - for (offset, requirement) in requirementInSignatures.extract(where: \.isProtocolInherited).offsetEnumerated() { - if offset.isStart { - Standard(":") - } else { - Standard(",") - } - Space() - try await requirement.descriptor.dumpContent(resolver: resolver, in: machO.context) - } - if !requirementInSignatures.isEmpty { - Space() - Keyword(.where) - Space() - - for (offset, requirement) in requirementInSignatures.offsetEnumerated() { - try await requirement.descriptor.dumpProtocolRequirement(resolver: resolver, in: machO.context) - if !offset.isEnd { - Standard(",") - Space() - } - } + for (offset, requirement) in requirementPartition.protocolInheritanceClause.offsetEnumerated() { + if offset.isStart { + Standard(":") + } else { + Standard(",") } + Space() + try await requirement.descriptor.dumpContent(resolver: resolver, in: machO.context) } + try await renderRequirementWhereClause(requirementPartition.protocolWhereClause, resolver: resolver) } /// Renders a protocol's `associatedtype` requirement lines, mirroring - /// `ProtocolDumper.associatedTypes`. + /// `ProtocolDumper.associatedTypes`, each with the requirements + /// `requirementPartition` attaches to it: an inheritance clause + /// (`associatedtype Nested: Swift.Sequence`) and a `where` clause. + /// `~Swift.Copyable` joins the inheritance clause for a name the image's + /// protocol extensions prove suppressible (SE-0503), which is the only + /// way the declaration is known. @SemanticStringBuilder - func renderProtocolAssociatedTypes(for dumped: MachOSwiftSection.`Protocol`, level: Int) async throws -> SemanticString { + func renderProtocolAssociatedTypes(for dumped: MachOSwiftSection.`Protocol`, requirementPartition: ProtocolRequirementPartition, suppressedInvertibleProtocolsByAssociatedTypeName: [String: InvertibleProtocolSet], level: Int) async throws -> SemanticString { + let resolver = typeDemangleResolver let associatedTypes = try dumped.descriptor.associatedTypes(in: machO.context) if !associatedTypes.isEmpty { for (offset, associatedType) in associatedTypes.offsetEnumerated() { @@ -242,6 +235,26 @@ extension SwiftDeclarationPrinter { Keyword(.associatedtype) Space() TypeDeclaration(kind: .other, associatedType) + let inheritanceClause = requirementPartition.associatedTypeInheritanceClauses[associatedType] ?? [] + for (inheritanceOffset, requirement) in inheritanceClause.offsetEnumerated() { + if inheritanceOffset.isStart { + Standard(":") + } else { + Standard(",") + } + Space() + try await requirement.descriptor.dumpProtocolContent(resolver: resolver, in: machO.context) + } + if let suppressedInvertibleProtocols = suppressedInvertibleProtocolsByAssociatedTypeName[associatedType] { + if inheritanceClause.isEmpty { + try await suppressedInvertibleProtocols.dumpInvertedProtocolsInheritance(resolver: resolver) + } else if suppressedInvertibleProtocols.hasInvertedProtocols { + Standard(",") + Space() + try await suppressedInvertibleProtocols.dumpInvertedProtocolNames(resolver: resolver) + } + } + try await renderRequirementWhereClause(requirementPartition.associatedTypeWhereClauses[associatedType] ?? [], resolver: resolver) if offset.isEnd { BreakLine() } @@ -249,6 +262,23 @@ extension SwiftDeclarationPrinter { } } + /// ` where A, B` — or nothing for no requirements. + @SemanticStringBuilder + private func renderRequirementWhereClause(_ requirements: [GenericRequirement], resolver: DemangleResolver) async throws -> SemanticString { + if !requirements.isEmpty { + Space() + Keyword(.where) + Space() + for (offset, requirement) in requirements.offsetEnumerated() { + try await requirement.descriptor.dumpProtocolRequirement(resolver: resolver, in: machO.context) + if !offset.isEnd { + Standard(",") + Space() + } + } + } + } + // MARK: - Extension merged associated-type typealiases /// Emits a deduplicated `typealias` block collected from sibling diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index a42868630..d85afafd3 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -74,6 +74,11 @@ public final class SwiftDeclarationPrinter: S case computed((any StaticFieldLayoutProvider)?) } + /// What names the source files of private declarations; see + /// `setPrivateDeclarationSourceFileProvider(_:)`. + @Mutex + private var privateDeclarationSourceFileProvider: (any PrivateDeclarationSourceFileProviding)? = nil + /// Memoized `__swift5_builtin` lookup behind `rawLayoutBuiltinStorage(of:)` /// (`SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift`), built once /// on first use with the same double-checked pattern as the layout @@ -198,6 +203,43 @@ public final class SwiftDeclarationPrinter: S typeNameResolverRegistry = .init() } + /// Prints every declaration whose name reads a private discriminator the + /// declaration it is printed inside does not under a comment naming the + /// source file `provider` recovers for the discriminator, or saying it + /// could not be recovered (evolution proposal + /// `private-declaration-source-files`); `nil` stops it. + /// + /// The provider is asked once for every private declaration printed: + /// search the whole image before the first print. + public func setPrivateDeclarationSourceFileProvider(_ provider: (any PrivateDeclarationSourceFileProviding)?) { + privateDeclarationSourceFileProvider = provider + } + + /// The source-file comment lines of a declaration named `nodes`, printed + /// inside the declaration named `enclosingNodes` (evolution proposal + /// `private-declaration-source-files`); each call site lays them out. None + /// without a provider, and the nodes are only worked out with one. + package func privateDeclarationSourceFileLines(for nodes: @autoclosure () -> [any DemanglingNode], enclosedBy enclosingNodes: @autoclosure () -> [any DemanglingNode] = []) -> [String] { + guard let privateDeclarationSourceFileProvider else { return [] } + return PrivateDeclarationSourceFileComments.lines(for: nodes(), enclosedBy: enclosingNodes(), provider: privateDeclarationSourceFileProvider) + } + + /// The names a definition prints in its header: a conformance + /// extension's protocol as well as the extended type. What its members' + /// source-file comments leave out. + private func headerNameNodes(of definition: some Definition) -> [any DemanglingNode] { + switch definition { + case let typeDefinition as TypeDefinition: + [typeDefinition.typeName.node] + case let protocolDefinition as ProtocolDefinition: + [protocolDefinition.protocolName.node] + case let extensionDefinition as ExtensionDefinition: + [extensionDefinition.extensionName.node] + (extensionDefinition.conformingProtocolName.map { [$0.node] } ?? []) + default: + [] + } + } + /// Exported-only gate (evolution proposal `exported-only-interface`): /// a type whose descriptor provably is not exported renders as NOTHING — /// an empty result every enclosing `BlockList` / `NestedDeclaration` @@ -237,6 +279,19 @@ public final class SwiftDeclarationPrinter: S BreakLine() } + // The files its private declarations come from (evolution proposal + // `private-declaration-source-files`), leaving out its parent's: a + // type nested in a private type is declared in that type's file. The + // parent, not the name's own context — a local type's is the function + // declaring it, which prints nowhere above it. And the parent at any + // level: a nested definition printed on its own must read as the one + // taken out of its parent's print (`marksNestedDefinitions`). + for line in privateDeclarationSourceFileLines(for: [typeDefinition.typeName.node], enclosedBy: typeDefinition.parent.map { [$0.typeName.node] } ?? []) { + Indent(level: level - 1) + Comment(line) + BreakLine() + } + // Type-level attributes, inferred for this print and kept local: // printing writes nothing to a definition, which is what lets several // tasks print one at once (evolution proposal @@ -369,10 +424,27 @@ public final class SwiftDeclarationPrinter: S try protocolDefinition.index(in: machO) + // Where each requirement prints, decided once for the header and the + // `associatedtype` lines alike (evolution proposal + // `protocol-requirement-placement`). + let requirementPartition = try ProtocolRequirementPartition( + requirements: dumpedProtocol.requirementInSignatures, + associatedTypeNames: dumpedProtocol.descriptor.associatedTypes(in: machO.context), + placement: configuration.protocolRequirementPlacement, + in: machO.context + ) + + // As a type's (evolution proposal `private-declaration-source-files`). + for line in privateDeclarationSourceFileLines(for: [protocolDefinition.protocolName.node], enclosedBy: protocolDefinition.parent.map { [$0.typeName.node] } ?? []) { + Indent(level: level - 1) + Comment(line) + BreakLine() + } + try await DeclarationBlock(level: level) { - try await renderProtocolDeclarationHeader(for: dumpedProtocol, displayParentName: displayParentName) + try await renderProtocolDeclarationHeader(for: dumpedProtocol, requirementPartition: requirementPartition, displayParentName: displayParentName) } body: { - try await renderProtocolAssociatedTypes(for: dumpedProtocol, level: level) + try await renderProtocolAssociatedTypes(for: dumpedProtocol, requirementPartition: requirementPartition, suppressedInvertibleProtocolsByAssociatedTypeName: protocolDefinition.suppressedInvertibleProtocolsByAssociatedTypeName, level: level) try await printDefinition(protocolDefinition, level: level) @@ -446,6 +518,15 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printIncludedExtensionDefinition(_ extensionDefinition: ExtensionDefinition, level: Int) async throws -> SemanticString { + // An extension of a private type, or a conformance to a private + // protocol, is declared in that type's or protocol's file (evolution + // proposal `private-declaration-source-files`). + for line in privateDeclarationSourceFileLines(for: headerNameNodes(of: extensionDefinition)) { + Indent(level: level - 1) + Comment(line) + BreakLine() + } + try await DeclarationBlock(level: level) { try await printExtensionHeader(extensionDefinition, level: level) } body: { @@ -635,9 +716,10 @@ public final class SwiftDeclarationPrinter: S let vtableTransformerClosure = vtableOffsetTransformerClosure let synthesizedPropertyWrapperMembers = synthesizedPropertyWrapperMembers(of: definition) + let enclosingNodes = headerNameNodes(of: definition) await MemberList(level: level) { for member in definition.orderedMembers where !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers, enclosingNodes: enclosingNodes) } // Terminal step: emit `deinit` for classes and noncopyable @@ -670,6 +752,7 @@ public final class SwiftDeclarationPrinter: S let vtableTransformerClosure = vtableOffsetTransformerClosure let synthesizedPropertyWrapperMembers = synthesizedPropertyWrapperMembers(of: definition) + let enclosingNodes = headerNameNodes(of: definition) // A class's vtable members come first, in slot order — the order the // class metadata lays its vtable out in, and for the class's own // slots the source's declaration order — the way the dump walks them @@ -679,13 +762,13 @@ public final class SwiftDeclarationPrinter: S // exactly as before. await MemberList(level: level) { for member in OrderedMember.vtableOrdered(OrderedMember.allMembers(from: definition)) where !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers, enclosingNodes: enclosingNodes) } } for category in MemberCategory.allCases { await MemberList(level: level) { for member in definition.members(in: category) where member.minVTableOffset == nil && !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers, enclosingNodes: enclosingNodes) } } } @@ -717,6 +800,11 @@ public final class SwiftDeclarationPrinter: S /// `MemberList`'s indent level. Returning a plain `SemanticString` without /// `Rows` would fuse them into one row and drop the `BreakLine + Indent` /// separators. + /// + /// `enclosingNodes` are the names of the definition the member is printed + /// in, whose private declarations its source-file comments leave out + /// (evolution proposal `private-declaration-source-files`): a member of a + /// private type is declared in that type's file. @SemanticStringBuilder private func renderMember( _ member: OrderedMember, @@ -725,11 +813,15 @@ public final class SwiftDeclarationPrinter: S offsetCommentOption: SwiftVisibilityOption, printExportStatus: Bool, vtableTransformerClosure: (@Sendable (Int, String?) -> SemanticString)?, - synthesizedPropertyWrapperMembers: SynthesizedPropertyWrapperMembers + synthesizedPropertyWrapperMembers: SynthesizedPropertyWrapperMembers, + enclosingNodes: [any DemanglingNode] ) async -> SemanticString { await Rows(level: level) { switch member { case .allocator(let function), .function(let function): + for line in privateDeclarationSourceFileLines(for: [function.node], enclosedBy: enclosingNodes) { + Comment(line) + } optionalContent(offsetCommentOption) { OffsetComment(prefix: offsetCommentPrefix, offset: function.offset, emit: true) } @@ -763,6 +855,9 @@ public final class SwiftDeclarationPrinter: S await printFunction(function, level: level) case .variable(let variable): + for line in privateDeclarationSourceFileLines(for: [variable.node], enclosedBy: enclosingNodes) { + Comment(line) + } // A stored property of an `@objc @implementation` carries its // REAL field offset (from the ObjC ivar list), so the generic // symbol-offset comment gives way to the field-offset one. @@ -799,6 +894,9 @@ public final class SwiftDeclarationPrinter: S } case .subscript(let `subscript`): + for line in privateDeclarationSourceFileLines(for: [`subscript`.node], enclosedBy: enclosingNodes) { + Comment(line) + } optionalContent(offsetCommentOption) { OffsetComment(prefix: offsetCommentPrefix, offset: `subscript`.offset, emit: true) } @@ -913,7 +1011,7 @@ public final class SwiftDeclarationPrinter: S } try await printUnderObjCVerdicts(of: variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in objcAttributes(objcFacts) - var printer = SemanticVariableNodePrinter(isStored: variable.isStored, isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: variable.hasSetter, indentation: level, delegate: self) + var printer = SemanticVariableNodePrinter(isStored: variable.isStored, isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, accessorKeywords: AccessorBlockKeywords(of: variable), indentation: level, delegate: self) try await printer.printRoot(variable.node.materialize()) } } @@ -931,7 +1029,7 @@ public final class SwiftDeclarationPrinter: S public func printThrowingSubscript(_ `subscript`: SubscriptDefinition, level: Int) async throws -> SemanticString { try await printUnderObjCVerdicts(of: `subscript`.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in objcAttributes(objcFacts) - var printer = SemanticSubscriptNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: `subscript`.hasSetter, indentation: level, delegate: self) + var printer = SemanticSubscriptNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, accessorKeywords: AccessorBlockKeywords(of: `subscript`), indentation: level, delegate: self) try await printer.printRoot(`subscript`.node.materialize()) } } diff --git a/Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift b/Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift new file mode 100644 index 000000000..26ae9d1a6 --- /dev/null +++ b/Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift @@ -0,0 +1,174 @@ +/// Readers for the few A64 encodings this package decodes by hand. +/// +/// Each reader answers `nil` for a word that is not the instruction it reads. +/// Addresses may be in any address space — unslid or runtime — as long as +/// the instruction's own address is given in the same one: `adrp`, `adr` and +/// the immediate branches are relative to it. +/// +/// Hand decoding exists for throughput: scanning every function of a dyld +/// shared cache through Capstone costs about 950 CPU seconds, through these +/// readers about 20 (measured on macOS 27.2, evolution proposal +/// `cross-reference-analysis`). +package enum ARM64InstructionWord { + /// The register number that names the zero register or the stack + /// pointer, depending on the instruction. + package static let zeroOrStackPointerRegister = 31 + + @inlinable + package static func signExtended(_ value: UInt64, bitWidth: Int) -> Int64 { + let shift = UInt64(64 - bitWidth) + return Int64(bitPattern: value << shift) >> Int64(shift) + } + + @inlinable + package static func adding(_ displacement: Int64, to address: UInt64) -> UInt64 { + UInt64(bitPattern: Int64(bitPattern: address) &+ displacement) + } + + /// `bl label`: the call's target. + @inlinable + package static func callTarget(_ word: UInt32, at address: UInt64) -> UInt64? { + guard word & 0xFC00_0000 == 0x9400_0000 else { return nil } + return adding(signExtended(UInt64(word & 0x03FF_FFFF) << 2, bitWidth: 28), to: address) + } + + /// `b label`, the unconditional form: the branch's target. + @inlinable + package static func branchTarget(_ word: UInt32, at address: UInt64) -> UInt64? { + guard word & 0xFC00_0000 == 0x1400_0000 else { return nil } + return adding(signExtended(UInt64(word & 0x03FF_FFFF) << 2, bitWidth: 28), to: address) + } + + /// `b.cond`, `cbz` / `cbnz` and `tbz` / `tbnz`: the target taken when the + /// condition holds. + @inlinable + package static func conditionalBranchTarget(_ word: UInt32, at address: UInt64) -> UInt64? { + if word & 0xFF00_0010 == 0x5400_0000 || word & 0x7E00_0000 == 0x3400_0000 { + return adding(signExtended(UInt64((word >> 5) & 0x7FFFF) << 2, bitWidth: 21), to: address) + } + if word & 0x7E00_0000 == 0x3600_0000 { + return adding(signExtended(UInt64((word >> 5) & 0x3FFF) << 2, bitWidth: 16), to: address) + } + return nil + } + + /// `adrp xd, label` and `adr xd, label`: the register written and the + /// address it receives. + @inlinable + package static func addressMaterialization(_ word: UInt32, at address: UInt64) -> (destination: Int, address: UInt64)? { + let destination = Int(word & 0x1F) + let immediate = (UInt64((word >> 5) & 0x7FFFF) << 2) | UInt64((word >> 29) & 0x3) + if word & 0x9F00_0000 == 0x9000_0000 { + return (destination, adding(signExtended(immediate << 12, bitWidth: 33), to: address & ~UInt64(0xFFF))) + } + if word & 0x9F00_0000 == 0x1000_0000 { + return (destination, adding(signExtended(immediate, bitWidth: 21), to: address)) + } + return nil + } + + /// `add xd, xn, #imm{, lsl #12}` and `sub xd, xn, #imm{, lsl #12}` on + /// 64-bit registers, the subtraction as a negative addend. + @inlinable + package static func addImmediate(_ word: UInt32) -> (destination: Int, source: Int, addend: Int64)? { + let opcode = word & 0xFF80_0000 + guard opcode == 0x9100_0000 || opcode == 0xD100_0000 else { return nil } + let shift: UInt64 = (word >> 22) & 1 == 1 ? 12 : 0 + let magnitude = Int64(bitPattern: UInt64((word >> 10) & 0xFFF) << shift) + return (Int(word & 0x1F), Int((word >> 5) & 0x1F), opcode == 0x9100_0000 ? magnitude : -magnitude) + } + + /// A 64-bit load from a base register plus a constant displacement: + /// `ldr xt, [xn, #imm]`, `ldur xt, [xn, #simm]`, the pre-indexed + /// `ldr xt, [xn, #simm]!`, and `ldraa` / `ldrab`. + @inlinable + package static func load(_ word: UInt32) -> (destination: Int, base: Int, displacement: Int64, writesBack: Bool)? { + let destination = Int(word & 0x1F) + let base = Int((word >> 5) & 0x1F) + if word & 0xFFC0_0000 == 0xF940_0000 { + return (destination, base, Int64((word >> 10) & 0xFFF) << 3, false) + } + if word & 0xFFE0_0C00 == 0xF840_0000 { + return (destination, base, signExtended(UInt64((word >> 12) & 0x1FF), bitWidth: 9), false) + } + if word & 0xFFE0_0C00 == 0xF840_0C00 { + return (destination, base, signExtended(UInt64((word >> 12) & 0x1FF), bitWidth: 9), true) + } + if word & 0xFF20_0400 == 0xF820_0400 { + let immediate = (UInt64((word >> 22) & 1) << 9) | UInt64((word >> 12) & 0x1FF) + return (destination, base, signExtended(immediate, bitWidth: 10) << 3, (word >> 11) & 1 == 1) + } + return nil + } + + /// `ret`, `retaa`, `retab`. + @inlinable + package static func isReturn(_ word: UInt32) -> Bool { + word & 0xFFFF_FC1F == 0xD65F_0000 || word == 0xD65F_0BFF || word == 0xD65F_0FFF + } + + /// A branch or a call through a register. + package struct RegisterBranch: Equatable, Sendable { + /// The register holding the destination. + package let target: Int + /// The register holding the pointer-authentication modifier + /// (`blraa` / `blrab` / `braa` / `brab`); `nil` for the forms without one. + package let modifier: Int? + package let isCall: Bool + package let isAuthenticated: Bool + + @inlinable + package init(target: Int, modifier: Int?, isCall: Bool, isAuthenticated: Bool) { + self.target = target + self.modifier = modifier + self.isCall = isCall + self.isAuthenticated = isAuthenticated + } + } + + /// `blr`, `br`, and their authenticating forms `blraa` / `blrab` / + /// `blraaz` / `blrabz` / `braa` / `brab` / `braaz` / `brabz`. + @inlinable + package static func registerBranch(_ word: UInt32) -> RegisterBranch? { + let target = Int((word >> 5) & 0x1F) + switch word & 0xFFFF_FC1F { + case 0xD63F_0000: + return RegisterBranch(target: target, modifier: nil, isCall: true, isAuthenticated: false) + case 0xD61F_0000: + return RegisterBranch(target: target, modifier: nil, isCall: false, isAuthenticated: false) + case 0xD63F_081F, 0xD63F_0C1F: + return RegisterBranch(target: target, modifier: nil, isCall: true, isAuthenticated: true) + case 0xD61F_081F, 0xD61F_0C1F: + return RegisterBranch(target: target, modifier: nil, isCall: false, isAuthenticated: true) + default: + break + } + switch word & 0xFFFF_F800 { + case 0xD73F_0800: + return RegisterBranch(target: target, modifier: Int(word & 0x1F), isCall: true, isAuthenticated: true) + case 0xD71F_0800: + return RegisterBranch(target: target, modifier: Int(word & 0x1F), isCall: false, isAuthenticated: true) + default: + return nil + } + } + + /// `movz xd, #imm{, lsl #shift}` and `movk xd, #imm{, lsl #shift}` on + /// 64-bit registers. `keepsOtherBits` is true for `movk`. + @inlinable + package static func moveWide(_ word: UInt32) -> (destination: Int, immediate: UInt16, shift: Int, keepsOtherBits: Bool)? { + let opcode = word & 0xFF80_0000 + guard opcode == 0xD280_0000 || opcode == 0xF280_0000 else { return nil } + return (Int(word & 0x1F), UInt16(truncatingIfNeeded: word >> 5), Int((word >> 21) & 0x3) * 16, opcode == 0xF280_0000) + } + + /// `mov xd, xm`, which is `orr xd, xzr, xm`. + @inlinable + package static func moveRegister(_ word: UInt32) -> (destination: Int, source: Int)? { + guard word & 0xFFE0_FFE0 == 0xAA00_03E0 else { return nil } + return (Int(word & 0x1F), Int((word >> 16) & 0x1F)) + } + + /// `nop`. + package static let noOperation: UInt32 = 0xD503_201F +} diff --git a/Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift b/Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift new file mode 100644 index 000000000..0ef837a6b --- /dev/null +++ b/Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift @@ -0,0 +1,87 @@ +/// Code the linker or the dyld cache builder put between a call and its +/// callee, recognized by its shape. +/// +/// Three shapes exist: +/// +/// - **A stub that loads its target from a GOT slot.** A standalone binary's +/// `__stubs` entry is `adrp x16, page` / `ldr x16, [x16, #offset]` / +/// `br x16`; an arm64e `__auth_stubs` entry, and the stubs a dyld cache +/// shares between all of its images (macOS 27, iOS 27), are `adrp x17, +/// page` / `add x17, x17, #offset` / `ldr x16, [x17]` / `braa x16, x17`. +/// - **A stub island**, which computes its target outright and loads +/// nothing: `adrp x16, page` / `add x16, x16, #offset` / `br x16`. The cache +/// builder places these between images when a `bl` cannot reach across the +/// cache's subcaches; islands may chain. +/// - **An Objective-C selector stub shared by the whole cache** (macOS 27, +/// iOS 27): `adrp x1, page` / `add x1, x1, #offset` / `b `. +/// `x1` receives the selector string itself, so the stub names the message. +/// A cache carries one such stub per selector per subcache, so the selector +/// string's address — not the stub's — identifies the message. +/// +/// The image's own `__objc_stubs` entries (`adrp x1` / `ldr x1, [x1, #selref]` +/// / `adrp x16` / `ldr x16, [x16, #objc_msgSend]` / `br x16`) are read through +/// MachOKit's `objcStubs(in:)`, not here. +package enum ARM64Trampoline: Equatable, Sendable { + /// The trampoline loads its target from the slot at `slotAddress`. + case slotLoad(slotAddress: UInt64) + /// The trampoline jumps to `target`, which it computes without a load. + case computed(target: UInt64) + /// A shared selector stub: the selector string lies at + /// `selectorAddress`, and the stub branches to `messageSendAddress`. + case selectorStub(selectorAddress: UInt64, messageSendAddress: UInt64) + + /// How many instruction words the longest shape occupies. + package static let maximumInstructionCount = 4 + + /// Recognizes the trampoline whose first instructions are `words`, + /// located at `address`. `words` may hold more instructions than the + /// shape needs. + package init?(words: some Collection, at address: UInt64) { + let instructions = Array(words.prefix(Self.maximumInstructionCount)) + if instructions.count >= 3, + let page = ARM64InstructionWord.addressMaterialization(instructions[0], at: address), page.destination == 1, + let offset = ARM64InstructionWord.addImmediate(instructions[1]), offset.destination == 1, offset.source == 1, + let messageSendAddress = ARM64InstructionWord.branchTarget(instructions[2], at: address &+ 8) { + self = .selectorStub( + selectorAddress: ARM64InstructionWord.adding(offset.addend, to: page.address), + messageSendAddress: messageSendAddress + ) + return + } + + // A GOT stub or an island: address arithmetic, then a load or a jump + // through the register the arithmetic produced. + var registerValues: [Int: UInt64] = [:] + for (index, word) in instructions.enumerated() { + let instructionAddress = address &+ UInt64(index * 4) + if let materialization = ARM64InstructionWord.addressMaterialization(word, at: instructionAddress) { + registerValues[materialization.destination] = materialization.address + } else if let arithmetic = ARM64InstructionWord.addImmediate(word) { + guard let source = registerValues[arithmetic.source] else { return nil } + registerValues[arithmetic.destination] = ARM64InstructionWord.adding(arithmetic.addend, to: source) + } else if let load = ARM64InstructionWord.load(word) { + guard !load.writesBack, let base = registerValues[load.base] else { return nil } + self = .slotLoad(slotAddress: ARM64InstructionWord.adding(load.displacement, to: base)) + return + } else if let branch = ARM64InstructionWord.registerBranch(word), !branch.isCall { + guard let target = registerValues[branch.target] else { return nil } + self = .computed(target: target) + return + } else if word != ARM64InstructionWord.noOperation { + return nil + } + } + return nil + } + + /// Reads the trampoline at `pointer`, the location in memory of the + /// code whose address is `address`. + package init?(readingAt pointer: UnsafeRawPointer, address: UInt64) { + var words: [UInt32] = [] + words.reserveCapacity(Self.maximumInstructionCount) + for index in 0 ..< Self.maximumInstructionCount { + words.append(UInt32(littleEndian: pointer.loadUnaligned(fromByteOffset: index * 4, as: UInt32.self))) + } + self.init(words: words, at: address) + } +} diff --git a/Sources/Support/Utilities/Alignment.swift b/Sources/Support/Utilities/Alignment.swift index 48552bd55..d052745c3 100644 --- a/Sources/Support/Utilities/Alignment.swift +++ b/Sources/Support/Utilities/Alignment.swift @@ -1,15 +1,13 @@ import Foundation extension FixedWidthInteger { - /*@inlinable*/ - /*@inline(__always)*/ + @inline(always) package func aligned(to alignment: Self) -> Self { assert(alignment > 0 && (alignment & (alignment - 1) == 0), "Alignment must be a power of 2") return (self &+ alignment &- 1) & ~(alignment &- 1) } - /*@inlinable*/ - /*@inline(__always)*/ + @inline(always) package mutating func align(to alignment: Self) { self = aligned(to: alignment) } diff --git a/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift b/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift new file mode 100644 index 000000000..96cf97f3b --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift @@ -0,0 +1,12 @@ +import MachOKitExtensions +import SwiftDeclarationRendering + +/// A wrapper that declares what it wraps can say so to the library: the +/// library then asks the reader beneath it whatever it needs to know about the +/// reader. +extension ForwardingMachOReader: MachOReaderWrapper where Declaration == DeclaredWrapper {} + +/// The printers take a reader that renders its own field-layout comments; a +/// declared wrapper renders them through the reader it wraps, with nothing +/// written here. +extension ForwardingMachOReader: FieldLayoutRenderable where Base: FieldLayoutRenderable, Declaration == DeclaredWrapper {} diff --git a/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader.swift b/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader.swift new file mode 100644 index 000000000..1d51746d6 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader.swift @@ -0,0 +1,189 @@ +import Foundation +import MachOKit +import MachOKitExtensions +import MachOReading +import MachOSwiftSection + +/// Whether a ``ForwardingMachOReader`` tells the library what it wraps. +package protocol ForwardingMachOReaderDeclaration: Sendable {} + +/// The reader declares the reader it forwards to — a host's wrapper that +/// adopted `MachOReaderWrapper`. +package enum DeclaredWrapper: ForwardingMachOReaderDeclaration {} + +/// The reader forwards every read and says nothing about it — a host's +/// wrapper written before `MachOReaderWrapper` existed. +package enum UndeclaredWrapper: ForwardingMachOReaderDeclaration {} + +/// A reader that forwards every requirement to `base` and adds nothing. +/// +/// The shape of a host's wrapper type — MachOKitUI's `MachOImageSource` and +/// `MachOFileSource` hold a `MachOImage` / `MachOFile` for their UI and +/// forward the reading protocols to it — so a test can read an image through +/// the wrapper and through `base` and expect the same answers. Every +/// requirement is forwarded, the defaulted ones too, so nothing a default +/// implementation computes differently from `base`'s own can tell the two +/// apart. +package struct ForwardingMachOReader: MachOSwiftSectionRepresentableWithCache { + package let base: Base + + package init(_ base: Base) { + self.base = base + } +} + +// MARK: - MachORepresentable + +extension ForwardingMachOReader { + package typealias LoadCommands = Base.LoadCommands + package typealias Symbol = Base.Symbol + package typealias Symbols64 = Base.Symbols64 + package typealias Symbols = Base.Symbols + package typealias IndirectSymbols = Base.IndirectSymbols + package typealias CFStrings32 = Base.CFStrings32 + package typealias CFStrings64 = Base.CFStrings64 + package typealias RebaseOperations = Base.RebaseOperations + package typealias BindOperations = Base.BindOperations + package typealias ExportTrie = Base.ExportTrie + package typealias Strings = Base.Strings + package typealias UTF16Strings = Base.UTF16Strings + package typealias FunctionStarts = Base.FunctionStarts + package typealias DataInCode = Base.DataInCode + package typealias DyldChainedFixups = Base.DyldChainedFixups + package typealias ExternalRelocations = Base.ExternalRelocations + package typealias CodeSign = Base.CodeSign + + package var is64Bit: Bool { base.is64Bit } + package var headerSize: Int { base.headerSize } + package var header: MachHeader { base.header } + package var loadCommands: LoadCommands { base.loadCommands } + package var endian: Endian { base.endian } + package var rpaths: [String] { base.rpaths } + package var dependencies: [DependedDylib] { base.dependencies } + package var segments: [any SegmentCommandProtocol] { base.segments } + package var segments64: AnySequence { base.segments64 } + package var segments32: AnySequence { base.segments32 } + package var preferredLoadAddress: UInt64? { base.preferredLoadAddress } + package var sections: [any SectionProtocol] { base.sections } + package var sections64: [Section64] { base.sections64 } + package var sections32: [Section] { base.sections32 } + package var symbols: AnyRandomAccessCollection { base.symbols } + package var symbols64: Symbols64? { base.symbols64 } + package var symbols32: Symbols? { base.symbols32 } + package var indirectSymbols: IndirectSymbols? { base.indirectSymbols } + package var symbolStrings: Strings? { base.symbolStrings } + package var cStrings: Strings? { base.cStrings } + package var allCStringTables: [Strings] { base.allCStringTables } + package var allCStrings: [String] { base.allCStrings } + package var uStrings: UTF16Strings? { base.uStrings } + package var cfStrings: [any CFStringProtocol]? { base.cfStrings } + package var cfStrings64: CFStrings64? { base.cfStrings64 } + package var cfStrings32: CFStrings32? { base.cfStrings32 } + package var embeddedInfoPlist: [String: Any]? { base.embeddedInfoPlist } + package var rebaseOperations: RebaseOperations? { base.rebaseOperations } + package var bindOperations: BindOperations? { base.bindOperations } + package var weakBindOperations: BindOperations? { base.weakBindOperations } + package var lazyBindOperations: BindOperations? { base.lazyBindOperations } + package var exportTrie: ExportTrie? { base.exportTrie } + package var exportedSymbols: [ExportedSymbol] { base.exportedSymbols } + package var bindingSymbols: [BindingSymbol] { base.bindingSymbols } + package var weakBindingSymbols: [BindingSymbol] { base.weakBindingSymbols } + package var lazyBindingSymbols: [BindingSymbol] { base.lazyBindingSymbols } + package var rebases: [Rebase] { base.rebases } + package var functionStarts: FunctionStarts? { base.functionStarts } + package var dataInCode: DataInCode? { base.dataInCode } + package var dyldChainedFixups: DyldChainedFixups? { base.dyldChainedFixups } + package var externalRelocations: ExternalRelocations? { base.externalRelocations } + package var classicBindingSymbols: [ClassicBindingSymbol]? { base.classicBindingSymbols } + package var classicLazyBindingSymbols: [ClassicBindingSymbol]? { base.classicLazyBindingSymbols } + package var codeSign: CodeSign? { base.codeSign } + package var expectedMachOFileSize: Int? { base.expectedMachOFileSize } + + package func closestSymbol(at offset: Int, inSection sectionNumber: Int, isGlobalOnly: Bool) -> Symbol? { + base.closestSymbol(at: offset, inSection: sectionNumber, isGlobalOnly: isGlobalOnly) + } + + package func closestSymbols(at offset: Int, inSection sectionNumber: Int, isGlobalOnly: Bool) -> [Symbol] { + base.closestSymbols(at: offset, inSection: sectionNumber, isGlobalOnly: isGlobalOnly) + } + + package func symbol(for offset: Int, inSection sectionNumber: Int, isGlobalOnly: Bool) -> Symbol? { + base.symbol(for: offset, inSection: sectionNumber, isGlobalOnly: isGlobalOnly) + } + + package func symbols(for offset: Int, inSection sectionNumber: Int, isGlobalOnly: Bool) -> [Symbol] { + base.symbols(for: offset, inSection: sectionNumber, isGlobalOnly: isGlobalOnly) + } + + package func symbols(named name: String, mangled: Bool) -> [Symbol] { + base.symbols(named: name, mangled: mangled) + } + + package func symbol(named name: String, mangled: Bool, inSection sectionNumber: Int, isGlobalOnly: Bool) -> Symbol? { + base.symbol(named: name, mangled: mangled, inSection: sectionNumber, isGlobalOnly: isGlobalOnly) + } + + package func contains(unslidAddress address: UInt64) -> Bool { + base.contains(unslidAddress: address) + } + + package func stripPointerTags(of rawVMAddr: UInt64) -> UInt64 { + base.stripPointerTags(of: rawVMAddr) + } +} + +// MARK: - MachORepresentableWithCache + +extension ForwardingMachOReader { + package typealias Cache = Base.Cache + package typealias Identifier = Base.Identifier + + package var imagePath: String { base.imagePath } + package var identifier: Identifier { base.identifier } + package var cache: Cache? { base.cache } + package var startOffset: Int { base.startOffset } + + package func resolveOffset(at address: UInt64) -> Int { + base.resolveOffset(at: address) + } +} + +// MARK: - Readable + +extension ForwardingMachOReader { + package func readElement(offset: Int) throws -> Element { + try base.readElement(offset: offset) + } + + package func readElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { + try base.readWrapperElement(offset: offset) + } + + package func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { + try base.readWrapperElement(offset: offset) + } + + package func readElements(offset: Int, numberOfElements: Int) throws -> [Element] { + try base.readElements(offset: offset, numberOfElements: numberOfElements) + } + + package func readElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { + try base.readWrapperElements(offset: offset, numberOfElements: numberOfElements) + } + + package func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { + try base.readWrapperElements(offset: offset, numberOfElements: numberOfElements) + } + + package func readString(offset: Int) throws -> String { + try base.readString(offset: offset) + } +} + +// MARK: - MachOSwiftSectionRepresentableWithCache + +extension ForwardingMachOReader { + package typealias SwiftSection = Base.SwiftSection + + package var swift: SwiftSection { base.swift } +} diff --git a/Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift b/Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift new file mode 100644 index 000000000..b296b48c6 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift @@ -0,0 +1,216 @@ +import Foundation +import MachOKit +import MachOFoundation +import Testing + +/// An on-the-fly fixture for how a protocol's requirement signature prints +/// (evolution proposal `protocol-requirement-placement`). +/// +/// The binary records a protocol's requirements only in their canonical +/// form, never where the source wrote them, so each protocol here collects +/// the requirement shapes the printer has to tell apart: +/// +/// - `CompositeRequirements`: same-type and superclass requirements whose +/// right-hand side is a composite type — an array, a tuple, an optional, a +/// bound generic class, an array of `Self`, and an array of a member whose +/// mangling names the protocol declaring it (`Seventh` conforms to two +/// protocols, so `Seventh.Element` is qualified with `Sequence`). +/// - `DirectRequirements`: conformance, superclass and layout requirements on +/// exactly `Self.Item`, one associated type with two, and a member of a +/// member (`Nested.Element`). +/// - `SameTypeRequirements`: same-type requirements between two associated +/// types (canonically `Self.First == Self.Second.Target`) and with `Self` +/// (`Self == Self.Third.Target`). +/// - `RecursiveRequirements`: `Child.Leaf: Hashable` on a protocol whose +/// `Child` conforms to it again — the shape the compiler's own printer +/// attaches to `Leaf`, changing its meaning. +/// - `RefinedRequirements` and `InheritedOnlyRequirements`: requirements on a +/// refined protocol's associated type (`Element`), which no +/// `associatedtype` of the protocol itself declares. +/// - `SubjectOnlyRequirements`: a superclass requirement on the refined +/// `Element` whose superclass names the protocol's own `First` +/// (`Element: GenericBase`). A conformance, superclass or layout +/// requirement goes by its subject alone, as in the compiler's own +/// printer, so this one stays on the protocol. +/// - `ClassBoundRequirements` and `MenuRequirements`: requirements on `Self` +/// (`AnyObject`, a refined protocol) beside one on an associated type. +/// +/// The declarations those protocols mention live in `supportSource`, apart +/// from `protocolSource`, so a printed form of the protocols compiles against +/// the same declarations again (`machOFile(compiling:)`). +package enum ProtocolRequirementPlacementFixture { + package static let moduleName = "ProtocolRequirementPlacementFixture" + + /// `Anchor` is ballast for the reader: a module without a class compiles + /// to a dylib with no `__DATA` segment (see + /// `ExportedOnlyLibraryEvolutionFixtureTests`). + package static let supportSource = """ + public protocol Marker {} + + public class BaseClass {} + + public class GenericBase {} + + public protocol Pointing { + associatedtype Target + } + + public final class Anchor { + public func run() {} + } + """ + + /// The protocols of `protocolSource`, in source order. + package static let protocolNames = [ + "CompositeRequirements", + "DirectRequirements", + "SameTypeRequirements", + "RecursiveRequirements", + "RefinedRequirements", + "InheritedOnlyRequirements", + "SubjectOnlyRequirements", + "ClassBoundRequirements", + "MenuRequirements", + ] + + package static let protocolSource = """ + public protocol CompositeRequirements { + associatedtype First + associatedtype Second where Second == [First] + associatedtype Third where Third == (First, [First]) + associatedtype Fourth where Fourth == First? + associatedtype Fifth: GenericBase + associatedtype Sixth where Sixth == [Self] + associatedtype Seventh: Sequence, Marker + associatedtype Eighth where Eighth == [Seventh.Element] + } + + public protocol DirectRequirements { + associatedtype Conforming: Marker, Hashable + associatedtype Subclass: BaseClass + associatedtype ClassBound: AnyObject + associatedtype ClassAndProtocol: BaseClass, Marker + associatedtype Nested: Sequence where Nested.Element: Marker + associatedtype Concrete where Concrete == Int + } + + public protocol SameTypeRequirements { + associatedtype First + associatedtype Second: Pointing where Second.Target == First + associatedtype Third: Pointing where Third.Target == Self + } + + public protocol RecursiveRequirements { + associatedtype Child: RecursiveRequirements where Child.Leaf: Hashable + associatedtype Leaf + } + + public protocol RefinedRequirements: Sequence where Element: Marker { + associatedtype Storage: Collection where Storage.Element == Element + } + + public protocol InheritedOnlyRequirements: Sequence where Element: Hashable {} + + public protocol SubjectOnlyRequirements: Sequence where Element: GenericBase { + associatedtype First + } + + public protocol ClassBoundRequirements: AnyObject { + associatedtype Item: AnyObject + } + + public protocol MenuRequirements: Identifiable where MenuItem: Marker { + associatedtype MenuItem + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + /// The fixture: `supportSource` and `protocolSource` in one library. + package static func machOFile() throws -> MachOFile { + try machOFile(compiling: protocolSource) + } + + /// `supportSource` and `protocolDeclarations` compiled into one library + /// named `moduleName`, as the fixture itself is, so every name a printed + /// protocol mentions resolves to the same declaration again. Each + /// distinct source compiles once per process. + package static func machOFile(compiling protocolDeclarations: String) throws -> MachOFile { + let libraryURL = try CompiledLibraries.shared.libraryURL(for: supportSource + "\n\n" + protocolDeclarations) + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + private enum WorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in WorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private final class CompiledLibraries: @unchecked Sendable { + static let shared = CompiledLibraries() + + private let lock = NSLock() + + private var libraryURLsBySource: [String: URL] = [:] + + /// Compiles under the lock: two tests asking for the same source wait + /// for one compiler run. The wait is on `swiftc`, never on a pool + /// thread. + func libraryURL(for source: String) throws -> URL { + lock.lock() + defer { lock.unlock() } + if let libraryURL = libraryURLsBySource[source] { + return libraryURL + } + let libraryURL = try Self.compile(source) + libraryURLsBySource[source] = libraryURL + return libraryURL + } + + private static func compile(_ source: String) throws -> URL { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + "swiftc", "-swift-version", "5", "-emit-library", + "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/Swift64DeclarationShapesFixture.swift b/Sources/TestSupport/MachOTestingSupport/Swift64DeclarationShapesFixture.swift new file mode 100644 index 000000000..2feab426c --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/Swift64DeclarationShapesFixture.swift @@ -0,0 +1,237 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOSwiftSection +import Testing + +/// An on-the-fly fixture for the declaration shapes Swift 6.4 introduced and +/// the readers once lost (evolution proposal +/// `borrow-accessors-and-suppressed-associated-types`): +/// +/// - SE-0507 `borrow` / `mutate` accessors on a property, a subscript and a +/// protocol requirement. Such a member has no getter or setter symbol, only +/// `…vb` / `…vz`, and printed as nothing at all. +/// - SE-0503 associated types declared `~Copyable` / `~Escapable`. The binary +/// records the declaration only through an extension of the protocol whose +/// signature suppresses the default, and an extension gets that default +/// only for a PRIMARY associated type — so each suppressed primary +/// associated type comes with such an extension, while `Strategy` (not +/// primary: its extension's `where Strategy: ~Copyable` mangles to nothing) +/// and `UnprovenElementContainer.Element` (no extension at all) cannot be +/// told apart from a Copyable one. `Index` is the Copyable control. +/// `ConstrainedSuppressedElementContainer.Element` is both suppressed and +/// constrained, so with requirements printed on the associated types +/// (evolution proposal `protocol-requirement-placement`) the suppression +/// joins an inheritance clause that is already there. +/// +/// Only a Swift 6.4 compiler builds this: 6.3 rejects the accessors as an +/// experimental feature it cannot enable in a production compiler. CI builds +/// with Xcode 26.6 and `SymbolTestsCore` must not change (it would move every +/// offset the ABI baselines pin), so the fixture is compiled here with the +/// first Swift 6.4 or newer toolchain found — the selected one, then any other +/// Xcode in `/Applications` — and a suite using it is enabled only when there +/// is one (`isAvailable`). +package enum Swift64DeclarationShapesFixture { + package static let moduleName = "Swift64DeclarationShapesFixture" + + package static let source = """ + // MARK: - SE-0507 borrow / mutate accessors + + public struct BorrowedStorage { + var stored: Int = 0 + + public init() {} + + public var borrowedOnly: Int { + borrow { stored } + } + + public var borrowedAndMutated: Int { + borrow { stored } + mutate { &stored } + } + + public var computed: Int { + get { stored } + set { stored = newValue } + } + + public subscript(position: Int) -> Int { + borrow { stored } + mutate { &stored } + } + } + + public protocol BorrowRequirement { + var element: Int { borrow mutate } + var readOnlyElement: Int { borrow } + } + + // MARK: - SE-0503 suppressed associated types + + public protocol SuppressedElementContainer: ~Copyable { + associatedtype Element: ~Copyable + associatedtype View: ~Escapable + associatedtype Payload: ~Copyable & ~Escapable + associatedtype Strategy: ~Copyable + associatedtype Index + + func count() -> Int + } + + extension SuppressedElementContainer where Self: ~Copyable, Element: ~Copyable { + public func isEmpty() -> Bool { count() == 0 } + } + + extension SuppressedElementContainer where View: ~Escapable { + public func hasView() -> Bool { true } + } + + extension SuppressedElementContainer where Payload: ~Copyable, Payload: ~Escapable { + public static func payloadDescription() -> String { "" } + } + + extension SuppressedElementContainer where Strategy: ~Copyable { + public func strategyDescription() -> String { "" } + } + + extension SuppressedElementContainer { + public func describe() -> String { "\\(count())" } + } + + public protocol UnprovenElementContainer { + associatedtype Element: ~Copyable + } + + public protocol SuppressibleMarker: ~Copyable {} + + public protocol ConstrainedSuppressedElementContainer { + associatedtype Element: SuppressibleMarker & ~Copyable + } + + extension ConstrainedSuppressedElementContainer where Element: ~Copyable { + public func elementDescription() -> String { "" } + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + /// Whether a Swift 6.4 or newer toolchain exists to compile the fixture. + package static var isAvailable: Bool { + toolchain != nil + } + + /// The developer directory of the toolchain the fixture compiles with — + /// `nil` for the selected one, which `xcrun` uses with no `DEVELOPER_DIR`. + private struct Toolchain: Sendable { + let developerDirectory: String? + } + + private static let toolchain: Toolchain? = { + let candidates: [String?] = [nil] + installedDeveloperDirectories() + return candidates.lazy + .filter { swiftVersion(developerDirectory: $0).map { $0 >= (6, 4) } ?? false } + .map { Toolchain(developerDirectory: $0) } + .first + }() + + private static func installedDeveloperDirectories() -> [String] { + let applicationsURL = URL(fileURLWithPath: "/Applications") + let applicationNames = (try? FileManager.default.contentsOfDirectory(atPath: applicationsURL.path)) ?? [] + return applicationNames + .filter { $0.hasPrefix("Xcode") && $0.hasSuffix(".app") } + .sorted() + .map { applicationsURL.appendingPathComponent($0).appendingPathComponent("Contents/Developer").path } + .filter { FileManager.default.fileExists(atPath: $0) } + } + + /// The `(major, minor)` of `swiftc -version` under `developerDirectory`. + private static func swiftVersion(developerDirectory: String?) -> (Int, Int)? { + guard let output = try? run(["swiftc", "-version"], developerDirectory: developerDirectory, capturesStandardOutput: true) else { return nil } + guard let range = output.range(of: #"Swift version (\d+)\.(\d+)"#, options: .regularExpression) else { return nil } + let numbers = output[range].dropFirst("Swift version ".count).split(separator: ".").compactMap { Int($0) } + guard numbers.count == 2 else { return nil } + return (numbers[0], numbers[1]) + } + + @discardableResult + private static func run(_ arguments: [String], developerDirectory: String?, capturesStandardOutput: Bool = false) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + if let developerDirectory { + // `swift test` hands the test process its own toolchain's + // `SDKROOT` and `DYLD_FRAMEWORK_PATH` (PrivateFrameworks included); + // inherited, they make another Xcode's `xcodebuild -find` load the + // wrong private frameworks and `xcrun` fail with exit 72. + var environment = ProcessInfo.processInfo.environment.filter { !$0.key.hasPrefix("DYLD_") && $0.key != "SDKROOT" } + environment["DEVELOPER_DIR"] = developerDirectory + process.environment = environment + } + let outputPipe = Pipe() + if capturesStandardOutput { + process.standardOutput = outputPipe + } + process.standardError = outputPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + let output = String(decoding: outputData, as: UTF8.self) + guard process.terminationStatus == 0 else { + throw CompilationError(diagnostics: output) + } + return output + } + + private enum WorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in WorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + /// Compiled once per process. + private static let compilationResult: Result = { + Result { + guard let toolchain else { + throw CompilationError(diagnostics: "no Swift 6.4 or newer toolchain is installed") + } + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + try run([ + // The language mode pinned, so a newer toolchain compiles the + // source the same way. Library evolution keeps the protocol + // requirements resilient, the way a framework ships them. + "swiftc", "-swift-version", "6", "-Onone", "-emit-library", "-enable-library-evolution", + "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ], developerDirectory: toolchain.developerDirectory) + return libraryURL + } + }() + + package static func machOFile() throws -> MachOFile { + switch try MachOKit.loadFromFile(url: try compilationResult.get()) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift b/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift new file mode 100644 index 000000000..9c1e2e028 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift @@ -0,0 +1,145 @@ +import Foundation +import Testing +import Capstone +import ARM64InstructionDecoding + +@Suite +struct ARM64InstructionWordTests { + private let address: UInt64 = 0x1_9810_09C0 + + @Test func callAndBranchTargetsInBothDirections() { + for target in [address + 0x8, address - 0x1_0000, address + 0x7FF_FFFC, address - 0x800_0000] { + #expect(ARM64InstructionWord.callTarget(InstructionEncoding.branchWithLink(at: address, to: target), at: address) == target) + #expect(ARM64InstructionWord.branchTarget(InstructionEncoding.branch(at: address, to: target), at: address) == target) + } + // Neither reader claims the other's instruction. + #expect(ARM64InstructionWord.callTarget(InstructionEncoding.branch(at: address, to: address + 8), at: address) == nil) + #expect(ARM64InstructionWord.branchTarget(InstructionEncoding.branchWithLink(at: address, to: address + 8), at: address) == nil) + } + + @Test func pageAddressAcrossFourGigabytes() throws { + let page: UInt64 = 0x1_E20F_A000 + let word = InstructionEncoding.adrp(17, at: address, page: page) + let materialization = try #require(ARM64InstructionWord.addressMaterialization(word, at: address)) + #expect(materialization.destination == 17) + #expect(materialization.address == page) + let backward = InstructionEncoding.adrp(1, at: address, page: 0x1_2000_0000) + #expect(ARM64InstructionWord.addressMaterialization(backward, at: address)?.address == 0x1_2000_0000) + } + + @Test func immediateArithmeticAndLoads() throws { + let add = try #require(ARM64InstructionWord.addImmediate(InstructionEncoding.add(17, 17, immediate: 0xD00))) + #expect(add.destination == 17 && add.source == 17 && add.addend == 0xD00) + let sub = try #require(ARM64InstructionWord.addImmediate(InstructionEncoding.sub(3, 4, immediate: 0x10))) + #expect(sub.destination == 3 && sub.source == 4 && sub.addend == -0x10) + + let load = try #require(ARM64InstructionWord.load(InstructionEncoding.loadUnsignedOffset(16, base: 16, byteOffset: 0x7E0))) + #expect(load.destination == 16 && load.base == 16 && load.displacement == 0x7E0 && !load.writesBack) + let preIndexed = try #require(ARM64InstructionWord.load(InstructionEncoding.loadPreIndexed(9, base: 8, byteOffset: 0x30))) + #expect(preIndexed.destination == 9 && preIndexed.base == 8 && preIndexed.displacement == 0x30 && preIndexed.writesBack) + let negative = try #require(ARM64InstructionWord.load(InstructionEncoding.loadPreIndexed(9, base: 8, byteOffset: -0x20))) + #expect(negative.displacement == -0x20) + } + + @Test func registerBranchesAndConstants() throws { + let tailCall = try #require(ARM64InstructionWord.registerBranch(InstructionEncoding.branchToRegisterAuthenticated(16, modifier: 17))) + #expect(tailCall == .init(target: 16, modifier: 17, isCall: false, isAuthenticated: true)) + let call = try #require(ARM64InstructionWord.registerBranch(InstructionEncoding.callRegisterAuthenticated(9, modifier: 16))) + #expect(call == .init(target: 9, modifier: 16, isCall: true, isAuthenticated: true)) + let plain = try #require(ARM64InstructionWord.registerBranch(InstructionEncoding.branchToRegister(16))) + #expect(plain == .init(target: 16, modifier: nil, isCall: false, isAuthenticated: false)) + + let blend = try #require(ARM64InstructionWord.moveWide(InstructionEncoding.moveKeep(16, immediate: 0x18B8, shift: 48))) + #expect(blend.destination == 16 && blend.immediate == 0x18B8 && blend.shift == 48 && blend.keepsOtherBits) + let alone = try #require(ARM64InstructionWord.moveWide(InstructionEncoding.moveZero(17, immediate: 0x489B))) + #expect(alone.destination == 17 && alone.immediate == 0x489B && alone.shift == 0 && !alone.keepsOtherBits) + let copy = try #require(ARM64InstructionWord.moveRegister(InstructionEncoding.moveRegister(19, 0))) + #expect(copy.destination == 19 && copy.source == 0) + + let conditional = InstructionEncoding.compareBranchZero(0, at: address, to: address + 0x40) + #expect(ARM64InstructionWord.conditionalBranchTarget(conditional, at: address) == address + 0x40) + } + + /// Capstone disassembles every hand-built word as the instruction the + /// readers took it for, so a wrong encoder cannot hide a wrong reader. + @Test func capstoneAgreesWithTheEncoders() throws { + let words: [UInt32] = [ + InstructionEncoding.adrp(17, at: address, page: 0x1_E20F_A000), + InstructionEncoding.add(17, 17, immediate: 0xD00), + InstructionEncoding.loadUnsignedOffset(16, base: 17, byteOffset: 0), + InstructionEncoding.branchToRegisterAuthenticated(16, modifier: 17), + InstructionEncoding.loadPreIndexed(9, base: 8, byteOffset: 0x30), + InstructionEncoding.moveKeep(16, immediate: 0x18B8, shift: 48), + InstructionEncoding.callRegisterAuthenticated(9, modifier: 16), + InstructionEncoding.branchWithLink(at: address + 28, to: address - 0x1_0000), + ] + let instructions = try Disassembler().decode(InstructionEncoding.bytes(of: words), address: address) + #expect(instructions.map(\.mnemonic) == ["adrp", "add", "ldr", "braa", "ldr", "movk", "blraa", "bl"]) + #expect(instructions[0].operands[1].immediateValue == 0x1_E20F_A000) + #expect(instructions[7].operands[0].immediateValue == Int64(address - 0x1_0000)) + } +} + +@Suite +struct ARM64TrampolineTests { + private let address: UInt64 = 0x1_9810_09C0 + + @Test func authenticatedSlotStub() { + // What macOS 27 shares between all images of its cache, and an + // arm64e image's own __auth_stubs entry. + let words = [ + InstructionEncoding.adrp(17, at: address, page: 0x1_E20F_A000), + InstructionEncoding.add(17, 17, immediate: 0xD00), + InstructionEncoding.loadUnsignedOffset(16, base: 17, byteOffset: 0), + InstructionEncoding.branchToRegisterAuthenticated(16, modifier: 17), + ] + #expect(ARM64Trampoline(words: words, at: address) == .slotLoad(slotAddress: 0x1_E20F_AD00)) + } + + @Test func standaloneSlotStub() { + let words = [ + InstructionEncoding.adrp(16, at: address, page: 0x1_0000_8000), + InstructionEncoding.loadUnsignedOffset(16, base: 16, byteOffset: 0x18), + InstructionEncoding.branchToRegister(16), + 0xD420_0020, + ] + #expect(ARM64Trampoline(words: words, at: address) == .slotLoad(slotAddress: 0x1_0000_8018)) + } + + @Test func stubIsland() { + let words = [ + InstructionEncoding.adrp(16, at: address, page: 0x1_8A4E_B000), + InstructionEncoding.add(16, 16, immediate: 0x8D8), + InstructionEncoding.branchToRegister(16), + ARM64InstructionWord.noOperation, + ] + #expect(ARM64Trampoline(words: words, at: address) == .computed(target: 0x1_8A4E_B8D8)) + } + + @Test func sharedSelectorStub() { + // The macOS 27.2 stub for `_makeKeyRegardlessOfVisibility`, which the + // cache keeps within a `b`'s reach of the `objc_msgSend` copy. + let stubAddress: UInt64 = 0x1_9001_E750 + let messageSend: UInt64 = 0x1_9000_0800 + let words = [ + InstructionEncoding.adrp(1, at: stubAddress, page: 0x1_F57F_7000), + InstructionEncoding.add(1, 1, immediate: 0xF98), + InstructionEncoding.branch(at: stubAddress + 8, to: messageSend), + 0xD420_0020, + ] + #expect(ARM64Trampoline(words: words, at: stubAddress) == .selectorStub(selectorAddress: 0x1_F57F_7F98, messageSendAddress: messageSend)) + } + + @Test func ordinaryCodeIsNoTrampoline() { + // pacibsp / stp x20, x19, [sp, #-0x20]! / stp x29, x30, [sp, #0x10] / add x29, sp, #0x10 + #expect(ARM64Trampoline(words: [0xD503_237F, 0xA9BE_4FF4, 0xA901_7BFD, 0x9100_43FD], at: address) == nil) + // A load from a register the arithmetic never set. + let words = [ + InstructionEncoding.adrp(17, at: address, page: 0x1_E20F_A000), + InstructionEncoding.loadUnsignedOffset(16, base: 8, byteOffset: 0), + InstructionEncoding.branchToRegister(16), + ARM64InstructionWord.noOperation, + ] + #expect(ARM64Trampoline(words: words, at: address) == nil) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift b/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift new file mode 100644 index 000000000..f6ee72dff --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift @@ -0,0 +1,117 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis + +/// Foundation's index, built once for the suite: a Debug build scans an image +/// of its size in seconds. +private enum FoundationIndex { + static let imageIndex = SharedAnalyzer.analyzer?.imagePaths.firstIndex { $0.hasSuffix("/Foundation.framework/Versions/C/Foundation") } + static let index = imageIndex.flatMap { SharedAnalyzer.analyzer?.referenceIndex(ofImageAt: $0) } +} + +/// A ``CodeReferenceIndex`` answers what a scan of its image would, at a +/// fraction of a whole table's memory. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct CodeReferenceIndexTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + /// Every key a whole table files references under, the index files the + /// same references under, in the same order; and it keeps nothing else + /// but the Swift type names, which a type query reads. + @Test func indexFilesEveryKeyLikeTheTable() throws { + let foundation = try #require(FoundationIndex.imageIndex) + let index = try #require(FoundationIndex.index) + let table = analyzer.referenceTable(ofImageAt: foundation) + var mismatchedKeys: [CodeReferenceTable.Key] = [] + for key in table.keys where index.references(to: [key]) != table.references(to: key) { + if mismatchedKeys.count < 5 { mismatchedKeys.append(key) } + } + #expect(mismatchedKeys.isEmpty, "\(mismatchedKeys)") + let keptReferences = table.references.filter { reference in + if reference.target.tableKey != nil { return true } + if case .swiftTypeName = reference.target { return true } + return false + } + #expect(index.referenceCount == keptReferences.count) + #expect(index.referenceCount < table.references.count) + } + + /// Several keys at once — a selector, a function in another image, a + /// class — come back exactly as a scan filtered by them finds them. + @Test func indexAnswersAQueryLikeAFilteredScan() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let swiftCore = try imageIndex(endingWith: "/libswiftCore.dylib") + let beginAccess = try #require(analyzer.functions(inImageAt: swiftCore).first { $0.name == .symbol("_swift_beginAccess") }) + let keys: Set = [.selector("orderWindow:relativeTo:"), .function(beginAccess.location), .objectiveCClass("NSWindow")] + let index = analyzer.referenceIndex(ofImageAt: appKit) + let fromIndex = index.references(to: keys) + #expect(!fromIndex.isEmpty) + #expect(fromIndex == analyzer.references(to: keys, inImageAt: appKit)) + } + + /// A Swift type's references — by descriptor and metadata, by the names + /// that mention it, and for a class by its class object — come back as a + /// scan for the type finds them. `Sa` is spelled out in names rather than + /// referred to, which takes demangling them. + @Test(arguments: [ + ("/Foundation.framework/Versions/C/Foundation", "10Foundation3URLV"), + ("/Foundation.framework/Versions/C/Foundation", "10Foundation11JSONEncoderC"), + ("/usr/lib/swift/libswiftCore.dylib", "Sa"), + ]) + func indexFindsSwiftTypesLikeTheScan(definingImageSuffix: String, key: String) throws { + let foundation = try #require(FoundationIndex.imageIndex) + let index = try #require(FoundationIndex.index) + let definer = try imageIndex(endingWith: definingImageSuffix) + let location = try #require(analyzer.swiftTypeDescriptorLocations(withKey: key, inImageAt: definer).first, "no type \(key)") + let identity = try #require(analyzer.swiftTypeIdentity(ofDescriptorAt: location)) + let fromIndex = analyzer.references(toSwiftType: identity, in: index) + #expect(!fromIndex.isEmpty) + #expect(fromIndex == analyzer.references(toSwiftType: identity, inImageAt: foundation)) + } + + /// What lets a host keep an index for every image it has open. + @Test func indexIsAFractionOfTheTable() throws { + let foundation = try #require(FoundationIndex.imageIndex) + let index = try #require(FoundationIndex.index) + let table = analyzer.referenceTable(ofImageAt: foundation) + #expect(index.approximateByteCount * 2 < table.approximateByteCount, "index \(index.approximateByteCount) bytes, table \(table.approximateByteCount) bytes") + } + + /// Naming what an index answers needs the image's function table, which + /// building the index keeps — unlike a whole-image scan for a table. + @Test func buildingAnIndexKeepsTheFunctionTable() throws { + let freshAnalyzer = try #require(CrossReferenceAnalyzer()) + let libobjc = try #require(freshAnalyzer.imagePaths.firstIndex { $0.hasSuffix("/usr/lib/libobjc.A.dylib") }) + #expect(freshAnalyzer.existingFunctionTable(ofImageAt: libobjc) == nil) + _ = freshAnalyzer.referenceIndex(ofImageAt: libobjc) + #expect(freshAnalyzer.existingFunctionTable(ofImageAt: libobjc) != nil) + } + + /// Progress is reported from the first function to the last, and a + /// report answered with "stop" ends the scan without an index. + @Test func progressReportsAndStops() throws { + let libobjc = try imageIndex(endingWith: "/usr/lib/libobjc.A.dylib") + var reports: [(Int, Int)] = [] + let index = analyzer.referenceIndex(ofImageAt: libobjc) { scannedFunctionCount, functionCount in + reports.append((scannedFunctionCount, functionCount)) + return true + } + #expect(index != nil) + let functionCount = try #require(reports.last?.1) + #expect(reports.first?.0 == 0) + #expect(reports.last?.0 == functionCount) + #expect(reports.allSatisfy { $0.1 == functionCount }) + + var stoppedReportCount = 0 + let stopped = analyzer.referenceIndex(ofImageAt: libobjc) { _, _ in + stoppedReportCount += 1 + return false + } + #expect(stopped == nil) + #expect(stoppedReportCount == 1) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift new file mode 100644 index 000000000..28c69b93b --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift @@ -0,0 +1,336 @@ +import Foundation +import Testing +import Capstone +import MachOKit +@testable import CrossReferenceAnalysis + +/// One analyzer for the whole suite: building it reads every image of the +/// shared cache. +enum SharedAnalyzer { + static let analyzer = CrossReferenceAnalyzer() +} + +/// Reads the shared cache mapped into the test process. AppKit and +/// SwiftUICore are read whether or not anything loaded them — the whole +/// cache is mapped into every process. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct CrossReferenceAnalyzerTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + private func function(named name: String, inImageAt imageIndex: Int) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: imageIndex).first { $0.name == .symbol(name) }, "no function \(name)") + } + + @Test func knowsEveryImageOfTheSharedCache() { + #expect(analyzer.images.count > 1000) + #expect(analyzer.imagePaths.contains { $0.hasSuffix("/libobjc.A.dylib") }) + #expect(!analyzer.messageSendLocations.isEmpty) + #expect(!analyzer.runtimeHelperLocations.isEmpty) + } + + /// The three messages this method sends — through the image's own + /// `__objc_stubs` up to macOS 26, through the stubs the cache shares + /// from macOS 27 — each to the method's own receiver. + @Test func objectiveCMethodSendsItsMessages() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let method = try function(named: "-[NSWindow makeKeyAndOrderFront:]", inImageAt: appKit) + let sends = analyzer.references(madeBy: method).compactMap { reference -> (String, ReceiverClassHint, CodeReference.Kind)? in + guard case .messageSend(let selector, let receiver) = reference.target else { return nil } + return (selector, receiver, reference.kind) + } + #expect(sends.map(\.0) == ["_makeKeyRegardlessOfVisibility", "orderWindow:relativeTo:", "_enableEnablingKeyEquivalentForDefaultButtonCell"]) + let everySendGoesToTheReceiver = sends.allSatisfy { $0.1 == .methodReceiver } + #expect(everySendGoesToTheReceiver) + #expect(sends.map(\.2) == [.call, .call, .tailCall]) + } + + /// A classic `objc_msgSend` inside the shared cache passes the selector + /// string's own address: the cache builder rewrote the load of the + /// selector reference into `adrp` / `add` of the string. + /// `-[NSObject debugDescription]` is `return [self description];`, which + /// macOS 27.2 compiles to `adrp x8; add x1, x8; b _objc_msgSend`. + @Test func classicSendsInsideTheCacheNameTheirSelector() throws { + let libobjc = try imageIndex(endingWith: "/usr/lib/libobjc.A.dylib") + let method = try function(named: "-[NSObject debugDescription]", inImageAt: libobjc) + let sends = analyzer.references(madeBy: method).compactMap { reference -> (String, ReceiverClassHint)? in + guard case .messageSend(let selector, let receiver) = reference.target else { return nil } + return (selector, receiver) + } + #expect(sends.map(\.0) == ["description"]) + #expect(sends.first?.1 == .methodReceiver) + } + + /// A forward branch carries what the registers hold to its target. + /// `+[NSObject instanceMethodForSelector:]` is `cbz x2, L; …; b ; L: …; bl `: `L` is reached + /// only from the entry, where `x0` is still the receiver. Forgetting the + /// registers after the tail call — a shortcut tried on the way — lost + /// that. + @Test func branchesCarryTheirStateToTheirTargets() throws { + let libobjc = try imageIndex(endingWith: "/usr/lib/libobjc.A.dylib") + let method = try function(named: "+[NSObject instanceMethodForSelector:]", inImageAt: libobjc) + let receivers = analyzer.references(madeBy: method).compactMap { reference -> ReceiverClassHint? in + guard case .messageSend("doesNotRecognizeSelector:", let receiver) = reference.target else { return nil } + return receiver + } + #expect(receivers == [.methodReceiver]) + } + + /// Two paths that reach one instruction leave a register known only + /// when both put the same thing in it. In + /// `-[NSString stringByAppendingString:]` one block puts the argument in + /// `x0`, the next puts `self`, and both jump to one `copyWithZone:` send; + /// reading straight down, as the first batch did, called its receiver + /// `self`. + @Test func pathsThatDisagreeLeaveTheRegisterUnknown() throws { + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let method = try function(named: "-[NSString stringByAppendingString:]", inImageAt: foundation) + let receivers = analyzer.references(madeBy: method).compactMap { reference -> ReceiverClassHint? in + guard case .messageSend("copyWithZone:", let receiver) = reference.target else { return nil } + return receiver + } + #expect(receivers == [.unknown]) + } + + /// A Swift image's calls into the Swift runtime go through a GOT stub + /// — the image's own `__auth_stubs` up to macOS 26, a stub the cache + /// shares from macOS 27 — and must land on the runtime's function. + @Test func callsThroughStubsReachTheRuntime() throws { + let swiftUICore = try imageIndex(endingWith: "/SwiftUICore.framework/Versions/A/SwiftUICore") + let swiftCore = try imageIndex(endingWith: "/libswiftCore.dylib") + let table = analyzer.referenceTable(ofImageAt: swiftUICore) + let beginAccessCalls = table.references.filter { reference in + guard case .function(let location) = reference.target, location.imageIndex == swiftCore else { return false } + return analyzer.symbolName(at: location) == "_swift_beginAccess" + } + #expect(beginAccessCalls.count > 100) + let everyCallIsMarkedAsAHelper = beginAccessCalls.allSatisfy { $0.isRuntimeHelperCall } + #expect(everyCallIsMarkedAsAHelper) + + let unrecognized = table.references.filter { if case .unrecognized = $0.target { true } else { false } } + #expect(unrecognized.count * 1000 < table.references.count, "unrecognized targets: \(unrecognized.count) of \(table.references.count)") + } + + @Test func tableGroupsReferencesByWhatTheyReference() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let table = analyzer.referenceTable(ofImageAt: appKit) + let senders = table.references(to: .selector("orderWindow:relativeTo:")) + let method = try function(named: "-[NSWindow makeKeyAndOrderFront:]", inImageAt: appKit) + #expect(senders.contains { $0.function == method.location }) + #expect(table.approximateByteCount > table.references.count) + } + + /// A query for some keys answers exactly what the whole table files under + /// them, in the same order. + @Test func filteredQueryMatchesTheTable() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let swiftCore = try imageIndex(endingWith: "/libswiftCore.dylib") + let table = analyzer.referenceTable(ofImageAt: appKit) + let beginAccess = try #require(table.keys.first { key in + if case .function(let location) = key { location.imageIndex == swiftCore } else { false } + }) + let keys: Set = [.selector("orderWindow:relativeTo:"), beginAccess] + let filtered = analyzer.references(to: keys, inImageAt: appKit) + let expected = table.references.filter { $0.target.tableKey.map(keys.contains) ?? false } + #expect(!filtered.isEmpty) + #expect(filtered == expected) + } + + /// A cross-image query scans thousands of images; keeping the function + /// table of each one held 1.5 GB after scanning a macOS 27.2 cache. + @Test func wholeImageScansKeepNoFunctionTable() throws { + let freshAnalyzer = try #require(CrossReferenceAnalyzer()) + let foundation = try #require(freshAnalyzer.imagePaths.firstIndex { $0.hasSuffix("/Foundation.framework/Versions/C/Foundation") }) + let table = freshAnalyzer.referenceTable(ofImageAt: foundation) + #expect(!table.references.isEmpty) + #expect(freshAnalyzer.existingFunctionTable(ofImageAt: foundation) == nil) + // Naming functions is what keeps one. + _ = freshAnalyzer.functions(inImageAt: foundation) + #expect(freshAnalyzer.existingFunctionTable(ofImageAt: foundation) != nil) + } + + /// Naming a query's results across many images keeps no function table + /// either, and names exactly what the image's own listing names. + @Test func namingResultsKeepsNoFunctionTable() throws { + let freshAnalyzer = try #require(CrossReferenceAnalyzer()) + let appKit = try #require(freshAnalyzer.imagePaths.firstIndex { $0.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) + let senders = freshAnalyzer.references(to: [.selector("orderWindow:relativeTo:")], inImageAt: appKit) + let named = freshAnalyzer.functions(containing: senders.map(\.function)) + #expect(freshAnalyzer.existingFunctionTable(ofImageAt: appKit) == nil) + #expect(named.count == Set(senders.map(\.function)).count) + let listed = Dictionary(uniqueKeysWithValues: analyzer.functions(inImageAt: appKit).map { ($0.location, $0) }) + let namesMatchTheListing = named.allSatisfy { listed[$0.key] == $0.value } + let namesTheSender = named.values.contains { $0.name == .symbol("-[NSWindow makeKeyAndOrderFront:]") } + #expect(namesMatchTheListing) + #expect(namesTheSender) + } + + @Test func prefiltersImagesBySelectorAndImport() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let everyImage = Array(analyzer.images.indices) + let senders = analyzer.imageIndices(referencingSelector: "orderWindow:relativeTo:", among: everyImage) + #expect(senders.contains(appKit)) + #expect(senders.count < everyImage.count / 10) + #expect(analyzer.imageIndices(referencingSelector: "noSuchSelectorAnywhere:forCrossReferenceTests:", among: everyImage).isEmpty) + + #expect(analyzer.imageIndices(importing: "_objc_release", among: [appKit]) == [appKit]) + #expect(analyzer.imageIndices(importing: "_noSuchFunctionForCrossReferenceTests", among: everyImage).isEmpty) + } + + /// A prefilter may drop only images that cannot reference the subject. + /// Every image it keeps that a scan finds sending the selector is a + /// sender; every image it drops must be one the scan finds nothing in. + /// From macOS 27 the sends go through stubs the cache shares, or pass the + /// selector string's own address — the image's selector reference is what + /// the prefilter reads, so it has to outlive both rewrites. + /// + /// The dropped images are sampled, every sixteenth: a Debug build scans + /// the whole cache in minutes, not seconds. + @Test(arguments: ["orderWindow:relativeTo:", "description", "count"]) + func selectorPrefilterKeepsEverySender(selector: String) throws { + let everyImage = Array(analyzer.images.indices) + let kept = analyzer.imageIndices(referencingSelector: selector, among: everyImage) + let keys: Set = [.selector(selector)] + #expect(!imagesReferencing(keys, among: Array(kept.prefix(64))).isEmpty) + let droppedSample = Self.sample(of: Set(everyImage).subtracting(kept)) + let missed = imagesReferencing(keys, among: droppedSample) + #expect(missed.isEmpty, "prefilter dropped senders: \(missed.sorted().prefix(5).map { analyzer.imagePaths[$0] })") + } + + /// The same for an exported function: an image that calls it is its own + /// or imports one of its names — even where the cache builder bound the + /// call straight to the function. + @Test(arguments: zip( + ["/CoreFoundation.framework/Versions/A/CoreFoundation", "/usr/lib/system/libdispatch.dylib"], + ["_CFRelease", "_dispatch_async"] + )) + func importPrefilterKeepsEveryCaller(imageSuffix: String, symbol: String) throws { + let owner = try imageIndex(endingWith: imageSuffix) + let function = try function(named: symbol, inImageAt: owner) + let everyImage = Array(analyzer.images.indices) + var kept: Set = [owner] + for name in [symbol] + function.foldedSymbolNames { + kept.formUnion(analyzer.imageIndices(importing: name, among: everyImage)) + } + let keys: Set = [.function(function.location), .importedSymbol(symbol)] + let importers = kept.subtracting([owner]).sorted() + #expect(!imagesReferencing(keys, among: Array(importers.prefix(64))).isEmpty) + let droppedSample = Self.sample(of: Set(everyImage).subtracting(kept)) + let missed = imagesReferencing(keys, among: droppedSample) + #expect(missed.isEmpty, "prefilter dropped callers: \(missed.sorted().prefix(5).map { analyzer.imagePaths[$0] })") + } + + /// The same for a Swift function, which few cache images import by name: + /// only 245 of the macOS 27.2 cache's 4,113 images keep any Swift symbol + /// among their undefined symbols, so a prefilter by imports kept the 44 + /// images importing `URL.path` and dropped every other caller. The images + /// that can bind to Foundation are what is kept now. + @Test func swiftFunctionPrefilterKeepsEveryCaller() throws { + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let symbol = "_$s10Foundation3URLV4pathSSvg" + let function = try function(named: symbol, inImageAt: foundation) + let everyImage = Array(analyzer.images.indices) + let kept = Set(analyzer.imageIndices(callingFunctionAt: function.location, symbolNames: [symbol] + function.foldedSymbolNames, among: everyImage)) + let keys: Set = [.function(function.location), .importedSymbol(symbol)] + let callers = kept.subtracting([foundation]).sorted() + #expect(!imagesReferencing(keys, among: Array(callers.prefix(64))).isEmpty) + let droppedSample = Self.sample(of: Set(everyImage).subtracting(kept)) + let missed = imagesReferencing(keys, among: droppedSample) + #expect(missed.isEmpty, "prefilter dropped callers: \(missed.sorted().prefix(5).map { analyzer.imagePaths[$0] })") + } + + /// Every sixteenth of `imageIndices`, in order. + private static func sample(of imageIndices: Set) -> [Int] { + imageIndices.sorted().enumerated().filter { $0.offset % 16 == 0 }.map(\.element) + } + + /// The images among `imageIndices` with any reference to `keys`. + private func imagesReferencing(_ keys: Set, among imageIndices: [Int]) -> Set { + let found = ImageIndexCollector() + let analyzer = analyzer + DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + if !analyzer.references(to: keys, inImageAt: imageIndex).isEmpty { found.insert(imageIndex) } + } + return found.indices + } + + /// Capstone decodes the same functions independently: every call and + /// every branch out of a function it finds, the scanner found at the + /// same address; and every call or branch out the scanner reports is one + /// of those, or a `br` — which Capstone cannot tell from a jump-table + /// jump, and the scanner reports when the register was loaded from + /// memory. + @Test func callSitesMatchCapstone() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let functions = analyzer.functions(inImageAt: appKit) + let disassembler = try Disassembler() + let image = analyzer.images[appKit] + let slide = try #require(image.vmaddrSlide) + var comparedFunctionCount = 0 + var comparedBranchOutCount = 0 + + for function in stride(from: 0, to: functions.count, by: max(1, functions.count / 400)).map({ functions[$0] }) where function.size >= 4 { + let pointer = try #require(UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(function.location.address)) &+ slide)) + let code = Data(bytes: pointer, count: function.size) + let instructions = disassembler.decode(code, address: function.location.address) + // Capstone stops at a word it cannot decode; compare only what it read whole. + guard instructions.count * 4 == function.size else { continue } + comparedFunctionCount += 1 + + let start = function.location.address + let end = start + UInt64(function.size) + var expected = Set() + var registerBranches = Set() + for instruction in instructions { + switch instruction.identifier { + case .bl, .blr, .blraa, .blraaz, .blrab, .blrabz, .braa, .braaz, .brab, .brabz: + expected.insert(instruction.address) + case .br: + registerBranches.insert(instruction.address) + case .b, .cbz, .cbnz, .tbz, .tbnz, .bc: + let operandIndex = instruction.identifier == .tbz || instruction.identifier == .tbnz ? 2 : (instruction.identifier == .cbz || instruction.identifier == .cbnz ? 1 : 0) + if operandIndex < instruction.operands.count, + let target = instruction.operands[operandIndex].immediateValue.map({ UInt64(bitPattern: $0) }), target < start || target >= end { + expected.insert(instruction.address) + comparedBranchOutCount += 1 + } + default: + break + } + } + // Type references sit on `adrp`, `add` and `ldr`; only calls and + // branches out are compared. + let found = Set(analyzer.references(madeBy: function).filter { $0.kind != .reference }.map(\.instructionAddress)) + let missing = expected.subtracting(found) + #expect(missing.isEmpty, "\(function.name.map { "\($0)" } ?? "unnamed") at 0x\(String(start, radix: 16)): missing \(missing.sorted().map { String($0, radix: 16) })") + let extra = found.subtracting(expected).subtracting(registerBranches) + #expect(extra.isEmpty, "\(function.name.map { "\($0)" } ?? "unnamed") at 0x\(String(start, radix: 16)): no call at \(extra.sorted().map { String($0, radix: 16) })") + } + #expect(comparedFunctionCount > 100) + // Without operands this half of the comparison would silently compare nothing. + #expect(comparedBranchOutCount > 1) + } +} + +/// Image indices gathered from concurrent scans. +final class ImageIndexCollector: @unchecked Sendable { + private let lock = NSLock() + private var collected = Set() + + func insert(_ imageIndex: Int) { + lock.lock() + defer { lock.unlock() } + collected.insert(imageIndex) + } + + var indices: Set { + lock.lock() + defer { lock.unlock() } + return collected + } +} diff --git a/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift b/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift new file mode 100644 index 000000000..942d16b96 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift @@ -0,0 +1,139 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +import Demangling +@testable import CrossReferenceAnalysis + +/// The names a function gets when the symbol table has none: the export +/// trie, the Objective-C method lists, the Swift metadata. Each source is +/// checked against the symbols where both exist. The images are picked for +/// what macOS 27.2 strips from them — SiriAppIntents' symbol table, Matter's +/// method symbols — so an update that strips them differently moves them. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct FallbackNamingTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + /// SiriAppIntents' symbol table holds two entries; its export trie names + /// tens of thousands of its functions. Every exported function start is + /// named by its export. + @Test func exportTrieNamesWhatTheSymbolTableDoesNot() throws { + let siriAppIntents = try imageIndex(endingWith: "/SiriAppIntents.framework/Versions/A/SiriAppIntents") + let table = analyzer.functionTable(ofImageAt: siriAppIntents) + let exports = analyzer.images[siriAppIntents].exportedSymbols.compactMap { symbol -> (UInt64, String)? in + guard let offset = symbol.offset else { return nil } + let address = UInt64(bitPattern: Int64(bitPattern: table.headerAddress) &+ Int64(offset)) + return (address >= table.textStart && address < table.textEnd) ? (address, symbol.name) : nil + } + #expect(exports.count > 1000) + var checked = 0 + for (address, name) in exports.prefix(300) { + let function = try #require(analyzer.function(containing: CodeLocation(imageIndex: siriAppIntents, address: address))) + guard function.location.address == address else { continue } + checked += 1 + let names = [function.name].compactMap { name -> String? in + if case .symbol(let symbol)? = name { return symbol } + return nil + } + function.foldedSymbolNames + #expect(names.contains(name), "\(name) at 0x\(String(address, radix: 16)) named \(String(describing: function.name))") + } + #expect(checked > 200) + } + + /// Where AppKit's symbol table names a method `-[Class(Category) sel]`, + /// the method lists name the same address `-[Class sel]`. + @Test func methodListsAgreeWithMethodSymbols() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let table = analyzer.functionTable(ofImageAt: appKit) + let methods = table.fallbackNames.objectiveCMethods() + #expect(methods.count > 50000) + var compared = 0 + var agreeing = 0 + for index in table.starts.indices { + guard let name = table.primaryName(ofFunctionAt: index), name[1] == 0x5B, name[0] == 0x2D || name[0] == 0x2B, + let method = methods[table.starts[index]] + else { continue } + compared += 1 + let symbol = String(cString: name) + if symbol == Self.withoutCategory("\(method.isClassMethod ? "+" : "-")[\(method.className) \(method.selector)]") || + Self.withoutCategory(symbol) == "\(method.isClassMethod ? "+" : "-")[\(method.className) \(method.selector)]" { + agreeing += 1 + } + } + #expect(compared > 50000) + #expect(Double(agreeing) / Double(max(compared, 1)) > 0.999, "\(agreeing) of \(compared) agree") + } + + /// An image whose Objective-C methods carry no symbols gets them named + /// from the method lists. + @Test func methodListsNameUnsymbolizedMethods() throws { + let matter = try imageIndex(endingWith: "/Matter.framework/Versions/A/Matter") + let methodNames = analyzer.functions(inImageAt: matter).filter { + if case .objectiveCMethod? = $0.name { return true } + return false + } + #expect(methodNames.count > 10000) + } + + /// Where SwiftUICore's symbol table names a metadata accessor, a + /// singleton completion function or a vtable implementation, the name + /// rebuilt from the metadata is the same symbol. + @Test func swiftMetadataNamesMatchTheirSymbols() throws { + let swiftUICore = try imageIndex(endingWith: "/SwiftUICore.framework/Versions/A/SwiftUICore") + let table = analyzer.functionTable(ofImageAt: swiftUICore) + var compared = 0 + var agreeing = 0 + var mismatches: [String] = [] + for index in table.starts.indices { + guard let name = table.primaryName(ofFunctionAt: index), + let rebuilt = table.fallbackNames.swiftName(at: table.starts[index]) + else { continue } + compared += 1 + let symbol = String(cString: name) + let folded = table.foldedNames[table.starts[index]]?.map { String(cString: $0) } ?? [] + if ([symbol] + folded).contains("_" + rebuilt) { + agreeing += 1 + } else if mismatches.count < 5 { + mismatches.append("\(symbol) vs \(rebuilt)") + } + } + #expect(compared > 5000) + #expect(Double(agreeing) / Double(max(compared, 1)) > 0.99, "\(agreeing) of \(compared) agree; e.g. \(mismatches)") + } + + /// In a Swift image with no symbol table to speak of, every type's + /// metadata accessor is named: a public type's by the export trie, any + /// other's rebuilt from its descriptor — and a rebuilt name demangles to + /// a metadata accessor. + @Test func everyAccessorOfAnUnsymbolizedImageIsNamed() throws { + let siriAppIntents = try imageIndex(endingWith: "/SiriAppIntents.framework/Versions/A/SiriAppIntents") + let functions = analyzer.functions(inImageAt: siriAppIntents) + let rebuiltAccessorNames = functions.compactMap { function -> String? in + guard case .swiftMetadata(let mangledName)? = function.name, mangledName.hasSuffix("Ma") else { return nil } + return mangledName + } + let exportedAccessorCount = functions.filter { + guard case .symbol(let symbol)? = $0.name else { return false } + return symbol.hasPrefix("_$s") && symbol.hasSuffix("Ma") + }.count + let typeCount = try analyzer.images[siriAppIntents].swift.typeContextDescriptors.count + #expect(rebuiltAccessorNames.count > 100) + #expect( + exportedAccessorCount + rebuiltAccessorNames.count >= typeCount * 9 / 10, + "\(exportedAccessorCount) exported and \(rebuiltAccessorNames.count) rebuilt accessor names for \(typeCount) types" + ) + for mangledName in rebuiltAccessorNames.prefix(200) { + let node = try demangleAsNode(mangledName) + #expect(node.children.first?.kind == .typeMetadataAccessFunction, "\(mangledName)") + } + } + + private static func withoutCategory(_ methodName: String) -> String { + guard let open = methodName.firstIndex(of: "("), let close = methodName.firstIndex(of: ")"), open < close else { return methodName } + return String(methodName[.. UInt32 { + let pageDelta = (Int64(bitPattern: target & ~UInt64(0xFFF)) - Int64(bitPattern: address & ~UInt64(0xFFF))) >> 12 + let immediate = UInt32(truncatingIfNeeded: pageDelta) & 0x1F_FFFF + return 0x9000_0000 | ((immediate & 0x3) << 29) | ((immediate >> 2) << 5) | UInt32(destination) + } + + static func add(_ destination: Int, _ source: Int, immediate: UInt32) -> UInt32 { + 0x9100_0000 | (immediate << 10) | (UInt32(source) << 5) | UInt32(destination) + } + + static func sub(_ destination: Int, _ source: Int, immediate: UInt32) -> UInt32 { + 0xD100_0000 | (immediate << 10) | (UInt32(source) << 5) | UInt32(destination) + } + + static func loadUnsignedOffset(_ destination: Int, base: Int, byteOffset: UInt32) -> UInt32 { + 0xF940_0000 | ((byteOffset / 8) << 10) | (UInt32(base) << 5) | UInt32(destination) + } + + static func loadPreIndexed(_ destination: Int, base: Int, byteOffset: Int32) -> UInt32 { + 0xF840_0C00 | ((UInt32(bitPattern: byteOffset) & 0x1FF) << 12) | (UInt32(base) << 5) | UInt32(destination) + } + + static func branch(at address: UInt64, to target: UInt64) -> UInt32 { + 0x1400_0000 | (UInt32(truncatingIfNeeded: Int64(bitPattern: target &- address) >> 2) & 0x03FF_FFFF) + } + + static func branchWithLink(at address: UInt64, to target: UInt64) -> UInt32 { + 0x9400_0000 | (UInt32(truncatingIfNeeded: Int64(bitPattern: target &- address) >> 2) & 0x03FF_FFFF) + } + + static func branchToRegister(_ register: Int) -> UInt32 { + 0xD61F_0000 | (UInt32(register) << 5) + } + + static func branchToRegisterAuthenticated(_ register: Int, modifier: Int) -> UInt32 { + 0xD71F_0800 | (UInt32(register) << 5) | UInt32(modifier) + } + + static func callRegisterAuthenticated(_ register: Int, modifier: Int) -> UInt32 { + 0xD73F_0800 | (UInt32(register) << 5) | UInt32(modifier) + } + + static func moveKeep(_ destination: Int, immediate: UInt16, shift: Int) -> UInt32 { + 0xF280_0000 | (UInt32(shift / 16) << 21) | (UInt32(immediate) << 5) | UInt32(destination) + } + + static func moveZero(_ destination: Int, immediate: UInt16) -> UInt32 { + 0xD280_0000 | (UInt32(immediate) << 5) | UInt32(destination) + } + + static func moveRegister(_ destination: Int, _ source: Int) -> UInt32 { + 0xAA00_03E0 | (UInt32(source) << 16) | UInt32(destination) + } + + static func compareBranchZero(_ register: Int, at address: UInt64, to target: UInt64) -> UInt32 { + 0xB400_0000 | ((UInt32(truncatingIfNeeded: Int64(bitPattern: target &- address) >> 2) & 0x7FFFF) << 5) | UInt32(register) + } + + static func bytes(of words: [UInt32]) -> Data { + var data = Data() + for word in words { + withUnsafeBytes(of: word.littleEndian) { data.append(contentsOf: $0) } + } + return data + } +} diff --git a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift new file mode 100644 index 000000000..dd620a10d --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift @@ -0,0 +1,51 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis + +/// A binary built for macOS 11 or earlier binds through lazy pointers and a +/// `__stub_helper`. dyld still binds every such slot when it loads the image +/// — measured on macOS 27.2: with `RTLD_LAZY`, the slot already holds `puts` +/// before the function is first called — so the scanner reads the slot as it +/// stands. This test is the sentinel for that: if dyld ever left a slot +/// unbound, it would point at the image's own `__stub_helper`, the call would +/// resolve there, and the scanner would need to fall back to the stub's +/// imported name. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct LazyBindingTests { + @Test func aLazilyBoundStubReachesItsTarget() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let source = directory.appendingPathComponent("LazyBinding.c") + try "#include \nvoid crossReferenceLazyBindingCall(void) { puts(\"called\"); }\n".write(to: source, atomically: true, encoding: .utf8) + let library = directory.appendingPathComponent("libLazyBinding.dylib") + + let compiler = Process() + compiler.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + compiler.arguments = [ + "clang", "-dynamiclib", "-arch", "arm64", "-O1", + // Classic dyld info rather than chained fixups: lazy pointers and a __stub_helper. + "-mmacosx-version-min=11.0", "-Wl,-no_fixup_chains", + "-o", library.path, source.path, + ] + try compiler.run() + compiler.waitUntilExit() + try #require(compiler.terminationStatus == 0, "could not build the lazily bound fixture") + _ = try #require(dlopen(library.path, RTLD_LAZY | RTLD_LOCAL)) + + let analyzer = try #require(CrossReferenceAnalyzer()) + let image = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/libLazyBinding.dylib") }) + let caller = try #require(analyzer.functions(inImageAt: image).first { $0.name == .symbol("_crossReferenceLazyBindingCall") }) + let call = try #require(analyzer.references(madeBy: caller).first) + + guard case .function(let location) = call.target else { + Issue.record("the call through the lazy pointer resolved to \(call.target), not to a function") + return + } + #expect(analyzer.imagePaths[location.imageIndex].hasSuffix("/libsystem_c.dylib")) + let callee = try #require(analyzer.function(containing: location)) + #expect(callee.location == location) + let names = (callee.name.map { [$0] } ?? []) + callee.foldedSymbolNames.map { .symbol($0) } + #expect(names.contains(.symbol("_puts")), "callee named \(names)") + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift new file mode 100644 index 000000000..a32ee4bac --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift @@ -0,0 +1,201 @@ +import Foundation +import Testing +import MachOKit +@testable import CrossReferenceAnalysis + +/// Where code takes a class object's address, the class a send goes to when +/// the code names it, and the class a super send starts above. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct ObjectiveCClassReferenceTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + private func function(named name: String, inImageAt imageIndex: Int) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: imageIndex).first { $0.name == .symbol(name) }, "no function \(name)") + } + + private func classLocation(named name: String, inImageAt imageIndex: Int) throws -> CodeLocation { + let locations = analyzer.objectiveCClassLocations(named: name, inImageAt: imageIndex) + #expect(locations.count == 1) + return try #require(locations.first, "\(analyzer.imagePaths[imageIndex]) defines no class \(name)") + } + + /// macOS 27.2 reaches a class three ways, and AppKit uses all three: + /// `adrp` / `add` of a class object of its own, a load from its own GOT, + /// and a load from the GOT pool the shared cache keeps outside every + /// image, for another image's class. A class's metaclass and every + /// alias name lead to the same class. + @Test func everyFormOfClassReferenceIsFound() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let string = try classLocation(named: "NSString", inImageAt: foundation) + let slide = try #require(analyzer.images[appKit].vmaddrSlide) + var forms = Set() + var classesLoadedFromElsewhere = Set() + for reference in analyzer.referenceTable(ofImageAt: appKit).references { + guard case .objectiveCClass(_, let location) = reference.target else { continue } + #expect(reference.kind == .reference) + let word = UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(reference.instructionAddress)) &+ slide)!.load(as: UInt32.self) + let form = word & 0xFF80_0000 == 0x9100_0000 ? "add" : "load" + forms.insert("\(form) of \(location.imageIndex == appKit ? "its own" : "another image's") class") + if form == "load", location.imageIndex != appKit { classesLoadedFromElsewhere.insert(location) } + } + #expect(forms.isSuperset(of: ["add of its own class", "load of its own class", "load of another image's class"])) + #expect(classesLoadedFromElsewhere.contains(string)) + } + + /// `[NSNotificationCenter _defaultCenterWithoutCreating]`, from an + /// Objective-C method: the class is loaded right before the send. + @Test func classLiteralReceiversNameTheirClass() throws { + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let method = try function(named: "+[NSThread currentThread]", inImageAt: foundation) + let receivers = analyzer.references(madeBy: method).compactMap { reference -> ReceiverClassHint? in + guard case .messageSend("_defaultCenterWithoutCreating", let receiver) = reference.target else { return nil } + return receiver + } + #expect(receivers == [.classLiteral("NSNotificationCenter")]) + } + + /// Swift calls an Objective-C class method through `objc_opt_self`, + /// which returns the class it was handed: `NSApplication.shared` loads + /// the class, calls `objc_opt_self`, then sends `sharedApplication` to + /// what came back. Forgetting `x0` across that call, as across any + /// other, lost the class. + @Test func classLiteralsSurviveObjcOptSelf() throws { + let swiftUI = try imageIndex(endingWith: "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") + let function = try function(named: "_$s7SwiftUI14_BenchmarkHostPAAE8_started4testyAA16_PerformanceTest_p_tF", inImageAt: swiftUI) + let receivers = analyzer.references(madeBy: function).compactMap { reference -> ReceiverClassHint? in + guard case .messageSend("sharedApplication", let receiver) = reference.target else { return nil } + return receiver + } + #expect(receivers == [.classLiteral("NSApplication")]) + } + + /// A super send starts above the class its `__objc_superrefs` slot + /// holds: the method's own class, a category's class included, and a + /// class method's metaclass reported as its class. The method's symbol + /// names the same class, which the scanner falls back on, so this does + /// not tell the slot apart; `superSendsInBlocksNameTheClassOfTheirMethod` + /// does. + @Test(arguments: zip( + ["-[NSDictionary(NSKeyValueCoding) valueForKey:]", "+[NSURL(NSURL) allocWithZone:]"], + ["valueForKey:", "allocWithZone:"] + )) + func superSendsNameTheClassOfTheirMethod(method name: String, selector: String) throws { + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let method = try function(named: name, inImageAt: foundation) + let className = String(name.dropFirst(2).prefix { $0 != "(" && $0 != " " }) + let superSends = analyzer.references(madeBy: method).filter { + if case .superMessageSend(selector, className) = $0.target { return true } + return false + } + #expect(!superSends.isEmpty) + // The superrefs load itself is no reference to the class. + #expect(!analyzer.references(madeBy: method).contains { + if case .objectiveCClass = $0.target { return true } + return false + }) + } + + /// A block that sends to `super` has no method symbol to take the class + /// from: only the `__objc_superrefs` slot names it — the class of the + /// method the block is written in, `NSWindow` for + /// `___37-[NSWindow foo:]_block_invoke`. + @Test func superSendsInBlocksNameTheClassOfTheirMethod() throws { + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + var compared = 0 + for function in analyzer.functions(inImageAt: appKit) { + guard case .symbol(let symbol)? = function.name, symbol.contains("_block_invoke"), + let bracket = symbol.firstIndex(of: "["), bracket > symbol.startIndex, + ["-", "+"].contains(symbol[symbol.index(before: bracket)]) + else { continue } + let className = String(symbol[symbol.index(after: bracket)...].prefix { $0 != " " && $0 != "(" }) + for reference in analyzer.references(madeBy: function) { + guard case .superMessageSend(_, let sendClassName) = reference.target else { continue } + compared += 1 + #expect(sendClassName == className, "\(symbol)") + } + if compared >= 50 { break } + } + #expect(compared >= 5) + } + + /// Where no symbol names the sending method, the superrefs slot still + /// gives its class — the one the method lists put the method in. + @Test func superSendsOfUnsymbolizedMethodsNameTheirClass() throws { + let matter = try imageIndex(endingWith: "/Matter.framework/Versions/A/Matter") + var compared = 0 + for function in analyzer.functions(inImageAt: matter) { + guard case .objectiveCMethod(let methodClassName, _, _)? = function.name else { continue } + for reference in analyzer.references(madeBy: function) { + guard case .superMessageSend(_, let className) = reference.target else { continue } + compared += 1 + #expect(className == methodClassName) + } + if compared >= 200 { break } + } + #expect(compared >= 200) + } + + /// The macOS and the Mac Catalyst SwiftUI both define this class; each + /// image's references lead to its own. + @Test func referencesTellApartClassesOfTheSameName() throws { + let name = "_TtC7SwiftUI13PinnedBarView" + let macOS = try imageIndex(endingWith: "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") + let catalyst = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") }) + for imageIndex in [macOS, catalyst] { + let own = try classLocation(named: name, inImageAt: imageIndex) + let locations = analyzer.references(to: [.objectiveCClass(name)], inImageAt: imageIndex).compactMap { reference -> CodeLocation? in + guard case .objectiveCClass(name, let location) = reference.target else { return nil } + return location + } + #expect(!locations.isEmpty) + #expect(Set(locations) == [own]) + } + } + + /// A class prefilter may drop only images that cannot reference the + /// class. Most images reach another image's class as + /// `_OBJC_CLASS_$_`; a block literal's `isa` + /// (`__NSConcreteStackBlock`) and an XPC type (`__xpc_type_dictionary`) + /// are reached under other names. + /// + /// The dropped images are sampled, every sixteenth: a Debug build scans + /// the whole cache in minutes, not seconds. + @Test(arguments: zip( + ["/AppKit.framework/Versions/C/AppKit", "/Foundation.framework/Versions/C/Foundation", "/usr/lib/system/libsystem_blocks.dylib", "/usr/lib/system/libxpc.dylib"], + ["NSWindow", "NSUUID", "__NSStackBlock__", "OS_xpc_dictionary"] + )) + func classPrefilterKeepsEveryReferencingImage(imageSuffix: String, className: String) throws { + let owner = try imageIndex(endingWith: imageSuffix) + let location = try classLocation(named: className, inImageAt: owner) + let everyImage = Array(analyzer.images.indices) + let kept = analyzer.imageIndices(referencingObjectiveCClassAt: location, among: everyImage) + #expect(kept.contains(owner)) + let importers = kept.filter { $0 != owner } + #expect(!imagesReferencing(className, at: location, among: Array(importers.prefix(64))).isEmpty) + let droppedSample = Self.sample(of: Set(everyImage).subtracting(kept)) + let missed = imagesReferencing(className, at: location, among: droppedSample) + #expect(missed.isEmpty, "prefilter dropped referencing images: \(missed.sorted().prefix(5).map { analyzer.imagePaths[$0] })") + } + + /// Every sixteenth of `imageIndices`, in order. + private static func sample(of imageIndices: Set) -> [Int] { + imageIndices.sorted().enumerated().filter { $0.offset % 16 == 0 }.map(\.element) + } + + /// The images among `imageIndices` that reference the class at `location`. + private func imagesReferencing(_ className: String, at location: CodeLocation, among imageIndices: [Int]) -> Set { + let found = ImageIndexCollector() + let analyzer = analyzer + DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + let references = analyzer.references(to: [.objectiveCClass(className)], inImageAt: imageIndex) + if references.contains(where: { $0.target == .objectiveCClass(name: className, location: location) }) { found.insert(imageIndex) } + } + return found.indices + } +} diff --git a/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift b/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift new file mode 100644 index 000000000..1ff269aad --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift @@ -0,0 +1,94 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis + +/// What a host prepares ahead of its queries — an image's names, the +/// prefilters' tables — is what a query would otherwise read first, and stays +/// until the host releases it. Each test makes an analyzer of its own: what +/// they check is what an analyzer keeps. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct PreparedImageDataTests { + private static func imageIndex(endingWith suffix: String, in analyzer: CrossReferenceAnalyzer) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + /// After `prepareNames(inImageAt:)`, naming a function and looking up a + /// class or a type read nothing more — and the names are the ones a query + /// reads on its own. + @Test func preparedNamesAreWhatAQueryReads() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let foundation = try Self.imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation", in: analyzer) + #expect(analyzer.existingFunctionTable(ofImageAt: foundation) == nil) + #expect(analyzer.approximateByteCount(ofImageDataAt: foundation) == 0) + + analyzer.prepareNames(inImageAt: foundation) + let table = try #require(analyzer.existingFunctionTable(ofImageAt: foundation)) + #expect(table.existingFallbackNames?.hasReadEverySource == true) + let indexes = analyzer.existingIndexes(ofImageAt: foundation) + #expect(indexes.classIndex?.hasReadEveryName == true) + #expect(indexes.swiftTypeIndex?.builtState.hasReadDescriptorSymbols == true) + + let lazilyNamed = try #require(CrossReferenceAnalyzer()).functions(inImageAt: foundation) + #expect(lazilyNamed.count > 10000) + #expect(analyzer.functions(inImageAt: foundation) == lazilyNamed) + } + + /// The estimate follows what is kept: the function table alone, then the + /// names read for it; nothing once released. + @Test func estimateFollowsWhatIsKept() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let libobjc = try Self.imageIndex(endingWith: "/usr/lib/libobjc.A.dylib", in: analyzer) + analyzer.keepFunctionTable(ofImageAt: libobjc) + let tableBytes = analyzer.approximateByteCount(ofImageDataAt: libobjc) + #expect(tableBytes > 0) + analyzer.prepareNames(inImageAt: libobjc) + #expect(analyzer.approximateByteCount(ofImageDataAt: libobjc) > tableBytes) + analyzer.releaseImageData(exceptForImagesAt: []) + #expect(analyzer.approximateByteCount(ofImageDataAt: libobjc) == 0) + } + + /// Releasing keeps the images asked for, with what was read for them, + /// and drops the rest — which a later query reads again. + @Test func releasingKeepsTheImagesAskedFor() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let libobjc = try Self.imageIndex(endingWith: "/usr/lib/libobjc.A.dylib", in: analyzer) + let foundation = try Self.imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation", in: analyzer) + analyzer.prepareNames(inImageAt: libobjc) + analyzer.prepareNames(inImageAt: foundation) + let keptBytes = analyzer.approximateByteCount(ofImageDataAt: libobjc) + + analyzer.releaseImageData(exceptForImagesAt: [libobjc]) + #expect(analyzer.existingFunctionTable(ofImageAt: libobjc)?.existingFallbackNames?.hasReadEverySource == true) + #expect(analyzer.existingIndexes(ofImageAt: libobjc).classIndex?.hasReadEveryName == true) + #expect(analyzer.approximateByteCount(ofImageDataAt: libobjc) == keptBytes) + #expect(analyzer.existingFunctionTable(ofImageAt: foundation) == nil) + #expect(analyzer.existingIndexes(ofImageAt: foundation).classIndex == nil) + #expect(analyzer.existingIndexes(ofImageAt: foundation).swiftTypeIndex == nil) + #expect(analyzer.approximateByteCount(ofImageDataAt: foundation) == 0) + #expect(!analyzer.functions(inImageAt: foundation).isEmpty) + } + + /// The prefilters' tables, prepared on one thread while a query asks for + /// them on another, are built once: the query waits instead of reading + /// every export trie again. + @Test func prefiltersAreBuiltOnce() async throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let preparing = Task.detached { analyzer.preparePrefilters() } + let asking = Task.detached { analyzer.renamedReexports().reexportsByProvider.count } + await preparing.value + let providerCount = await asking.value + #expect(analyzer.hasPreparedPrefilters) + #expect(providerCount > 0) + #expect(analyzer.renamedReexportBuildCount == 1) + } + + /// Reading the export tries on the calling thread alone finds what + /// reading them on every core finds, in the same order. + @Test func serialAndConcurrentReadsAgree() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let serial = RenamedReexportIndex(analyzer: analyzer, concurrently: false) + let concurrent = RenamedReexportIndex(analyzer: analyzer, concurrently: true) + #expect(serial.reexportsByProvider.values.reduce(0) { $0 + $1.count } > 1000) + #expect(serial.reexportsByProvider == concurrent.reexportsByProvider) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift b/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift new file mode 100644 index 000000000..de6fdef7b --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift @@ -0,0 +1,170 @@ +import Foundation +import Testing +import Capstone +@testable import CrossReferenceAnalysis + +/// What `RegisterFile.forgetRegistersWritten(by:)` forgets for the +/// instructions the scanner does not model: every general-purpose register +/// the instruction writes — a write-back base, an atomic's old value, a +/// pair's second register, a vector element moved out — and, for a plain +/// load or store, nothing else. +@Suite +struct RegisterFileTests { + /// An instruction and the general-purpose registers it writes, spelled + /// from the architecture's encoding tables. The encodings are the + /// assembler's. + struct Instruction: CustomTestStringConvertible, Sendable { + let word: UInt32 + let assembly: String + let written: Set + + var testDescription: String { assembly } + } + + static let writingInstructions: [Instruction] = [ + // Single registers that write back their base. + .init(word: 0xF841_0509, assembly: "ldr x9, [x8], #16", written: [8, 9]), + .init(word: 0xB840_4D09, assembly: "ldr w9, [x8, #4]!", written: [8, 9]), + .init(word: 0xF801_0509, assembly: "str x9, [x8], #16", written: [8]), + .init(word: 0x3800_1D09, assembly: "strb w9, [x8, #1]!", written: [8]), + .init(word: 0x3CC1_0500, assembly: "ldr q0, [x8], #16", written: [8]), + .init(word: 0xFC1F_8D00, assembly: "str d0, [x8, #-8]!", written: [8]), + .init(word: 0xB880_4509, assembly: "ldrsw x9, [x8], #4", written: [8, 9]), + .init(word: 0xF820_1D09, assembly: "ldraa x9, [x8, #8]!", written: [8, 9]), + // Atomics return the old value, whatever their ordering. + .init(word: 0xF821_0002, assembly: "ldadd x1, x2, [x0]", written: [2]), + .init(word: 0xF821_8002, assembly: "swp x1, x2, [x0]", written: [2]), + .init(word: 0xF8E1_0002, assembly: "ldaddal x1, x2, [x0]", written: [2]), + .init(word: 0xF8BF_C002, assembly: "ldapr x2, [x0]", written: [2]), + // Pairs that write back their base. + .init(word: 0xA8C1_0500, assembly: "ldp x0, x1, [x8], #16", written: [0, 1, 8]), + .init(word: 0xA9BF_0500, assembly: "stp x0, x1, [x8, #-16]!", written: [8]), + .init(word: 0xACC1_0500, assembly: "ldp q0, q1, [x8], #32", written: [8]), + .init(word: 0x6D81_0500, assembly: "stp d0, d1, [x8, #16]!", written: [8]), + .init(word: 0x68C1_0500, assembly: "ldpsw x0, x1, [x8], #8", written: [0, 1, 8]), + // Exclusives, ordered accesses, compare and swap. + .init(word: 0xC87F_0500, assembly: "ldxp x0, x1, [x8]", written: [0, 1]), + .init(word: 0xC822_0500, assembly: "stxp w2, x0, x1, [x8]", written: [2]), + .init(word: 0x4822_7D04, assembly: "casp x2, x3, x4, x5, [x8]", written: [2, 3]), + .init(word: 0xC8A2_7D04, assembly: "cas x2, x4, [x8]", written: [2]), + .init(word: 0xC85F_FD00, assembly: "ldaxr x0, [x8]", written: [0]), + .init(word: 0xC802_FD00, assembly: "stlxr w2, x0, [x8]", written: [2]), + .init(word: 0xC8DF_FD00, assembly: "ldar x0, [x8]", written: [0]), + // Structure loads and stores that write back their base. + .init(word: 0x4CDF_7100, assembly: "ld1 {v0.16b}, [x8], #16", written: [8]), + .init(word: 0x4C89_A100, assembly: "st1 {v0.16b, v1.16b}, [x8], x9", written: [8]), + .init(word: 0x0DDF_9100, assembly: "ld1 {v0.s}[1], [x8], #4", written: [8]), + .init(word: 0x4DDF_C900, assembly: "ld1r {v0.4s}, [x8], #4", written: [8]), + // Literal, load-acquire unscaled, and the memory copy and set + // instructions, which move all three of their registers. + .init(word: 0x5800_0000, assembly: "ldr x0, #0", written: [0]), + .init(word: 0xD940_8100, assembly: "ldapur x0, [x8, #8]", written: [0]), + .init(word: 0xD9C0_0900, assembly: "ldapr x0, [x8], #8", written: [0, 8]), + .init(word: 0x1901_0440, assembly: "cpyfp [x0]!, [x1]!, x2!", written: [0, 1, 2]), + .init(word: 0x19C2_0420, assembly: "setp [x0]!, x1!, x2", written: [0, 1]), + // Moves out of a vector or floating-point register. + .init(word: 0x0E0C_3C20, assembly: "umov w0, v1.s[1]", written: [0]), + .init(word: 0x4E08_3C20, assembly: "mov x0, v1.d[0]", written: [0]), + .init(word: 0x4E01_2C20, assembly: "smov x0, v1.b[0]", written: [0]), + .init(word: 0x9E66_0020, assembly: "fmov x0, d1", written: [0]), + .init(word: 0x9E58_F420, assembly: "fcvtzs x0, d1, #3", written: [0]), + .init(word: 0x1E38_0020, assembly: "fcvtzs w0, s1", written: [0]), + // System register reads. + .init(word: 0xD53B_D060, assembly: "mrs x0, tpidrro_el0", written: [0]), + .init(word: 0xD528_7500, assembly: "sysl x0, #0, c7, c5, #0", written: [0]), + // SVE and SME instructions that yield a general register. + .init(word: 0x04E0_E3E0, assembly: "cntd x0", written: [0]), + .init(word: 0x0421_5040, assembly: "addvl x0, x1, #2", written: [0]), + .init(word: 0x04BF_5020, assembly: "rdvl x0, #1", written: [0]), + .init(word: 0x04BF_5820, assembly: "rdsvl x0, #1", written: [0]), + // A system call returns in `x0` and `x1`. + .init(word: 0xD400_1001, assembly: "svc #0x80", written: [0, 1]), + // Everything else that computes into a register. + .init(word: 0xDAC1_43F0, assembly: "xpaci x16", written: [16]), + .init(word: 0x1100_0508, assembly: "add w8, w8, #1", written: [8]), + ] + + /// Plain loads and stores, the bulk of the code: only a load's + /// destination is forgotten, never the base or a stored register. + static let plainAccesses: [Instruction] = [ + .init(word: 0xF940_0509, assembly: "ldr x9, [x8, #8]", written: [9]), + .init(word: 0xB940_0509, assembly: "ldr w9, [x8, #4]", written: [9]), + .init(word: 0xF86A_6909, assembly: "ldr x9, [x8, x10]", written: [9]), + .init(word: 0x386A_6909, assembly: "ldrb w9, [x8, x10]", written: [9]), + .init(word: 0xF900_0509, assembly: "str x9, [x8, #8]", written: []), + .init(word: 0x3D80_0500, assembly: "str q0, [x8, #16]", written: []), + .init(word: 0xA941_0500, assembly: "ldp x0, x1, [x8, #16]", written: [0, 1]), + .init(word: 0xA901_0500, assembly: "stp x0, x1, [x8, #16]", written: []), + .init(word: 0x4C40_7100, assembly: "ld1 {v0.16b}, [x8]", written: []), + .init(word: 0xC8DF_FD00, assembly: "ldar x0, [x8]", written: [0]), + ] + + /// The registers the file no longer knows after `word`, when it knew + /// every one of them before. + private func forgottenRegisters(by word: UInt32) -> Set { + let registers = RegisterFile() + for register in 0 ..< 31 { + registers.setAddress(0x1_0000 &+ UInt64(register) &* 8, of: register) + } + registers.forgetRegistersWritten(by: word) + return Set((0 ..< 31).filter { registers.builtAddress(of: $0) == nil }) + } + + @Test(arguments: writingInstructions) + func forgetsEveryRegisterAnInstructionWrites(_ instruction: Instruction) { + let forgotten = forgottenRegisters(by: instruction.word) + #expect(instruction.written.isSubset(of: forgotten), "keeps \(instruction.written.subtracting(forgotten).sorted())") + } + + @Test(arguments: plainAccesses) + func aPlainAccessForgetsOnlyWhatItLoads(_ instruction: Instruction) { + #expect(forgottenRegisters(by: instruction.word) == instruction.written) + } + + /// Signing or authenticating a pointer in place leaves the register + /// meaning what it meant; stripping one is not followed. + @Test func pointerAuthenticationKeepsTheRegister() { + #expect(forgottenRegisters(by: 0xDAC1_0230).isEmpty) // pacia x16, x17 + #expect(forgottenRegisters(by: 0xDAC1_1A30).isEmpty) // autda x16, x17 + } + + /// Registers Capstone lists as written that the architecture does not + /// write: it counts the base of a compare and swap among them, which + /// `cas` and `casp` only read. + private static let capstoneOverstatements: [UInt32: Set] = [ + 0x4822_7D04: [8], // casp x2, x3, x4, x5, [x8] + 0xC8A2_7D04: [8], // cas x2, x4, [x8] + ] + + /// Capstone, a decoder written independently of the tables above, + /// names no general-purpose register they leave out. + @Test func capstoneNamesNoOtherWrittenRegister() throws { + let disassembler = try Disassembler() + for instruction in Self.writingInstructions + Self.plainAccesses { + let decoded = disassembler.decode(InstructionEncoding.bytes(of: [instruction.word]), address: 0x1_0000) + let decodedInstruction = try #require(decoded.first, "Capstone cannot decode \(instruction.assembly)") + let written = Set((decodedInstruction.registersWritten + decodedInstruction.implicitRegistersWritten).compactMap(Self.generalPurposeRegisterNumber)) + .subtracting(Self.capstoneOverstatements[instruction.word] ?? []) + #expect(written.isSubset(of: instruction.written), "\(instruction.assembly): Capstone also writes \(written.subtracting(instruction.written).sorted())") + } + } + + /// `x0`–`x30` by number, the 32-bit names folded onto them; `nil` for + /// the zero register, the stack pointer and everything that is not a + /// general-purpose register. + private static func generalPurposeRegisterNumber(_ register: AArch64Reg) -> Int? { + switch register { + case .fp: return 29 + case .lr: return 30 + default: break + } + let rawValue = Int(register.rawValue) + if rawValue >= Int(AArch64Reg.w0.rawValue), rawValue <= Int(AArch64Reg.w30.rawValue) { + return rawValue - Int(AArch64Reg.w0.rawValue) + } + if rawValue >= Int(AArch64Reg.x0.rawValue), rawValue <= Int(AArch64Reg.x28.rawValue) { + return rawValue - Int(AArch64Reg.x0.rawValue) + } + return nil + } +} diff --git a/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift b/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift new file mode 100644 index 000000000..c6437bd7f --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift @@ -0,0 +1,55 @@ +import Foundation +import Testing +import MachOKit +@testable import CrossReferenceAnalysis + +/// A function or a class that another image re-exports under a name of its +/// own is imported by that name, and the prefilters keep its importers: +/// AppKit calls libsystem_platform's `__platform_strlen` as libsystem_c's +/// `_strlen`, and SkyLight's `_SLSMainConnectionID` as CoreGraphics' +/// `_CGSMainConnectionID` — one of 273 SkyLight functions it reaches through +/// CoreGraphics' names on macOS 27.2. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct RenamedReexportTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + @Test(arguments: zip( + ["/usr/lib/system/libsystem_platform.dylib", "/SkyLight.framework/Versions/A/SkyLight"], + ["__platform_strlen", "_SLSMainConnectionID"] + )) + func callersImportingARenamedReexportAreKept(imageSuffix: String, symbol: String) throws { + let owner = try imageIndex(endingWith: imageSuffix) + let appKit = try imageIndex(endingWith: "/AppKit.framework/Versions/C/AppKit") + let function = try #require(analyzer.functions(inImageAt: owner).first { $0.name == .symbol(symbol) || $0.foldedSymbolNames.contains(symbol) }, "no function \(symbol)") + // AppKit does call it. + #expect(!analyzer.references(to: [.function(function.location)], inImageAt: appKit).isEmpty) + let kept = analyzer.imageIndices(callingFunctionAt: function.location, symbolNames: [symbol], among: analyzer.images.indices) + #expect(kept.contains(appKit)) + } + + /// The names come from every image's export trie, and follow a + /// re-export made through an umbrella: acfsSupport re-exports + /// `_kMDConfigErase`, which Metadata defines, from CoreServices, which + /// re-exports Metadata whole. + @Test func reexportedNamesSpellWhatCallersImport() throws { + let platform = try imageIndex(endingWith: "/usr/lib/system/libsystem_platform.dylib") + let strlenNames = analyzer.reexportedNames(ofSymbolsNamed: ["__platform_strlen"], inImageAt: platform) + #expect(strlenNames == ["_strlen"]) + let metadata = try imageIndex(endingWith: "/Metadata.framework/Versions/A/Metadata") + #expect(analyzer.reexportedNames(ofSymbolsNamed: ["_kMDConfigErase"], inImageAt: metadata) == ["_xkMDConfigErase"]) + #expect(analyzer.reexportedNames(ofSymbolsNamed: ["_strlen"], inImageAt: platform).isEmpty) + } + + /// UIFoundation re-exports CoreText's `CTEmojiImageAsset` as + /// `NSEmojiImageAsset`, which is the name CharacterPicker imports. + @Test func importersOfARenamedClassAreKept() throws { + let coreText = try imageIndex(endingWith: "/CoreText.framework/Versions/A/CoreText") + let characterPicker = try imageIndex(endingWith: "/CharacterPicker.framework/Versions/A/CharacterPicker") + let location = try #require(analyzer.objectiveCClassLocations(named: "CTEmojiImageAsset", inImageAt: coreText).first) + #expect(analyzer.imageIndices(referencingObjectiveCClassAt: location, among: analyzer.images.indices).contains(characterPicker)) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift new file mode 100644 index 000000000..b7a410050 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift @@ -0,0 +1,83 @@ +import Foundation +import Testing +import MachOKit +@testable import CrossReferenceAnalysis + +/// An image outside the shared cache — a third-party app's own binary, here +/// the SymbolTestsCore fixture — calls other images through its own +/// `__stubs` / `__auth_stubs`, whose GOT slots dyld bound when it loaded the +/// image. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct StandaloneImageTests { + private static var fixturePath: String { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .appendingPathComponent("Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore") + .path + } + + @Test func callsThroughTheImagesOwnStubsReachTheirTargets() throws { + // A fresh worktree has no fixture: build it, or link the main + // checkout's DerivedData (AGENTS.md, "a snapshot or baseline test just went red"). + _ = try #require(dlopen(Self.fixturePath, RTLD_NOW), "cannot load the SymbolTestsCore fixture at \(Self.fixturePath)") + // An analyzer is a snapshot; this one is made after the fixture loaded. + let analyzer = try #require(CrossReferenceAnalyzer()) + let fixture = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("SymbolTestsCore.framework/Versions/A/SymbolTestsCore") }) + #expect(!analyzer.images[fixture].header.isInDyldCache) + + let swiftCore = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/libswiftCore.dylib") }) + let table = analyzer.referenceTable(ofImageAt: fixture) + let intoSwiftCore = table.references.filter { reference in + if case .function(let location) = reference.target { location.imageIndex == swiftCore } else { false } + } + let intoItself = table.references.filter { reference in + if case .function(let location) = reference.target { location.imageIndex == fixture } else { false } + } + let stuckAtAName = table.references.filter { reference in + if case .importedSymbol = reference.target { true } else { false } + } + #expect(!intoSwiftCore.isEmpty) + #expect(!intoItself.isEmpty) + #expect(stuckAtAName.isEmpty, "stubs whose slot was not followed: \(Set(stuckAtAName.map { "\($0.target)" }).sorted().prefix(5))") + let someCallIsAHelper = table.references.contains { $0.isRuntimeHelperCall } + #expect(someCallIsAHelper) + } + + /// An image outside the cache goes by where dyld loaded it: a framework's + /// install name is `@rpath/…`, which names no file, and a host that knows + /// the image by its path has to find it by that path. + @Test func aFrameworkOutsideTheCacheGoesByItsLoadedPath() throws { + _ = try #require(dlopen(Self.fixturePath, RTLD_NOW), "cannot load the SymbolTestsCore fixture at \(Self.fixturePath)") + let analyzer = try #require(CrossReferenceAnalyzer()) + let fixture = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("SymbolTestsCore.framework/Versions/A/SymbolTestsCore") }) + let path = analyzer.imagePaths[fixture] + #expect(path.hasPrefix("/"), "\(path)") + #expect(URL(fileURLWithPath: path).resolvingSymlinksInPath() == URL(fileURLWithPath: Self.fixturePath).resolvingSymlinksInPath()) + #expect(analyzer.imageIndex(forPath: path) == fixture) + // The install name still finds it: load commands link by it. + #expect(analyzer.imageIndex(forPath: "@rpath/SymbolTestsCore.framework/Versions/A/SymbolTestsCore") == fixture) + } + + /// The bundle the tests run in has no install name at all. + @Test func aBundleGoesByItsLoadedPath() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let testBundle = try #require(analyzer.images.firstIndex { $0.ptr == #dsohandle }, "the test bundle is not among the images") + #expect(analyzer.images[testBundle].header.fileType == .bundle) + var information = Dl_info() + #expect(dladdr(#dsohandle, &information) != 0) + let loadedPath = String(cString: try #require(information.dli_fname)) + #expect(analyzer.imagePaths[testBundle] == loadedPath) + #expect(analyzer.imageIndex(forPath: loadedPath) == testBundle) + } + + /// A bundle linked with `-bundle_loader` binds to the main executable + /// through no load command, so every bundle counts as linking it. + @Test func aBundleCountsAsLinkingTheMainExecutable() throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let executable = try #require(analyzer.images.firstIndex { $0.header.fileType == .execute }) + let testBundle = try #require(analyzer.images.firstIndex { $0.ptr == #dsohandle }) + #expect(analyzer.imageIndices(linkingImageAt: executable, among: analyzer.images.indices).contains(testBundle)) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift new file mode 100644 index 000000000..49bf40de5 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift @@ -0,0 +1,275 @@ +import Foundation +import Testing +import MachOKit +import Demangling +import ARM64InstructionDecoding +@testable import CrossReferenceAnalysis + +/// Swift type references: calls to a type's metadata accessor and the +/// accessor's address, the address of its metadata, and the mangled names +/// code instantiates. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct SwiftTypeReferenceTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + private func imageIndex(endingWith suffix: String) throws -> Int { + try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(suffix) }, "no image ending with \(suffix)") + } + + private func identity(ofTypeWithKey key: String, inImageEndingWith suffix: String) throws -> SwiftTypeIdentity { + let imageIndex = try imageIndex(endingWith: suffix) + let location = try #require(analyzer.swiftTypeDescriptorLocations(withKey: key, inImageAt: imageIndex).first, "no type \(key)") + return try #require(analyzer.swiftTypeIdentity(ofDescriptorAt: location)) + } + + /// The first nominal type a symbol names, as a key. + private func key(ofSymbol symbol: String) -> String? { + var mangled = Substring(symbol) + if mangled.hasPrefix("_") { mangled = mangled.dropFirst() } + guard let node = try? demangleAsNode(String(mangled)) else { return nil } + return CrossReferenceAnalyzer.nominalKeys(in: node).first + } + + /// Wherever SwiftUICore calls a metadata accessor a symbol names, the + /// type the call is reported to reference is the one the symbol names. + /// A type nested in a constrained extension is where the two came apart: + /// its descriptor's context spells the extension's requirements, which + /// is why a key comes from the descriptor's `…Mn` symbol. + @Test func accessorCallsReferenceTheTypeTheAccessorNames() throws { + let swiftUICore = try imageIndex(endingWith: "/SwiftUICore.framework/Versions/A/SwiftUICore") + let table = analyzer.referenceTable(ofImageAt: swiftUICore) + var callees: [UInt64: CodeLocation] = [:] + for reference in table.references where reference.kind != .reference { + if case .function(let location) = reference.target { callees[reference.instructionAddress] = location } + } + var compared = 0 + var disagreements: [String] = [] + for reference in table.references where reference.kind == .reference { + guard case .swiftType(let descriptor) = reference.target, + let callee = callees[reference.instructionAddress], + let symbol = analyzer.symbolName(at: callee), symbol.hasSuffix("Ma") + else { continue } + compared += 1 + let key = analyzer.swiftTypeIdentity(ofDescriptorAt: descriptor)?.key + if key != self.key(ofSymbol: symbol), disagreements.count < 5 { disagreements.append("\(symbol): \(key ?? "nil")") } + } + #expect(compared > 10000) + #expect(disagreements.isEmpty, "\(disagreements)") + } + + /// Wherever SwiftUICore builds an address with an `adrp` and the `add` + /// right after it, and a symbol sits at that address, the type the + /// reference is reported for is the one the symbol names: its metadata + /// (`…N`) or its metadata accessor (`…Ma`). + @Test func addressReferencesReferenceTheTypeAtTheAddress() throws { + let swiftUICore = try imageIndex(endingWith: "/SwiftUICore.framework/Versions/A/SwiftUICore") + let image = analyzer.images[swiftUICore] + let slide = try #require(image.vmaddrSlide) + let symbols = try #require(image.symbols64) + var symbolsByAddress: [UInt64: [String]] = [:] + for symbolIndex in 0 ..< symbols.numberOfSymbols { + let entry = symbols.symbols[symbolIndex] + guard entry.n_type & 0xE0 == 0, entry.n_type & 0x0E == 0x0E else { continue } + let name = String(cString: symbols.stringBase.advanced(by: Int(entry.n_un.n_strx))) + guard name.hasPrefix("_$s"), name.hasSuffix("N") || name.hasSuffix("Ma") else { continue } + symbolsByAddress[entry.n_value, default: []].append(name) + } + func word(at address: UInt64) -> UInt32 { + UnsafeRawPointer(bitPattern: Int(bitPattern: UInt(address)) &+ slide)!.load(as: UInt32.self) + } + var compared = 0 + var disagreements: [String] = [] + for reference in analyzer.referenceTable(ofImageAt: swiftUICore).references where reference.kind == .reference { + guard case .swiftType(let descriptor) = reference.target, + let arithmetic = ARM64InstructionWord.addImmediate(word(at: reference.instructionAddress)), + let page = ARM64InstructionWord.addressMaterialization(word(at: reference.instructionAddress - 4), at: reference.instructionAddress - 4), + page.destination == arithmetic.source, + let names = symbolsByAddress[ARM64InstructionWord.adding(arithmetic.addend, to: page.address)] + else { continue } + compared += 1 + let key = analyzer.swiftTypeIdentity(ofDescriptorAt: descriptor)?.key + if !names.contains(where: { self.key(ofSymbol: $0) == key }), disagreements.count < 5 { disagreements.append("\(names): \(key ?? "nil")") } + } + #expect(compared > 1000) + #expect(disagreements.isEmpty, "\(disagreements)") + } + + /// Foundation instantiates types from mangled names through its V2 + /// helper; each name is read from the `{ offset, length }` record the + /// call passes in `x1`, lies in `__swift5_typeref`, and demangles. + @Test func instantiationsReadTheirNamesFromTheRecord() throws { + let foundation = try imageIndex(endingWith: "/Foundation.framework/Versions/C/Foundation") + let section = try #require(analyzer.images[foundation].sections64.first { $0.sectionName == "__swift5_typeref" }) + let typeReferenceRange = UInt64(section.address) ..< UInt64(section.address) + UInt64(section.size) + var names = Set() + for reference in analyzer.referenceTable(ofImageAt: foundation).references { + guard case .swiftTypeName(let name) = reference.target, case .mangledName(let location, _) = name else { continue } + #expect(typeReferenceRange.contains(location.address)) + names.insert(name) + } + #expect(names.count > 500) + let demangled = names.filter { !analyzer.swiftTypeKeys(in: $0).isEmpty } + #expect(Double(demangled.count) / Double(max(names.count, 1)) > 0.98, "\(demangled.count) of \(names.count) demangle") + } + + /// A query keeps a mangled name when one of its symbolic references + /// leads to the type's descriptor, and demangles names only for a type a + /// name may spell out. Checked against demangling every name of the + /// image: for each type its names mention, the query keeps exactly the + /// names whose demangled form mentions the type — no name mentions an + /// ordinary type without a symbolic reference to it. + /// + /// For the four standard library types the query falls back on the same + /// demangling this compares against, so they guard only against a + /// symbolic reference leading to the wrong descriptor. + @Test(arguments: ["/Foundation.framework/Versions/C/Foundation", "/SwiftData.framework/Versions/A/SwiftData"]) + func queriesKeepExactlyTheNamesThatMentionTheType(imageSuffix: String) throws { + let imageIndex = try imageIndex(endingWith: imageSuffix) + let slide = try #require(analyzer.images[imageIndex].vmaddrSlide) + var keysByName: [SwiftTypeName: Set] = [:] + var mentions: [CodeLocation: Int] = [:] + for reference in analyzer.referenceTable(ofImageAt: imageIndex).references { + guard case .swiftTypeName(let name) = reference.target, case .mangledName(let location, let length) = name, keysByName[name] == nil else { continue } + // A name that does not demangle has nothing to compare against. + let keys = analyzer.swiftTypeKeys(in: name) + guard !keys.isEmpty else { continue } + keysByName[name] = Set(keys) + // The descriptors the name's symbolic references lead to. + let bytes = UnsafePointer(bitPattern: Int(bitPattern: UInt(location.address)) &+ slide)! + var position = 0 + while position < length { + let byte = bytes[position] + if byte == 0x01 || byte == 0x02 { + let field = UInt(bitPattern: bytes + position + 1) + var descriptor = UInt(bitPattern: Int(bitPattern: field) &+ Int(UnsafeRawPointer(bytes + position + 1).loadUnaligned(as: Int32.self))) + if byte == 0x02 { descriptor = UInt(UnsafeRawPointer(bitPattern: descriptor)!.loadUnaligned(as: UInt64.self) & 0x7FFF_FFFF_FFFF) } + if let descriptorLocation = analyzer.location(ofDescriptorAtRuntimeAddress: descriptor) { mentions[descriptorLocation, default: 0] += 1 } + } + position += byte >= 0x01 && byte <= 0x17 ? 5 : (byte >= 0x18 && byte <= 0x1F ? 9 : 1) + } + } + // The types the names refer to most — protocols have no type context + // descriptor and drop out — and four the standard library spells out. + var identities = mentions.sorted { $0.value > $1.value }.compactMap { analyzer.swiftTypeIdentity(ofDescriptorAt: $0.key) }.prefix(40).map { $0 } + let standardLibrary = try self.imageIndex(endingWith: "/usr/lib/swift/libswiftCore.dylib") + for key in ["Sa", "Sq", "SD", "SS"] { + let location = try #require(analyzer.swiftTypeDescriptorLocations(withKey: key, inImageAt: standardLibrary).first, "no \(key)") + identities.append(try #require(analyzer.swiftTypeIdentity(ofDescriptorAt: location))) + } + #expect(identities.count >= 24) + #expect(identities.contains { SwiftTypeQuery.mayBeSpelledOut($0.key) }) + #expect(identities.contains { !SwiftTypeQuery.mayBeSpelledOut($0.key) }) + var mismatches: [String] = [] + for identity in identities { + let query = SwiftTypeQuery(identity: identity, analyzer: analyzer) + for (name, keys) in keysByName where query.matches(.swiftTypeName(name)) != keys.contains(identity.key) { + if mismatches.count < 5 { mismatches.append("\(identity.key) in \(keys.sorted())") } + } + } + #expect(mismatches.isEmpty, "\(mismatches)") + } + + /// The macOS and the Mac Catalyst SwiftUI define the same types. A query + /// for the macOS one finds nothing in the Catalyst image, which uses its + /// own; the Catalyst one's query finds its references there — this class + /// also as an Objective-C class. + @Test func queriesTellApartTypesOfTheSameKey() throws { + let macOS = try identity(ofTypeWithKey: "7SwiftUI13PinnedBarViewC", inImageEndingWith: "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") + let catalyst = try identity(ofTypeWithKey: "7SwiftUI13PinnedBarViewC", inImageEndingWith: "/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") + #expect(macOS.objectiveCClassLocation != nil) + #expect(macOS.descriptorLocation != catalyst.descriptorLocation) + let catalystImage = catalyst.descriptorLocation.imageIndex + #expect(analyzer.references(toSwiftType: macOS, inImageAt: catalystImage).isEmpty) + #expect(!analyzer.references(toSwiftType: catalyst, inImageAt: catalystImage).isEmpty) + } + + /// A type prefilter may drop only images that cannot reference the type. + /// Few cache images keep a Swift symbol among their undefined symbols, so + /// the images that can bind to the defining image are what is kept: + /// SharedWithYou imports nothing for `URL` and calls its metadata + /// accessor all the same, through a GOT stub the cache builder bound. + /// + /// The dropped images are sampled, every sixteenth: a Debug build scans + /// the whole cache in minutes, not seconds. + @Test(arguments: zip( + ["/Foundation.framework/Versions/C/Foundation", "/SwiftUICore.framework/Versions/A/SwiftUICore", "/Foundation.framework/Versions/C/Foundation"], + ["10Foundation3URLV", "7SwiftUI4TextV", "10Foundation11JSONEncoderC"] + )) + func typePrefilterKeepsEveryReferencingImage(imageSuffix: String, key: String) throws { + let identity = try identity(ofTypeWithKey: key, inImageEndingWith: imageSuffix) + let everyImage = Array(analyzer.images.indices) + let kept = analyzer.imageIndices(referencingSwiftType: identity, among: everyImage) + #expect(kept.contains(identity.descriptorLocation.imageIndex)) + let importers = kept.filter { $0 != identity.descriptorLocation.imageIndex } + #expect(!imagesReferencing(identity, among: Array(importers.prefix(64))).isEmpty) + let droppedSample = Set(everyImage).subtracting(kept).sorted().enumerated().filter { $0.offset % 16 == 0 }.map(\.element) + let missed = imagesReferencing(identity, among: droppedSample) + #expect(missed.isEmpty, "prefilter dropped referencing images: \(missed.sorted().prefix(5).map { analyzer.imagePaths[$0] })") + } + + /// A type its image exports no symbol for — no descriptor, no metadata, no + /// metadata accessor — can be referenced from that image alone. AppKit's + /// `NSSmartNamingSuggestion` is internal, and the prefilter kept every image + /// linking AppKit for it: a Type References query on it scanned most of + /// the cache, minutes in a Debug build. + @Test func typesNoImageExportsAreLookedForInTheirOwnImage() throws { + let identity = try identity(ofTypeWithKey: "6AppKit23NSSmartNamingSuggestionV", inImageEndingWith: "/AppKit.framework/Versions/C/AppKit") + let appKit = identity.descriptorLocation.imageIndex + let everyImage = Array(analyzer.images.indices) + + #expect(analyzer.imageIndices(referencingSwiftType: identity, among: everyImage) == [appKit]) + // The images linking AppKit do not reference it: every sixty-fourth of them, scanned. + let linkingImages = Set(analyzer.imageIndices(linkingImageAt: appKit, among: everyImage)).subtracting([appKit]) + let sample = linkingImages.sorted().enumerated().filter { $0.offset % 64 == 0 }.map(\.element) + #expect(imagesReferencing(identity, among: sample).isEmpty) + } + + /// Looking a type up by its key builds the keys of the types its + /// descriptor names alike only, and finds what comparing every type's key + /// finds — for every type of these images. Few keys are left whose name + /// cannot be read, which are compared with every type's. + @Test(arguments: ["/Foundation.framework/Versions/C/Foundation", "/AppKit.framework/Versions/C/AppKit"]) + func typeLookupsCompareSameNamedTypesOnly(imageSuffix: String) throws { + let imageIndex = try imageIndex(endingWith: imageSuffix) + let typeIndex = SwiftTypeIndex(image: analyzer.images[imageIndex], imageIndex: imageIndex) + var locationsByKey: [String: Set] = [:] + for address in typeIndex.descriptorAddresses { + guard let key = typeIndex.key(ofDescriptorAt: address) else { continue } + locationsByKey[key, default: []].insert(typeIndex.location(ofRuntimeAddress: address)) + } + #expect(locationsByKey.count > 500) + var unreadableNameCount = 0 + for (key, locations) in locationsByKey { + if SwiftTypeIndex.typeName(inKey: key) == nil { unreadableNameCount += 1 } + #expect(Set(typeIndex.descriptorLocations(withKey: key)) == locations, "\(key)") + } + #expect(unreadableNameCount * 100 < locationsByKey.count, "\(unreadableNameCount) of \(locationsByKey.count) keys") + } + + /// Whether an image exports a type's symbols is looked up in its export + /// trie, and agrees with reading the whole trie — for every type of these + /// images. + @Test(arguments: ["/Foundation.framework/Versions/C/Foundation", "/AppKit.framework/Versions/C/AppKit"]) + func exportLookupsAgreeWithTheWholeTrie(imageSuffix: String) throws { + let imageIndex = try imageIndex(endingWith: imageSuffix) + let exportedNames = Set(analyzer.images[imageIndex].exportedSymbols.map(\.name)) + let typeIndex = SwiftTypeIndex(image: analyzer.images[imageIndex], imageIndex: imageIndex) + var exportedTypeCount = 0 + for address in typeIndex.descriptorAddresses { + guard let key = typeIndex.key(ofDescriptorAt: address) else { continue } + let isExported = ["Mn", "Ma", "N"].contains { exportedNames.contains("_$s" + key + $0) } + #expect(analyzer.isSwiftTypeExported(withKey: key, fromImageAt: imageIndex) == isExported, "\(key)") + if isExported { exportedTypeCount += 1 } + } + #expect(exportedTypeCount > 100) + } + + private func imagesReferencing(_ identity: SwiftTypeIdentity, among imageIndices: [Int]) -> Set { + let found = ImageIndexCollector() + let analyzer = analyzer + DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + if !analyzer.references(toSwiftType: identity, inImageAt: imageIndices[position]).isEmpty { found.insert(imageIndices[position]) } + } + return found.indices + } +} diff --git a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift new file mode 100644 index 000000000..dde419050 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift @@ -0,0 +1,65 @@ +import Foundation +import Testing +import Demangling +import MachOReading +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import CrossReferenceAnalysis + +/// A type of this test bundle that nothing else names: its key comes from +/// its `…Mn` symbol. Internal, so that no private discriminator joins it. +struct TransientDescriptorKeyProbe {} + +/// A type query demangles names nothing bounds — every accessor symbol and +/// mangled name a scan meets — so none of them may stay behind in a cache the +/// process never evicts: the shared `NodeCache`, or the memo an in-process +/// `SymbolicDemangler.demangleType(for:in:)` fills. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct TypeNameRetentionTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + /// A type key no other name in the process spells: module `M`, and an + /// identifier with 32 random letters. + private static func uniqueTypeKey() -> (key: String, identifier: String) { + let letters = UUID().uuidString.compactMap(\.hexDigitValue).map { Character(UnicodeScalar(UInt8(ascii: "a") + UInt8($0))) } + let identifier = "TransientProbe" + String(letters) + return ("1M\(identifier.utf8.count)\(identifier)V", identifier) + } + + /// Whether the shared `NodeCache` held an identifier leaf spelling + /// `text`: interning one it already holds leaves its count as it was. + /// Interning elsewhere in the process can make a held leaf look new, + /// never a new one look held. + private static func sharedNodeCacheHoldsIdentifier(_ text: String) -> Bool { + let count = NodeCache.shared.count + _ = NodeCache.shared.intern(kind: .identifier, text: text) + return NodeCache.shared.count == count + } + + @Test func anAccessorSymbolLeavesNoTreeBehind() { + let (key, identifier) = Self.uniqueTypeKey() + #expect(analyzer.swiftTypeKeys(in: .accessorSymbol("$s\(key)Ma")) == [key]) + #expect(!Self.sharedNodeCacheHoldsIdentifier(identifier)) + } + + @Test func aMangledNameLeavesNoTreeBehind() throws { + let (key, identifier) = Self.uniqueTypeKey() + let buffer = try #require(strdup(key)) + defer { free(buffer) } + // Any image's slide turns the buffer's address into a location. + let slide = try #require(analyzer.images[0].vmaddrSlide) + let location = CodeLocation(imageIndex: 0, address: UInt64(bitPattern: Int64(Int(bitPattern: buffer)) &- Int64(slide))) + #expect(analyzer.swiftTypeKeys(in: .mangledName(location: location, length: key.utf8.count)) == [key]) + let mangledName = try MangledName.resolve(at: UnsafeRawPointer(buffer), in: InProcessContext.shared) + #expect(!SymbolicDemangler.processScopedMemoHoldsType(for: mangledName)) + #expect(!Self.sharedNodeCacheHoldsIdentifier(identifier)) + } + + @Test func aDescriptorSymbolLeavesNoTreeBehind() throws { + let imageIndex = try #require(analyzer.images.firstIndex { $0.ptr == #dsohandle }, "the test bundle is not among the images") + let key = try #require(_mangledTypeName(TransientDescriptorKeyProbe.self)) + let location = try #require(analyzer.swiftTypeDescriptorLocations(withKey: key, inImageAt: imageIndex).first) + #expect(analyzer.swiftTypeIdentity(ofDescriptorAt: location)?.key == key) + #expect(!Self.sharedNodeCacheHoldsIdentifier("TransientDescriptorKeyProbe")) + } +} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift index fdd7b9b95..24dfdc6e4 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift @@ -144,7 +144,8 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// The same image across archived macOS caches, picked by version: list /// in `cacheVersions` the directories under /// `/Volumes/DyldSharedCaches/macOS` that hold a cache, oldest first. A - /// cache named by its version is labeled with it, so every label is a + /// cache is labeled with its version, or with the major release + /// `versionLabelsByCacheVersion` names for it, so every label is a /// version number and the union interface also spells each lifecycle one /// attribute can express as `@available(macOS, …)`. A version whose image /// carries no Swift metadata drops off the axis (see @@ -205,7 +206,19 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { "27.0", ] } - override class var cachePaths: [DyldSharedCachePath] { cacheVersions.map { .macOS($0) } } + /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and + /// 12.0.1, so those are the directories the volume has; the axis + /// still labels them 11.0 and 12.0, the versions an SDK's + /// `@available` attributes name. + class var versionLabelsByCacheVersion: [String: String] { ["11.0.1": "11.0", "12.0.1": "12.0"] } + + override class var cachePaths: [DyldSharedCachePath] { + cacheVersions.map { cacheVersion in + let cachePath = DyldSharedCachePath.macOS(cacheVersion) + guard let versionLabel = versionLabelsByCacheVersion[cacheVersion] else { return cachePath } + return DyldSharedCachePath(rawValue: cachePath.rawValue, versionLabel: versionLabel) + } + } override class var cacheImageName: MachOImageName { .SwiftUI } diff --git a/Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift b/Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift new file mode 100644 index 000000000..7626f15b0 --- /dev/null +++ b/Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSymbols +import MachOTestingSupport +import MachOFixtureSupport + +/// A host's wrapper — MachOKitUI's `MachOFileSource` / `MachOImageSource` — +/// around a reader of the system dyld shared cache. +/// +/// A file read out of a cache files its symbols at `value − sharedRegionStart`, +/// and an in-process cache image counts its addresses from where it is loaded. +/// Both were worked out only for a bare reader, so a wrapper's symbols stayed at +/// their raw values and its addresses were counted from the start of the shared +/// region. +/// +/// Combine is an image no other suite reads, so the symbol index this suite +/// builds for it is built through the wrapper. +@Suite(ExclusiveImageAccess(MachOImageName.Combine.rawValue)) +struct WrappedReaderSymbolTests { + @Test("a wrapper of a cache file files its Swift symbols where the file does") + func cacheFileWrapperFilesSwiftSymbolsLikeTheFile() throws { + let combine = try Self.combineInSystemCache() + let wrapper = ForwardingMachOReader(combine) + #expect(wrapper.swiftSymbols == combine.swiftSymbols) + } + + @Test("a wrapper of a cache file finds the file's type descriptor symbols at their offsets") + func cacheFileWrapperIndexesSymbolsAtTheirOffsets() throws { + let combine = try Self.combineInSystemCache() + let wrapper = ForwardingMachOReader(combine) + // Combine's own nominal type descriptors: the symbol table also lists + // the descriptors Combine imports (`$ss12StaticStringVMn`), which sit + // at no offset in it. + let descriptorSymbols = combine.swiftSymbols.filter { $0.name.hasSuffix("Mn") && $0.name.contains("$s7Combine") } + try #require(!descriptorSymbols.isEmpty) + for descriptorSymbol in descriptorSymbols { + let symbolsAtOffset = wrapper.symbols(offset: descriptorSymbol.offset) + #expect(symbolsAtOffset?.contains { $0.name == descriptorSymbol.name } == true, "\(descriptorSymbol.name)") + } + } + + @Test("a wrapper of an in-process cache image prints the image's addresses") + func inProcessCacheImageWrapperPrintsTheImageAddresses() throws { + let foundation = try #require(MachOImage(named: .Foundation)) + try #require(foundation.cache != nil, "Foundation is expected to be loaded from the shared cache") + let wrapper = ForwardingMachOReader(foundation) + for offset in [0, 0x1000, 0x10_0000] { + #expect(wrapper.address(forOffset: offset) == foundation.address(forOffset: offset)) + } + } + + private static func combineInSystemCache() throws -> MachOFile { + let fullCache = try FullDyldCache(path: .current) + return try #require(fullCache.machOFile(named: .Combine)) + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/PrivateDeclarationSourceFileCommentsTests.swift b/Tests/SwiftDeclarationRenderingTests/PrivateDeclarationSourceFileCommentsTests.swift new file mode 100644 index 000000000..c21617fa8 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/PrivateDeclarationSourceFileCommentsTests.swift @@ -0,0 +1,153 @@ +import Foundation +import Testing +import Demangling +import SwiftInspection +@testable import SwiftDeclarationRendering + +/// The comments dump and interface print above a declaration to say which +/// source files its private declarations come from (evolution proposal +/// `private-declaration-source-files`). +/// +/// The `SymbolTestsCore` manglings are the fixture's own symbols; `md5 -s +/// 'SymbolTestsCoreCodable.swift'`, computed outside this code base, is +/// `b89e435df71e951d297eee1adcd6ddd8`. The `Main` ones are written for these +/// tests — no source declares a type with two discriminators, but a +/// specialized definition's name reads its arguments' — and `swift-demangle` +/// prints them as the comments above them say. +@Suite +struct PrivateDeclarationSourceFileCommentsTests { + private static let codableDiscriminator = "_B89E435DF71E951D297EEE1ADCD6DDD8" + + private static let firstDiscriminator = "_0123456789ABCDEF0123456789ABCDEF" + + private static let secondDiscriminator = "_FEDCBA9876543210FEDCBA9876543210" + + /// The answers of a recovery done elsewhere; one it has none for was not + /// recovered. + private struct RecoveredSourceFiles: PrivateDeclarationSourceFileProviding { + let sourceFileByDiscriminator: [String: PrivateDeclarationSourceFile] + + func sourceFile(forPrivateDiscriminator discriminator: String) -> PrivateDeclarationSourceFile? { + sourceFileByDiscriminator[discriminator] + } + } + + private static let recoveredSourceFiles = RecoveredSourceFiles(sourceFileByDiscriminator: [ + codableDiscriminator: .init(fileName: "Codable.swift", moduleName: "SymbolTestsCore", isSynthesized: false), + firstDiscriminator: .init(fileName: "Box.swift", moduleName: "Main", isSynthesized: false), + secondDiscriminator: .init(fileName: "Payload.swift", moduleName: "Main", isSynthesized: false), + ]) + + private static func lines(for mangledNames: [String], enclosedBy enclosingMangledName: String? = nil) throws -> [String] { + let nodes: [any DemanglingNode] = try mangledNames.map { try demangleAsNodeTransient($0) } + let enclosingNodes: [any DemanglingNode] = try enclosingMangledName.map { [try demangleAsNodeTransient($0)] } ?? [] + return PrivateDeclarationSourceFileComments.lines(for: nodes, enclosedBy: enclosingNodes, provider: recoveredSourceFiles) + } + + // MARK: - Wording + + @Test func recoveredFileIsNamed() { + let line = PrivateDeclarationSourceFileComments.line( + for: PrivateDeclaration(name: "CodingKeys", discriminator: Self.codableDiscriminator), + sourceFile: .init(fileName: "Codable.swift", moduleName: "SymbolTestsCore", isSynthesized: false), + printedModuleName: "SymbolTestsCore" + ) + #expect(line == "CodingKeys is declared in Codable.swift") + } + + /// SwiftUICore's declarations print under their ABI module name, SwiftUI, + /// while the digest was made with the framework's own. + @Test func hashedModuleIsNamedWhenTheDeclarationPrintsUnderAnother() { + let line = PrivateDeclarationSourceFileComments.line( + for: PrivateDeclaration(name: "EnabledKey", discriminator: "_09CE35833F3876FE3A3A46977D61FC64"), + sourceFile: .init(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false), + printedModuleName: "SwiftUI" + ) + #expect(line == "EnabledKey is declared in Enabled.swift of module SwiftUICore") + } + + @Test func synthesizedFileIsNamedAfterTheFileItWasMadeFor() { + let line = PrivateDeclarationSourceFileComments.line( + for: PrivateDeclaration(name: "Storage", discriminator: Self.firstDiscriminator), + sourceFile: .init(fileName: "Box.swift", moduleName: "Main", isSynthesized: true), + printedModuleName: "Main" + ) + #expect(line == "Storage is declared in the file the compiler synthesized for Box.swift") + } + + /// The interface prints no discriminator anywhere else, so this line is + /// the only place a reader finds it. + @Test func unrecoveredFileIsSaidSoWithTheDiscriminator() { + let line = PrivateDeclarationSourceFileComments.line( + for: PrivateDeclaration(name: "PrivateDoppelganger", discriminator: "_1282F137F8790A6AF4B7E2738A640142"), + sourceFile: nil, + printedModuleName: "SymbolTestsCore" + ) + #expect(line == "PrivateDoppelganger is declared in a source file whose name could not be recovered (private discriminator _1282F137F8790A6AF4B7E2738A640142)") + } + + @Test func declarationWithoutANameIsLeftUnnamed() { + let line = PrivateDeclarationSourceFileComments.line( + for: PrivateDeclaration(name: nil, discriminator: Self.firstDiscriminator), + sourceFile: .init(fileName: "Box.swift", moduleName: "Main", isSynthesized: false), + printedModuleName: "Main" + ) + #expect(line == "Declared in Box.swift") + } + + // MARK: - Which discriminators get a line + + @Test func privateTypeGetsALine() throws { + // nominal type descriptor for SymbolTestsCore.CodableTests.GenericCodableTest.(CodingKeys in _B89E…) + #expect(try Self.lines(for: ["$s15SymbolTestsCore12CodableTestsO07GenericC4TestV10CodingKeys33_B89E435DF71E951D297EEE1ADCD6DDD8LLOMn"]) == [ + "CodingKeys is declared in Codable.swift", + ]) + } + + /// The type a nested private type is declared in reads the same + /// discriminator: one line, naming the type the declaration is. + @Test func oneDiscriminatorGetsOneLineNamingTheLastDeclarationReadWithIt() throws { + // Main.(Holder in _0123…).(Inner in _0123…) + #expect(try Self.lines(for: ["$s4Main6Holder33_0123456789ABCDEF0123456789ABCDEFLLV5Inner33_0123456789ABCDEF0123456789ABCDEFLLVD"]) == [ + "Inner is declared in Box.swift", + ]) + } + + @Test func eachDiscriminatorGetsALineInTheOrderTheNameReadsThem() throws { + // Main.(Box in _0123…) + #expect(try Self.lines(for: ["$s4Main3Box33_0123456789ABCDEF0123456789ABCDEFLLVyAA1P33_FEDCBA9876543210FEDCBA9876543210LLVGD"]) == [ + "Box is declared in Box.swift", + "P is declared in Payload.swift", + ]) + } + + /// A member of a private type is declared in the type's file: the type's + /// own line already says so. + @Test func discriminatorOfTheEnclosingDeclarationGetsNoLine() throws { + // SymbolTestsCore.CodableTests.GenericCodableTest.(CodingKeys in _B89E…).stringValue.getter : Swift.String + #expect(try Self.lines( + for: ["$s15SymbolTestsCore12CodableTestsO07GenericC4TestV10CodingKeys33_B89E435DF71E951D297EEE1ADCD6DDD8LLO11stringValueSSvg"], + enclosedBy: "$s15SymbolTestsCore12CodableTestsO07GenericC4TestV10CodingKeys33_B89E435DF71E951D297EEE1ADCD6DDD8LLOMn" + ).isEmpty) + } + + @Test func privateMemberOfAPublicTypeGetsALine() throws { + // Main.Holder.(helper in _0123…)() -> () + #expect(try Self.lines(for: ["$s4Main6HolderV6helper33_0123456789ABCDEF0123456789ABCDEFLLyyF"], enclosedBy: "$s4Main6HolderVMn") == [ + "helper is declared in Box.swift", + ]) + } + + /// A conformance's header reads two names, the type's and the + /// protocol's; a discriminator both read gets one line. + @Test func linesAcrossNamesAreOnePerDiscriminator() throws { + #expect(try Self.lines(for: [ + // Main.(Box in _0123…) + "$s4Main3Box33_0123456789ABCDEF0123456789ABCDEFLLVD", + // Main.(Holder in _0123…).(Inner in _0123…) + "$s4Main6Holder33_0123456789ABCDEF0123456789ABCDEFLLV5Inner33_0123456789ABCDEF0123456789ABCDEFLLVD", + ]) == [ + "Inner is declared in Box.swift", + ]) + } +} diff --git a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift new file mode 100644 index 000000000..7047b49b6 --- /dev/null +++ b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift @@ -0,0 +1,39 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import MachOTestingSupport + +/// A protocol's same-type or superclass requirement whose right-hand side is +/// a composite type prints that type (evolution proposal +/// `protocol-requirement-placement`). Reading only the associated type names +/// out of it printed a different requirement: `Self.Second == [Self.First]` +/// as `Self.Second == Self.First`, `Self.Sixth == [Self]` as +/// `Self.Sixth == [A]`. +@Suite +struct ProtocolRequirementRightHandSideDumpTests { + private func protocolDump(named name: String) async throws -> String { + let machOFile = try ProtocolRequirementPlacementFixture.machOFile() + for protocolDescriptor in try machOFile.swift.protocolDescriptors { + guard try protocolDescriptor.name(in: machOFile.context) == name else { continue } + return try await MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: machOFile.context).dump(using: .demangleOptions(.interface), in: machOFile).string + } + Issue.record("protocol \(name) not found") + return "" + } + + @Test(arguments: [ + "Self.Second == [Self.First]", + "Self.Third == (Self.First, [Self.First])", + "Self.Fourth == Self.First?", + "Self.Fifth: ProtocolRequirementPlacementFixture.GenericBase", + "Self.Sixth == [Self]", + "Self.Eighth == [Self.Seventh.Element]", + ]) + func compositeRightHandSidePrintsAsItself(requirement: String) async throws { + let dump = try await protocolDump(named: "CompositeRequirements") + #expect(dump.contains(requirement), "\(dump)") + } +} diff --git a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift new file mode 100644 index 000000000..b9721cf92 --- /dev/null +++ b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift @@ -0,0 +1,63 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import MachOTestingSupport + +/// The dump of the declaration shapes Swift 6.4 introduced (evolution +/// proposal `borrow-accessors-and-suppressed-associated-types`): a member +/// whose only accessors are SE-0507 `borrow` / `mutate` is listed like any +/// other, and an associated type an extension proves suppressible says so. +@Suite(.enabled(if: Swift64DeclarationShapesFixture.isAvailable, "needs a Swift 6.4 or newer toolchain")) +struct Swift64DeclarationShapeDumpTests { + private func structDump(named name: String) async throws -> String { + let machOFile = try Swift64DeclarationShapesFixture.machOFile() + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .struct(let structDescriptor) = typeContextDescriptor, try structDescriptor.name(in: machOFile.context) == name else { continue } + return try await Struct(descriptor: structDescriptor, in: machOFile.context).dump(using: .demangleOptions(.test), in: machOFile).string + } + Issue.record("struct \(name) not found") + return "" + } + + private func protocolDump(named name: String) async throws -> String { + let machOFile = try Swift64DeclarationShapesFixture.machOFile() + for protocolDescriptor in try machOFile.swift.protocolDescriptors where try protocolDescriptor.name(in: machOFile.context) == name { + return try await MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: machOFile.context).dump(using: .demangleOptions(.test), in: machOFile).string + } + Issue.record("protocol \(name) not found") + return "" + } + + @Test(arguments: [ + "BorrowedStorage.borrowedOnly.borrow : Swift.Int", + "BorrowedStorage.borrowedAndMutated.borrow : Swift.Int", + "BorrowedStorage.borrowedAndMutated.mutate : Swift.Int", + "BorrowedStorage.subscript.borrow : (Swift.Int) -> Swift.Int", + "BorrowedStorage.subscript.mutate : (Swift.Int) -> Swift.Int", + ]) + func memberListsItsBorrowAndMutateAccessors(accessor: String) async throws { + let dump = try await structDump(named: "BorrowedStorage") + #expect(dump.contains(accessor), "\(dump)") + } + + @Test(arguments: [ + "associatedtype Element: ~Swift.Copyable", + "associatedtype View: ~Swift.Escapable", + "associatedtype Payload: ~Swift.Copyable & ~Swift.Escapable", + ]) + func associatedTypeShowsTheSuppressionItsExtensionsProve(line: String) async throws { + let dump = try await protocolDump(named: "SuppressedElementContainer") + let lines = dump.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + #expect(lines.contains(line), "\(dump)") + } + + @Test func associatedTypesWithoutEvidenceStayBare() async throws { + let dump = try await protocolDump(named: "SuppressedElementContainer") + let lines = dump.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + #expect(lines.contains("associatedtype Strategy"), "\(dump)") + #expect(lines.contains("associatedtype Index"), "\(dump)") + } +} diff --git a/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift b/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift new file mode 100644 index 000000000..3d952bf46 --- /dev/null +++ b/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift @@ -0,0 +1,112 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import Demangling +@_spi(Internals) import SwiftInspection +import MachOTestingSupport +import MachOFixtureSupport + +/// A host's wrapper around an in-process `MachOImage` — MachOKitUI's +/// `MachOImageSource` — demangling the image's names. +/// +/// SwiftUI's associated-type witnesses reach the opaque types of SwiftUICore. +/// Read through the image, such a reference is recorded as the descriptor's +/// absolute address. Read through a wrapper the library did not recognize as +/// in-process, it was recorded as an offset from SwiftUI's header. Where +/// SwiftUICore lies below SwiftUI — the dyld shared cache's layout from macOS 27 +/// on; macOS 15 and 26 map it above — that offset is negative, and converting it +/// to `UInt64` trapped (`Fatal error: Negative value is not representable`). +/// +/// Both tests run their body in a child process, so a trap fails the test rather +/// than ending the run. +@Suite +struct WrappedReaderDemanglingTests { + @Test("a wrapper that declares the image it wraps demangles every witness exactly like the image") + func declaredWrapperDemanglesLikeItsImage() async { + await #expect(processExitsWith: .success) { + exit(Self.compareDeclaredWrapperWithItsImage()) + } + } + + @Test( + "a wrapper that does not declare what it wraps reads a lower image's opaque type without trapping", + .enabled(if: swiftUICoreIsMappedBelowSwiftUI, "SwiftUI reaches an opaque type in a lower image only where the cache maps SwiftUICore below it (macOS 27 on)") + ) + func undeclaredWrapperDoesNotTrap() async { + await #expect(processExitsWith: .success) { + exit(Self.demangleThroughUndeclaredWrapper()) + } + } +} + +extension WrappedReaderDemanglingTests { + /// Whether this process's dyld shared cache maps SwiftUICore below SwiftUI, + /// read off the cache's own image list so that nothing is loaded to answer it. + private static var swiftUICoreIsMappedBelowSwiftUI: Bool { + guard let cache = DyldCacheLoaded.current, let imageEntries = cache.imageInfos else { return false } + func headerAddress(ofImageAt path: String) -> UInt64? { + imageEntries.first { $0.path(in: cache) == path }?.layout.address + } + guard let swiftUICoreAddress = headerAddress(ofImageAt: "/System/Library/Frameworks/SwiftUICore.framework/Versions/A/SwiftUICore"), + let swiftUIAddress = headerAddress(ofImageAt: "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI") + else { return false } + return swiftUICoreAddress < swiftUIAddress + } + + /// SwiftUI mapped into this process, or `nil` when it cannot be loaded. + private static func loadedSwiftUI() -> MachOImage? { + _ = dlopen("/System/Library/Frameworks/SwiftUI.framework/SwiftUI", RTLD_LAZY) + return MachOImage(named: .SwiftUI) + } + + /// Every associated-type witness SwiftUI records, as a mangled name. + private static func witnessTypeNames(in image: MachOImage) -> [MangledName] { + guard let associatedTypes = try? image.swift.associatedTypes else { return [] } + return associatedTypes.flatMap { associatedType in + associatedType.records.compactMap { record in + try? record.substitutedTypeName(in: image.context) + } + } + } + + /// `EXIT_SUCCESS` when the wrapper's tree equals the image's for every + /// witness, and at least one of them refers to an opaque type — the node an + /// unrecognized wrapper recorded as an offset instead of an address. Whether + /// any of those lies below SwiftUI depends on the host's cache layout, which + /// makes it the other test's precondition rather than this one's. + private static func compareDeclaredWrapperWithItsImage() -> Int32 { + guard let image = loadedSwiftUI() else { return EXIT_FAILURE } + let wrapper = ForwardingMachOReader(image) + var opaqueReferenceCount = 0 + for name in witnessTypeNames(in: image) { + let imageNode = try? SymbolicDemangler.demangleTypeUncached(for: name, in: image.context) + let wrapperNode = try? SymbolicDemangler.demangleTypeUncached(for: name, in: wrapper.context) + guard imageNode == wrapperNode else { return EXIT_FAILURE } + opaqueReferenceCount += (imageNode?.all(of: .opaqueTypeDescriptorSymbolicReference) ?? []).count + } + return opaqueReferenceCount > 0 ? EXIT_SUCCESS : EXIT_FAILURE + } + + /// `EXIT_SUCCESS` when at least one witness, read through the image, refers + /// to an opaque type below SwiftUI — the reference that trapped — and + /// demangling every witness through the undeclared wrapper returns. + private static func demangleThroughUndeclaredWrapper() -> Int32 { + guard let image = loadedSwiftUI() else { return EXIT_FAILURE } + let names = witnessTypeNames(in: image) + let imageStartAddress = UInt64(UInt(bitPattern: image.ptr)) + var referencesBelowTheImage = 0 + for name in names { + let imageNode = try? SymbolicDemangler.demangleTypeUncached(for: name, in: image.context) + let opaqueReferences = imageNode?.all(of: .opaqueTypeDescriptorSymbolicReference) ?? [] + referencesBelowTheImage += opaqueReferences.filter { ($0.index ?? .max) < imageStartAddress }.count + } + guard referencesBelowTheImage > 0 else { return EXIT_FAILURE } + let wrapper = ForwardingMachOReader(image) + for name in names { + _ = try? SymbolicDemangler.demangleTypeUncached(for: name, in: wrapper.context) + } + return EXIT_SUCCESS + } +} diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift index e2316f84e..a0a643f5e 100644 --- a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -2,6 +2,7 @@ @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +@_spi(Support) import SwiftPrivateDiscriminators import SwiftDeclarationRendering import OutputTransformer import SwiftOutputTransformer @@ -38,12 +39,17 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, case plain case markedOptionalContent case everyOptionWithTransformers + /// The comments naming private declarations' source files (evolution + /// proposal `private-declaration-source-files`), measured against a + /// nested definition's parent whatever level it prints at. + case privateDeclarationSourceFiles var description: String { switch self { case .plain: "plain" case .markedOptionalContent: "marked optional content" case .everyOptionWithTransformers: "every option with transformers" + case .privateDeclarationSourceFiles: "private declaration source files" } } @@ -51,7 +57,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, var configuration = SwiftDeclarationPrintConfiguration() configuration.marksNestedDefinitions = true switch self { - case .plain: + case .plain, .privateDeclarationSourceFiles: break case .markedOptionalContent: configuration.marksOptionalContent = true @@ -80,6 +86,18 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, } } + /// The index of the indexer's image; built per reader, as the index's + /// initializers are. + private static func privateDeclarationSourceFileIndex(of indexer: SwiftDeclarationIndexer) -> PrivateDiscriminatorSourceFileIndex? { + if let fileIndexer = indexer as? SwiftDeclarationIndexer { + PrivateDiscriminatorSourceFileIndex(indexer: fileIndexer) + } else if let imageIndexer = indexer as? SwiftDeclarationIndexer { + PrivateDiscriminatorSourceFileIndex(indexer: imageIndexer) + } else { + nil + } + } + private static func nestedDefinitionCount(of typeDefinition: TypeDefinition) -> Int { typeDefinition.protocolChildren.count + typeDefinition.typeChildren.reduce(0) { $0 + 1 + nestedDefinitionCount(of: $1) } @@ -125,6 +143,11 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, if variant.resolvesOpaqueTypes { printer.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) } + if variant == .privateDeclarationSourceFiles { + let index = try #require(Self.privateDeclarationSourceFileIndex(of: indexer)) + index.recoverSourceFiles(ofEveryDeclarationIn: indexer) + printer.setPrivateDeclarationSourceFileProvider(index) + } typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString // Every definition a region can name, by the identity the printer diff --git a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift new file mode 100644 index 000000000..bb9b63489 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift @@ -0,0 +1,238 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@testable import MachOTestingSupport + +/// How the interface prints a protocol's requirement signature (evolution +/// proposal `protocol-requirement-placement`): every requirement in the +/// protocol's `where` clause, or each on the associated type it is about. The +/// binary cannot say where the source wrote a requirement, so the one thing +/// both placements must guarantee is that they state the same requirements — +/// which `printedProtocolsCompileBackToTheSameRequirementSignatures` checks +/// the only way that does not trust the printer: compiling what it printed. +@Suite(.serialized) +struct ProtocolRequirementPlacementInterfaceTests { + private func printedInterface(of machOFile: MachOFile, configuration printConfiguration: SwiftDeclarationPrintConfiguration = .init()) async throws -> String { + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: machOFile) + try await builder.prepare() + return try await builder.printRoot().string + } + + private static func configuration(placement: ProtocolRequirementPlacement) -> SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.protocolRequirementPlacement = placement + return configuration + } + + /// A top-level protocol's lines, header to closing brace. + private static func protocolBlock(named name: String, in interface: String) -> String? { + let lines = interface.components(separatedBy: "\n") + guard let headerIndex = lines.firstIndex(where: { $0.hasPrefix("protocol \(name):") || $0.hasPrefix("protocol \(name) ") }) else { return nil } + if lines[headerIndex].hasSuffix("{}") { + return lines[headerIndex] + } + guard let closingIndex = lines[headerIndex...].firstIndex(of: "}") else { return nil } + return lines[headerIndex ... closingIndex].joined(separator: "\n") + } + + /// Each protocol's requirement signature as its descriptor records it, + /// printed by the demangler (`A.Second == [A.First]`) through the generic + /// requirement dump, never through the protocol printer under test. + private static func requirementSignatures(in machOFile: MachOFile) async throws -> [String: [String]] { + var requirementSignatures: [String: [String]] = [:] + for protocolDescriptor in try machOFile.swift.protocolDescriptors { + let protocolModel = try MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: machOFile.context) + var requirements: [String] = [] + for requirement in protocolModel.requirementInSignatures { + let requirementText = try await requirement.descriptor.dump(using: .default, in: machOFile.context).string + requirements.append("\(requirement.descriptor.flags.kind) \(requirementText)") + } + requirementSignatures[protocolModel.name] = requirements + } + return requirementSignatures + } + + // MARK: - Composite right-hand sides + + /// A same-type or superclass requirement whose right-hand side is a + /// composite type prints that type. Reading only the associated type + /// names out of it printed a different requirement: + /// `Self.Second == [Self.First]` as `Self.Second == Self.First`. + @Test(arguments: [ + "Self.Second == [Self.First]", + "Self.Third == (Self.First, [Self.First])", + "Self.Fourth == Self.First?", + "Self.Fifth: ProtocolRequirementPlacementFixture.GenericBase", + "Self.Sixth == [Self]", + "Self.Eighth == [Self.Seventh.Element]", + ]) + func compositeRightHandSidePrintsAsItself(requirement: String) async throws { + let interface = try await printedInterface(of: ProtocolRequirementPlacementFixture.machOFile()) + #expect(interface.contains(requirement), "\(interface)") + } + + // MARK: - Placement + + struct PlacementCase: Sendable, CustomTestStringConvertible { + let protocolName: String + let blockWithRequirementsOnAssociatedTypes: String + + var testDescription: String { protocolName } + } + + /// The blocks follow the compiler's `-emit-module-interface` for the same + /// source, except `RecursiveRequirements`, where the compiler prints + /// `associatedtype Leaf : Swift.Hashable` — a requirement on `Self.Leaf` + /// that the protocol does not have. + static let placementCases: [PlacementCase] = [ + PlacementCase( + protocolName: "CompositeRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol CompositeRequirements { + associatedtype First + associatedtype Second where Self.Second == [Self.First] + associatedtype Third where Self.Third == (Self.First, [Self.First]) + associatedtype Fourth where Self.Fourth == Self.First? + associatedtype Fifth: ProtocolRequirementPlacementFixture.GenericBase + associatedtype Sixth where Self.Sixth == [Self] + associatedtype Seventh: ProtocolRequirementPlacementFixture.Marker, Swift.Sequence + associatedtype Eighth where Self.Eighth == [Self.Seventh.Element] + } + """ + ), + PlacementCase( + protocolName: "DirectRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol DirectRequirements { + associatedtype Conforming: ProtocolRequirementPlacementFixture.Marker, Swift.Hashable + associatedtype Subclass: ProtocolRequirementPlacementFixture.BaseClass + associatedtype ClassBound: AnyObject + associatedtype ClassAndProtocol: ProtocolRequirementPlacementFixture.BaseClass, ProtocolRequirementPlacementFixture.Marker + associatedtype Nested: Swift.Sequence where Self.Nested.Element: ProtocolRequirementPlacementFixture.Marker + associatedtype Concrete where Self.Concrete == Swift.Int + } + """ + ), + PlacementCase( + protocolName: "SameTypeRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol SameTypeRequirements { + associatedtype First where Self.First == Self.Second.Target + associatedtype Second: ProtocolRequirementPlacementFixture.Pointing + associatedtype Third: ProtocolRequirementPlacementFixture.Pointing where Self == Self.Third.Target + } + """ + ), + PlacementCase( + protocolName: "RecursiveRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol RecursiveRequirements { + associatedtype Child: ProtocolRequirementPlacementFixture.RecursiveRequirements where Self.Child.Leaf: Swift.Hashable + associatedtype Leaf + } + """ + ), + PlacementCase( + protocolName: "RefinedRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol RefinedRequirements: Swift.Sequence where Self.Element: ProtocolRequirementPlacementFixture.Marker { + associatedtype Storage: Swift.Collection where Self.Element == Self.Storage.Element + } + """ + ), + PlacementCase( + protocolName: "InheritedOnlyRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol InheritedOnlyRequirements: Swift.Sequence where Self.Element: Swift.Hashable {} + """ + ), + PlacementCase( + protocolName: "SubjectOnlyRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol SubjectOnlyRequirements: Swift.Sequence where Self.Element: ProtocolRequirementPlacementFixture.GenericBase { + associatedtype First + } + """ + ), + PlacementCase( + protocolName: "ClassBoundRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol ClassBoundRequirements: AnyObject { + associatedtype Item: AnyObject + } + """ + ), + PlacementCase( + protocolName: "MenuRequirements", + blockWithRequirementsOnAssociatedTypes: """ + protocol MenuRequirements: Swift.Identifiable { + associatedtype MenuItem: ProtocolRequirementPlacementFixture.Marker + } + """ + ), + ] + + @Test(arguments: placementCases) + func requirementsPrintOnTheAssociatedTypesTheyAreAbout(_ placementCase: PlacementCase) async throws { + let interface = try await printedInterface(of: ProtocolRequirementPlacementFixture.machOFile(), configuration: Self.configuration(placement: .associatedTypes)) + let block = try #require(Self.protocolBlock(named: placementCase.protocolName, in: interface), "\(interface)") + #expect(block == placementCase.blockWithRequirementsOnAssociatedTypes) + } + + /// The default keeps every requirement in the protocol's header, so no + /// `associatedtype` line carries one. + @Test(arguments: ProtocolRequirementPlacementFixture.protocolNames) + func defaultPlacementLeavesEveryAssociatedTypeBare(protocolName: String) async throws { + let interface = try await printedInterface(of: ProtocolRequirementPlacementFixture.machOFile()) + let block = try #require(Self.protocolBlock(named: protocolName, in: interface), "\(interface)") + for line in block.components(separatedBy: "\n").dropFirst() { + #expect(!line.contains(":") && !line.contains(" where "), "\(protocolName): \(line)") + } + } + + /// The guarantee both placements make: what they print states the + /// protocol's requirement signature exactly. Each printed form of the + /// fixture's protocols is compiled again, as the same module and against + /// the same supporting declarations, and every protocol must come back + /// with the requirement signature it started from — the canonical + /// signature being all the binary ever knew of the source. + @Test(arguments: ProtocolRequirementPlacement.allCases) + func printedProtocolsCompileBackToTheSameRequirementSignatures(placement: ProtocolRequirementPlacement) async throws { + let fixture = try ProtocolRequirementPlacementFixture.machOFile() + let interface = try await printedInterface(of: fixture, configuration: Self.configuration(placement: placement)) + let printedProtocols = try ProtocolRequirementPlacementFixture.protocolNames.map { protocolName in + try #require(Self.protocolBlock(named: protocolName, in: interface), "\(protocolName) missing from:\n\(interface)") + } + let printedSource = printedProtocols.joined(separator: "\n\n") + let recompiledFixture = try ProtocolRequirementPlacementFixture.machOFile(compiling: printedSource) + + let originalRequirementSignatures = try await Self.requirementSignatures(in: fixture) + let recompiledRequirementSignatures = try await Self.requirementSignatures(in: recompiledFixture) + for protocolName in ProtocolRequirementPlacementFixture.protocolNames { + let originalRequirementSignature = try #require(originalRequirementSignatures[protocolName]) + #expect(recompiledRequirementSignatures[protocolName] == originalRequirementSignature, "\(protocolName), printed as:\n\(printedSource)") + } + } + + /// The diff and evolution interfaces print a protocol's `associatedtype` + /// lines without requirements, so their header keeps every requirement + /// whatever the placement says — the same header the default prints. + @Test(arguments: ProtocolRequirementPlacementFixture.protocolNames) + func diffHeaderKeepsEveryRequirement(protocolName: String) async throws { + let fixture = try ProtocolRequirementPlacementFixture.machOFile() + let defaultInterface = try await printedInterface(of: fixture) + let defaultHeader = try #require(Self.protocolBlock(named: protocolName, in: defaultInterface)?.components(separatedBy: "\n").first, "\(defaultInterface)") + + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: Self.configuration(placement: .associatedTypes)), eventHandlers: [], in: fixture) + try await builder.prepare() + let qualifiedName = "\(ProtocolRequirementPlacementFixture.moduleName).\(protocolName)" + let protocolDefinition = try #require(builder.indexer.allProtocolDefinitions.values.first { $0.protocolName.name == qualifiedName }) + let diffHeader = try await builder.printer.printProtocolHeader(protocolDefinition, level: 1).string + #expect(defaultHeader.hasPrefix(diffHeader + " {"), "\(diffHeader)\n\(defaultHeader)") + } +} diff --git a/Tests/SwiftInterfaceTests/ReaderKindCastScanTests.swift b/Tests/SwiftInterfaceTests/ReaderKindCastScanTests.swift new file mode 100644 index 000000000..9502afb3c --- /dev/null +++ b/Tests/SwiftInterfaceTests/ReaderKindCastScanTests.swift @@ -0,0 +1,80 @@ +import Foundation +import Testing + +/// The library tells readers apart through `asMachOImage` / `asMachOFile` / +/// `underlyingReader` (MachOKitExtensions), never through a cast to +/// `MachOImage` / `MachOFile`. +/// +/// A cast cannot see through a host's wrapper (MachOKitUI's `MachOImageSource` +/// and `MachOFileSource`), so every one of them treated a wrapper as neither +/// reader: most quietly dropped what they work out, and the in-process opaque +/// type reference trapped. Bind / rebase resolution had already been made +/// wrapper-aware (`MachOBindRebaseResolving`) when that in-process path was +/// written as a cast, which is why this is a scan rather than a review note. +@Suite +struct ReaderKindCastScanTests { + @Test("no library module tells readers apart with a cast") + func libraryModulesDoNotCastReaders() throws { + var offendingLines: [String] = [] + for fileURL in try Self.librarySourceFiles() { + let contents = try String(contentsOf: fileURL, encoding: .utf8) + for (lineNumber, line) in contents.components(separatedBy: .newlines).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//"), Self.castsToAConcreteReader(code) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect( + offendingLines.isEmpty, + """ + ask `asMachOImage` / `asMachOFile` / `underlyingReader` what a reader is, so a wrapper answers \ + for the reader it wraps: + \(offendingLines.joined(separator: "\n")) + """ + ) + } + + /// The scan must be able to see a cast, and must not invent one — its + /// silence proves nothing otherwise. + @Test("the scan sees a reader cast and nothing else") + func theScanDiscriminates() { + #expect(Self.castsToAConcreteReader("if let machOImage = machO as? MachOImage {")) + #expect(Self.castsToAConcreteReader("if machO is MachOFile {")) + #expect(Self.castsToAConcreteReader("let machOFile = machO as! MachOFile")) + #expect(Self.castsToAConcreteReader("if let machOImageContext = context as? MachOContext {")) + #expect(Self.castsToAConcreteReader("case let machOFile as MachOFile: machOFile.imagePath")) + + #expect(!Self.castsToAConcreteReader("extension ImageUniverse where MachO == MachOImage {")) + #expect(!Self.castsToAConcreteReader("extension ReadingContext where Self == MachOContext {")) + #expect(!Self.castsToAConcreteReader("if let machOImage = machO.asMachOImage {")) + #expect(!Self.castsToAConcreteReader("let machOFile: MachOFile = fileImage")) + #expect(!Self.castsToAConcreteReader("if let machOImages = machO as? MachOImageCollection {")) + } + + private static let readerCastExpression = try! NSRegularExpression( + pattern: #"\b(as[?!]?|is)\s+(MachOImage|MachOFile|MachOContext<\s*MachO(Image|File)\s*>)(?![A-Za-z0-9_])"# + ) + + private static func castsToAConcreteReader(_ code: String) -> Bool { + readerCastExpression.firstMatch(in: code, range: NSRange(code.startIndex..., in: code)) != nil + } + + /// Every Swift file of a library module: `Sources///…`, the + /// `TestSupport` group left out — fixtures there hold the concrete readers + /// on purpose. + private static func librarySourceFiles() throws -> [URL] { + let sourcesDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // SwiftInterfaceTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + .appendingPathComponent("Sources") + let enumerator = try #require(FileManager.default.enumerator(at: sourcesDirectory, includingPropertiesForKeys: nil)) + var files: [URL] = [] + for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" { + let groupName = fileURL.pathComponents.drop(while: { $0 != "Sources" }).dropFirst().first + if groupName == "TestSupport" { continue } + files.append(fileURL) + } + return files + } +} diff --git a/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift b/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift new file mode 100644 index 000000000..9d8d5e583 --- /dev/null +++ b/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift @@ -0,0 +1,113 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftPrinting +import SwiftInterface +@testable import MachOTestingSupport + +/// The interface of the declaration shapes Swift 6.4 introduced (evolution +/// proposal `borrow-accessors-and-suppressed-associated-types`). The expected +/// spellings are the compiler's own: a swiftinterface prints `{ borrow mutate }` +/// and `associatedtype Element: ~Copyable` for these declarations. +@Suite(.enabled(if: Swift64DeclarationShapesFixture.isAvailable, "needs a Swift 6.4 or newer toolchain")) +struct Swift64DeclarationShapeInterfaceTests { + /// The fixture is a handful of declarations, so each test builds its own. + private func printedInterface(printConfiguration: SwiftDeclarationPrintConfiguration = .init()) async throws -> String { + let builder = try SwiftInterfaceBuilder(configuration: SwiftInterfaceBuilderConfiguration(printConfiguration: printConfiguration), eventHandlers: [], in: try Swift64DeclarationShapesFixture.machOFile()) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The lines of the block whose header line, trimmed, starts with + /// `prefix` — trimmed, header and closing brace excluded. + private func blockLines(startingWith prefix: String, in interface: String) -> [String]? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces).hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[(start + 1)...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[(start + 1) ..< end].map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + } + + // MARK: - SE-0507 borrow / mutate accessors + + @Test(arguments: [ + ("var borrowedOnly: Swift.Int {", ["borrow"]), + ("var borrowedAndMutated: Swift.Int {", ["borrow", "mutate"]), + ("var computed: Swift.Int {", ["get", "set"]), + ]) + func propertyPrintsItsDeclaredAccessors(header: String, accessors: [String]) async throws { + let interface = try await printedInterface() + let storageLines = try #require(blockLines(startingWith: "struct BorrowedStorage", in: interface), "\(interface)") + let headerIndex = try #require(storageLines.firstIndex(of: header), "\(storageLines)") + #expect(Array(storageLines[(headerIndex + 1)...].prefix(accessors.count + 1)) == accessors + ["}"], "\(storageLines)") + } + + @Test func subscriptPrintsBorrowAndMutate() async throws { + let interface = try await printedInterface() + let storageLines = try #require(blockLines(startingWith: "struct BorrowedStorage", in: interface), "\(interface)") + let headerIndex = try #require(storageLines.firstIndex { $0.hasPrefix("subscript(") && $0.hasSuffix("-> Swift.Int {") }, "\(storageLines)") + #expect(Array(storageLines[(headerIndex + 1)...].prefix(3)) == ["borrow", "mutate", "}"], "\(storageLines)") + } + + /// A protocol whose requirements are all SE-0507 accessors printed as an + /// empty `protocol BorrowRequirement {}`. + @Test func protocolRequirementPrintsBorrowAndMutate() async throws { + let interface = try await printedInterface() + let protocolLines = try #require(blockLines(startingWith: "protocol BorrowRequirement", in: interface), "\(interface)") + #expect(protocolLines == [ + "var element: Swift.Int {", + "borrow", + "mutate", + "}", + "var readOnlyElement: Swift.Int {", + "borrow", + "}", + ]) + } + + // MARK: - SE-0503 suppressed associated types + + /// A primary associated type an extension suppresses prints its + /// suppression; an ordinary one cannot carry the evidence (`Strategy`), + /// and the Copyable control (`Index`) prints bare. + @Test(arguments: [ + ("associatedtype Element", "associatedtype Element: ~Swift.Copyable"), + ("associatedtype View", "associatedtype View: ~Swift.Escapable"), + ("associatedtype Payload", "associatedtype Payload: ~Swift.Copyable & ~Swift.Escapable"), + ("associatedtype Strategy", "associatedtype Strategy"), + ("associatedtype Index", "associatedtype Index"), + ]) + func associatedTypePrintsTheSuppressionItsExtensionsProve(declarationPrefix: String, expectedLine: String) async throws { + let interface = try await printedInterface() + let protocolLines = try #require(blockLines(startingWith: "protocol SuppressedElementContainer", in: interface), "\(interface)") + let line = try #require(protocolLines.first { $0 == declarationPrefix || $0.hasPrefix(declarationPrefix + ":") }, "\(protocolLines)") + #expect(line == expectedLine) + } + + /// Without an extension the declaration is unknowable, so the reading + /// stays the default rather than guessing. + @Test func associatedTypeWithoutEvidencePrintsBare() async throws { + let interface = try await printedInterface() + let protocolLines = try #require(blockLines(startingWith: "protocol UnprovenElementContainer", in: interface), "\(interface)") + #expect(protocolLines.contains("associatedtype Element"), "\(protocolLines)") + } + + /// With requirements printed on the associated types (evolution proposal + /// `protocol-requirement-placement`), a proven suppression joins the + /// inheritance clause after the requirements, as the compiler writes + /// `associatedtype Element: P, ~Copyable`. In the protocol's `where` + /// clause the requirement leaves the suppression alone on the line. + @Test(arguments: [ + (ProtocolRequirementPlacement.protocolWhereClause, "associatedtype Element: ~Swift.Copyable"), + (ProtocolRequirementPlacement.associatedTypes, "associatedtype Element: Swift64DeclarationShapesFixture.SuppressibleMarker, ~Swift.Copyable"), + ]) + func suppressionJoinsTheInheritanceClauseOfItsAssociatedType(placement: ProtocolRequirementPlacement, expectedLine: String) async throws { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.protocolRequirementPlacement = placement + let interface = try await printedInterface(printConfiguration: printConfiguration) + let protocolLines = try #require(blockLines(startingWith: "protocol ConstrainedSuppressedElementContainer", in: interface), "\(interface)") + #expect(protocolLines.contains(expectedLine), "\(protocolLines)") + } +} diff --git a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift new file mode 100644 index 000000000..458da3667 --- /dev/null +++ b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift @@ -0,0 +1,78 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftPrinting +import SwiftInterface +import SwiftDeclarationRendering +@testable import MachOTestingSupport + +/// The fixture's interface printed through a host's wrapper — a type that +/// forwards every read to a `MachOFile` or an in-process `MachOImage`, as +/// MachOKitUI's `MachOFileSource` / `MachOImageSource` do — must be the bytes +/// the reader itself prints. +/// +/// Every comment kind and the interface header are on, so an image path, an +/// address, a field offset, a layout or a resolved opaque type that the library +/// works out only for a bare reader shows up as a difference. +/// +/// The wrapper prints first. It shares the reader's per-image caches (its +/// `identifier` is the reader's), so what it builds the reader's print then +/// reads too; printed second, it could read caches the reader built and hide a +/// difference. +@Suite(.serialized) +final class WrappedReaderInterfaceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + @Test("a wrapper of the fixture file prints the file's interface") + func fileWrapperPrintsTheFileInterface() async throws { + let wrapperInterface = try await Self.interface(of: ForwardingMachOReader(machOFile)) + let fileInterface = try await Self.interface(of: machOFile) + #expect(Self.firstDifference(between: wrapperInterface, and: fileInterface) == nil) + } + + @Test("a wrapper of the fixture image prints the image's interface") + func imageWrapperPrintsTheImageInterface() async throws { + let wrapperInterface = try await Self.interface(of: ForwardingMachOReader(machOImage)) + let imageInterface = try await Self.interface(of: machOImage) + #expect(Self.firstDifference(between: wrapperInterface, and: imageInterface) == nil) + } + + private static func interface(of machO: MachO) async throws -> String { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.printFieldOffset = true + printConfiguration.printExpandedFieldOffsets = true + printConfiguration.printMemberAddress = true + printConfiguration.printVTableOffset = true + printConfiguration.printPWTOffset = true + printConfiguration.printExportStatus = true + printConfiguration.printTypeLayout = true + printConfiguration.printEnumLayout = true + let configuration = SwiftInterfaceBuilderConfiguration( + printConfiguration: printConfiguration, + interfaceHeaderInfo: InterfaceHeaderInfo( + machO: machO, + generatorName: "WrappedReaderInterfaceTests", + generatorVersion: "0", + generatedDate: Date(timeIntervalSince1970: 0) + ) + ) + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machO) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The first line the two interfaces disagree on, or `nil` when they are + /// the same. + private static func firstDifference(between wrapperInterface: String, and readerInterface: String) -> String? { + let wrapperLines = wrapperInterface.components(separatedBy: "\n") + let readerLines = readerInterface.components(separatedBy: "\n") + for (lineIndex, (wrapperLine, readerLine)) in zip(wrapperLines, readerLines).enumerated() where wrapperLine != readerLine { + return "line \(lineIndex + 1):\n wrapper: \(wrapperLine)\n reader: \(readerLine)" + } + guard wrapperLines.count == readerLines.count else { + return "the wrapper printed \(wrapperLines.count) lines, the reader \(readerLines.count)" + } + return nil + } +} diff --git a/Tests/SwiftLayoutTests/StandardLibraryLeafLayoutTests.swift b/Tests/SwiftLayoutTests/StandardLibraryLeafLayoutTests.swift new file mode 100644 index 000000000..a9a32c4c5 --- /dev/null +++ b/Tests/SwiftLayoutTests/StandardLibraryLeafLayoutTests.swift @@ -0,0 +1,229 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import Demangling +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout + +/// The standard library's own images, read out of the host's dyld shared +/// cache as files — the way `swift-section` reads a system image offline. A +/// separate type on purpose: a `@Suite(.enabled(if:))` condition that reads a +/// static of the suite it decorates is a circular macro reference. +enum HostStandardLibraryImages { + static let libswiftCorePath = "/usr/lib/swift/libswiftCore.dylib" + + /// Declares fields of `Builtin.Job`, `Builtin.Executor` and + /// `Builtin.RawUnsafeContinuation`, yet carries no builtin leaf record: + /// the compiler emits those for the standard library alone. + static let concurrencyPath = "/usr/lib/swift/libswift_Concurrency.dylib" + + static var isAvailable: Bool { FullDyldCache.cachedHost != nil } + + static func image(atPath path: String) throws -> MachOFile { + let hostCache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache") + return try #require(hostCache.machOFile(by: .path(path)), "the host dyld shared cache has no \(path)") + } +} + +/// What the static engine answers for the compiler's builtin leaf types — the +/// layouts every standard library type bottoms out in — checked against the +/// two authorities the binaries carry: libswiftCore's `__swift5_builtin` leaf +/// records and the runtime's value-witness tables. The last test turns the +/// same check on `KnownLayoutTable`, whose frozen layouts must be exactly what +/// libswiftCore's own metadata computes. +@Suite(.enabled(if: HostStandardLibraryImages.isAvailable)) +struct StandardLibraryLeafLayoutTests { + /// The five facts a value-witness table records about a layout, compared as + /// one value so a mismatch prints both sides in full. + private struct WitnessedLayout: Equatable, CustomStringConvertible { + let size: Int + let stride: Int + let alignment: Int + let extraInhabitantCount: Int + let isBitwiseTakable: Bool + + init(_ staticLayout: StaticTypeLayout) { + self.size = staticLayout.size + self.stride = staticLayout.stride + self.alignment = staticLayout.alignment + self.extraInhabitantCount = staticLayout.extraInhabitantCount + self.isBitwiseTakable = staticLayout.isBitwiseTakable + } + + /// The live value-witness table of `runtimeType`: the runtime's own answer. + init(runtimeLayoutOf runtimeType: Any.Type) throws { + let metadata = try MetadataWrapper.resolve(at: unsafeBitCast(runtimeType, to: UnsafeRawPointer.self), in: .inProcess) + let valueWitnessTable = try metadata.valueWitnessTable(in: .inProcess) + self.size = Int(valueWitnessTable.layout.size) + self.stride = Int(valueWitnessTable.layout.stride) + self.alignment = Int(valueWitnessTable.layout.flags.alignment) + self.extraInhabitantCount = Int(valueWitnessTable.layout.numExtraInhabitants) + self.isBitwiseTakable = valueWitnessTable.layout.flags.isBitwiseTakable + } + + var description: String { + "(size: \(size), stride: \(stride), alignment: \(alignment), " + + "extraInhabitantCount: 0x\(String(extraInhabitantCount, radix: 16)), " + + "isBitwiseTakable: \(isBitwiseTakable))" + } + } + + /// A builtin leaf as libswiftCore's `__swift5_builtin` section records it. + struct RecordedLeaf: Sendable, CustomTestStringConvertible { + let builtinName: String + let layout: StaticTypeLayout + var testDescription: String { builtinName } + } + + /// A `_Concurrency` type whose only stored field is a builtin leaf that no + /// image records, so the engine answers the leaf from what it knows. + enum ConcurrencyLeafHolder: CaseIterable, Sendable, CustomTestStringConvertible { + case unownedJob + case unownedSerialExecutor + case unsafeContinuation + + var qualifiedTypeName: String { + switch self { + case .unownedJob: "Swift.UnownedJob" + case .unownedSerialExecutor: "Swift.UnownedSerialExecutor" + case .unsafeContinuation: "Swift.UnsafeContinuation" + } + } + + var runtimeType: Any.Type { + switch self { + case .unownedJob: UnownedJob.self + case .unownedSerialExecutor: UnownedSerialExecutor.self + case .unsafeContinuation: UnsafeContinuation.self + } + } + + var testDescription: String { qualifiedTypeName } + } + + private func structDescriptor(named qualifiedTypeName: String, in machO: MachOFile) throws -> StructDescriptor? { + for contextDescriptor in try machO.swift.contextDescriptors { + guard + case .struct(let structDescriptor)? = contextDescriptor.typeContextDescriptorWrapper, + (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) + .flatMap(NodeTypeNaming.nominalQualifiedName(of:)) == qualifiedTypeName + else { continue } + return structDescriptor + } + return nil + } + + /// The builtin type name a builtin mangling demangles to (`Bi1_` → + /// `Builtin.Int1`), the spelling both the resolver and the index key on. + private func builtinTypeName(of builtinNode: Node) throws -> String { + let builtinTypeNameNode = builtinNode.kind == .type ? builtinNode.firstChild : builtinNode + return try #require(builtinTypeNameNode?.text, "\(builtinNode) is not a builtin type") + } + + // The literals are what libswiftCore's records carry, read from the raw + // section bytes; builtin leaf layouts are fixed by the ABI. + @Test("A leaf libswiftCore records is found under the builtin's own name", arguments: [ + RecordedLeaf(builtinName: "Builtin.Int1", layout: StaticTypeLayout(size: 1, stride: 1, alignmentMask: 0, extraInhabitantCount: 254, isBitwiseTakable: true)), + RecordedLeaf(builtinName: "Builtin.FPIEEE16", layout: StaticTypeLayout(size: 2, stride: 2, alignmentMask: 1, extraInhabitantCount: 0, isBitwiseTakable: true)), + RecordedLeaf(builtinName: "Builtin.IntLiteral", layout: StaticTypeLayout(size: 16, stride: 16, alignmentMask: 7, extraInhabitantCount: 0x7FFF_FFFF, isBitwiseTakable: true)), + RecordedLeaf(builtinName: "Builtin.UnsafeValueBuffer", layout: StaticTypeLayout(size: 24, stride: 24, alignmentMask: 7, extraInhabitantCount: 0, isBitwiseTakable: false)), + ]) + func recordedLeafIsFoundByBuiltinName(recordedLeaf: RecordedLeaf) throws { + let builtinIndex = try BuiltinTypeLayoutIndex(machO: HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.libswiftCorePath)) + #expect(builtinIndex.layout(forTypeName: recordedLeaf.builtinName) == recordedLeaf.layout) + } + + /// Another image's field of one of these types reaches libswiftCore through + /// the dependency closure, where the type's only stored field is a leaf + /// that libswiftCore's records alone describe. + @Test("A standard library type over a leaf only libswiftCore records lays out like the runtime", arguments: [ + "s7Float16V", + "s12StaticBigIntV", + ]) + func standardLibraryTypeOverRecordedLeafMatchesRuntime(mangledTypeName: String) throws { + let runtimeType = try #require(_typeByName(mangledTypeName), "the runtime has no \(mangledTypeName)") + let runtimeLayout = try WitnessedLayout(runtimeLayoutOf: runtimeType) + let universe = try ImageUniverse.dependencyClosure(root: HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.concurrencyPath)) + let staticLayout = try StaticTypeLayoutResolver(imageUniverse: universe) + .layout(forTypeNode: demangleAsNode(mangledTypeName, isType: true), in: universe.rootImage) + #expect(WitnessedLayout(staticLayout) == runtimeLayout) + } + + /// The leaves the engine must answer itself — every image but libswiftCore + /// declares builtin fields without recording them — must agree with + /// libswiftCore's record of the same leaf. + @Test("A leaf answered without a record matches libswiftCore's record of it", arguments: [ + "Bi1_", "Bi8_", "Bi16_", "Bi32_", "Bi64_", "Bi128_", "Bw", + "Bf16_", "Bf32_", "Bf64_", + "Bp", "Bo", "Bb", "BO", + ]) + func leafAnsweredWithoutRecordMatchesLibswiftCoresRecord(builtinMangling: String) throws { + let builtinNode = try demangleAsNode(builtinMangling, isType: true) + let builtinName = try builtinTypeName(of: builtinNode) + let libswiftCoreIndex = try BuiltinTypeLayoutIndex(machO: HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.libswiftCorePath)) + let recordedLayout = try #require(libswiftCoreIndex.layout(forTypeName: builtinName), "libswiftCore records no \(builtinName)") + + let universe = try ImageUniverse.singleImage(HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.concurrencyPath)) + let answeredLayout = try StaticTypeLayoutResolver(imageUniverse: universe).layout(forTypeNode: builtinNode, in: universe.rootImage) + #expect(answeredLayout == recordedLayout) + } + + @Test("A concurrency type over a leaf no image records lays out like the runtime", arguments: ConcurrencyLeafHolder.allCases) + func concurrencyLeafHolderMatchesRuntime(holder: ConcurrencyLeafHolder) throws { + let runtimeLayout = try WitnessedLayout(runtimeLayoutOf: holder.runtimeType) + let concurrency = try HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.concurrencyPath) + let structDescriptor = try #require(try structDescriptor(named: holder.qualifiedTypeName, in: concurrency), "libswift_Concurrency declares no \(holder.qualifiedTypeName)") + let staticLayout = try StaticLayoutCalculator(machO: concurrency).typeLayout(ofStruct: structDescriptor) + #expect(WitnessedLayout(staticLayout) == runtimeLayout) + } + + /// `Builtin.DefaultActorStorage` is the inline storage of a default actor, + /// `Builtin.NonDefaultDistributedActorStorage` that of a distributed actor + /// with a custom executor; the compiler gives both as an artificial stored + /// field. IRGen lowers both as `NumWords_DefaultActor` / + /// `NumWords_NonDefaultDistributedActor` (12) machine words at twice the + /// pointer alignment, with no spare bits. + @Test("An actor's inline storage is twelve words at twice the pointer alignment", arguments: ["BD", "Bd"]) + func actorStorageLeaf(builtinMangling: String) throws { + let universe = try ImageUniverse.singleImage(HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.concurrencyPath)) + let layout = try StaticTypeLayoutResolver(imageUniverse: universe) + .layout(forTypeNode: demangleAsNode(builtinMangling, isType: true), in: universe.rootImage) + #expect(layout == StaticTypeLayout(size: 96, stride: 96, alignmentMask: 15, extraInhabitantCount: 0, isBitwiseTakable: true)) + } + + /// Each libswiftCore struct the table names is laid out from its own field + /// records down to libswiftCore's leaf records. A field whose type the + /// table also names (`Character`'s `String`) is answered by the table; that + /// entry is checked at its own top level, so every entry rests on the + /// binary. + @Test("Every frozen layout in KnownLayoutTable is what libswiftCore's own metadata computes") + func knownLayoutTableAgreesWithLibswiftCore() throws { + let libswiftCore = try HostStandardLibraryImages.image(atPath: HostStandardLibraryImages.libswiftCorePath) + let calculator = try StaticLayoutCalculator(machO: libswiftCore) + var comparedTypeNames: Set = [] + for contextDescriptor in try libswiftCore.swift.contextDescriptors { + guard + case .struct(let structDescriptor)? = contextDescriptor.typeContextDescriptorWrapper, + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: libswiftCore.context)) + .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), + let frozenLayout = KnownLayoutTable.layout(forFullyQualifiedTypeName: qualifiedTypeName) + else { continue } + comparedTypeNames.insert(qualifiedTypeName) + do { + let computedLayout = try calculator.typeLayout(ofStruct: structDescriptor) + #expect(computedLayout == frozenLayout, "\(qualifiedTypeName): libswiftCore computes \(computedLayout), the table says \(frozenLayout)") + } catch { + Issue.record("\(qualifiedTypeName): libswiftCore's metadata does not lay out — \(error)") + } + } + // A table that no longer meets the libswiftCore types it names would + // pass vacuously. + #expect(comparedTypeNames.isSuperset(of: [ + "Swift.Bool", "Swift.Int", "Swift.Double", "Swift.String", "Swift.Character", + "Swift.Array", "Swift.Dictionary", "Swift.Set", + "Swift.UnsafePointer", "Swift.UnsafeRawBufferPointer", "Swift.Unmanaged", + ]), "compared only \(comparedTypeNames.sorted())") + } +} diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift index 12f90b98c..e94117d28 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift @@ -5,6 +5,7 @@ import MachOFixtureSupport @testable import MachOTestingSupport @_spi(Support) import SwiftIndexing import SwiftInspection +import SwiftDeclarationRendering @testable @_spi(Support) import SwiftPrivateDiscriminators /// An image's private discriminators, recovered from candidates the image's @@ -128,6 +129,34 @@ struct PrivateDiscriminatorSourceFileIndexTests { #expect(index.searchCount == 1) } + /// A printer naming the file of every private declaration it shows + /// searches once for the whole image (evolution proposal + /// `private-declaration-source-files`), and every answer after that is a + /// lookup — the same answer a request of its own gets. + @Test func wholeImageIsSearchedOnceAndAnsweredFromThen() async throws { + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.machOFile(.unstripped)) + try await indexer.prepare() + let index = PrivateDiscriminatorSourceFileIndex(indexer: indexer, knownFileNames: []) + + index.recoverSourceFiles(ofEveryDeclarationIn: indexer) + #expect(index.searchCount == 1) + + #expect(index.sourceFile(forPrivateDiscriminator: Self.unstrippedFixtureDiscriminator) == PrivateDeclarationSourceFile(fileName: "Fixture.swift", moduleName: "LocalTypeFixtureUnstripped", isSynthesized: false)) + #expect(index.sourceFile(forPrivateDiscriminator: try Self.hiddenValuesDiscriminator(in: indexer)) != nil) + #expect(index.searchCount == 1) + } + + /// What the whole-image search found is what a printer is told, and what + /// it did not find reads as not recovered rather than being searched for + /// again. + @Test func providerAnswersWhatTheSearchFound() { + let index = PrivateDiscriminatorSourceFileIndex(imagePath: Self.swiftUICorePath, knownFileNames: []) { Self.swiftUICoreNames } + #expect(index.sourceFile(forPrivateDiscriminator: Self.enabledDiscriminator) == PrivateDeclarationSourceFile(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false)) + #expect(index.sourceFile(forPrivateDiscriminator: Self.unrecoverableDiscriminator) == nil) + #expect(index.sourceFile(forPrivateDiscriminator: Self.unrecoverableDiscriminator) == nil) + #expect(index.searchCount == 2) + } + /// The indexer's deinit is what releases the image's caches /// (`SharedCacheRegistry`), and a host keeps the index as long as the /// image: once the names are read, the index lets go of the indexer. diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index f50327791..7c1cc64a0 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -70,6 +70,7 @@ struct CommandRequestMappingTests { "--emit-expanded-field-offsets", "--emit-member-addresses", "--emit-vtable-offsets", "--emit-pwt-addresses", "--emit-type-layout", "--emit-enum-layout", "--emit-export-status", "--emit-header", + "--emit-private-source-files", "--output-path", "out.txt", ]).makeRequest() #expect(request.sections == .only([.protocols, .types])) @@ -81,6 +82,7 @@ struct CommandRequestMappingTests { #expect(request.emitsTypeLayout) #expect(request.emitsEnumLayout) #expect(request.emitsExportStatus) + #expect(request.emitsPrivateDeclarationSourceFiles) #expect(request.emitsHeader) #expect(request.destination == .file(path: "out.txt")) } @@ -115,7 +117,8 @@ struct CommandRequestMappingTests { "--show-c-imported-types", "--parse-opaque-return-type", "--resolve-c-module-names", "--supplementary-apinotes", "/tmp/Extra.apinotes", "--emit-offset-comments", "--sort-members-by-offset", "--exported-only", - "--infer-objc-overrides", "--module-selectors", "--emit-header", + "--infer-objc-overrides", "--module-selectors", "--requirements-on-associated-types", "--emit-header", + "--emit-private-source-files", ]).makeRequest() #expect(request.showsCImportedTypes) #expect(request.parsesOpaqueReturnTypes) @@ -125,7 +128,9 @@ struct CommandRequestMappingTests { #expect(request.printsExportedDeclarationsOnly) #expect(request.infersObjCOverridesFromSelectorNames) #expect(request.usesModuleSelectors) + #expect(request.protocolRequirementPlacement == .associatedTypes) #expect(request.emitsHeader) + #expect(request.emitsPrivateDeclarationSourceFiles) } @Test("interface prints without module selectors unless asked") @@ -133,6 +138,11 @@ struct CommandRequestMappingTests { #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().usesModuleSelectors == false) } + @Test("interface keeps protocol requirements in the protocol's where clause unless asked") + func interfaceRequirementPlacementDefault() throws { + #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().protocolRequirementPlacement == .protocolWhereClause) + } + @Test("--emit-expanded-field-offsets implies the offset comments") func interfaceExpandedFieldOffsets() throws { #expect(try InterfaceCommand.parse(["/tmp/Sample", "--emit-expanded-field-offsets"]).makeRequest().fieldOffsetComments == .expanded) diff --git a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift index de8b1a96a..a9bedbbb0 100644 --- a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift +++ b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift @@ -225,6 +225,20 @@ struct DumpAndInterfaceRequestTests { #expect(output.indexingLabels == [nil]) } + /// The placement reaches the printer: the fixture's class-bound protocol + /// keeps `AnyObject` on itself either way, and its `Self.Item: AnyObject` + /// moves from the protocol's `where` clause onto `Item`. + @Test("A protocol requirement on an associated type prints there when asked") + func interfaceRequirementsOnAssociatedTypes() async throws { + let inWhereClause = RecordingOutput() + try await InterfaceRequest(source: Self.fixture).run(output: inWhereClause, environment: .testing) + let onAssociatedTypes = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, protocolRequirementPlacement: .associatedTypes).run(output: onAssociatedTypes, environment: .testing) + + #expect(inWhereClause.printedProduct.contains("protocol ClassBoundGenericProtocol: AnyObject where Self.Item: AnyObject {\n associatedtype Item\n")) + #expect(onAssociatedTypes.printedProduct.contains("protocol ClassBoundGenericProtocol: AnyObject {\n associatedtype Item: AnyObject\n")) + } + /// With a header, "Preparing…" is announced before the header's symbol /// index build rather than after it, so nothing is heard for the whole /// build otherwise. diff --git a/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift b/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift new file mode 100644 index 000000000..b349e2202 --- /dev/null +++ b/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift @@ -0,0 +1,153 @@ +import Foundation +import Testing +import MachOTestingSupport +import SwiftSectionKit + +/// `dump` and `interface` naming the source file of each private declaration +/// (evolution proposal `private-declaration-source-files`). +/// +/// The files' discriminators were computed outside this code base, with +/// `md5 -s` over the module name followed by the file name: +/// `SymbolTestsCoreCodable.swift` is `b89e435d…`, `SymbolTestsCoreStructs.swift` +/// `930e68b5…`, `SymbolTestsCorePrivateDoppelgangers.swift` `82f1a700…`, +/// `SymbolTestsCorePrivateDoppelgangersSecondFile.swift` `1282f137…` — a name +/// no candidate spells, its plural sitting inside it — and +/// `LocalTypeFixtureUnstrippedFixture.swift` `2ea5a000…`. +@Suite +struct PrivateDeclarationSourceFileRequestTests { + private static let symbolTestsCore = MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: nil) + + /// One dump of the fixture with the option, which the tests reading it + /// share: indexing the image and searching its discriminators is what + /// takes the time. + private static let symbolTestsCoreDump = Task { try await dump(symbolTestsCore) } + + private static func dump(_ source: MachOSource, emitsPrivateDeclarationSourceFiles: Bool = true) async throws -> String { + let output = RecordingOutput() + try await DumpRequest(source: source, emitsPrivateDeclarationSourceFiles: emitsPrivateDeclarationSourceFiles).run(output: output, environment: .testing) + return output.printedProduct + } + + /// One interface of the fixture with the option, shared like the dump. + private static let symbolTestsCoreInterface = Task { try await interface(symbolTestsCore) } + + private static func interface(_ source: MachOSource, emitsPrivateDeclarationSourceFiles: Bool = true) async throws -> String { + let output = RecordingOutput() + try await InterfaceRequest(source: source, emitsPrivateDeclarationSourceFiles: emitsPrivateDeclarationSourceFiles).run(output: output, environment: .testing) + return output.printedProduct + } + + /// The line right above the first one that, its indentation left out, + /// starts with `prefix`; also without its indentation. + private static func line(above prefix: String, in product: String) -> String? { + lines(above: prefix, in: product).first + } + + /// The lines right above every one that, its indentation left out, + /// starts with `prefix`; also without their indentation. + private static func lines(above prefix: String, in product: String) -> [String] { + let lines = product.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + return lines.indices.dropFirst().filter { lines[$0].hasPrefix(prefix) }.map { lines[$0 - 1] } + } + + // MARK: - dump + + @Test("dump names the file above a private type") + func dumpNamesTheFileOfAPrivateType() async throws { + let product = try await Self.symbolTestsCoreDump.value + #expect(Self.line(above: "enum SymbolTestsCore.CodableTests.GenericCodableTest.(CodingKeys in _B89E435DF71E951D297EEE1ADCD6DDD8) {", in: product) == "// CodingKeys is declared in Codable.swift") + } + + /// Two files each declare a `private struct PrivateDoppelganger`; the + /// second file's name is one no candidate spells. + @Test("dump tells same-named private types apart, and says when a file could not be recovered") + func dumpTellsSameNamedPrivateTypesApart() async throws { + let product = try await Self.symbolTestsCoreDump.value + #expect(Self.line(above: "struct SymbolTestsCore.(PrivateDoppelganger in _82F1A700CE81FEBE6E5E3FC5D7722250) {", in: product) == "// PrivateDoppelganger is declared in PrivateDoppelgangers.swift") + #expect(Self.line(above: "struct SymbolTestsCore.(PrivateDoppelganger in _1282F137F8790A6AF4B7E2738A640142) {", in: product) == "// PrivateDoppelganger is declared in a source file whose name could not be recovered (private discriminator _1282F137F8790A6AF4B7E2738A640142)") + } + + @Test("dump names the file above a private protocol and above a conformance of a private type") + func dumpNamesTheFileOfAPrivateProtocolAndConformance() async throws { + let product = try await Self.symbolTestsCoreDump.value + #expect(Self.line(above: "protocol SymbolTestsCore.(PrivateDoppelgangerProtocol in _82F1A700CE81FEBE6E5E3FC5D7722250)", in: product) == "// PrivateDoppelgangerProtocol is declared in PrivateDoppelgangers.swift") + #expect(Self.line(above: "extension SymbolTestsCore.Structs.(PrivateProtocolTest in _930E68B58AC9D850D1A6B7A3A1786E37): Swift.Hashable {", in: product) == "// PrivateProtocolTest is declared in Structs.swift") + } + + /// The fixture's private declarations are all types, so every member + /// that reads a discriminator is a member of one. + @Test("dump does not repeat a private type's file on its members") + func dumpDoesNotRepeatTheFileOnMembersOfAPrivateType() async throws { + let product = try await Self.symbolTestsCoreDump.value + #expect(Self.line(above: "SymbolTestsCore.CodableTests.GenericCodableTest.(CodingKeys in _B89E435DF71E951D297EEE1ADCD6DDD8).stringValue.getter", in: product)?.hasPrefix("//") == false) + } + + @Test("dump only adds comment lines, and adds none without the option") + func dumpOnlyAddsCommentLines() async throws { + let withSourceFiles = try await Self.symbolTestsCoreDump.value + let withoutSourceFiles = try await Self.dump(Self.symbolTestsCore, emitsPrivateDeclarationSourceFiles: false) + let sourceFileLines = withSourceFiles.components(separatedBy: "\n").filter { $0.contains(" is declared in ") } + #expect(!sourceFileLines.isEmpty) + #expect(!withoutSourceFiles.contains(" is declared in ")) + #expect(withSourceFiles.components(separatedBy: "\n").filter { !$0.contains(" is declared in ") } == withoutSourceFiles.components(separatedBy: "\n")) + } + + /// `Holder` is public; its `private func hiddenValues()` says where it is, + /// and so does the type declared in that method, whose name runs through + /// it. + @Test("dump names the file of a public type's private member", ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) + func dumpNamesTheFileOfAPrivateMember() async throws { + let source = MachOSource.file(path: try LocalTypeFixture.libraryURL(.unstripped).path, architecture: nil) + let product = try await Self.dump(source) + #expect(Self.line(above: "LocalTypeFixtureUnstripped.Holder.(hiddenValues in _2EA5A000E301E8E89BE43D5FB26A4D0E)() -> Any", in: product) == "// hiddenValues is declared in Fixture.swift") + let hiddenTypeLine = try #require(product.components(separatedBy: "\n").first { $0.hasPrefix("struct ") && $0.contains("Hidden #1") }) + #expect(Self.line(above: hiddenTypeLine, in: product) == "// hiddenValues is declared in Fixture.swift") + } + + // MARK: - interface + + /// The interface prints no discriminator anywhere, so these two headers + /// read the same but for the comment above them. + @Test("interface tells same-named private types apart, and says when a file could not be recovered") + func interfaceTellsSameNamedPrivateTypesApart() async throws { + let product = try await Self.symbolTestsCoreInterface.value + #expect(Self.lines(above: "struct PrivateDoppelganger {", in: product) == [ + "// PrivateDoppelganger is declared in PrivateDoppelgangers.swift", + "// PrivateDoppelganger is declared in a source file whose name could not be recovered (private discriminator _1282F137F8790A6AF4B7E2738A640142)", + ]) + } + + @Test("interface names the file above a private type nested in a public one, and above an extension of a private type") + func interfaceNamesTheFileOfNestedTypesAndExtensions() async throws { + let product = try await Self.symbolTestsCoreInterface.value + #expect(Self.line(above: "enum PrivateProtocolTest {", in: product) == "// PrivateProtocolTest is declared in Structs.swift") + #expect(Self.line(above: "extension SymbolTestsCore.Structs.PrivateProtocolTest: Swift.Hashable {", in: product) == "// PrivateProtocolTest is declared in Structs.swift") + } + + @Test("interface does not repeat a private type's file on its members") + func interfaceDoesNotRepeatTheFileOnMembersOfAPrivateType() async throws { + let product = try await Self.symbolTestsCoreInterface.value + let membersOfPrivateTypes = product.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + let hashableExtension = try #require(membersOfPrivateTypes.firstIndex(of: "extension SymbolTestsCore.Structs.PrivateProtocolTest: Swift.Hashable {")) + #expect(membersOfPrivateTypes[hashableExtension + 1] == "var hashValue: Swift.Int {") + } + + @Test("interface only adds comment lines, and adds none without the option") + func interfaceOnlyAddsCommentLines() async throws { + let withSourceFiles = try await Self.symbolTestsCoreInterface.value + let withoutSourceFiles = try await Self.interface(Self.symbolTestsCore, emitsPrivateDeclarationSourceFiles: false) + #expect(withSourceFiles.contains(" is declared in ")) + #expect(!withoutSourceFiles.contains(" is declared in ")) + #expect(withSourceFiles.components(separatedBy: "\n").filter { !$0.contains(" is declared in ") } == withoutSourceFiles.components(separatedBy: "\n")) + } + + /// The local type `Hidden` prints inside `Holder`, under the comment + /// naming the method that declares it; the source-file one follows. + @Test("interface names the file of a public type's private member", ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) + func interfaceNamesTheFileOfAPrivateMember() async throws { + let source = MachOSource.file(path: try LocalTypeFixture.libraryURL(.unstripped).path, architecture: nil) + let product = try await Self.interface(source) + #expect(Self.line(above: "func hiddenValues() -> Any", in: product) == "// hiddenValues is declared in Fixture.swift") + #expect(Self.line(above: "struct Hidden {", in: product) == "// hiddenValues is declared in Fixture.swift") + } +} diff --git a/Tests/SwiftThunkAnalysisTests/ThunkRegisterTrackerTests.swift b/Tests/SwiftThunkAnalysisTests/ThunkRegisterTrackerTests.swift new file mode 100644 index 000000000..b3ea428b6 --- /dev/null +++ b/Tests/SwiftThunkAnalysisTests/ThunkRegisterTrackerTests.swift @@ -0,0 +1,34 @@ +import Testing +@testable import SwiftThunkAnalysis + +/// What a register pair access does to its base register in the tracker +/// `ObjCMethodThunkReferences` reads addresses with. +@Suite +struct ThunkRegisterTrackerTests { + private let base = ThunkRegister(number: 8) + private let first = ThunkRegister(number: 0) + private let second = ThunkRegister(number: 1) + + /// `ldp x0, x1, [x8], #16` and `stp x0, x1, [x8, #-16]!` move `x8`, so + /// the address it held is no longer known. + @Test func aWriteBackPairForgetsItsBase() { + var loading = ThunkRegisterTracker() + loading.apply(.materializePageAddress(destination: base, pageBaseAddress: 0x4000)) + loading.apply(.loadPairFromMemory(first: first, second: second, base: base, displacement: 0, adjustsBase: true)) + #expect(loading.address(of: base) == nil) + + var storing = ThunkRegisterTracker() + storing.apply(.materializePageAddress(destination: base, pageBaseAddress: 0x4000)) + storing.apply(.storePairToMemory(first: first, second: second, base: base, displacement: -16, adjustsBase: true)) + #expect(storing.address(of: base) == nil) + } + + /// Without write-back the base keeps its address. + @Test func aPairWithoutWriteBackKeepsItsBase() { + var tracker = ThunkRegisterTracker() + tracker.apply(.materializePageAddress(destination: base, pageBaseAddress: 0x4000)) + tracker.apply(.loadPairFromMemory(first: first, second: second, base: base, displacement: 16, adjustsBase: false)) + tracker.apply(.storePairToMemory(first: first, second: second, base: base, displacement: 16, adjustsBase: false)) + #expect(tracker.address(of: base) == 0x4000) + } +} diff --git a/Tests/SwiftThunkAnalysisTests/ThunkTypeEvaluatorTests.swift b/Tests/SwiftThunkAnalysisTests/ThunkTypeEvaluatorTests.swift index fa64781a4..be8487f31 100644 --- a/Tests/SwiftThunkAnalysisTests/ThunkTypeEvaluatorTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ThunkTypeEvaluatorTests.swift @@ -547,6 +547,30 @@ struct ThunkTypeEvaluatorTests { #expect(stackForgotten == nil) } + /// A pair that writes back moves its base, a general register as much + /// as the stack pointer: after `ldp x2, x3, [x0], #16` or + /// `stp x2, x3, [x0, #-16]!`, `x0` no longer points at the first + /// argument. + @Test func aWriteBackPairMovesItsBase() { + let movedByLoading = evaluated(sequence([ + .loadPairFromMemory(first: register(2), second: register(3), base: register(0), displacement: 0, adjustsBase: true), + .loadFromMemory(destination: register(1), base: register(0), displacement: 0), + .moveImmediate(destination: register(0), value: 0), + .call(target: Self.mutexAccessor), + .returnFromFunction, + ])) + #expect(movedByLoading == nil) + + let movedByStoring = evaluated(sequence([ + .storePairToMemory(first: register(2), second: register(3), base: register(0), displacement: -16, adjustsBase: true), + .loadFromMemory(destination: register(1), base: register(0), displacement: 0), + .moveImmediate(destination: register(0), value: 0), + .call(target: Self.mutexAccessor), + .returnFromFunction, + ])) + #expect(movedByStoring == nil) + } + /// A type argument that could not be named makes the bound type /// unnameable rather than partially named. @Test func anUnnameableTypeArgumentYieldsNoType() {