diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 3b19f1575..b4157c4b8 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,18 +120,19 @@ 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|StandardLibraryLeafLayoutTests|ProtocolRequirementPlacementInterfaceTests|ProtocolRequirementRightHandSideDumpTests|PrivateDeclarationSourceFileCommentsTests|PrivateDeclarationSourceFileRequestTests|ReaderKindCastScanTests|WrappedReaderInterfaceTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|ClassHierarchyBuildStackTests|SpecializationEntryPointExecutorTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|DependencyClosureTests|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|FileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests|StandardLibraryLeafLayoutTests|ProtocolRequirementPlacementInterfaceTests|ProtocolRequirementRightHandSideDumpTests|PrivateDeclarationSourceFileCommentsTests|PrivateDeclarationSourceFileRequestTests|ReaderKindCastScanTests|WrappedReaderInterfaceTests|StructuredCommentTests|CommentConstructionScanTests|CommentStructureContractTests|CommentStructureShapeTests|ConditionalWitnessCommentStructureTests|StaticFieldLayoutProviderReuseTests|StandaloneFileReadingTests|ThunkEnvironmentImageTablesTests|ConsoleEventHandlerLineTests|SymbolIndexDemangledIndexTests)(/|$)' - - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) + - name: Run the concurrent printing suite on a one-thread cooperative pool (${{ matrix.configuration }}) + # The SharedCache suites this step was written for moved to + # MachOKitExtensions with the cache itself and run in that package's + # own tests now; the incident below is why they existed. # The runner has 3 cores, so the Swift Concurrency cooperative pool is # 3 threads wide. On 2026-09-29 three tests each blocked one of those # threads waiting for work that itself needed a thread, and the whole # test process froze. With the pool forced down to one thread, a test # that blocks a pool thread on such work hangs here on every run — # rather than only when three of them happen to line up — and the - # step timeout turns the hang into a failure. The two - # `differentKeysParallelVia…` tests are skipped: they prove overlap, - # which needs two pool threads by design. + # step timeout turns the hang into a failure. # `ConcurrentDefinitionPrintingTests` is here because a definition's # first print blocks every other print of it until its one indexing # pass ends (`DefinitionIndexing`); that pass must never need a pool @@ -145,8 +146,7 @@ jobs: --skip-build \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|ConcurrentDefinitionPrintingTests)/' \ - --skip 'differentKeysParallelVia' + --filter '\.(ConcurrentDefinitionPrintingTests)/' - name: Run the concurrent printing suite on a one-thread pool without the large-stack executor (${{ matrix.configuration }}) # The step above cannot catch an indexing pass that needs a pool diff --git a/AGENTS.md b/AGENTS.md index c7422fc41..d79c36018 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,22 +19,25 @@ swift-section (CLI — a wrapper: flags, error wording, stream routing, exit cod ├── SwiftDeclarationRendering │ └── SwiftThunkAnalysis (Capstone; the kind-9 accessor-thunk reader) └── SwiftDump - └── SwiftInspection - └── MachOSwiftSection (ABI model — depends on MachOBase ONLY) - └── MachOBase (umbrella: reading / resolving / pointers) - └── MachOPointers - └── MachOReading, MachOResolving - └── MachOKitExtensions (external), MachOKit (external) + └── SwiftObjCInterop (the Objective-C side of Swift types — MachOObjCSection enters here) + └── SwiftInspection + └── MachOSwiftSection (ABI model — depends on MachOBase ONLY; re-exports MachOBase and Utilities) + └── MachOBase (external, MachOKitExtensions — umbrella: reading / resolving / pointers) + └── MachOPointers (external, MachOKitExtensions) + └── MachOReading, MachOResolving (external, MachOKitExtensions) + └── MachOKitExtensions (external), MachOKit (external) SwiftInspection and everything above it also import - MachOFoundation (umbrella = MachOBase + MachOSymbols + MachODependencies) - └── MachOSymbols (symbol index + demangling), MachODependencies - └── MachOCaches, MachOBase + SwiftSymbols (the Swift symbol index: SwiftSymbolIndexStore, demangling) + MachOFoundation (external, MachOKitExtensions — umbrella = MachOBase + MachOSymbols + MachODependencies) + └── MachOSymbols (external, MachOKitExtensions — symbol table, the sweep SwiftSymbols routes, the C/C++ store), + MachODependencies (external, MachOKitExtensions) + └── MachOCaches (external, MachOKitExtensions), 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. `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). +`SwiftLayout` is a peer of that spine: it depends on `SwiftObjCInterop` + `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`; `SwiftThunkAnalysis` depends on `SwiftObjCInterop` too. `TypeIndexing`, `SwiftDiffing`, `SwiftPrivateDiscriminators` and `OutputTransformer` hang off the same level as the modules that use them. The cross-reference analysis is three modules in three packages: MachOKitExtensions' `MachOCodeReferences` reads machine code on MachOKit, `MachOAddressResolution` and `ARM64InstructionDecoding` (both MachOKitExtensions too; `SwiftThunkAnalysis` and `SwiftDeclarationRendering` share the address resolution) and knows no language; MachOObjCSection's `ObjCCodeReferences` adds sends, class lists and method lists; this package's `CrossReferenceAnalysis` reaches up to `SwiftInspection` and `MachOSwiftSection` (Swift metadata, `SymbolicDemangler`, mangled names) and is the public facade. -**`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). +**`Sources/` is grouped by layer, not flat**: `Support/`, `Symbols/`, `ABI/`, `Analysis/`, `Declaration/`, `Output/`, `Commands/`, `Executables/`, `TestSupport/`, each holding the targets of that layer (the former `MachO/` group is gone: its modules moved to MachOKitExtensions, and the Swift half of the symbol index lives in `Symbols/SwiftSymbols`). 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). ## What each module does @@ -44,36 +47,42 @@ One or two lines each; the linked document is the authority. - **Demangling** (upstream package) — mangled symbol → `Node` AST → printed Swift, plus the remangler. `Node.Kind` covers ~200 mangling node kinds. - **MachOSwiftSection** — the ABI model: the `__swift5_*` sections, every descriptor shape in them, and Swift's position-independent relative pointers. Self-contained — `MachOBase` only, no symbol index, no demangler; a descriptor exposes an implementation's *offset* and `SwiftInspection` attributes the name ([SelfContainedABILayer.md](Documentations/Internal/SelfContainedABILayer.md)). -- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors, a local or private type's anonymous contexts named by `AnonymousContextNameIndex` and the descriptors' own symbols, and `LocalTypeNaming` telling a local type's name apart, `privateDeclarations` (a `[PrivateDeclaration]`) the private declarations a name reads — not a declaring function's signature, not a position-based `$` address), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). +- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors, a local or private type's anonymous contexts named by `AnonymousContextNameIndex` and the descriptors' own symbols, and `LocalTypeNaming` telling a local type's name apart, `privateDeclarations` (a `[PrivateDeclaration]`) the private declarations a name reads — not a declaring function's signature, not a position-based `$` address), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`. It reads no Objective-C metadata — that is `SwiftObjCInterop`, one layer up. +- **SwiftObjCInterop** — the Objective-C side of Swift types, and where `MachOObjCSection` enters the Swift-facing stack: per-image indexes of `@objc @implementation` classes, of the Swift classes a source renamed for the ObjC runtime (`SwiftClassObjectIndex` — every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss), of the Swift classes with no class object in `__objc_classlist`, and of the `@objc` protocols declared in Swift; the seam through which a host hands over the ObjC class hierarchies it already indexed (`ObjCClassHierarchyProviding`), the library's own reader behind it and the ancestor chain followed into a standalone file's dependency closure; the per-class ObjC member table (`ObjCMemberTable`); the ClangImporter's naming rules, and the records an ObjC class, category or protocol is imported into Swift from (`ObjCImportedContainerIndex`). A Swift class's ObjC-side name is not always `_TtC…`: in a file, a category on another image's Swift class names it by the class metadata symbol it is bound to (`_$s…CN`). Read every such name through `NodeTypeNaming.swiftClassNode(fromRuntimeName:)`, never a `hasPrefix("_Tt")` check — one printed `extension __C._$s…` and found none of its `@objc` witnesses. The linker merges a binary's categories on its own classes into those classes, so `__objc_catlist` lists only categories on other images' classes. An `@objc` protocol declared in Swift has NO protocol descriptor and a class's conformance to an ObjC protocol has NO conformance record — the facts live in `__swift5_fieldmd`, `protocol_t` and `class_ro_t`. [Modules/SwiftObjCInterop.md](Documentations/Internal/Modules/SwiftObjCInterop.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. -- **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). +- **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. Its files split by visibility: a `public` type that stays in the model after indexing goes under `Model/`; code that only runs while the model is built (`package` / `internal`) goes under `Indexing/` — a new `TypeDefinition+…` step goes in `Indexing/TypeDefinition/`, never beside `TypeDefinition.swift`. [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. `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. +- **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, and the folding of what an attached macro generated back into the macro attribute (`@Observable`, unless `expandsMacros`; `printMacroExpansion(of:attachedTo:level:)` prints the expansion on its own, `printMacroExpansionParts(of:attachedTo:)` in the pieces Xcode places, two levels deep as the macros themselves are: `@Observable` writes `@ObservationTracked` on each property, whose nested expansion is the accessor block and the storage — [0093-observable-macro-folding](Documentations/Evolutions/0093-observable-macro-folding.md), [0095-observable-nested-expansion](Documentations/Evolutions/0095-observable-nested-expansion.md)). - **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`. - **SwiftSectionKit** — everything `swift-section` does, as a library: one request type per subcommand (`DumpRequest`, `ABIDiffRequest`, `ObjCDumpRequest`, …), run against a host-supplied `SwiftSectionOutput` that receives the product, the diagnostics and the indexing-event handlers on three separate channels; `MachOSource` is the one Mach-O loader every request shares. A public product. [Modules/SwiftSectionKit.md](Documentations/Internal/Modules/SwiftSectionKit.md), caller guide [SwiftSectionKit.md](Documentations/SwiftSectionKit.md). - **SwiftInterface** — the orchestrator: single-version, two-version diff, and N-version evolution interfaces, all three over one shared structure walk. [Modules/SwiftInterface.md](Documentations/Internal/Modules/SwiftInterface.md). - **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. +- **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. Take a Swift class's table by its Swift qualified name (`table(forSwiftClassQualifiedName:)`): the runtime-name table is an ObjC class's and ties no Swift member through thunk code, so in a stripped image every tie vanishes (`ObjCProtocolWitnesses` hit this). [Modules/SwiftThunkAnalysis.md](Documentations/Internal/Modules/SwiftThunkAnalysis.md). +- **CrossReferenceAnalysis** — what each function of an in-process `MachOImage` — or, made with `init(dyldCache:)` / `init(machOFiles:)`, of every image of a dyld cache file or of standalone files — 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 (through `objc_msgSend`, and the libobjc entry points that stand for sends — `objc_alloc_init` is `alloc` and `init`), 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. Code ld64 rewrote — `adr`, a literal `ldr`, a `nop` / `ldr x16, ` / `br x16` stub, common in third-party apps — reads as the pair it was rewritten from. 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. In file mode an image is a `CodeImage` whose reader is a `MachOFile`; anything a reader's own API reads (MachOObjCSection, MachOSwiftSection) goes through `asMachOImage` / `asMachOFile` or the Swift-section protocol, and every `__LINKEDIT` table through `ImageLinkEdit`, which reads both kinds alike. `FileCrossReferenceMemory` is a value holding its storage `unowned(unsafe)` — a class there made every read through `any CrossReferenceMemory` retain and release, and a whole-cache scan six times slower; the image set keeps the storage alive. A standalone file's chained-fixup rebase is an offset from its `__TEXT`, not an address (`SlotResolver`; an executable's `__TEXT` is at 0x100000000). Every `CodeReference` carries the `route` it took (direct, own stub, stub island, cache-shared stub, pointer slot, built address, literal load, indirect); string literals are recorded only when the analyzer was made to (`recordingStringReferences`) or a query asks for a string key, and an address built by subtraction never names one (Swift keeps a large literal as its address less 32). What an address is — a function's body, a stub and where it leads, a slot and what it holds, a string — is `symbolication(of:)`; the core's `AddressPlace` decides the structure, the facade adds what the language layers know. Strip a pointer read out of the process with the platform's mask (`CrossReferenceMemory.addressMask`, from `InProcessContext.addressMask`), never a constant: an iPhone's addresses are 36 bits and its signature starts at bit 39, where a Mac's 47-bit mask leaves it in place (`AddressMaskScanTests`). **It is three modules in three packages, joined by recognizers** ([0097-offline-cross-references-and-symbolication](Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md) split it, [0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md) moved the lower two): MachOKitExtensions' `MachOCodeReferences` (memory, images, function tables, the scan — was `CrossReferenceCore`), MachOObjCSection's `ObjCCodeReferences` (was `CrossReferenceObjC`) and this package's `CrossReferenceAnalysis` (the Swift layer and the facade). The core spells no `objc_` / `swift_` name (MachOKitExtensions' `SourceScanTests`): a language-specific recognition goes into that language's session (`CodeReferenceRecognitionSession`), never into the core's scan, and what a layer keeps per image hangs on the function table as an attachment. Every read of image memory goes through `CrossReferenceMemory` — only the core's `InProcessCrossReferenceMemory` turns an address into a pointer (scanned in each package; here `MemoryAccessScanTests`). A change to the scan itself is now a change in MachOKitExtensions, released before this package can use it. [Modules/CrossReferenceAnalysis.md](Documentations/Internal/Modules/CrossReferenceAnalysis.md) is still the overall description of the three; the lower two packages document their own boundaries. +- **ARM64InstructionDecoding** (MachOKitExtensions) — 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. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). +- **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. +- **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). - **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. ### The Mach-O infrastructure -- **MachOBase** — umbrella over `MachOKitExtensions` / `MachOReading` / `MachOResolving` / `MachOPointers` / `Utilities`: everything the ABI model is allowed to see. `MachOSwiftSection` re-exports it. -- **MachOFoundation** — `MachOBase` + `MachOSymbols` + `MachODependencies`: the umbrella for everything above the ABI model. -- **MachOReading / MachOResolving** — reading abstractions; address/offset resolution. `MachOResolving` also holds the symbol *value* types (`Symbol`, `Symbols`, `SymbolOrElement`), which carry no lookup behavior — "the symbols at this offset" is a query, not a read. -- **MachOPointers** — relative and indirect pointer types, plus `SymbolOrElementPointer`. -- **MachOSymbols** — the symbol *index*: table parsing, demangling, the per-image node stores, and `LargeStackTaskExecution`; also collects the image's `_symbolic` symbols into a table of their own that no offset or name query sees (`symbolicManglingSymbols(in:)`). [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.md). -- **MachOCaches** — the per-image cache primitive, NOT dyld shared cache support (that is `MachOKitExtensions` and `MachODependencies`): `SharedCache` (get-or-build per image, one build shared by concurrent callers, the build closure supplied at the call site), `SharedCacheKey` (hashes a file on its UUID alone, an image read from a dyld cache on its own and its cache's) and `SharedCacheRegistry` + `SharedCacheEvictionGroup` (which caches an indexer claims for an image and what its last live instance evicts). [Modules/MachOCaches.md](Documentations/Internal/Modules/MachOCaches.md). -- **MachODependencies** — the one dependency-resolution implementation every feature shares (`DependencyClosure`, the in-process and file locators, `DependencySearchPath`, `SharedDependencyClosure` for consumers of one root that resolve lazily). The file locator filters dyld-cache candidates by platform (`DependencyPlatforms`, from `LC_BUILD_VERSION`): the host's macOS cache is every root's default search path and carries Mac Catalyst UIKit / SwiftUI under `/System/iOSSupport`, which an iOS root used to resolve to by bare name. Reach the host's cache through `FullDyldCache.cachedHost` (MachOKitExtensions), never `FullDyldCache.host`: `host` opens and maps all 82 files of a macOS 27 cache on every read, and a locator is built per root — an evolution over 51 archived caches held 51 copies open (`FileDependencyLocatorTests` pins the sharing). [Modules/MachODependencies.md](Documentations/Internal/Modules/MachODependencies.md). -- **MachOKitExtensions** (external sibling, `../MachOKitExtensions`) — MachOKit extensions. Four behaviors this repo's tests still pin live there: legacy `LC_DYLD_INFO` bind resolution (`LegacyDyldInfoBindTests`), ranked dyld-cache image name lookup (`DyldCacheImageSearchTests`), whether an in-process image is in the shared cache — read from its header flag, never from its load address (`MachOImageCacheMembershipTests`) — and an image's identity carrying the dyld cache it was read from (`DyldCacheTwinImageTests`): one build can sit in two caches at different addresses — SwiftUI in macOS 13.5 and 13.6, `LC_UUID` included — so nothing per image may key on `LC_UUID` alone. It cannot move back in-repo — `MachOObjCSection` depends on it, which would make a package-level cycle. +Everything in this section except `SwiftSymbols` is external: since 0.25.0 these modules are products of the MachOKitExtensions package (2.0.0 on), under the same module names. A change to one of them is a MachOKitExtensions change and release first; their implementation notes live in that repository's `Documentations/Internal/`. + +- **MachOBase** (external, MachOKitExtensions) — umbrella over `MachOKitExtensions` / `MachOReading` / `MachOResolving` / `MachOPointers`: everything the ABI model is allowed to see. It no longer re-exports `Utilities`, which stays in this repo; `MachOSwiftSection` re-exports both `MachOBase` and `Utilities` (`Sources/ABI/MachOSwiftSection/Exported.swift`). +- **MachOFoundation** (external, MachOKitExtensions) — `MachOBase` + `MachOSymbols` + `MachODependencies`: the umbrella for everything above the ABI model, which imports `SwiftSymbols` beside it. +- **MachOReading / MachOResolving** (external, MachOKitExtensions) — reading abstractions; address/offset resolution. `MachOResolving` also holds the symbol *value* types (`Symbol`, `Symbols`, `SymbolOrElement`), which carry no lookup behavior — "the symbols at this offset" is a query, not a read. Implementation note: MachOKitExtensions' `Documentations/Internal/ReadingContextAbstraction.md`. +- **MachOPointers** (external, MachOKitExtensions) — relative and indirect pointer types, plus `SymbolOrElementPointer`. +- **MachOSymbols** (external, MachOKitExtensions) — the language-neutral half of the symbol index: the 16-byte-row `SymbolTable`, `SymbolRowBucket`, `SymbolValueOffsetConverter`, the `NlistProtocol` checks, `SymbolLanguage`, the one-pass sweep over symbol table and export trie (`SymbolSweep`, steered by a `SymbolTableRouting`), and a `SymbolIndexStore` that holds C / C++ / Objective-C names only (eviction group `.symbolStore`). The building blocks this repo uses are `@_spi(Internals)`. [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md). +- **SwiftSymbols** (this repo, `Sources/Symbols/SwiftSymbols`) — the Swift symbol index: `SwiftSymbolIndexStore` routes the sweep through `SwiftSymbolTableRouting`, then demangles, classifies and holds the per-image node stores; also `LargeStackTaskExecution`, and the image's `_symbolic` symbols in a table of their own that no offset or name query sees (`symbolicManglingSymbols(in:)`). Eviction group `.swiftSymbolStore`, dependency key `swiftSymbolIndexStore`. [Modules/SwiftSymbols.md](Documentations/Internal/Modules/SwiftSymbols.md). +- **MachOCaches** (external, MachOKitExtensions) — the per-image cache primitive, NOT dyld shared cache support (that is `MachOKitExtensions` and `MachODependencies`): `SharedCache` (get-or-build per image, one build shared by concurrent callers, the build closure supplied at the call site), `SharedCacheKey` (hashes a file on its UUID alone, an image read from a dyld cache on its own and its cache's) and `SharedCacheRegistry` + `SharedCacheEvictionGroup` (which caches an indexer claims for an image and what its last live instance evicts). [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md). +- **MachODependencies** (external, MachOKitExtensions) — the one dependency-resolution implementation every feature shares (`DependencyClosure`, the in-process and file locators, `DependencySearchPath`, `SharedDependencyClosure` for consumers of one root that resolve lazily). The file locator filters dyld-cache candidates by platform (`DependencyPlatforms`, from `LC_BUILD_VERSION`): the host's macOS cache is every root's default search path and carries Mac Catalyst UIKit / SwiftUI under `/System/iOSSupport`, which an iOS root used to resolve to by bare name. Reach the host's cache through `FullDyldCache.cachedHost` (MachOKitExtensions), never `FullDyldCache.host`: `host` opens and maps all 82 files of a macOS 27 cache on every read, and a locator is built per root — an evolution over 51 archived caches held 51 copies open (`FileDependencyLocatorTests` in MachOKitExtensions pins the sharing). [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md). +- **MachOKitExtensions** (external sibling, `../MachOKitExtensions`) — MachOKit extensions, and since its 2.0.0 also the products listed above: `MachOReading`, `MachOResolving`, `MachOPointers`, `MachOCaches`, `MachOSymbols`, `MachODependencies`, `MachOBase` and `MachOFoundation`. Developing against a local MachOKitExtensions branch other than the one `../MachOKitExtensions` checks out takes a directory named exactly `MachOKitExtensions`: SwiftPM resolves a local dependency's path to its real directory and names the package after it. Four behaviors this repo's tests still pin live there: legacy `LC_DYLD_INFO` bind resolution (`LegacyDyldInfoBindTests`), ranked dyld-cache image name lookup (`DyldCacheImageSearchTests`), whether an in-process image is in the shared cache — read from its header flag, never from its load address (`MachOImageCacheMembershipTests`) — and an image's identity carrying the dyld cache it was read from (`DyldCacheTwinImageTests`): one build can sit in two caches at different addresses — SwiftUI in macOS 13.5 and 13.6, `LC_UUID` included — so nothing per image may key on `LC_UUID` alone. It cannot move back in-repo — `MachOObjCSection` depends on it, which would make a package-level cycle. Printing and indexing are peers; neither depends on the other. @@ -102,6 +111,8 @@ swift run swift-section diff # two-sided ABI diff; eith swift run swift-section evolution … # N-version lineage swift run swift-section transformer tokens # also: templates | config — the discovery surface swift run swift-section objc dump # the Objective-C side: dump | interface | snapshot | diff | evolution +swift run swift-section refs --selector --dyld-shared-cache # who references a selector / symbol / class / function / ivar / string (arm64 code) +swift run swift-section symbolicate
--uses-system-dyld-shared-cache # what an unslid address is # Each subcommand's --help is the authority on its flags. The one that is easy not to # know exists: --dependency-search-path (dump / interface / snapshot), which points the @@ -142,8 +153,8 @@ python3 Scripts/test-run-rendering-ab-verification.py - Swift Testing runs test bodies on **512 KB cooperative threads**. A test calling a library entry point gets the large-stack executor from that entry's own `LargeStackTaskExecution.run`; a test driving the demangler or printer *directly* in deep recursion does not — wrap such a body in `LargeStackTaskExecution.run` when the hop cost or the 8 MB pool depth is what is being measured. "The suite passed" is not evidence the executor was used. -- **Never block a cooperative thread with an untimed wait on work that itself needs a pool thread** — a `DispatchQueue.global()` block, a `Task`. The CI runner has 3 cores, so the pool is 3 threads wide: on 2026-09-29 three such tests froze the whole test process there, while a 10-core machine never lines three up. Give the counterpart a `Thread { … }.start()` of its own, or run the blocking side on one. CI re-runs the `SharedCache` suites on a one-thread pool (`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`) to catch this; a new suite that blocks on purpose belongs in that step. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). -- **Look a definition up by its full `name` or by `declaredNameForTesting` (MachOTestingSupport), never by `currentName`.** `currentName` is the display name dump and interface print in a declaration header — the printed name's last dot-separated component — and a function-local type's is the tail of its enclosing function's signature. A test indexing the test binary sees the library's local types: a `Hashable` enum declared in a function returning `Int` read as a second `Int` candidate, and a specialization test passed or failed on `Set` order ([ReviewAdjudications A52](Documentations/Internal/ReviewAdjudications.md)). +- **Never block a cooperative thread with an untimed wait on work that itself needs a pool thread** — a `DispatchQueue.global()` block, a `Task`. The CI runner has 3 cores, so the pool is 3 threads wide: on 2026-09-29 three such tests froze the whole test process there, while a 10-core machine never lines three up. Give the counterpart a `Thread { … }.start()` of its own, or run the blocking side on one. CI re-runs `ConcurrentDefinitionPrintingTests` on a one-thread pool (`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`) to catch this — the `SharedCache` suites that step was written for moved to MachOKitExtensions with the cache; a new suite that blocks on purpose belongs in that step. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). +- **Look a definition up by its full `name` or by `declaredNameForTesting` (SwiftSectionTestingSupport), never by `currentName`.** `currentName` is the display name dump and interface print in a declaration header — the printed name's last dot-separated component — and a function-local type's is the tail of its enclosing function's signature. A test indexing the test binary sees the library's local types: a `Hashable` enum declared in a function returning `Int` read as a second `Int` candidate, and a specialization test passed or failed on `Set` order ([ReviewAdjudications A52](Documentations/Internal/ReviewAdjudications.md)). - **A suite asserting on whole-process state derived from an image must declare `ExclusiveImageAccess(.TheFixture)` — and so must every other suite touching that image.** A one-sided declaration excludes nothing. `.serialized` does not work (it orders within one container only, and `swift test` links everything into one process) and neither does a global actor (these tests are `async`, and `await` yields the actor). Do not assert exclusivity in a doc comment: `grep ExclusiveImageAccess` finds every declared user, grepping a fixture name does not. - **A `swift test` process never enforces pointer authentication, even built and reported as arm64e** — auth fixups are strip-applied there, so signed slots read back bare. Any "verified because the suite passed as arm64e" claim is a placebo; verify by spawning a real arm64e child process, as `Arm64eSignedVWTPointerTests` does. - **`SymbolTestsCore` must not enable the CoroutineAccessors feature** — it would move every implementation offset the ABI baselines pin. A suite needing a `…Twc` compiles its own fixture and asserts structurally. @@ -191,25 +202,27 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **A runtime metatype becomes a node only through `RuntimeTypeNameDemangling.node(forMetatype:)`, never bare `_mangledTypeName` + demangle.** The runtime spells a private type's anonymous context by its descriptor address, which the printers render as nothing or as `(unknown context at $…)` — a specialized header read `struct .WindowPortal<…>`, and a private type argument lost its module and every enclosing type. - **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([0062-local-type-context-names](Documentations/Evolutions/0062-local-type-context-names.md)). - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. -- **Picking the symbol that belongs to a given conformance or protocol out of an address's `Symbols` goes through `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`, never a loop that demangles, searches and prints each symbol.** Identical code folding puts over a thousand names on one SwiftUI witness address and every conformance asks that address again: four such loops (extension and protocol indexing, both protocol dumpers) made the attribution quadratic — half the time of printing a whole image. The query groups an address once and answers from the grouping ([0065-faster-lazy-definition-indexing](Documentations/Evolutions/0065-faster-lazy-definition-indexing.md)). +- **Picking the symbol that belongs to a given conformance or protocol out of an address's `Symbols` goes through `SwiftSymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`, never a loop that demangles, searches and prints each symbol.** Identical code folding puts over a thousand names on one SwiftUI witness address and every conformance asks that address again: four such loops (extension and protocol indexing, both protocol dumpers) made the attribution quadratic — half the time of printing a whole image. The query groups an address once and answers from the grouping ([0065-faster-lazy-definition-indexing](Documentations/Evolutions/0065-faster-lazy-definition-indexing.md)). - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). -- **Never let a demangle or print hop while you hold a lock.** On a 512 KB thread each call hops to a large-stack worker and blocks on it, so every thread waiting on the lock waits behind the hop — without bound once the pool saturates (`SymbolIndexStore.lateDemangledNode`, 2026-08-03). Under a lock, either be on a large stack already — inside a `LargeStackTaskExecution.run` entry point, or past one `StackSafeExecutor.withLargeStack` taken *before* locking (`IndexerConformanceProvider.classHierarchy()`) — or demangle outside the lock and insert-if-absent under it. A synchronous API runs on whatever thread its host calls it from. The sites that rely on their entry point's executor: [ReviewAdjudications A61](Documentations/Internal/ReviewAdjudications.md). -- **A `MachOFile` symbol's `offset` is its raw `n_value` — an address, not the file offset MachOKit's doc comment claims.** Into the index it goes through `SymbolValueOffsetConverter`; as an address it is used as is (`ThunkAddressSpace.address(forSymbolValue:)`). A dylib's `__TEXT` at 0 makes the two look interchangeable; a main executable's at 0x100000000 does not. **A STABS entry (`nlist.isDebuggingEntry`) never supplies an offset or an address**: an `N_GSYM` carries the value 0 under the very name of the symbol it describes. The index lets one only reserve its name's row (`SymbolTableBuilder.reserveRow`), which keeps members in source order — dropping the entries outright reorders 42 SymbolTestsCore snapshots. `ExecutableImageSymbolOffsetTests` pins the offsets. -- **Changing a struct layout in `MachOSymbols` needs `swift package clean`.** Incremental builds have been observed linking stale downstream objects (runtime SIGSEGV in `outlined destroy`). Moving a public type across modules or flipping a dependency edge does the same. Clean first, diagnose second. +- **Never let a demangle or print hop while you hold a lock.** On a 512 KB thread each call hops to a large-stack worker and blocks on it, so every thread waiting on the lock waits behind the hop — without bound once the pool saturates (`SwiftSymbolIndexStore.lateDemangledNode`, 2026-08-03). Under a lock, either be on a large stack already — inside a `LargeStackTaskExecution.run` entry point, or past one `StackSafeExecutor.withLargeStack` taken *before* locking (`IndexerConformanceProvider.classHierarchy()`) — or demangle outside the lock and insert-if-absent under it. A synchronous API runs on whatever thread its host calls it from. The sites that rely on their entry point's executor: [ReviewAdjudications A61](Documentations/Internal/ReviewAdjudications.md). +- **A `MachOFile` symbol's `offset` is its raw `n_value` — an address, not the file offset MachOKit's doc comment claims.** Into the index it goes through `SymbolValueOffsetConverter` (MachOKitExtensions' `MachOSymbols`); as an address it is used as is (`ImageAddressSpace.address(forSymbolValue:)`, MachOKitExtensions' `MachOAddressResolution`). A dylib's `__TEXT` at 0 makes the two look interchangeable; a main executable's at 0x100000000 does not. **A STABS entry (`nlist.isDebuggingEntry`) never supplies an offset or an address**: an `N_GSYM` carries the value 0 under the very name of the symbol it describes. MachOKitExtensions' `SymbolSweep` lets one only reserve its name's row, which keeps members in source order — dropping the entries outright reorders 42 SymbolTestsCore snapshots. `ExecutableImageSymbolOffsetTests` pins the offsets. +- **The Swift symbol index is `SwiftSymbolIndexStore`; never write a bare `SymbolIndexStore` in this repo.** That name is MachOKitExtensions' C / C++ / Objective-C store, whose queries share the Swift store's method names — a wrong name compiles and finds no Swift symbol. Likewise the eviction group is `.swiftSymbolStore` (`.symbolStore` is the C/C++ store's) and the dependency key `\.swiftSymbolIndexStore`. `SymbolIndexStoreNamingScanTests` fails on a bare one. +- **Changing a struct layout in `SwiftSymbols` (or in MachOKitExtensions' `MachOSymbols`) needs `swift package clean`.** Incremental builds have been observed linking stale downstream objects (runtime SIGSEGV in `outlined destroy`). Moving a public type across modules or flipping a dependency edge does the same. Clean first, diagnose second. -Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.md), [NodeStoreMigrationPlan.md](Documentations/Internal/NodeStoreMigrationPlan.md), [SharedNodeStoreMigration.md](Documentations/Internal/SharedNodeStoreMigration.md). +Detail: [Modules/SwiftSymbols.md](Documentations/Internal/Modules/SwiftSymbols.md), MachOKitExtensions' [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md), [NodeStoreMigrationPlan.md](Documentations/Internal/NodeStoreMigrationPlan.md), [SharedNodeStoreMigration.md](Documentations/Internal/SharedNodeStoreMigration.md). -- **`@LocatableLayoutWrapping` generates the three storage-level requirements** (`var layout`, `let offset`, `init(layout:offset:)`). Write only the nested `Layout` struct — and **keep the conformance on the declaration**, the macro deliberately does not add it. A member the host declares itself is left alone, with a warning. +- **`@ResolvableLocatableLayoutWrapper` generates the three storage-level requirements** (`var layout`, `let offset`, `init(layout:offset:)`) **and the `ResolvableLocatableLayoutWrapper` conformance**. Write only the nested `Layout` struct. A wrapper that is one of the refining protocols (`MetadataProtocol`, `ContextDescriptorProtocol`, `TopLevelDescriptor`, …) still names it on the declaration — it carries the `Layout` constraint — and the macro then adds no conformance. **The file must `import MachOKit`**: the expansion names `LayoutWrapper`, which `MachOBase` does not re-export, and fails with "cannot find type 'LayoutWrapper' in scope". A member the host declares itself is left alone, with a warning. - **`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.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. +- **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 were deprecated forwarders from 0.22.0 until 0.25.0 deleted them ([0057-reading-context-migration](Documentations/Evolutions/0057-reading-context-migration.md)): never bring one back — a caller passes `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 constrained overload calls (`RelativeDirectPointerProtocol`); a caller inside that extension that names the method instead reaches the unconstrained witness and skips the guard. +- **A flag word's accessors are `@BitField` declarations (FrameworkToolbox), never a hand-written mask and shift** — three hand-written ones read the wrong bits and stopped the process on ordinary input ([0085-abi-flag-words-bit-field](Documentations/Evolutions/0085-abi-flag-words-bit-field.md)). A kind that can grow with the compiler is optional, so an unknown value reads as `nil`; a single bit with both values named, or a kind with a fallback case, takes `default:`, written in full (`default: ContextDescriptorKind.unknown`). An optional `SpecialProtocolKind` makes a bare `.none` mean `nil` — write `.some(.none)`. A set of single bits is an `OptionSet`; `@FlagSet` builds `ClassFlags` and `InvertibleProtocolSet`, and the members it generates are invisible to the coverage scanner, so they are not registered. After changing a public property's type, clean before building: an incremental build kept an object that still called the old getter, and the link failed. @@ -220,14 +233,15 @@ Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.m - + -- **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. +- **What belongs to the file a reader reads — a mapping, a handle — hangs off MachOKit's `fileHandleIdentity`, never off the `MachOFile` or `DyldCache` instance.** MachOKit assembles a new instance for every image and sub-cache, so per-instance state is per image: RuntimeViewer's offline service mapped one cache file 343 times and ran out of descriptors. Bytes are read through the mapping MachOKit made when it opened the file (`fileBytes`, SPI Support), which every instance from that opening shares — never through a mapping of the reading layer's own, nor a `Data` per read. +- **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` (SwiftInspection) / `objcImplementationClassReader` (SwiftObjCInterop) instead of an `as? MachOFile` / `as? MachOImage` split. - **A build closure must not query the entry it is building.** On the builder's own thread that traps with the key; after a thread hop (`withLargeStack`) it hangs, undetected. -- **Eviction belongs to the registry**: the indexer claims what its `prepare()` found absent and its last live instance evicts it plus every group that `follows` it. `MachOCaches` declares no group: a module declares its own in a `SharedCacheEvictionGroup+.swift` extension, and a cache whose entries point into another group's storage says `follows:` at creation. The three `removeCache` helpers are the explicit form and forward to `SharedCacheRegistry.evict(groups:for:)`. +- **Eviction belongs to the registry**: the indexer claims what its `prepare()` found absent and its last live instance evicts it plus every group that `follows` it. `MachOCaches` (MachOKitExtensions) declares no group: a module declares its own in a `SharedCacheEvictionGroup+.swift` extension, and a cache whose entries point into another group's storage says `follows:` at creation. The three `removeCache` helpers are the explicit form and forward to `SharedCacheRegistry.evict(groups:for:)`. - **The library never reacts to memory pressure.** The per-instance monitors that used to `removeAll()` bypassed the ownership rules and freed nothing (live `NodeReference`s pin the storage). A host sheds state by calling `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()`. -[Modules/MachOCaches.md](Documentations/Internal/Modules/MachOCaches.md). +MachOKitExtensions' [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md). @@ -239,7 +253,7 @@ Every offset in `MachOSwiftSection` is `unslidVirtualAddress - sharedRegionStart - `MachOFile.fileOffset(of:)` (file accounting — **not** the inverse of what `readElements(offset:)` takes) - `FullDyldCache.address(of:)` (a third) -Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` routes through `fileOffset(of:)` and so fails `offsetOutOfBounds` on a cache image — a pre-existing gap in reading *absolute* pointers offline, which the ABI model never hits because its own reads are relative. And `ExportedSymbol.offset` is an offset from the **mach header**, which MachOKit hands over unchanged for a cache image; the one correct conversion is `ThunkAddressSpace.address(forExportedSymbolOffset:)`. +Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` routes through `fileOffset(of:)` and so fails `offsetOutOfBounds` on a cache image — a pre-existing gap in reading *absolute* pointers offline, which the ABI model never hits because its own reads are relative. And `ExportedSymbol.offset` is an offset from the **mach header**, which MachOKit hands over unchanged for a cache image; the one correct conversion is `ImageAddressSpace.address(forExportedSymbolOffset:)` (MachOKitExtensions' `MachOAddressResolution`). @@ -261,7 +275,7 @@ Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` r - **Logging is the floor, not the reporting path.** Anything a host should see is dispatched as a `SwiftIndexEvents` payload and the host decides where it lands; `Dispatcher.dispatch` falls back to `#log` when no handler is attached. What counts as a failure is `Payload.unhandledFailureDescription`, an exhaustive `switch` **on purpose** — a new failure case must opt in explicitly, or it silently escapes that floor. - **Never use `FileHandle.standardError/Output.write(_:)`** — that overload raises an uncatchable ObjC exception on a closed or broken stream and aborts the host. Use `fputs` / `fwrite`. Pinned by a source scan (`PrintFailureEventTests.libraryModulesWriteToNoProcessStream`) carrying a shrink-only allowlist. - The CLI's console handler writes to **stderr**: stdout carries the generated Swift / JSON, and writing there corrupts the product output (issue #102). -- **`MachODependencies` sits *below* the event layer**: its failures are data (`searchPathLoadFailures`, `unresolvedLoadNames`), returned to the caller and never logged there. +- **`MachODependencies` (MachOKitExtensions) sits *below* the event layer**: its failures are data (`searchPathLoadFailures`, `unresolvedLoadNames`), returned to the caller and never logged there. [EventBasedDegradationReporting.md](Documentations/Internal/EventBasedDegradationReporting.md). @@ -273,8 +287,9 @@ Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` r - **The printers' error contract inverts by level.** Inside a definition, a failing field fails the whole type. At the top level — `printRoot` and the nested children loops alike — printing catches **per definition**: one type/protocol/extension/nested child that throws drops only itself, never its block. A block-level catch once blanked every type of a legacy binary's interface. - **A name's `kind` takes no part in its equality.** The node identifies the type; `kind` is derived differently per producer and the two disagree for C-imported types. - **A nested definition's print may depend on its `level` only through indentation.** A host with `marksNestedDefinitions` takes each nested type or protocol out of its parent's print instead of printing it again, removing one indentation level per nesting depth; a hard-coded level, or a line a renderer does not indent, breaks that silently for the host. `NestedDefinitionRegionContractTests` reports it. -- **Never write a module-qualified name into output as text** (`"Swift.Copyable"`, `module + "." + name`). Print it as a node through the type printer or the caller's `DemangleResolver`, so SE-0491 module selectors (`usesModuleSelectors` / `DemangleOptions.useModuleSelectors`, `Swift::Copyable`) reach it; `ModuleSelectorInterfaceTests.noNameKeepsItsDottedQualification` sweeps a fixture's interface for leftovers. A node handed to the interface printer must outlive the print — it memoizes fragments by node identity. Lookup keys are the exception: they stay dotted, printed with fixed presets that never carry the option. [0064-module-selectors](Documentations/Evolutions/0064-module-selectors.md). +- **Never write a module-qualified name into output as text** (`"Swift.Copyable"`, `module + "." + name`). Print it as a node through the type printer or the caller's `DemangleResolver`, so SE-0491 module selectors (`usesModuleSelectors` / `DemangleOptions.useModuleSelectors`, `Swift::Copyable`) and the `any` keyword on existentials (`usesExistentialAny`, on by default / `DemangleOptions.useExistentialAny`) reach it — a fixed preset (`.default`, `.interface`) carries neither, so a display print with one spells `P` where the rest of the output spells `any P`; hand another printer the caller's spelling as `DemangleOptions.interfaceSpellingOptions`. `ModuleSelectorInterfaceTests.noNameKeepsItsDottedQualification` sweeps a fixture's interface for leftovers. A node handed to the interface printer must outlive the print — it memoizes fragments by node identity, which is also why an existential under a keyword written already (`any P.Type`, `any P`) prints bare through `printExistentialConstraint`, never through `printName`: the same node prints with `any` everywhere else. Lookup keys are the exception: they stay dotted and bare, printed with fixed presets that never carry the options. [0064-module-selectors](Documentations/Evolutions/0064-module-selectors.md), [0092-existential-any](Documentations/Evolutions/0092-existential-any.md). - The `Name` types are deliberately **not `Codable`**. A mangled symbol already is the tree's serialized form — persist `mangleAsString(node)` and read it back with `demangleAsNode(_:)` rather than reintroducing a node encoding. +- **A comment the interface prints is built by a `StructuredComment` factory** (SwiftDeclarationRendering), which spells its text once as segments that each play a role — marker, label, value — and prints the same one `.comment` atom `Comment` did. A bare `Comment(` / `InlineComment(` / `.comment` atom in SwiftDeclarationRendering, SwiftPrinting, SwiftInterface or SwiftDeclaration fails `CommentConstructionScanTests`: it prints fine and carries no structure for a host that marks comments ([0084-comment-structure](Documentations/Evolutions/0084-comment-structure.md)). Print the factory's value through `comment(_:as:)` — the printer's or the render configuration's — with its `AnnotationRegion.Kind`, which is where `marksCommentStructure` reaches it; appended directly, it prints unmarked, and `CommentStructureContractTests` reports a comment in no region. - [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). @@ -285,7 +300,9 @@ Library entry points run their body on the demangler's large-stack task executor **Never start an unstructured `Task {}` inside a wrapped entry point**: SE-0417 means it does not inherit the preference (child tasks and default actors do). Nesting is a no-op, and below macOS 15 / iOS 18 the body runs unchanged. [LargeStackTaskExecutorAdoption.md](Documentations/Internal/LargeStackTaskExecutorAdoption.md). -Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [0066-concurrent-definition-printing](Documentations/Evolutions/0066-concurrent-definition-printing.md). +**Work a library call waits for synchronously goes to a private serial `DispatchQueue`, never `DispatchQueue.global()` or a private concurrent queue.** Those two need a non-overcommit thread, and while every cooperative thread of the class is blocked — a synchronous library entry on each, waiting on its large-stack hop — the blocked threads still count against the class's width: the block never starts and the waiter waits for ever. `DemanglingWave` hung a 10-core machine's whole test run this way. A serial queue targets an overcommit root and always gets a thread, and `concurrentPerform` started inside it still spreads over every core (`SymbolIndexDemangledIndexTests.firstReadersOnEveryCooperativeThreadAllFinish`). + +Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not cleared for it: its reads no longer share a `FileHandle` position (they load from MachOKit's mapping, `fileBytes`) and MachOKit 0.55.102 made a dyld cache's remembered tables safe to fill from several threads, but nobody has run parallel printing on it against the checks above. `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [0066-concurrent-definition-printing](Documentations/Evolutions/0066-concurrent-definition-printing.md). @@ -319,4 +336,4 @@ Keeping this file's module list and `Documentations/README.md`'s index in sync w ## Work in progress -**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. **A depth counts only the contexts that declare parameters — take it from `GenericParameterDepthLayout`, never from the parent chain or `TargetGenericContext.depth`**: a generic type that declares nothing (`Outer.Middle`) opens no depth, and one extension context can span several (`extension Outer.SecondMiddle where …`). Eight readers once counted ancestors or list positions instead: five named `B` in `Outer.Middle.Inner` as `A2` while every field and requirement read `A1`, and three in the opaque-type and thunk paths substituted an opaque type's arguments from the wrong level, trapped on an extension spanning two depths, or left a type declared in a generic extension unnamed. The offline path (`specialize` on a `MachOFile`) is complete too; the specialization's `typeName` hangs each argument on its own level (`Outer.Inner`) on both paths. +**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. **A depth counts only the contexts that declare parameters — take it from `GenericParameterDepthLayout`, never from the parent chain or `TargetGenericContext.depth`**: a generic type that declares nothing (`Outer.Middle`) opens no depth, and one extension context can span several (`extension Outer.SecondMiddle where …`). Eight readers once counted ancestors or list positions instead: five named `B` in `Outer.Middle.Inner` as `A2` while every field and requirement read `A1`, and three in the opaque-type and thunk paths substituted an opaque type's arguments from the wrong level, trapped on an extension spanning two depths, or left a type declared in a generic extension unnamed. An opaque type's comes from `make(forOpaqueType:genericContext:in:)`: its parents also include the anonymous context of the function — and, in a debug build, the property — declaring it, which adds parameters like any other context; counting only the nearest type or extension trapped RuntimeViewer's debug build. The offline path (`specialize` on a `MachOFile`) is complete too; the specialization's `typeName` hangs each argument on its own level (`Outer.Inner`) on both paths. diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 17d8f70c4..f6bf33167 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.24.0", + "version": "0.25.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 b1364c508..00ed48e68 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.24.0", + "version": "0.25.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 964fcf082..f0b61a565 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -4,11 +4,13 @@ description: >- Recovering Swift and Objective-C declarations and ABI facts from a Mach-O binary or a dyld shared cache with the `swift-section` CLI — dumping types / protocols / conformances, generating a .swiftinterface offline, Objective-C headers with IMP addresses, diffing the API - of two builds, tracking it across OS versions, and the static field-offset / type-layout / - enum-layout comments. Read before running swift-section, and whenever a task needs type - information out of a binary without loading it into a process. Triggers on swift-section, - swift-section objc, objc-section, MachOSwiftSection, __swift5_types, swiftinterface, - ABI diff, ABI baseline. + of two builds, tracking it across OS versions, the static field-offset / type-layout / + enum-layout comments, and — from arm64 code — the callers of a selector, symbol, class or + function across a whole dyld shared cache and what an address is. Read before running + swift-section, and whenever a task needs type information or cross references out of a binary + without loading it into a process. Triggers on swift-section, swift-section objc, + objc-section, swift-section refs, swift-section symbolicate, MachOSwiftSection, + __swift5_types, swiftinterface, ABI diff, ABI baseline, xrefs, callers. --- # swift-section @@ -44,8 +46,12 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, `--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`, 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 +/ `dump --enable-module-selectors`, from 0.24.0 +`interface --requirements-on-associated-types` and `--emit-private-source-files`, and from +0.25.0 `objc evolution --interface` / `--emit-available` / `--platform`, +`objc interface --swift`, `interface --no-existential-any` / `dump --disable-existential-any`, +`interface --expand-macros` and the `refs` and `symbolicate` subcommands. +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". @@ -60,6 +66,8 @@ missing, say so rather than silently producing a weaker answer — the alternati | How did this API evolve across N OS versions? | `evolution` | | Reformat the memory-layout comments the two above emit | `transformer` | | Objective-C headers, IMP addresses, or an Objective-C API diff (0.20.0+, formerly the separate `objc-section` executable) | `objc` — read `references/objc.md` first | +| Who calls this selector / symbol / function, who references this class, ivar or string — across a whole dyld shared cache or an app's files | `refs` — read `references/cross-references.md` first | +| What is this address: which function and how far into it, a stub and where it leads, a slot and what it holds | `symbolicate` — same reference | `dump` is the default subcommand: `swift-section ` is `swift-section dump `. @@ -162,13 +170,38 @@ SE-0491 module selectors — `Swift::Int` instead of `Swift.Int`, the spelling a too: `interface --module-selectors`, `dump --enable-module-selectors` (one of the demangler switches below). +Existential types carry the `any` keyword by default in both outputs (from 0.25.0), as the +compiler writes a `.swiftinterface`: `any P`, `(any P)?`, `any P.Type` for the existential +metatype, `(any P).Type` for the metatype of the existential (older builds print `P.Protocol`), +and `any Any.Type` — a lone `Any` or `AnyObject` stays bare. Older builds print every +existential bare, so `Swift.Collection` in their output is `any Collection`. The off switches: +`interface --no-existential-any`, `dump --disable-existential-any`. A stored property of a +constrained existential type (`any Boxed`) printed in older builds as its arguments alone — +`var boxed: Swift.Int` in `interface`, `symbolic existential type … ` in `dump` — +so read such a line from an older build as a constrained existential of unknown protocol, not +as the type it names. + +A class the `@Observable` macro expanded prints the way its source reads (from 0.25.0): +`@Observation.Observable` above the class, each tracked property as the stored `var x: T` it +was declared as, a stored `var` the macro left alone under `@Observation.ObservationIgnored` +on a line of its own (a property wrapper's attribute gets a line of its own too), and no registrar, no `access(keyPath:)` / `withMutation(keyPath:_:)` / `shouldNotifyObservers`, no +`extension X: Observation.Observable {}`. In the binary each tracked `x` is a computed property +over private storage `_x`; `interface --expand-macros` prints that, as older builds always did. +A tracked property whose accessors are stripped or dead-stripped (an internal class in an app or +OS framework) carries a note naming the storage it was synthesized from; when nothing in the +image names `y` or gives `_y` an initial value or accessors of its own, an +`@ObservationIgnored var _y` reads as a tracked `y` behind such a note. SwiftData +`@Model` classes are not folded. `dump` keeps every generated member and adds +`@Observation.Observable` to the class's header line. + Only `dump` has: `--sections`, `--preferred-binary-order`, and the demangler option group (`--demangle-options default|simplified|interface` plus ~22 `--enable-…` / `--disable-…` 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`, `--requirements-on-associated-types`. +`--supplementary-apinotes`, `--infer-objc-overrides`, `--requirements-on-associated-types`, +`--expand-macros`. `--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`, @@ -263,9 +296,23 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 - `evolution --interface --emit-available` adds a genuine `@available(, introduced: …, obsoleted: …)` line above each declaration whose whole lifecycle one attribute can express. **No attribute is not "no lifecycle"**: a declaration that disappeared and came back, one that was only `modified`, or any involved label that is not a numeric version (the file-name fallback!) gets none — pass numeric `--labels` and read the `// [●○●]` comment, which is always there. The versions are axis points, not exact release versions. The platform is inferred from every input's `LC_BUILD_VERSION` (a simulator counts as its device); an input whose platform `@available` has no name for (DriverKit), or inputs of different platforms, fail with exit code 64 — name it with `--platform` (only valid with `--emit-available`, which is only valid with `--interface`). - `--fail-on-breaking` makes a breaking change a nonzero exit — that, not the report text, is the CI signal. -- Compare binaries in **similar strip states**. A symbol-rich build against a stripped one - reports the same protocol requirement as a member swap, because a stripped protocol diffs by - witness-table slot rather than by symbol. +- **A version whose image carries no local Swift symbols cannot show non-exported members** + (SwiftUI in the macOS 13.0–14.8 caches is the case to know). It is detected per input, and + such a member's absence there is never read as a removal: in `evolution` its bitmap position + reads `◍` (not observable, but present in the versions on both sides — inferred) or `◌` (not + observable, nothing claimed), a change across such versions is phrased `removed between 12.7 + and 15.0` / `added between …` (first observed at the later version, which is where it counts + for the verdict), the interface legend names those versions, and a lifecycle whose `◌` span + reaches an axis end or sits between different observations gets no `@available` (between two + absences it keeps it). A member unseen only because its container is unseen carries no + annotation of its own (read the container's); neither does one unseen only between two + absences, which says nothing. `diff` lists what one side cannot show in a + `Not observable on the old/new side` section (`unobservableDeclarations` in `--json`), never + as removed or added and never breaking. Types, conformances, stored fields, enum cases and exported members stay + observable, so their absence is still a real removal. `diff --interface` does not apply this. +- Even so, compare binaries in **similar strip states** where you can. A symbol-rich build + against a stripped one reports the same protocol requirement as a member swap, because a + stripped protocol diffs by witness-table slot rather than by symbol. - **A snapshot does not cross format versions.** The JSON carries a `formatVersion`; any other version is rejected with a typed error, and the fix is to regenerate the baseline with the current tool. Format 6 (0.21.0 and later) rejects every format-5 baseline: in an image stripped @@ -273,7 +320,20 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 descriptor names (see §9), which an old baseline would report as added wholesale. Format 7 (0.23.0 and later) rejects every format-6 baseline: a type declared in a function or closure body is recorded under its own full name now (see §9), and an old baseline would report each one as removed — - a breaking change — and added again. + a breaking change — and added again. Format 13 (0.25.0 and later) rejects every earlier baseline, + for five reasons: in an optimized build the newer tool also records the members whose only symbol + is their `@objc` thunk, their initializing entry point or that entry point's function signature + specialization (see §9), which an old baseline would report as added; a snapshot now records whether its image keeps local Swift symbols and whether + each member is exported, which the not-observable rule above needs; an image's extensions now + hold the members of its own module's types that no definition in the image gathers — SwiftUI's + members of the types SwiftUICore defines, an internal namespace whose type descriptor was stripped — + which earlier tools left out of `interface` and the snapshot, and an old baseline would report as + added (`dump` does not show them); a stored field whose type is a constrained existential + (`any Boxed`) is recorded as that existential, where it used to read as its arguments alone, + and an old baseline would report each such field as changed; and a property's SE-0400 init + accessor is one of its accessors now, so an old baseline would report every property that has + one as changed. Formats 8 through 12 only ever existed on the development branch, between those + changes. ## 8. `--resolve-c-module-names` (interface, macOS only) @@ -312,13 +372,49 @@ 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 ``. +- **In an optimized app binary, a member may print at the address of its `@objc` thunk, and an + `init` at its initializing entry point or at that entry point's specialization.** Whole-module + optimization can inline an internal `@objc` member's body into its Objective-C thunk (`$s…To`) + and delete the Swift entry point, and inline a class initializer's allocating entry point into + its callers; Swift 6.4 also replaces the initializing entry point by its function signature + specialization (`…fcTf…`), which takes its arguments differently. The member is then rebuilt + from the code that survived: `--emit-member-addresses` points at the thunk, which uses the + Objective-C calling convention (`self` in `x0`, `_cmd` in `x1`), at the initializing entry + point, or at its specialization. `dump` lists the members only a thunk names under + `/* [ObjC Thunk] … */` sections. +- **A generic class, or one registered through `__objc_stublist` (its superclass is in another module, or is generic), has no class object, so its Objective-C method list comes from its Swift metadata.** `override` is printed where its superclass chain can be followed. When the superclass is a Swift class of another binary (SwiftUI's `NSHostingView<…>`), the chain stops there and the class's members print with `@objc` but without `override`. - **`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. +- **`@storageRestrictions(initializes: _x) init` in an accessor block is inferred, not read** + (from 0.25.0). No binary records the attribute (SE-0400 init accessors): it is printed when + the type has a stored property `_x` of the property's own type — what `@Observable` and most + hand-written storage do — and it never lists `accesses:`. Otherwise a bare `init` prints under + `// init accessor: the binary does not record which stored properties it initializes`. **No + `init` line does not mean no init accessor**: the compiler gives one internal access unless it + is `@usableFromInline`, so an optimized, dead-stripped image (most OS frameworks, shipped + apps) keeps only the exported ones. `dump` lists each one it finds as `X.x.init : T`, with the + inference on the line above. - **Enum-layout patterns marked "not resolved offline"** mean only the extra-inhabitant *index* is derivable statically; the concrete bytes need the live metadata. +- **An `@objc protocol` whose requirements carry `@objc(selector)`, under the comment + "Swift names follow the ClangImporter's rules for these selectors"**, is declared in Swift, + but the binary keeps no Swift name for any requirement of an `@objc` protocol. When no class + of the binary implements one, its Swift name is derived from the selector the way the + importer would, so it can differ from the source (`removeObject(at:)` for `remove(at:)`); + the selector, which is what the protocol means to the runtime, is exact. A requirement under + `// Taken from the conformer X.` is X's own member and exact. `__C.NSObject` after such a + protocol's colon is the `NSObject` *protocol* (Swift's `NSObjectProtocol`), spelled the way + the compiler mangles it. `dump --sections protocols` on an image with no Swift protocols + reports `__swift5_protos not found` and still lists these. +- **Objective-C protocols after a class's superclass** (`class X: __C.NSObject, M.P, + __C.NSCopying`) come from the class's Objective-C metadata: a conformance to an `@objc` + protocol has no Swift conformance record. An extension in the class's own module is folded + into the class there, so its conformances show in the header too, while + `extension __C.NSView: M.P {}` is an extension of another module's class (its category). + Neither shows in `diff`, `evolution` or a snapshot. - **`@objc(Name)` above a class** is the name the Objective-C runtime knows it by, and matters even when it equals the Swift name (`@objc(NSScrollPocket) class NSScrollPocket`): without it the runtime name would be the `_TtC…` mangling. That is also the class name `objc` headers @@ -345,4 +441,5 @@ The repository is [MachOSwiftSection](https://github.com/MxIris-Reverse-Engineer | How to read an enum-layout comment | `Documentations/SwiftEnumLayout.md` (`_zh` companion) | | Writing supplementary `.apinotes` for a private framework | `Documentations/SupplementaryTypeMappings.md` | | The `objc` subcommands in full, including the snapshot / diff / evolution workflow | `Documentations/ObjCCommandLine.md` (`_zh` companion); the traps are in `references/objc.md` beside this file | +| `refs` and `symbolicate`: the line format, the routes, the traps | `references/cross-references.md` beside this file | | What each flag does, authoritatively | `swift-section --help` (and `swift-section objc --help`) — generated from the code, so it cannot drift | diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md new file mode 100644 index 000000000..9f84b70bc --- /dev/null +++ b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md @@ -0,0 +1,75 @@ +# `refs` and `symbolicate` + +Two subcommands that read arm64 machine code rather than metadata: who references a selector, +a symbol, a class, a function, an instance variable or a string — and what an address is. They +work on a whole dyld shared cache (an archived one, another device's, or the running system's, +read from its files) or on a set of standalone Mach-O files read together, without IDA and +without loading anything into a process. + +```bash +# Every send of a selector across a whole cache +swift-section refs --selector makeKeyAndOrderFront: \ + --dyld-shared-cache /Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e + +# References to a class, only in the images named +swift-section refs --class NSWindow --uses-system-dyld-shared-cache --in-image AppKit --json + +# What one function calls, in instruction order +swift-section refs --function 0x1880a1000 --callees --uses-system-dyld-shared-cache + +# An app's executable and its frameworks, read together; a fat file needs -a +swift-section refs --symbol _objc_msgSend Foo.app/Contents/MacOS/Foo \ + Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e + +# What these addresses are +swift-section symbolicate 0x19012345 0x1e1226590 --uses-system-dyld-shared-cache +``` + +## What a `refs` line says + +``` + + +``` + +- **site** — the referencing instruction's address. **function** — the function it lies in, + by its symbol, or, where the symbol table names none, by the export trie, the Objective-C + method lists or the Swift metadata (`-[NSWindow …]`, `…Ma`); its address when nothing names it. +- **kind** — `call`, `tailCall` (a branch out that does not return), or `reference` (an + address taken: a class object, a type's metadata, a string, an ivar offset). +- **route** — how the code got there: `direct`, `imageStub`, `stubIsland`, `cacheSharedStub` + (macOS / iOS 27's selector and GOT stubs outside every image), `pointerSlot`, + `addressMaterialization`, `literalLoad`, `indirect`. A reference that went through a stub is + as real as a direct one; the route is what to check before trusting it. +- **target** — `send sel:` (`to self`, `to NSWindow` when the receiver is known), a function + and its image, a class, `ivar Class._name`, a string, `type …`, `indirect` (`at offset …` when the callee was loaded from memory). + +A one-line summary goes to stderr: how many references, in how many images, and how many images +were scanned. + +## Things that will bite + +- **Addresses are unslid**, in and out — the ones IDA, `ipsw` and `dyld_info` show. A cache's + images share one address space; **standalone files each have their own**, and two dylibs + linked at 0 overlap. `--function` names the file with `--function-image` when the address is + ambiguous (the command says so), and `symbolicate` takes `--in-image` for the same reason. +- **A fat file needs `-a`**, as everywhere in this tool. Only arm64 / arm64e slices can be + analyzed; anything else fails with "holds no arm64 code". +- **`--in-image` narrows where to look, not where the subject is.** `refs --symbol _foo + --in-image AppKit` finds `_foo` wherever it is defined and lists AppKit's calls to it. It takes + a path or a file name; a file name can match two images in a macOS cache (the Mac Catalyst + variant under `/System/iOSSupport`), and both are searched. +- **Only the images that can reference the subject are scanned**: the ones whose + `__objc_selrefs` hold the selector, that import the symbol or class, or that link the image + defining a Swift function. `--string` is the exception — any image can hold a literal — so on a + whole cache, name the images. +- **`--class` on a class no symbol exports** (most private classes in a cache) reads every + image's class list first; the first such query takes a few seconds longer. +- **`--json`** prints one document whose every address is a hexadecimal string, never a number. + Its field names are a contract. `--limit` keeps the first references in image and address + order and sets `isTruncated`. +- **Not reported, by design or not yet**: a call through a vtable, a witness table or any + register says `indirect` with what the call site shows (the offset of the load, the pointer- + authentication discriminator) but no callee — never which table it was; a Swift class's stored-property offset variables are not + reported as ivar references; an app read together with the running system's cache is not + supported — read the app's files alone, and a call into a system library stays the imported + symbol it is. diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/references/objc.md b/AgentPlugins/swift-section/skills/swift-section-cli/references/objc.md index 306205f78..5741822d0 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/references/objc.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/references/objc.md @@ -25,6 +25,9 @@ swift-section objc interface NSTextInputContext \ swift-section objc interface NSTextInputContext --uses-system-dyld-shared-cache -n AppKit \ --emit-method-imp-addresses --emit-property-accessor-addresses +# The same class as Swift imports it, like Xcode's Generated Interface (from 0.25.0) +swift-section objc interface NSColor --uses-system-dyld-shared-cache -n AppKit --swift + # A standalone binary; a universal one needs -a, and without it the error lists the slices swift-section objc interface SomeClass /path/to/Binary -a arm64e --emit-method-imp-addresses @@ -33,6 +36,17 @@ swift-section objc dump /path/to/dyld_shared_cache_arm64e --dyld-shared-cache -n --emit-method-imp-addresses --emit-property-accessor-addresses \ --emit-ivar-offsets --emit-property-attributes \ -o AppKit.h + +# Several versions of one image merged into one header, each declaration rendered as +# `dump` renders it and annotated with its lifecycle (`// [○●●] added in 26.5`) +swift-section objc evolution \ + 15.5/dyld_shared_cache_arm64e \ + 26.5/dyld_shared_cache_arm64e \ + 27.0/dyld_shared_cache_arm64e \ + --dyld-shared-cache -n AppKit \ + --labels 15.5,26.5,27.0 \ + --interface --emit-available \ + -o AppKit-evolution.h ``` - The loading options are spelled exactly as in the Swift subcommands: `--dyld-shared-cache` @@ -68,6 +82,26 @@ swift-section objc dump /path/to/dyld_shared_cache_arm64e --dyld-shared-cache -n superclass defined in another binary is not followed, so `--strip-overrides` removes almost nothing and inherited members such as `init` stay listed. Inside one cache the chain crosses images normally. When you need the full chain, read the image inside its cache. +- **Swift classes that have no class object are listed from their Swift metadata**, each under a comment saying why. A generic class prints under its Swift name with its generic parameters (`@interface Module.Panel : NSPanel`): its `class_ro_t` is the template every instantiation is built from, and has no name of its own. A class registered through `__objc_stublist` (its superclass is in another module, or is a generic class) prints under its `_TtC…` name. A superclass that is a Swift class of another binary keeps its Swift spelling (`SwiftUI.NSHostingView`), and `--strip-overrides` cannot see past it. A snapshot written by 0.24.0 or earlier lacks these classes, so a `diff` against it reports each of them as added. +- **`interface --swift` infers its names; it does not read them.** It applies the + ClangImporter's naming rules to what the binary records, and about 81 % of AppKit's public + members come out with the name the SDK gives them. What only the SDK has is missing: API + notes and `NS_SWIFT_NAME` renames, enum and option-set type names (such an argument prints as + its integer type), collection element types, nullability (objects print as `T!`). Imported + types keep their Objective-C names under `__C`. Where the printed name would not lead the + compiler back to the selector, `@objc(selector)` pins it — trust the selector over the name. + What Swift implements prints as Swift declares it: a Swift class as the Swift class, an + `@objc @implementation` class as its implementation's body (its Swift-only members too) with + the Objective-C methods no Swift member answers to last, the members of a Swift extension as + those Swift members. In an OS framework the thunks are stripped and inlined, so members are + paired by name; a property the header marks `NS_REFINED_FOR_SWIFT` whose Swift implementation + left no symbol shows as a `// NS_REFINED_FOR_SWIFT: var __name: …` comment, right above the + Swift property that took its plain name. A + class shows only its own members: the linker merges a binary's categories on its own classes + into them, and the categories a dyld cache attached ahead of time are left out, so only a + category on another binary's class is a category. It indexes the binary's Swift side first, + so it is slower than the header — about 16 seconds for AppKit. Structs and unions have no + Swift view. - **The ivar offsets of pure Swift classes (`_TtC…` names) are unreliable** — file and in-process readings disagree, and some ivars are dropped. Take Swift layout from the Swift subcommands (`--emit-field-offsets`). @@ -77,6 +111,8 @@ swift-section objc dump /path/to/dyld_shared_cache_arm64e --dyld-shared-cache -n - **Snapshots do not cross format versions.** A snapshot JSON carries a `formatVersion`; any other version is rejected with `Unsupported ObjC API snapshot format version …`, and the fix is to regenerate the baseline with the current tool. +- **`objc evolution --interface` needs binaries and labels.** It renders live declarations, so a snapshot input is a usage error. With cache inputs every default label is the file name, `dyld_shared_cache_arm64e`, so pass `--labels`. `--platform` takes the availability macros' spelling (`macos`, `ios`, `macCatalyst`, `driverkit`), not the Swift `@available` one (`macOS`); it is not validated, so a Swift spelling silently produces `API_AVAILABLE(macOS(…))`. +- **No macro is not "no lifecycle".** A declaration present from the first version and removed later gets no `API_OBSOLETED`, because the macro needs the version that introduced it; one that disappeared and came back, or was only modified, gets none either. The `// [●●○] removed in …` comment is always there. A class, protocol or category added or removed as a whole is annotated on its `@interface` / `@protocol` line only, and its members carry no annotations of their own. ## Where the details live diff --git a/Changelogs/0.25.0.md b/Changelogs/0.25.0.md new file mode 100644 index 000000000..e319d2b25 --- /dev/null +++ b/Changelogs/0.25.0.md @@ -0,0 +1,55 @@ +# 0.25.0 + +## Breaking + +- `MachOReading`, `MachOResolving`, `MachOPointers`, `MachOCaches`, `MachODependencies`, `MachOSymbols`, `MachOBase` and `MachOFoundation` moved to MachOKitExtensions 2.0.0; take those products from that package. +- The Swift symbol index moved from `MachOSymbols` to the new `SwiftSymbols` product, and `SymbolIndexStore` is now `SwiftSymbolIndexStore`. +- Removed the reading APIs that take a Mach-O or a raw pointer, `AsyncResolvable` and `ResilientWitness.implementationAddress(in: machO)`; pass `machO.context` or `.inProcess` instead. +- The Objective-C types of `SwiftInspection`, such as `ObjCMemberTable` and `ObjCClassHierarchyProviding`, moved to the new `SwiftObjCInterop` product. +- ABI snapshots now use format version 13; regenerate snapshots written by 0.24.0. +- `interface` and `dump` now write `any` before existential types; use `interface --no-existential-any` or `dump --disable-existential-any` to turn it off. +- `ExportStatus` gains `.declarationHasNoSymbol` and `.declarationIsCImported`; exhaustive `switch`es must handle them. +- `CodeReferenceTarget` and `CodeReferenceTable.Key` gain instance variable, C string and constant string cases; exhaustive `switch`es must handle them. +- Flag word kinds that can grow with the compiler, such as `MethodDescriptorFlags.kind` and `FunctionTypeFlags.convention`, are now optional. +- `ClassFlags` is now an option set, and `InvertibleProtocolKind`'s raw value is now a `UInt16`. +- Types conforming to `OpaqueTypeResolving` must implement `opaqueType(forNode:index:spellingOptions:)`. +- `AssociatedTypeWitnessProjection` is now `ResolvedAssociatedTypeWitness`, and `ConditionalWitnessCandidate` is now `ResolvedAssociatedTypeWitness.ConditionalCandidate`; the old names are deprecated. +- Requires MachOKitExtensions 2.0.0, MachOObjCSection 0.8.207, swift-demangling 0.7.4, MachOKit 0.55.102, swift-semantic-string 0.6.0 and FrameworkToolbox 0.17.0 or later. + +## New + +- New `swift-section refs` lists the code that references a selector, symbol, class, function, instance variable or string. +- New `swift-section symbolicate` tells what an unslid address is: a function, a stub, a pointer slot, a string or a symbol. +- `CrossReferenceAnalyzer` now reads a dyld shared cache file or standalone Mach-O files offline, through `init(dyldCache:)` and `init(machOFiles:)`. +- Cross references now include Objective-C instance variable accesses, C string and CFString literals, and the `route` each reference took. +- New `CrossReferenceAnalyzer.symbolication(of:)` tells what any address is. +- `dump` and `interface` now show `@objc` protocols declared in Swift and the Objective-C protocols Swift classes adopt. +- `interface` now prints `@Observable` classes as written in source; `interface --expand-macros` and `expandsMacros` print the expansion instead. +- New `printMacroExpansionParts(of:attachedTo:)` returns an `@Observable` expansion in the two levels Xcode shows. +- `dump`, `interface` and `diff` now include SE-0400 `init` accessors. +- New `objc interface --swift` and `ObjCInterfaceRequest.printsSwiftImport` print Objective-C classes, categories and protocols as Swift imports them. +- New `objc evolution --interface` merges versions into one annotated header, and `--emit-available` adds `API_AVAILABLE` / `API_OBSOLETED`. +- `ABIEvolutionBuilder.evolution(ofImageGroups:versions:)` and `AnySwiftEvolutionInterfaceBuilder` compare versions made of several images and report declarations that moved between them. +- New `SwiftDeclarationPrintConfiguration.marksCommentStructure` marks the kind and segments of each comment. +- `printExportedDeclarationsOnly` now works in marking mode, so a host can hide non-exported members from a search corpus printed once. + +## Improved + +- Reading Mach-O files and dyld shared cache images offline is much faster. +- `evolution` and `diff` no longer report members as removed in versions whose stripped symbols hide them. +- Cross references now count `objc_alloc_init`, `objc_opt_isKindOfClass` and similar libobjc calls as the sends they stand for. +- `dump` and `interface` now show members an optimized build kept only as an `@objc` thunk or an initializing entry point. +- `swift-section objc` now shows generic Swift classes and other Swift classes without a static class object. +- `interface` now shows members an image declares on another image's types, such as SwiftUI's on SwiftUICore types. + +## Fixed + +- Fixed `ExistentialTypeFlags.classConstraint` and `ProtocolDescriptorFlags.classConstraint` crashing, and `FunctionTypeFlags.convention` reading the wrong bits. +- Fixed a crash from running out of file descriptors when reading many images of a dyld shared cache. +- Fixed occasional crashes when several threads first read the same file or dyld shared cache image. +- Fixed constrained existential fields such as `any Boxed` printing as their argument type. +- Fixed opaque result types in Debug-built images printing a bare `some` or the wrong constraint. +- Fixed `interface --exported-only` keeping non-exported types of AppKit, and dropping C types with `--show-c-imported-types`. +- Fixed `swift-section objc` reading garbage method names from macOS 11 dyld shared caches. +- Fixed cross references missing calls in code rewritten by ld64 and misreading addresses on iOS devices. +- Fixed a crash in `CrossReferenceAnalysis` on a malformed export trie. diff --git a/Documentations/Evolutions/0027-locatable-layout-wrapping-macro.md b/Documentations/Evolutions/0027-locatable-layout-wrapping-macro.md index 8d84bdc71..54ccb8e28 100644 --- a/Documentations/Evolutions/0027-locatable-layout-wrapping-macro.md +++ b/Documentations/Evolutions/0027-locatable-layout-wrapping-macro.md @@ -66,3 +66,4 @@ public struct MethodDescriptor: ResolvableLocatableLayoutWrapper { | 2026-09-11 | 顺带把三处 `var offset` 统一为 `let offset` | 全库无赋值点,是历史偶然差异,宏只能生成一种形状 | | 2026-09-11 | 状态 Draft → Accepted | 用户批准方案原样,三个决策点(只生成三项要求 / 97 处一次性全换 / 改扫描器认宏)均按推荐执行 | | 2026-09-11 | 状态 Accepted → Implemented,落地取号 0027 | 97 处全部迁移,全量测试绿(除两处已知的 `SharedCacheTests` 墙钟 flaky,单独复跑 0.41 秒通过),覆盖率不变式四条绿且 baseline / allowlist 零漂移,`-dump-macro-expansions` 抽查确认展开与手写逐字一致。不另写配套实现说明(AGENTS.md 的 Key Patterns 已收录约定,提案 + 任务报告足够);未引入新术语,术语表不动 | +| 2026-11-06 | 「宏只生成三项要求、不生成 conformance」的决定被推翻,宏改名 `@ResolvableLocatableLayoutWrapper` | 宏与遵循在 98 个类型上总是成对出现;见 [0087-resolvable-locatable-layout-wrapper-macro](0087-resolvable-locatable-layout-wrapper-macro.md) | diff --git a/Documentations/Evolutions/0057-reading-context-migration.md b/Documentations/Evolutions/0057-reading-context-migration.md index 833409b6a..165ad4403 100644 --- a/Documentations/Evolutions/0057-reading-context-migration.md +++ b/Documentations/Evolutions/0057-reading-context-migration.md @@ -3,7 +3,7 @@ - **状态**: Implemented - **作者**: JH - **创建日期**: 2026-09-30 -- **最后更新**: 2026-10-01 +- **最后更新**: 2026-11-11 - **所属愿景**: 无 - **关联提案**: [0018-self-contained-abi-layer](0018-self-contained-abi-layer.md)(「`ReadingContext` 只管读、不带符号服务」的定位出自这里,本提案延续它)、[0025-key-path-component-and-property-descriptor](0025-key-path-component-and-property-descriptor.md)(记下了「新接口三套都写」的惯例,本提案推翻它)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(按镜像缓存与驱逐的现行规则) - **实现分支 / PR**: `refactor/reading-context-migration`(worktree `.worktrees/MachOSwiftSection-ReadingContextMigration`),[PR #129](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/129) @@ -261,7 +261,7 @@ extension ReadingContext { 10. 0.22.0 发布(Changelog 写明废弃清单与三处行为变化)。 11. RuntimeViewer、MachOKitUI、swift-decompiler 各提迁移 PR。 -12. 0.25.0(原定 0.23.0,2026-10-15 与 2026-10-26 两次推迟,见决策日志):删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 +12. 0.25.0(原定 0.23.0,2026-10-15 与 2026-10-26 两次推迟,见决策日志):删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。**已完成**(2026-11-11,见决策日志)。 **收尾判断**(落地时写进决策日志):是否需要配套实现说明(预期更新 `ReadingContextAbstraction.md` 即可,不另写);新术语「缓存范围」登记进术语表。 @@ -342,3 +342,4 @@ extension ReadingContext { | 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 写明新期限。 | +| 2026-11-11 | 删除全部废弃转发与转发套件 | 按 MachOKitExtensions 的提案「把 MachOReading 与 MachOResolving 迁入本包」,与迁移放在同一版:废弃写法不随模块进入 MachOKitExtensions。下游已迁完:MachOKitUI 的 `main` 与 RuntimeViewer 的 `next` 早已改用 `ReadingContext`,swift-decompiler 在同名功能分支 `feature/move-reading-and-resolving-modules` 上迁掉最后 13 处(编译器报出的,比文本搜到的多 3 处 `dumpName(using:in:)`)。删去 344 个读取写法的转发与整个 `AsyncResolvable`;`ResilientWitness.implementationAddress(in: machO)` 是本提案改名留下的旧名,同属废弃转发,一并删除;`DeprecatedReadingFormsTests` 删除。13 个基线生成器去掉指针版初始化器的键;另有两个名字独一份的指针版写法(`MetadataWrapper.metadata`、`TargetGenericContext.uniqueCurrentRequirementsInProcess`)删后连键一起消失,覆盖率不变式报为多余登记,按它的要求从登记表删去,并删掉对着它们的两个测试——它们测的是替代写法的本进程路径,`asMetadata` 另有自己的测试,顶层类型的 `uniqueCurrentRequirements` 也不读内存,覆盖没有损失。基线用 CI 的 Xcode 26.6 按 CI 设置编出的样本重新生成,只有这 14 个文件的登记行变化(用 Xcode 27.2 编的样本会让 70 个基线的偏移整体漂移,不能用)。 | diff --git a/Documentations/Evolutions/0076-objc-runtime-send-entry-points.md b/Documentations/Evolutions/0076-objc-runtime-send-entry-points.md new file mode 100644 index 000000000..28483585a --- /dev/null +++ b/Documentations/Evolutions/0076-objc-runtime-send-entry-points.md @@ -0,0 +1,56 @@ +# 0076 - 交叉引用把 libobjc 的专用发送入口记成消息发送 + +- **状态**: Implemented +- **创建日期**: 2026-10-27 +- **最后更新**: 2026-10-27 +- **所属愿景**: 无 +- **关联提案**: [0072](0072-cross-reference-analysis.md)(交叉引用分析) +- **实现分支 / PR**: `fix/cross-reference-review-findings`(worktree `.worktrees/MachOSwiftSection-CrossReferenceReviewFixes`,基于 `next`),2026-10-27 本地合入 `next` +- **配套文档**: [Modules/CrossReferenceAnalysis.md](../Internal/Modules/CrossReferenceAnalysis.md)「libobjc 的发送入口」一节;[2026-10-27 审查记录](../../Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md) 第 2 条 + +## 摘要 + +clang 不把每个 Objective-C 发送都编成 `objc_msgSend`:`[[Foo alloc] init]` 编成 `objc_alloc_init(Foo)`,`[x isKindOfClass:c]` 编成 `objc_opt_isKindOfClass(x, c)`,`[Foo new]`、`[x class]`、`[x self]`、`[x respondsToSelector:s]`、`[Foo alloc]` 也各有一个 libobjc 入口。交叉引用扫描只把 `objc_msgSend` 和 `objc_msgSendSuper2` 当发送,这些入口记成普通函数调用,按 selector 查调用者时就漏掉。macOS 26.6 的 AppKit 里,`objc_alloc_init` 有 2,488 处调用,而按 selector 发送的 `init` 只有 720 处,查 `init` 的调用者漏掉约 78%;`isKindOfClass:`、`respondsToSelector:`、`alloc`、`new` 按 selector 发送的一处都没有(`objc_opt_isKindOfClass` 3,369 处、`objc_opt_respondsToSelector` 2,977 处、`objc_alloc` 4,180 处、`objc_opt_new` 590 处),查它们的调用者结果是空的。本案把这些入口的调用记成它们代表的发送。 + +## 方案 + +**认哪些入口,记成什么。** 入口和 `objc_msgSend` 一样按 libobjc 里的位置认:经桩、GOT 或缓存共用的桩到达那里都算;桩跟不过去、只剩导入名时按名字认。 + +| 入口 | 记成的发送 | +|------|-----------| +| `objc_alloc` | `alloc` | +| `objc_allocWithZone` | `allocWithZone:` | +| `objc_alloc_init` | `alloc` 与 `init` 两条,同一条指令 | +| `objc_opt_new` | `new` | +| `objc_opt_self` | `self` | +| `objc_opt_class` | `class` | +| `objc_opt_isKindOfClass` | `isKindOfClass:` | +| `objc_opt_respondsToSelector` | `respondsToSelector:` | + +**结果的形状不变,没有公开 API 改动。** + +- 发送照旧是 `.messageSend(selector:receiver:)`,`kind` 是 `.call` 或 `.tailCall`,`isRuntimeHelperCall` 为 false,表里归在 `.selector(名字)` 下,`CodeReferenceIndex` 不用改。 +- 和 `objc_msgSend` 一样,这处调用只记发送、不再同时记成对这个 C 函数的调用:按函数查 `_objc_alloc_init` 的调用者不再有结果。这些调用的 selector 永远已知,按 selector 查才是对的问法。 +- 接收者按 `x0` 判断,和 `objc_msgSend` 相同(`methodReceiver`、`classLiteral`、`unknown`)。`objc_alloc_init` 的 `init` 发给刚分配出来的实例,不是 `x0` 里的类,接收者记 `.unknown`。给它一个「某类的新实例」的提示要往公开的 `ReceiverClassHint` 里加一个 case,RuntimeViewer 里对它的穷举 switch 会编不过,这次不做。 +- `objc_opt_self`、`objc_opt_class` 调用之后 `x0` 照旧保留,类字面量接收者的识别不受影响。 + +**不认的入口。** `objc_retain`、`objc_release`、`objc_autorelease` 不算:ARC 插入的调用和 MRC 下源码里的 `[x retain]` 编出来的是同一个调用,分不开,继续当作 runtime helper。`swift_getInitializedObjCClass` 不是发送,只保留「原样返回传入的类」的处理。 + +**预筛。** `imageIndices(referencingSelector:among:)` 只看镜像的 `__objc_selrefs`,而一个镜像可能只经 `objc_alloc_init` 发送 `init`,`__objc_selrefs` 里根本没有 `init`。查上表里的 selector 时,导入了对应入口符号(`_objc_alloc_init` 等)的镜像也留下,定义这些入口的 libobjc 也留下。 + +**测试。** 测试里现场编一个 Objective-C dylib,覆盖上表每个入口,断言每处调用记成对应的发送;修改前这些调用是对 libobjc 函数的 `.function`。预筛另测这个一个 selector 引用都没有的镜像,八个 selector 的预筛都留下它;整个缓存上的预筛测试加上 `isKindOfClass:`(AppKit 里它只经 `objc_opt_isKindOfClass` 发送)。 + +**影响。** 查这些 selector 的调用者,结果会多出很多;按函数查这些 C 入口的调用者,结果会消失。RuntimeViewer 不用改代码,发版说明里要写这个行为变化。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-27 | Created as Draft | 2026-10-27 的审查发现,查 selector 的调用者会漏掉经 libobjc 专用入口的发送,AppKit 里查 `init` 漏掉约 78% | +| 2026-10-27 | `objc_alloc_init` 记 `alloc` 与 `init` 两条发送 | 它就是 `[[cls alloc] init]`,查 `alloc` 和查 `init` 的人都该找到它 | +| 2026-10-27 | 只记发送,不同时记成对 C 函数的调用 | 与 `objc_msgSend` 的处理一致;同时记两种会让每处调用多一条引用,按函数查这些入口的需求又几乎不存在 | +| 2026-10-27 | `init` 的接收者记 `.unknown`,不加新的接收者提示 | 新 case 是公开 enum 的破坏性改动;`.unknown` 不失真 | +| 2026-10-27 | 不认 `objc_retain` / `objc_release` / `objc_autorelease` | ARC 插入的调用与源码里的发送分不开 | +| 2026-10-27 | 用户批准,状态改为 Accepted | — | +| 2026-10-27 | 实现完成,状态改为 In Progress | 修复前 16 个用例全部失败、修复后通过;全量测试在 JHs-Mac-Studio-Ultra 上通过。合入 `next` 时取号并改为 Implemented | +| 2026-10-27 | 合入 `next`,取号 0076,状态改为 Implemented | 与方案只有一处不同:预筛除了导入这些入口的镜像,也留下定义它们的 libobjc。模块文档的「libobjc 的发送入口」一节就是实现说明,不另写使用指南;没有新术语要登记。没做完的项:无 | diff --git a/Documentations/Evolutions/0077-thunk-only-objc-members.md b/Documentations/Evolutions/0077-thunk-only-objc-members.md new file mode 100644 index 000000000..a2fda4537 --- /dev/null +++ b/Documentations/Evolutions/0077-thunk-only-objc-members.md @@ -0,0 +1,49 @@ +# 0077 - 只剩 `@objc` thunk 或 initializing entry point 的成员照样建出来 + +- **状态**: Implemented +- **创建日期**: 2026-10-27 +- **最后更新**: 2026-10-27 +- **关联 issue**: [#137](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/issues/137)(Swift 侧)、[#138](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/issues/138) +- **关联提案**: [0054-interface-descriptor-only-vtable-members](0054-interface-descriptor-only-vtable-members.md)(同一种「替身成员符号」的先例) +- **实现分支**: `fix/thunk-only-objc-members`(已合入 `next`) +- **配套文档**: [ThunkOnlyObjCMembers.md](../Internal/ThunkOnlyObjCMembers.md)(实现说明) + +## 摘要 + +优化构建(`-O`、整模块优化)里,编译器常把成员的 Swift 实现内联掉,只留下另一个入口。一种是 `@objc` 成员:函数体被内联进它的 Objective-C thunk(`$s…To`),Swift entry point 消失。另一种是 class 的 `init`:allocating entry point(`…fC`)被内联进调用方后删掉,只剩 initializing entry point(`…fc`)。成员模型只从实现符号(以及提案 0054 的 `Tq` 替身)建成员,所以这两种成员在 `interface` 里整个消失,前一种在 `dump` 里也消失。Xcode 27.2 的 `Xcode Service` 可执行文件里,前一种有 7 个类、22 个成员(`canBecomeKey`、`layout()`、`windowWillClose(_:)` 这类),后一种有 9 个 `init`。改法沿用提案 0054:真实符号没有声明这个成员时,用镜像里剩下的那个入口造一个替身成员符号。 + +## 方案 + +1. **符号索引**(MachOSymbols):`To` thunk 符号照旧登记成「这个名字是 `@objc`」的标记,此外再按成员类别、类型名与类型节点分桶登记进第四个成员索引,与实现符号、`Tq`、protocol witness 三个索引并列。查询返回 thunk 自己的符号。 +2. **声明模型**(SwiftDeclaration、SwiftIndexing):类的各类成员与 extension 的成员,在实现符号和 0054 的 `Tq` 替身之后再补两种替身。只补真实符号没有声明的成员,判据与 0054 相同:按成员实体节点结构相等。 + - **从 initializing entry point 造的替身**(#138):把 `…fc` 符号改写成 allocator 的形状,即节点 `constructor` 换成 `allocator`、名字后缀 `fc` 换成 `fC`、偏移仍是 `fc` 的地址。这样 vtable 里实现为 null 的 `__allocating_init` 槽照常按节点联结上,ObjC 方法表照常按 allocator 名换成 `…fcTo` 联结,ABI 身份也与没被内联时相同。 + - **从 `@objc` thunk 造的替身**(#137):去掉 `objCAttribute` 子节点得到成员节点,名字去掉 `To` 后缀(`…fcTo` 再按上一条改成 allocator),偏移用 thunk 自己的地址,因为它是这个成员唯一的代码。下游按名字推导的几处(导出判定、ObjC 方法表联结、`@objc` 标记)都把替身当成它顶替的实现符号来读,不用改。 +3. **dump**(SwiftDump):class 与 extension 的成员列表在各类别之后加一节 `/* [ObjC Thunk] <类别> */`,列出只剩 thunk 的成员。判断方法是实现名、它的合并形式(`Tm`)以及 `init` 的另一个 entry point 都不存在。行尾照常挂 ObjC 方法表的联结注释。只剩 initializing entry point 的 `init`,dump 本来就列在 `/* Constructor */` 下,不动。 +4. **ABI 快照**:格式版本加一,旧基线会把新建出来的成员全报成新增。草案 `evolution-unobservable-presence` 也要加一,谁先落地谁取 8。 + +没有询问就采用的假设: + +- interface 不给替身成员加额外标注,地址注释照常输出,指向 thunk 或 `fc`;替身的来历只在 dump 里写明。 +- 泛型类和经 `__objc_stublist` 登记的类没有静态的 ObjC 方法表,它们的替身成员只有 `@objc`、没有 `override`。这要等 #137 的 ObjC 侧,另立一份提案,并与 MachOObjCSection 协作。 +- `…ToTm`(几个 thunk 共用的合并函数体)不建成员。 +- 新索引走 `processMemberSymbol` 分类,`@objc subscript` 的 thunk 也一并进索引;原来的标记表不认 subscript,这一点顺带补上。 + +验证: + +- 新增一个现场编译的 fixture,用 `-O` 编译、不 strip:内部类对 ObjC 成员的覆写、`@objc` 方法、`override init()`,泛型类的覆写,以及只剩 `fc` 的 `init`。先写测试,确认改动前失败。 +- 改动涉及索引与打印,按项目规则跑渲染 A/B;预期系统框架的输出不变,或只多出替身成员。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-27 | Created as Draft | #137 与 #138 的 triage 定位到成员模型只认实现符号;用户要求本库与 MachOObjCSection 两边并行开工。 | +| 2026-10-27 | 轻量档,状态 Accepted | 用户批准开工;改法沿用提案 0054 已落地的替身成员符号。 | +| 2026-10-27 | #138 并入本提案 | `@objc` thunk 替身里的 `init` 来自 `…fcTo`,去掉后缀得到的是 initializing entry point,模型要先接受它;分两次改要把同一处改两遍。 | +| 2026-10-27 | #137 的 ObjC 侧另立提案 | 让 `objc dump` 和 ObjC 方法表看见泛型类与 stub-list 类,需要 MachOObjCSection 先加 API,与本提案互不依赖。 | +| 2026-10-27 | 状态 In Progress | 实现提交到 `fix/thunk-only-objc-members`;修复前在 Ultra 上跑新测试,7 个暴露问题的测试全部失败(24 处),3 个只核对前提的测试通过。 | +| 2026-10-27 | 顺带修 initializer 的 `@objc` | 一个 initializer 有 thunk,整个类的 initializer 都被打成 `@objc`(旧问题);补回的 initializer 会把它放大,改为按每个 initializer 自己的 thunk 名判断。属于显而易见的 bug 修复,记在本提案里。 | +| 2026-10-27 | 同类问题一并修:重载的方法 | 标记表只记成员名,重载共用名字,Swift-only 的重载也被打成 `@objc`;方法同样改为按自己的符号名查 thunk。属性名在类型内唯一,不改。 | +| 2026-10-27 | 验证完成,等待落地 | 全量测试与渲染 A/B 都在 Ultra 上跑完(结果见实现说明);`TO` thunk 也会挂在 `fC` 上,但这些全是导入 ObjC initializer 的桥接 thunk,不影响打印出的成员,代码不为它改。 | +| 2026-10-27 | 状态 Implemented,编号 0077,合入 `next` | 用户批准落地。实现说明写在 [ThunkOnlyObjCMembers.md](../Internal/ThunkOnlyObjCMembers.md);没有新 flag,不需要使用指南,CLI skill 补了快照格式与输出解读两条;新术语 stand-in member symbol 与 thunk-only member 登记进术语表。偏离方案之处:顺带修了 initializer 与重载方法的 `@objc` 误标。 | +| 2026-10-27 | 后续项 | #137 的 ObjC 侧(泛型类与 stub-list 类的 `class_ro_t`、`objc dump` 列出它们、ObjC 方法表据此给 `override`)另立提案,MachOObjCSection 的 host-supplied-classes 提案已获批准、正在实现。A/B 中看到的两个旧问题另开 #139(下划线开头的普通存储属性被当成 property wrapper 的 backing storage)与 #140(dump 把类方法的空 vtable 槽打成 `class func static`)。 | diff --git a/Documentations/Evolutions/0078-objc-classes-without-class-objects.md b/Documentations/Evolutions/0078-objc-classes-without-class-objects.md new file mode 100644 index 000000000..838829967 --- /dev/null +++ b/Documentations/Evolutions/0078-objc-classes-without-class-objects.md @@ -0,0 +1,60 @@ +# 0078 - 没有 class object 的 Swift 类:从 Swift 元数据读出它们的 ObjC 类数据 + +- **状态**: Implemented +- **创建日期**: 2026-10-27 +- **最后更新**: 2026-10-28 +- **关联 issue**: [#137](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/issues/137)(ObjC 侧) +- **关联提案**: [0077-thunk-only-objc-members](0077-thunk-only-objc-members.md)(Swift 侧);MachOObjCSection 的 0014 `host-supplied-classes`(跨仓库,提供本提案要用的 `ObjCSuppliedClass`,随 MachOObjCSection 0.8.201 发布) +- **实现分支**: `feature/objc-classes-without-class-objects`(已合入 `next`) +- **配套文档**: [ClassesWithoutClassObjects.md](../Internal/ClassesWithoutClassObjects.md)(实现说明) + +## 摘要 + +有三种 Swift 类在文件里没有静态的 class object:泛型类;父类在别的 resilience domain 的非泛型类;父类是本模块泛型类的非泛型类。`__objc_classlist` 里没有它们,后两种只在 `__objc_stublist` 里登记一个 stub。`swift-section objc` 的各个子命令因此看不见它们;本库自己的 ObjC 方法表(判 `override` 与显式 selector 的证据)也读不到它们,所以提案 0077 补回来的只剩 thunk 的成员,在这些类里只有 `@objc`、没有 `override`。它们的 `class_ro_t` 其实都静态存在,只是要从 Swift 元数据才能找到。MachOObjCSection 0.8.201 新增了 `ObjCSuppliedClass`,让宿主把这种类交给 `ObjCInterfaceIndexer`;本提案让本库算出这些类交出去,同时让本库自己的 ObjC 方法表也认识它们。 + +## 方案 + +1. **按镜像的索引** `SwiftClassWithoutClassObjectIndex`(SwiftInspection,`SharedCache`,`.objcHierarchy` 驱逐组,跟随 `.symbolStore`):从类型描述符枚举三种类,每一种算出 `class_ro_t`、元类的 `class_ro_t`、stub、名字、父类,以及有没有 ObjC 祖先。 + - **泛型类**:generic metadata pattern 的 extra-data pattern 里,`class_ro_t` 在 pattern 数据的第 (`ClassRODataOffset` − `OffsetInWords`) 个字,元类的在第 (`MetaclassRODataOffset` − `OffsetInWords`) 个字(运行时 `initializeClassMetadataFromPattern` 的算法)。模板里的 `class_ro_t.name` 是空指针,名字用 Swift 限定名加上各层泛型参数(`Xcode_Service.MenuBarPanelWindow`;嵌套在泛型里的写成 ``)。 + - **父类在别的 resilience domain 的非泛型类**(Resilient 策略):`ResilientClassMetadataPattern.data` 是 `class_ro_t`,`metaclass` 指向的元类的 `data` 字段是元类的 `class_ro_t`;stub 来自描述符的 `ObjCResilientClassStubInfo`。 + - **父类是本模块泛型类的非泛型类**(Singleton 策略):静态 incomplete metadata 本身就是一个 class object 的形状,`class_ro_t` 与元类都经 MachOObjCSection 的读取器从它读出;描述符里不记 stub,而这种 stub 是非公开的,只有完整 stub 的私有符号 `…CMt`,isa 字段在它后面一个字;剥掉 local 符号的镜像里没有这个符号,就不记。Update 与 FixedOrUpdate 策略的类同样有 singleton 初始化,但它们的元数据在 class list 里,按偏移排除。 + - 绝对指针(class object 的 `data` 与 `isa` 字段)一律经 MachOObjCSection 的读取器解,相对指针自己解,这样 dyld cache 的几套偏移不必在这里处理。 + - **有没有 ObjC 祖先**:看类标志位的 `UsesSwiftRefcounting`(ObjC 对象模型下为 0),继承 `NSObject` 的 actor 例外。 + - **父类**:ObjC 父类给它的运行时名(`__C.NSPanel` 给 `NSPanel`),没有声明父类的给 `_TtCs12_SwiftObject`;同一镜像里有 class object 的 Swift 父类给它的运行时名;同一镜像里同样没有 class object 的给它在本索引里的名字;其余(别的镜像里的 Swift 类)给 Swift 写法,只作显示用。 +2. **交给 MachOObjCSection**:SwiftIndexing 新增公开的 `ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`,交出全部泛型类,以及 `__objc_stublist` 登记的那些非泛型类——编译器只给有 ObjC 祖先的类登记 stub,MachOObjCSection 给这两类写的注释也是「registered through `__objc_stublist`」。SwiftSectionKit 的 `ObjCInterfaceSession` 与 `ObjCAPIRequests` 两处构造索引器时传入;SwiftIndexing 的 `ObjCInterfaceIndexerClassHierarchyProvider` 在 `classGroup(forName:)` 落空时查 `suppliedClassGroup(forName:)`。 +3. **本库的 ObjC 方法表**:`ObjCClassMethodIndex.runtimeNames(forSwiftClassQualifiedName:in:)` 也给出本索引里的名字,`hierarchy(forRuntimeName:in:)` 在没有 class object 时从算出的 `class_ro_t` 读方法表,父类按上面的规则续链;父类同样没有 class object 时,祖先链里新增一种位置 `ObjCSuperclassLocation.withoutClassObject` 接着走。按名字找 ObjC 父类的 `ObjCAncestorResolver.classObject(named:)` 在进程内也到已加载的镜像里找:进程内 class object 的父类都是真指针,原本用不着按名字找,没有 class object 的类却只有父类的名字。方法表这一侧不过滤 ObjC 祖先:纯 Swift 类没有 ObjC 方法,自然不出表。 +4. **依赖**:MachOObjCSection 的要求升到 `"0.8.201" ..< "0.9.0"`,随之要求 MachOKit 0.55.100、swift-objc-dump 0.8.102。 + +已知限制(本版不做): + +- 父类是另一个镜像里的 Swift 类时(`Xcode Service` 的 `MenuBarLabelHostingView` 继承 SwiftUI 的 `NSHostingView`,SwiftUI 的类继承 SwiftUICore 的类),链在那里断,`override` 照旧不判。非泛型的那种可以按限定名到依赖镜像的 class list 里找,留作后续。 +- 本库自己的读取器读不到挂在 stub 上的 category(Swift `extension` 里的 `@objc` 成员),因为 `targetClassName(of:)` 从 stub 读不出名字;MachOObjCSection 的索引器按 `classStubOffset` 归类,宿主走 provider 时没有这个问题。 + +验证: + +- fixture `ClassesWithoutClassObjectsFixture`(测试时现编:一个开 library evolution 的 kit,加上使用它的客户端,`.full` 与 `strip -x` 两种):三种类各一个,加一个纯 Swift 的泛型类、一个没有 ObjC 祖先的 Singleton 类和一个有 class object 的对照组。 +- 先在不含本改动的 `next` 上跑 interface 与 `objc dump` 两组行为测试,确认失败;再在分支上确认通过。 +- `Xcode Service`:两个类在 `objc dump` 里出现、方法表与 MachOObjCSection 那边的测试一致;`MenuBarPanelWindow` 的 `canBecomeKey` 等成员在 interface 里变成 `@objc override`。 +- 渲染 A/B:Swift 侧 interface 应只多出 `override` 与 `@objc`(以及随之少掉的 `final`);dump 多出 ObjC 方法表的注释。 + +## 后续项 + +- **别的镜像里的 Swift 父类续链**:非泛型的那种(SwiftUI 的类继承 SwiftUICore 的类)按限定名到依赖镜像的 class list 里找 class object;泛型的那种(`NSHostingView<…>`)要跨镜像读它的 generic metadata pattern。 +- **本库读取器读挂在 stub 上的 category**:按 category 的目标指针与 `classStubOffset` 比对,像 MachOObjCSection 的索引器那样归到类上。 +- **RuntimeViewer 采用**:它的 ObjC 侧包着自己的 `ObjCInterfaceIndexer`(`RuntimeObjCInterfaceIndexer`),读文件时传入 `ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)` 就能列出这些类。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-27 | Created as Draft,状态 Accepted | #137 的 ObjC 侧;用户批准本库与 MachOObjCSection 两边并行开工,MachOObjCSection 的 host-supplied-classes 提案已获批准。轻量档。 | +| 2026-10-27 | 与 MachOObjCSection 商定的 API | `ObjCSuppliedClass(name:superClassName:readOnlyDataOffset:metaclassReadOnlyDataOffset:classStubOffset:kind:)`;`classStubOffset` 是 stub 的 `isa` 字段(公开 stub 的 `…CMs` 所指),由本库要求加上,用来把挂在 stub 上的 category 归到这个类。 | +| 2026-10-27 | 改为 In Progress;依赖直接用 MachOObjCSection 0.8.201 | 对面已发版(tag 指向 e40982f),不必再用 SwiftPM 的 edit 模式指向它的工作树。 | +| 2026-10-27 | 非泛型的两类只交出有 ObjC 祖先的,泛型类全交 | 编译器只把有 ObjC 祖先的类的 stub 登记进 `__objc_stublist`(`GenMeta.cpp` 的 `emitClassMetadata`),MachOObjCSection 的注释写的正是这一点;泛型类哪个表都不进,注释「instantiated at runtime」对所有泛型类都成立。索引本身两种都记,本库的方法表不过滤。 | +| 2026-10-27 | 别的镜像里的 Swift 父类只作显示,不续链 | 运行时名要用旧式 mangling 拼,本库没有旧式 remangler;按限定名到依赖镜像找 class object 可行,但不在 #137 的范围里,记为后续。 | +| 2026-10-27 | 进程内也按名字找 ObjC 父类 | 起初把进程内断链记成已知限制,但已有的 `optimizedImageInProcessDeclaresWhatTheFileDeclares` 要求进程内与文件打印出同样的声明,泛型类在进程内少了 `override` 就红了。`ObjCAncestorResolver` 本来就持有进程内根的已加载镜像,按名字查与文件的依赖闭包用同一套 export trie 预检。 | +| 2026-10-27 | Singleton 类的 stub 找 `…CMt`,不找 `…CMs` | 探针证实非公开 stub 只定义完整 stub 的私有符号 `…CMt`(`emitObjCResilientClassStub` 只在公开时才给 isa 字段定义别名 `…CMs`),isa 字段在它后面一个字。 | +| 2026-10-27 | 父类名改用 `.interface` 预设打印 | `Xcode Service` 上抓到 `.interfaceType` 预设去掉泛型实参,`MenuBarLabelHostingView` 的父类读成了 `SwiftUI.NSHostingView`。fixture 加了一个父类是别的模块泛型类的例子。 | +| 2026-10-27 | 渲染 A/B 的差异全部是预期中的改进 | 96 对里 30 对不同,都在 SwiftUI 与 SwiftUICore,没有删掉的声明,也没有类型变化。interface 只多出关键字:`override`、`static` 改成 `override class`、剥过符号的模拟器腿上的 `@objc`,以及 12 处显式 selector。显式 selector 逐个核过:两个 focus 方法与基线给有 class object 的兄弟类的判定相同,`_nsAttributedSubstringFromRange:` 与基线在 iOS 18.5 模拟器腿上的判定相同,`springLoadingHighlightExited:` 是 `NSHostingView` 方法表里的真实 selector。dump 只多出方法表与祖先链的注释。两侧渲染耗时相同。细节见实现说明的「验证」。 | +| 2026-10-27 | 改为 Implemented,编号 0078 | 用户批准:A/B 差异全部是预期中的改进就合入 `next`。配套文档写了实现说明 [ClassesWithoutClassObjects.md](../Internal/ClassesWithoutClassObjects.md),不需要单独的使用指南(CLI 的变化写进了 [ObjCCommandLine.md](../ObjCCommandLine.md) 第 5 条与插件 skill);新术语 class without a class object 已登记进术语表。 | +| 2026-10-28 | 落地后更正:只有父类在别的 resilience domain 的类,category 才指向 stub | 核对编译器源码(`GenClass.cpp` 的 `getClassMetadataRef()`、`GenDecl.cpp` 的 `emitExtension`):只有 `AncestryFlags::ResilientOther` 的类,category 指向 stub、放进 `__objc_catlist2`。父类是本模块泛型类的类,category 指向类自己的 metadata,按 `class_ro_t` 里的运行时名归类,本库的读取器照常并入,`classStubOffset` 用不上;泛型类的 `extension` 不许有 `@objc` 成员。所以正文已知限制与后续项里的「挂在 stub 上的 category」只涉及前一种类,那条后续项还要先读 `__objc_catlist2`。实现不变;代码注释、实现说明与 [ObjCMemberRecovery.md](../Internal/ObjCMemberRecovery.md) 同批改正,正文保持落地时的原样。MachOObjCSection 的文档在它的 `next` 上同样改正了(4efe0dd)。 | diff --git a/Documentations/Evolutions/0079-swift-declared-objc-protocols.md b/Documentations/Evolutions/0079-swift-declared-objc-protocols.md new file mode 100644 index 000000000..810470c59 --- /dev/null +++ b/Documentations/Evolutions/0079-swift-declared-objc-protocols.md @@ -0,0 +1,163 @@ +# 0079 - Swift 源码定义的 `@objc` 协议,以及类对 ObjC 协议的遵循 + +- **状态**: Implemented +- **创建日期**: 2026-10-28 +- **最后更新**: 2026-10-28 +- **所属愿景**: 无 +- **关联提案**: [0048-objc-member-selector-recovery](0048-objc-member-selector-recovery.md)(ObjC 成员表:按 selector 把类的 ObjC 方法联结到 Swift 成员,本提案从这里取实现者的签名)、[0078-objc-classes-without-class-objects](0078-objc-classes-without-class-objects.md)(没有 class object 的类的 `class_ro_t`,它们的协议表也从那里读) +- **实现分支 / PR**: `feature/swift-declared-objc-protocols`(已合入 `next`) +- **配套文档**: [SwiftDeclaredObjCProtocols.md](../Internal/SwiftDeclaredObjCProtocols.md) + +## 摘要 + +Swift 源码里定义的 `@objc` 协议在 `dump` 和 `interface` 里都不出现。编译器给这种协议只生成 ObjC 运行时的协议记录(`protocol_t`,登记在 `__objc_protolist`),不在 `__swift5_protos` 里生成 protocol descriptor(`GenMeta.cpp` 的 `emitProtocolDecl` 在 `isObjC()` 分支直接返回),而本库只从 protocol descriptor 认协议。这些协议现在只以两种形式出现:作为类型被引用时的名字,以及 protocol extension 成员组成的 `extension DVTFoundation.DVTTeamCredential { … }`。同一个原因带出第二个缺口:ObjC 协议没有 witness table,`__swift5_proto` 里也就没有遵循记录,所以 Swift 类对任何 ObjC 协议的遵循在 interface 里全部丢失——Swift 定义的协议是这样,`NSCopying`、各种 delegate 这类导入的协议也是这样(`class DVTIconReference: __C.NSObject` 少了 `DVTResourceReference, NSCopying`)。需求由 RuntimeViewer 会话转来,样本是 Xcode 的 DVTFoundation,里面有 11 个这样的协议。本提案从 ObjC 元数据与反射元数据把两者都还原出来。 + +## 方案 + +### 哪些 `@objc` 协议是本镜像定义的 + +- **以 `__swift5_fieldmd` 为准**:`emitProtocolDecl` 在进入 `isObjC()` 分支之前就调用了 `emitFieldDescriptor`,所以本模块定义的每个 `@objc` 协议都有一条 kind 为 `ObjCProtocol` 的 field descriptor,名字是协议的 Swift mangling。DVTFoundation 实测正好 11 条,两个用 `@objc(Name)` 改过名的也在其中。ABI 层要新增 `__swift5_fieldmd` 的整段遍历:本库目前只顺着类型描述符的指针读 field descriptor,而协议没有类型描述符指向它。 +- **不靠 `protocol_t.flags` 的 bit 0(`ProtocolDescriptorFlags::IsSwift`)**:这一位只说明这份记录是哪个编译器生成的,两个方向都会错。 + - 本镜像引用别的模块定义的 Swift `@objc` 协议时,Swift 也会生成一份带这一位的弱定义副本(`GenObjC.cpp` 的 `getObjCProtocolGlobalVars`),只看这一位会把别人的协议当成自己的。 + - ObjC 代码经生成的 `-Swift.h` 头文件引用 Swift 协议时,clang 生成的副本这一位是 0。DVTFoundation 里 DVTNFASupport 定义的 `_TtP13DVTNFASupport24NFAImageDownloadObserver_` 就是这样,引用它的 `NFAImageDownloaderDelegate` 是 ObjC 类。 + - Swift 与 clang 生成的记录符号名不同(Swift 的是 `_PROTOCOL_<名字>`,clang 的是 `_OBJC_PROTOCOL_$_<名字>`),链接时不会合并。一个 Swift 协议若既被 Swift 代码引用、又被 ObjC 代码经 `-Swift.h` 引用,同一镜像的 `__objc_protolist` 里就有两份同名记录,一份这一位是 1,一份是 0。 + - 所以配对与退回路径都只看名字;同名的两份都在时,协议体取这一位为 1 的那份(Swift 自己生成的)。 +- **field descriptor 与 `protocol_t` 的配对**:没改名的按运行时名 `_TtP<模块><名字>_` 配;改过名的按「ObjC 名等于 Swift 名的最后一段」配,DVTFoundation 的两个都是 `@objc(X) protocol X` 这种写法。运行时名与默认的 `_TtP…` 不同,就说明源码写了 `@objc(Name)`,interface 照样打出来。ObjC 名与 Swift 名不同的配不上:照样打出声明,协议体里写一行注释说明找不到它的 ObjC 记录;dump 列出没配上的记录。 +- **镜像没有反射元数据时**(编译时关掉了)退回:运行时名是 `_TtP…` 且模块是本镜像的 Swift 模块之一的,算本镜像定义。这时改过名的协议认不出来。 +- 结果放进 SwiftInspection 的一个按镜像的索引(`SharedCache`,带驱逐组),同时给出「运行时名 → Swift 名」的换算,第二部分与 SwiftLayout 都用它。 + +### 协议声明怎么写 + +- **头部**:`@objc protocol X: A, B`,改过名的加 `@objc(运行时名)`。继承的协议来自 `protocol_t` 的协议表,名字的换算见下文「ObjC 协议名换成 Swift 名」。 +- **要求**:逐条读 `protocol_t` 的四张方法表(required / optional 各分实例与类)、属性表,以及带类名的扩展类型编码(extended method types,例如 `teamNameFor:error:` 是 `@"NSString"32@0:8@"NSString"16^@24`)。 + - 属性的 getter 与 setter selector 归到属性上;有没有 setter 看属性表的 readonly 标记与 setter selector。 + - `objectAtIndexedSubscript:` 这类归到 subscript;`init` 家族的 selector 是初始化器。 + - 类方法打 `static`,optional 的要求打 `@objc optional`。 +- **二进制里没有要求的 Swift 符号**:探针确认,无论 public 还是 internal、开不开 library evolution,编译器都不给 `@objc` 协议的要求生成任何 Swift 符号。和协议有关的 Swift 符号只有 protocol extension 成员、field descriptor、typeref,以及用 key path 引用属性时生成的 key path getter(local 符号,`strip -x` 后就没了)。剥过 local 符号的镜像里只剩导出的 protocol extension 成员。 +- **Swift 签名有两个来源**: + 1. **本镜像里的 Swift 实现者**,签名是精确的。采纳这个协议的 Swift 类(读第二部分的协议表,采纳子协议的也算)有 ObjC 成员表(提案 0048),按 selector 找到联结上的 Swift 成员,照抄它的签名,并打一行注释说明取自哪个实现者。只认符号与 thunk 联结的前两档,不认只按名字的第三档。签名在协议自己的索引里经成员表读取,不去索引实现者的类型定义——索引期不许索引别的定义。 + 2. **只有 selector**:Swift 名照 ClangImporter 的规则从 selector 推出,再用 `@objc(原 selector)` 把 selector 钉住。Swift 拼法可能与源码不同,ObjC 层面的含义不变。 + - 名字移植 importer 的 `omitNeedlessWords`(`lib/Basic/StringExtras.cpp`): + - 在第一段的最后一个介词处拆出基名与第一个参数标签(`splitBaseName`,`instantiateWithOwner:options:` → `instantiate(withOwner:options:)`); + - 按参数与返回值的类型名删掉多余的词(`nameForObject:` 的参数是 `id`,删掉 `Object` 得到 `name(for:)`); + - 初始化器去掉 `With`(`initWithFrame:` → `init(frame:)`); + - `…error:` 与 `…AndReturnError:` 按编译器的 error 约定还原成 `throws`; + - completion handler 保持 closure 形式,不改写成 `async`:importer 两种都给,一条协议要求只能打一种。 + - 再去掉 Swift 在第一个参数标签前插入的 `With`:第一个标签以 `with` 开头、后面还有词时去掉 `with`(`hangPoints(withInput:)` → `hangPoints(input:)`)。这是编译器那条插入规则的逆运算,探针里 4 条只差 `with` 的全部改对;源码本来就写了 `withInput:` 这种标签的会被改成 `input:`,同样由 `@objc(selector)` 钉住。 + - 类型从扩展类型编码换算,也照 importer 的桥接规则:`NSString` → `String`、`NSArray` → `[Any]`、`NSDictionary` → `[AnyHashable : Any]`、`id` → `Any`、`id

` → 协议存在类型、block → closure;Swift 类按 `_TtC` 名 demangle,改过运行时名的 Swift 类经 `SwiftClassObjectIndex` 换回 Swift 名。可空性不知道,一律写 `!`,与 importer 对没有可空性标注的 ObjC 声明的做法相同。编码由本库自己的小解析器读(只覆盖扩展类型编码);类型以 node 构造、经打印器输出,不拼字符串,模块选择器才能生效。 + - 协议体里有这种要求时,开头打一行注释,说明 Swift 名是从 selector 推出来的。 + - 探针(2026-10-28,Swift 6.4.2)的做法:只拿二进制里的事实拼出 ObjC 头文件,交给真正的 ClangImporter(`swift-synthesize-interface`)导入,再和源码原名对比。 + - 编译器自己推导 selector 的 15 条要求,12 条还原出源码原名(其中 `refresh() async throws` 对上的是 importer 另给的 async 版本)。没对上的 3 条都差在 Swift 插入的 `With`:`hangPoints(input:)` 成了 `hangPoints(withInput:)`。 + - 照苹果写法显式写了 selector 的 10 条,5 条对上,包括 `@objc(nameForObject:) func name(for:)`、`@objc(indexOfObject:) func index(of:)`。没对上的有 `@objc(removeObjectAtIndex:) func remove(at:)`(成了 `removeObject(at:)`)、`@objc(stringByAppendingString:) func appending(_:)`(成了 `string(byAppending:)`),以及 `@objc(isEnabled) var enabled`:属性表里记的名字就是 `isEnabled`。 + - 对不上的都由 `@objc(selector)` 钉住,含义不变。 + + DVTFoundation 的两个协议打成这样(实测输出): + + ```swift + @objc protocol DVTActorProtocol { + // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them. + @objc(userVisibleRolesForDeveloperTeamId:) func userVisibleRoles(forDeveloperTeamId: Swift.String!) -> [Any]! + @objc(teamNameFor:error:) func teamName(for: Swift.String!) throws -> Swift.String + @objc(developerTeamIds) var developerTeamIds: [Any]! { + get + } + } + @objc protocol DVTResourceReference: __C.NSObject { + // Taken from the conformer DVTFoundation.DVTIconReference. + @objc var resourceKey: __C.NSCopying { + get + } + } + ``` + + 取自实现者的要求:实现者的成员按 selector 与它的 ObjC 方法联结上,声明照抄那个成员、上下文换成协议;`@objc(selector)` 只在编译器从这个 Swift 名推出的 selector 与实际的不同时才写(按 `ObjCMemberShape` 移植的编译器推导判断),推不出来时照写。 + +- **protocol extension 成员**(现在单独打成 `extension DVTFoundation.DVTTeamCredential { … }`)改作协议的默认实现,打在协议声明后面,与普通 Swift 协议一致。 +- 嵌套在类型里的 `@objc` 协议(SE-0404,少见)打进顶层的 `extension 父类型 { … }`。 + +### 类对 ObjC 协议的遵循 + +- **数据从哪来**:编译器把一个声明写的 ObjC 协议遵循记进它那份类数据的协议表(`GenClass.cpp` 的 `visitConformances` 用 `getLocalConformances(.OnlyExplicit)` 按声明位置取)。同一模块里的 extension 会并进类自己的数据,它写的遵循也记在类的 `class_ro_t` 里(探针确认:这种镜像根本没有 `__objc_catlist`);只有 extension 别的模块的类(ObjC 类,或别的模块的 Swift 类)时才生成 category,遵循记在 category 的协议表里。新的按镜像索引 `ObjCProtocolAdoptionIndex` 读本镜像每个 Swift 类的 `class_ro_t`(没有 class object 的类从提案 0078 的 `SwiftClassWithoutClassObjectIndex` 取)和每个 category 的协议表;`ObjCClassMethodIndex` 与 provider 接缝不改。 +- **interface**:`class_ro_t` 里的协议打进类声明头部、父类之后(`class DVTIconReference: __C.NSObject, DVTFoundation.DVTResourceReference, __C.NSCopying`);每个 category 打成一个 `extension X: P, Q {}`(`extension __C.NSDateFormatter: P {}`)。编译器还会把「非 ObjC 协议继承的 ObjC 协议」记进表里(`getObjCProtocols` 的递归):类有遵循记录的 Swift 协议若是本镜像的、能从它的 requirement signature 判定出继承了那个 ObjC 协议,就去掉不打。diff 与 evolution 的渲染器不打这两样,与 ABI 快照一致。 +- **模型**:类的协议是 `TypeDefinition.objcProtocolNames`,在类的 `index(in:)` 里读;category 的是 indexer 的 `objcCategoryConformances`(`ObjCCategoryConformance`:被 extension 的类、协议名),在 `prepare()` 里收集。 +- **dump**:类的 dump 在头部下加一行 `// ObjC protocols: …`,隐含的协议标注 `(implied by a Swift conformance)`;category 的遵循放进 `protocolConformances` 段,写成 `extension X: P {} // ObjC category at 0x…`。 + +### ObjC 协议名换成 Swift 名 + +两部分共用这一套: + +- `_TtP…_` 按旧式 mangling 解出模块与名字。 +- 本镜像改过名的 Swift 协议查上面的索引。 +- 别的镜像定义、又改过名的 Swift 协议,到依赖闭包里那个镜像的同一种索引里找(与 ObjC 祖先链用同一个闭包)。只有本镜像持有 Swift 生成、却没有声明认领的那份记录,它的名字才去找:clang 生成的记录名字的是 ObjC 协议。只查带反射元数据的镜像(改过名的协议只能经 field descriptor 认出),第一个命中为准,按名字缓存。找不到就按 ObjC 名写;dump 末尾那条「没认领的记录」注释在找到的名字后面写出 Swift 名。改成别的名字的协议(`@objc(KITRenamedObserver) protocol RenamedKitObserver`)在它自己的镜像里也配不上,所以找不到。 +- 导入的 ObjC 协议写成 `__C.`,与编译器的 mangling 一致(`So8NSObject_p`),也与现有输出一致(SymbolTestsCore 的 `protocol ObjCInheritingProtocolTest: __C.NSObject`)。`NSObjectProtocol` 这种 Swift 名由打印时的 type database 按 APINotes 给出,与其它 `__C` 名字一样。 + +### 其余 + +- **dump**:放进现有的 `protocols` 段,按段排与按二进制顺序排两种方式都放。每条要求同时写出 Swift 声明与 ObjC 侧的事实:selector、类型编码、required 还是 optional、联结上的实现者与联结依据(`To` 符号或 thunk 的代码)。段末一行注释列出 Swift 生成、本镜像没有声明认领的记录。 +- **模型**:SwiftDeclaration 新增独立的定义类型 `ObjCProtocolDefinition`(Swift 名、运行时名、是否改过名、继承的协议、要求、默认实现 extension),indexer 新增 `objcProtocolDefinitions` 与 `allObjCProtocolDefinitions`。要求用 `ObjCProtocolRequirementDefinition` 表示(selector、setter selector、实例还是类、required 还是 optional、类型编码、Swift 声明的 node、签名来源:selector 或实现者的 `TypeName`),不伪造符号。不把 `ProtocolDefinition.protocolDescriptor` 改成可选:那会破坏下游源码。 +- **`--exported-only`**:这种协议自己没有符号,判断不了是否导出,按无结论保留。新增无结论 case `ExportStatus.declarationHasNoSymbol`:下游 RuntimeViewer、MachOKitUI、swift-decompiler、MachOViewer 都没有穷举 `ExportStatus` 的 `switch`。 +- **SwiftLayout**:`ObjCProtocolIndex` 在原有的 `_TtP` 名读法之外,并上新索引给出的本镜像协议,存在类型的布局也能认出改过名的与嵌套在类型里的协议;原读法保留,别的模块协议在本镜像的副本、没有反射元数据的镜像仍靠它。 +- **默认开启**,不加 CLI flag。 + +### 不做 + +- ABI snapshot、diff、evolution 暂不收录这两类事实:要改快照格式,记为后续。 +- 不到别的镜像里找协议的实现者。 +- APINotes 的 `SwiftName` 改名不还原,这种导入协议按 ObjC 名写。 +- 同一模块里的 extension 写的遵循,编译器并进类自己的数据,与类声明写的分不出来,都打在类头部;链接器做 category merging 时 category 里的也一样。 +- 隐含的协议只认本镜像的 Swift 协议:类遵循的是别的镜像的 Swift 协议时,它继承的 ObjC 协议照样打出来。 + +### 验证 + +- 测试时现编的 fixture,覆盖:没改名的协议、`@objc(同名)` 与 `@objc(不同名)` 的协议;required 与 optional、实例与类、只读与可写属性、subscript、初始化器、`throws`、block 参数;继承 `NSObjectProtocol` 与另一个 `@objc` 协议;嵌套在类型里的协议;protocol extension 成员;在类声明里与在 extension 里采纳协议的 Swift 实现者;采纳 `NSCopying` 的类;遵循一个继承了 `NSCopying` 的 Swift 协议的类(隐含协议);extension Foundation 的类采纳协议(category);没有实现者的协议;引用另一个模块定义的 Swift `@objc` 协议,含改成自身名字的(跨镜像查找)与改成别的名字的(证明副本不会被当成本镜像定义的);装着改名协议与嵌套协议存在类型的结构体(SwiftLayout,对照运行时字段偏移);关掉反射元数据与 `strip -x` 两个变体。 +- 命名规则的单元测试以探针里真实 ClangImporter 的输出为准:同一批 selector 与类型,移植的规则要给出与 importer 相同的 Swift 名。 +- SymbolTestsCore 已有三个 Swift `@objc` 协议,快照随之更新。`ObjCClassWrappers.swift` 里说 `@objc protocol` 会生成 Swift protocol descriptor 的注释是错的,同批改正。 +- DVTFoundation 手工核对:11 个协议都打出来;`DVTIconReference` 的头部有 `DVTResourceReference, NSCopying`;只是被引用的 `NFAImageDownloadObserver`(DVTNFASupport 定义)不打成声明。 +- 渲染 A/B:差异只应是新增的协议声明、类头部与 extension 上的 ObjC 遵循,以及挪到协议后面的 protocol extension,不应有消失的声明。 + +### 落地步骤 + +每一步都能单独编译通过、带上自己的测试,完成后提交并推送功能分支。测试在 Ultra 上跑。 + +1. **找出本镜像定义的 `@objc` 协议**:ABI 层遍历 `__swift5_fieldmd`;SwiftInspection 的按镜像索引,含配对、退回路径与「运行时名 → Swift 名」的换算;读 `protocol_t` 的方法表、属性表与扩展类型编码。MachOObjCSection 的 `extendedMethodTypes(in:)` 只返回表里第一条,本库按下标读整张表。测试用测试时现编的 fixture,带一个引用另一个模块 Swift `@objc` 协议的镜像,以及关掉反射元数据的变体。(已完成,`02b3d5f5`) +2. **从 selector 推出 Swift 声明**:移植 importer 的命名规则、去掉 Swift 插入的 `With`、类型编码解析与桥接,构造声明的 node。测试以探针里真实 ClangImporter 的输出为准。(已完成,`ae6b78f0`、`e56ad3ff`) +3. **声明模型与索引**:`ObjCProtocolDefinition` 与要求的类型、indexer 的集合、实现者的签名、protocol extension 改作默认实现、导出状态。(已完成,`62362503`、`bf1e6d0a`) +4. **打印**:interface 的协议声明,以及 dump 的 `protocols` 段。(已完成,`bfecf4bf`) +5. **类对 ObjC 协议的遵循**:读 `class_ro_t` 与 category 的协议表,打在类声明头部、`extension X: P {}` 与 dump 里。(已完成,`07c6153f`) +6. **SwiftLayout 的 `ObjCProtocolIndex`** 改用新索引。(已完成,`86568e48`) +7. **验证**:SymbolTestsCore 的快照、全量测试、渲染 A/B、DVTFoundation 手工核对。(已完成,快照 `7e42d054`;结果见实现说明「验证」) +8. **文档**:实现说明、模块文档、`CLAUDE.md` 的模块清单、术语表、演进账本、插件 skill、文档索引。(已完成) + +### 后续项 + +- RuntimeViewer 采用:列出并打印新的定义类型。 +- ABI 快照、diff、evolution 收录这两类事实(要改快照格式)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-28 | Created as Draft,轻量档 | RuntimeViewer 会话转来的需求:interface 与 dump 完全不输出 Swift 源码定义的 `@objc` 协议,样本是 DVTFoundation。 | +| 2026-10-28 | 类对 ObjC 协议的遵循放进同一份提案 | 用户决定。两部分读同一份 ObjC 协议表、用同一套 ObjC 名到 Swift 名的换算,而遵循的影响面比协议声明还大。 | +| 2026-10-28 | 只有 selector 的要求:Swift 名照 ClangImporter 的规则从 selector 推出,再用 `@objc(原 selector)` 钉住 | 用户决定。selector 钉住之后 ObjC 层面的含义不变,名字又读起来像 Swift。最初选的「Swift 名直接照抄 selector」被这个替代;「协议体里只写 ObjC 声明的注释」没有采用。类型照 importer 桥接、可空性未知写 `!`,是随之采用的假设。 | +| 2026-10-28 | 本镜像定义了哪些协议以 `__swift5_fieldmd` 为准,`protocol_t` 的 IsSwift 位只用来挑候选 | 本镜像引用别的模块的 Swift `@objc` 协议时,也有一份带 IsSwift 位的副本。DVTFoundation 实测两种来源都是 11 条,改过名的两个都在 fieldmd 里。 | +| 2026-10-28 | 新增独立的定义类型,不动 `ProtocolDefinition` | 把 `protocolDescriptor` 改成可选会破坏下游源码;新类型是纯增量,RuntimeViewer 跟进展示即可。 | +| 2026-10-28 | IsSwift 位连挑候选也不用,配对与退回路径只看名字;同名记录有两份时协议体取这一位为 1 的那份 | 核实时发现 clang 生成的副本这一位是 0(DVTFoundation 里的 `_TtP13DVTNFASupport24NFAImageDownloadObserver_`)。Swift 与 clang 的记录符号名不同(`_PROTOCOL_<名字>` 与 `_OBJC_PROTOCOL_$_<名字>`),不会合并,所以混合语言镜像里同一个 Swift 协议可能有两份同名记录,一份 1、一份 0。前面那条「IsSwift 位只用来挑候选」的决定由此作废。这一行起初把原因写成「链接器只留一份同名弱定义」,RuntimeViewer 会话用 `nm` 与 clang 源码指出不成立,已更正。 | +| 2026-10-28 | 名字移植 importer 的完整 `omitNeedlessWords`,包括依赖类型名的删词 | 用户要求先用探针验证。探针显示 `@objc(nameForObject:) func name(for:)` 这种苹果写法要靠按类型名删词才能还原(参数是 `id`,删掉 `Object`);起初的方案只移植 `splitBaseName`,由此改正。探针也确认「只剩 selector」与访问级别无关:所有 Swift `@objc` 协议的要求都没有 Swift 符号。 | +| 2026-10-28 | 用户批准,开始实现;去掉 Swift 插入的 `With` 这一步要加 | 用户决定。 | +| 2026-10-28 | 拆出落地步骤 | 方案原来没有能逐步验证的步骤。 | +| 2026-10-28 | 扩展类型编码按下标读整张表,类型编码用本库自己的小解析器 | MachOObjCSection 0.8.201 的 `extendedMethodTypes(in:)` 只返回第一条;swift-objc-dump 的 `ObjCTypeDecodeKit` 不是对外的 product,只能经 `ObjCDump` 间接 import。两处都在本库里解决,不为此给别的仓库发版。 | +| 2026-10-28 | 导入的 ObjC 协议在 `__C` 里保留 ObjC 名,不加 `Protocol` 后缀(偏离方案) | 编译器的 mangling 就是 ObjC 名(`So8NSObject_p`),现有输出也这样写(`__C.NSObject`),结构比较才对得上;开着 type database 时,打印按 APINotes 换成 `NSObjectProtocol`,自己加后缀反而让它查不到。原方案的写法要靠「同名类存在」判断,还依赖依赖闭包,不稳定。 | +| 2026-10-28 | 实现者的签名经按 Swift 全名索引的成员表找,声明的上下文换成协议;是否写 `@objc(selector)` 按编译器从成员名推导 selector 的规则判断 | 按运行时名索引的成员表是给 ObjC 类用的,它要求 thunk 代码引用的成员属于 `__C.<运行时名>`,strip 过的镜像里 Swift 类的成员因此一个都联结不上(只有 `To` 符号那一档能用,测试正是在 strip 变体上红的)。成员表对 witness 一律不给显式 selector 的判定,因为它的 selector 继承自协议;在协议声明里这条要求本身就是声明处,没有继承,所以改用推导判断。签名来源的类名改为 `TypeName`,经 resolver 打印,模块选择器才生效。 | +| 2026-10-28 | 新增 `ExportStatus.declarationHasNoSymbol` | 方案留待落地时定。下游四个仓库都没有穷举 `ExportStatus` 的 `switch`,新增 case 是安全的;单用 `imageHasNoExportInformation` 会把「镜像没有导出信息」与「声明本来就没有符号」混在一起。 | +| 2026-10-28 | 嵌套在类型里的 `@objc` 协议纳入 fixture 与测试 | 方案写了要支持,fixture 里原来没有这种协议。探针确认它的运行时名是 `_TtPC…`,旧的 `_TtP` 两段式解析认不出,正好是 SwiftLayout 一步要补的。 | +| 2026-10-28 | 同一模块里的 extension 写的遵循打在类头部;category 的遵循不限于本镜像的类,一律打成 `extension X: P {}`(偏离方案) | 探针发现编译器把同一模块里的 extension 并进类自己的数据,只有 extension 别的模块的类才生成 category。所以方案里「category 里的协议打成 `extension X: P {}`」实际只发生在 extension 别的模块的类时,而这正是方案原意(extension 里写的遵循打成 extension),范围相应改为所有 category。为此新增 `ObjCCategoryConformance` 与 indexer 的 `objcCategoryConformances`;`TypeDefinition` 只记 `class_ro_t` 的那份。 | +| 2026-10-28 | 类与 category 的协议由新的 `ObjCProtocolAdoptionIndex` 直接读,不改 `ObjCClassMethodIndex` 与 provider 接缝(偏离方案) | 找实现者要「谁采纳了协议 P」的反查,打印要「类 X 采纳了哪些」,两种查法都在这个索引里一次建好;provider 接缝是 RuntimeViewer 用的公开 API,不动它下游就不用跟着改。读协议表本身很便宜。 | +| 2026-10-28 | 隐含的协议按遵循记录判断:只认本镜像的 Swift 协议,category 的目标若是 ObjC 类,按遵循记录里的 ObjC 类名对上 | 别的镜像的 Swift 协议要读它的 requirement signature,得加载那个镜像,代价与收益不成比例;没有 `@objc` 成员的 extension 本来就不生成 category(探针确认),category 里出现隐含协议的情况很少。 | +| 2026-10-28 | 别的模块改过名的 Swift 协议只对「Swift 生成、本镜像不认领」的记录名去依赖闭包里找,只查带反射元数据的镜像,锁外建索引、锁内按名字缓存 | clang 生成的记录名字的就是 ObjC 协议,没必要找;改过名的协议只能经 field descriptor 认出,跳过没有 fieldmd 的镜像能免掉系统缓存里绝大多数镜像的读取。建索引要 demangle,按项目规则不能在解析器的锁里做。 | +| 2026-10-28 | `@objc(selector)` 与声明写在同一行 | 本库其它 `@objc(…)` 都这样打;方案示例里分成两行只是排版。 | +| 2026-10-28 | dump 的要求经 dump 的 resolver 打印,类型不加糖 | dump 的其它符号都不加糖(`Swift.Optional<…>`),这里一致地写成 `Swift.ImplicitlyUnwrappedOptional<…>`。 | +| 2026-10-28 | 新套件不加进 CI 的过滤名单 | 与最近几个 ObjC 方向的功能一致(它们的套件也没进名单);新套件测试时现编 fixture,SymbolTestsCore 的两个快照套件已在 CI 里,覆盖输出的变化。 | +| 2026-10-29 | 私有协议的声明头与 dump 的名字只打裸名,不带私有鉴别器 | RuntimeViewer 验收时发现,AppKit 的私有协议 `TextShadowViewControllerDelegate` 打成了 `@objc protocol (TextShadowViewControllerDelegate in _05EA0EB8E781FFE22747790FC22932B1) {`。Swift 协议的声明头在正常打印路径上只打裸名,只有 ABI diff 为了区分只差鉴别器的两次构建才显示它;这里原先无条件显示,与之不一致,而这种协议本来就不进 diff。用户决定改成只打裸名。fixture 原先没有私有的 `@objc` 协议,所以测试没发现,这次补上一个。 | +| 2026-10-28 | 实现完成,待用户看过后收尾 | 全量测试 2648 个通过;渲染 A/B 64 对差异逐行归类全部在预期内,没有删掉或改动任何已有声明;DVTFoundation 手工核对通过。 | +| 2026-10-28 | 改为 Implemented,编号 0079 | 用户看过后收尾,合入 `next`。配套文档写了实现说明 [SwiftDeclaredObjCProtocols.md](../Internal/SwiftDeclaredObjCProtocols.md);不需要单独的使用指南:功能默认开启、没有新的 CLI flag,`dump` 与 `interface` 输出的变化写进了插件 skill。新术语 Swift-declared `@objc` protocol、category conformance、implied ObjC protocol、unclaimed record 已登记进术语表。上文「后续项」的两条留待以后。 | diff --git a/Documentations/Evolutions/0080-objc-evolution-interface.md b/Documentations/Evolutions/0080-objc-evolution-interface.md new file mode 100644 index 000000000..1cbb125aa --- /dev/null +++ b/Documentations/Evolutions/0080-objc-evolution-interface.md @@ -0,0 +1,44 @@ +# 0080 - `objc evolution --interface`:带演进标注的合并 ObjC 头文件 + +- **状态**: Implemented +- **创建日期**: 2026-10-28 +- **最后更新**: 2026-10-29 +- **关联提案**: [0013-swift-evolution-interface-builder](0013-swift-evolution-interface-builder.md)(Swift 一侧的同一种视图);MachOObjCSection 一侧的库提案 [0015-objc-evolution-interface](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/main/Documentations/Evolutions/0015-objc-evolution-interface.md)(合并与标注的渲染,随 0.8.204 发布) +- **实现分支 / PR**: `feature/objc-evolution-interface`(worktree `.worktrees/MachOSwiftSection-ObjCEvolutionInterface`,自 `next` 分出) + +## 摘要 + +`swift-section objc evolution` 现在只输出逐条变化的报告(每个声明一条存在位图加事件列表)和 JSON。读 AppKit 这种有几千个类的框架时,很难从中看出全貌。Swift 一侧早有 `evolution --interface`:把各版本合并成一份 interface,在有变化的声明上标出位图和事件。本提案给 ObjC 加上同一种视图:把 N 个版本的头文件按声明合并成一份,外观沿用 `objc dump` 的渲染,在类、协议、分类以及它们的方法、属性、ivar 上标出在哪一版加入、删除或修改,并可选地补上 `API_AVAILABLE` / `API_OBSOLETED`。CLI 和集成测试都做。 + +## 方案 + +- **分工**:合并和标注的渲染放在 MachOObjCSection。ObjC 的声明模型、头文件渲染器和现有的演进报告都在那里,由负责那个仓库的会话实现并发版,那边另有一份提案。本库只做接线:CLI 选项、SwiftSectionKit 的请求、集成测试和文档。 +- **声明从哪来**:每个版本用现有的头文件渲染器(`objc dump` 和 RuntimeViewer 用的那一套)渲染声明,再按快照里的 identity key(`class:NSView`、`method:-initWithFrame:`、`property:-title`、`ivar:_style`、`adopts:…`)对齐,这样每条标注都和 `objc evolution` 报告里的一条 lineage 一一对应。「modified」沿用快照的 payload 比较,显示时给出两个版本各自渲染出的那一行。每个版本渲染完就释放它的索引器,不让 N 个索引器同时留在内存里:51 个版本的 AppKit 放不下。 +- **标注**:照 Swift 的写法。文件头写出版本轴,以及位图每一位对应的版本。有变化的声明在行尾加 `// [●○●] added in X`、`removed in X` 或 `modified in X: 旧 → 新`;删掉的声明留在合并结果里原来的位置。加上 `--emit-available` 时再补一行可用性:只有引入的写 `API_AVAILABLE`,引入后又删掉的写 `API_OBSOLETED`(SDK 里这个宏带引入、废弃、移除三个版本)。一条标注表达不了的生命周期(删了又加回、只被修改过)不写这一行,位图注释照旧都在。平台从各输入的 `LC_BUILD_VERSION` 推出,也可以用 `--platform` 指定。 +- **CLI**:`swift-section objc evolution --interface [--emit-available [--platform ]]`。`--interface` 与 `--json`、`--summary-only` 互斥。`--interface` 下每个输入都必须是二进制或 cache,传入快照 JSON 会报错退出:快照里没有渲染头文件所需的完整声明,这一点和 Swift 的 `--interface` 相同。`--fail-on-breaking` 照常生效。 +- **集成测试**:在 `ObjCAPIEvolutionTests.swift` 里新加一组套件,版本轴与已有的报告格式套件相同(三版本轴,以及 51 个归档 cache),输出 `-ObjCEvolutionInterface.h`;归档套件带上 `macOS` 的可用性标注。报告格式的那组保留,Swift 一侧两种视图也都有。 +- **同批更新**:`ObjCCommandLine.md`(及 `_zh`)、agent 插件里的 `swift-section-cli` skill 与 `references/objc.md`、演进账本。SwiftSectionKit 和 CLI 各加测试:选项校验、快照输入被拒,以及用 fixture 二进制完整跑通一次。 +- **依赖**:MachOObjCSection 发出带这个渲染器的版本后,本库抬依赖下限;在那之前用本地兄弟依赖开发。 + +## 落地步骤 + +1. [x] **选项与校验**:SwiftSectionKit 的 `ObjCAPIEvolutionRequest` 加带标注头文件这种输出,可用性分「不写 / 从 `LC_BUILD_VERSION` 推断 / 指定平台」三种,平台按 ObjC 可用性宏的写法(`macos`、`ios`、`macCatalyst` …);`--interface` 下的快照输入报错。CLI 加 `--interface`、`--emit-available`、`--platform` 及互斥校验,错误照现有措辞翻译成用法错误。两侧各加测试。这一步还没有渲染器,`--interface` 校验通过后报「渲染器尚未接入」。 +2. [x] **接上渲染**:对接 MachOObjCSection 的渲染接口(先用本地兄弟依赖),去掉第 1 步的占位;用 fixture 二进制完整跑通一次。 +3. [x] **集成测试**:`ObjCAPIEvolutionTests.swift` 新加一组套件,输出 `-ObjCEvolutionInterface.h`。 +4. [x] **文档**:`ObjCCommandLine.md`(及 `_zh`)、agent 插件的 `swift-section-cli` skill 与 `references/objc.md`、演进账本。 +5. [x] **依赖**:MachOObjCSection 发版后抬依赖下限,用远端依赖重新验证。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-28 | Created as Draft | 用户要的是在头文件上标出演进,而不是逐条报告;刚加的报告格式集成测试不是想要的形式 | +| 2026-10-28 | 声明沿用 `objc dump` 的渲染,不用快照里的签名行 | 用户选定:外观和 `objc dump`、RuntimeViewer 一致,有参数名、ivar 块和分组;代价是 `--interface` 只接受二进制或 cache | +| 2026-10-28 | CLI 和集成测试都做 | 用户选定,与 Swift 一侧一致:集成测试走的就是 CLI 背后的同一个接口 | +| 2026-10-28 | 用户批准,开始实现 | 状态改为 Accepted;精简提案原本没有落地步骤,按方案拆成五步,第 1 步不依赖 MachOObjCSection 的渲染器,先做 | +| 2026-10-28 | 第 1 步:平台推断失败用 ObjC 自己的错误类型 `ObjCAvailabilityPlatformInferenceError`;`--platform` 不校验拼写 | Swift 一侧的错误讲的是 `@available`,ObjC 要讲可用性宏,平台名也不同(`macos` 而不是 `macOS`,还多出 `driverkit`);不校验拼写与 Swift 一侧一致,宏以后加平台也不用改 CLI | +| 2026-10-28 | 第 2 步:接 MachOObjCSection 的 `ObjCEvolutionInterfaceBuilder`(`addVersion` 逐个交版本、`build(availabilityPlatform:)` 出头文件与 `ObjCAPIEvolution`);写文件时补上打印会加的换行 | 接口由那边的会话设计,逐个交版本、交完即可释放索引器,正好满足内存要求;补换行让文件和打印出来的字节完全相同,与 lineage 报告写文件的做法一致 | +| 2026-10-28 | 第 3 步:新套件单独成组(`ObjCEvolutionInterfaceTestSuite`),版本轴直接引用报告格式套件的;归档套件传 `macos` 平台 | 与 Swift 一侧「报告一组、带标注接口一组」的分法一致;归档套件的标签都是版本号,宏能写出来 | +| 2026-10-28 | 第 4 步:文档里写明 cache 输入要传 `--labels`、`--platform` 用宏的拼法、从第一版就在后来删掉的声明不写宏 | 三处都是读输出时最容易误会的地方:不传标签时每个 cache 的默认标签都是同一个文件名;`macOS` 这类 Swift 拼法不会报错,只会写出错的宏 | +| 2026-10-29 | 第 5 步:依赖下限抬到 MachOObjCSection 0.8.204,跳过 0.8.203 | 用 Xcode 26.6 跑全量测试时发现,上游新代码里一个局部常量和它初始化闭包里调用的方法同名,Swift 6.3 的类型检查器因此崩溃;Xcode 27.2(Swift 6.4)能编过,所以上游自测没有发现。0.8.203 在修复之前就打了 tag,上游保留它、另发了修好的 0.8.204 | +| 2026-10-29 | 实现完成,用户验收后落地为 0080 | 用法写在 `ObjCCommandLine.md`(及 `_zh`)「带标注的头文件」一节,渲染器的设计记在 MachOObjCSection 的提案 0015,本库只是接线,不另写使用指南或实现说明;没有新术语,术语表里 union interface 一条补上了 ObjC 一侧 | diff --git a/Documentations/Evolutions/0081-evolution-unobservable-presence.md b/Documentations/Evolutions/0081-evolution-unobservable-presence.md new file mode 100644 index 000000000..2b7bc06f5 --- /dev/null +++ b/Documentations/Evolutions/0081-evolution-unobservable-presence.md @@ -0,0 +1,94 @@ +# 0081 - evolution 与 diff 区分「不存在」和「看不见」 + +- **状态**: Implemented +- **创建日期**: 2026-10-24 +- **最后更新**: 2026-10-29 +- **所属愿景**: 无 +- **关联提案**: [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`),2026-10-29 合入 `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` 从 8 升到 9(起草时是 7 升到 8,落地前 8 已被 0077 占用),旧快照照已有的 `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`「查不到就是全程都在、从未变化」的约定因此仍然成立。成员只在它自己看不见、而容器在那个版本观测在场,并且那段区段有话可说(推断存在,或让边界变得不确定)时才因此收录;只因容器看不见而看不见的成员由容器的 lineage 交代,与增删容器的成员一样,diff 里也只列容器。 +- `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 一致、轴上没有被剥版本时 JSON 不出现新字段、v9 编解码,以及两个文本报告。`UnobservablePresenceFixture` 现编三版 dylib、中间一版 `strip -x`,在快照这一层验证判据与导出判定,并端到端验证联合接口的每一种注解。`EvolutionMarkingTests` 覆盖新符号、新短语、短语顺序、图例与 `@available` 的边界规则,`InterfaceAnnotationStyleTests` 覆盖着色。实数据用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution,与同一命令在 `next` 上的输出逐行对比。 + +**文档**:同批更新 `ABIEvolutionDesign.md`、`ABIDiffDesignAndLimitations.md` 第 6 节、`Modules/SwiftInterface.md`,在术语表登记 unobservable,并更新 `AgentPlugins/swift-section` 的 skill(evolution 输出多了两个符号和两种短语)。 + +**落地步骤**(每一步单独构建通过、相关测试通过后提交): + +1. (已完成)快照记下两件事,格式版本升到 9:`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),开始实现 | 方案与全部假设照单通过 | +| 2026-10-24 | 判据读符号表条目的 `N_EXT` 位(新增 `NlistProtocol.isLocal`),不沿用 `isExternal` | 实现中发现本库的 `isExternal` 只指未定义的导入,符号表那两条收集路径收的是全部已定义符号、导出的也在内;照字面用它,被剥的版本也会因为导出符号而被判成「有 local Swift 符号」,fixture 的测试当场抓到。`ExportFacts` 注释里「只收 local 符号」的旧说法顺带更正 | +| 2026-10-24 | 成员导出判定的组合规则收进 `SymbolIndexStore.isExportedIncludingDerivedSymbols(names:in:)` | 快照要的判定和 interface 的 `// not exported` 注释是同一条规则(任一入口导出即为导出、查不到就不下结论);printer 原来自己写了一份,现在两边都调这一处,不会走样 | +| 2026-10-24 | 测试改用专门的三版本 fixture(`UnobservablePresenceFixture`,中间一版 `strip -x`),在快照这一层验证判据 | 方案原想用 `ObjCImplementationFixture` 的被剥变体单测 `SymbolIndexStore`;改在冻结结果上测能同时覆盖判据与导出判定,而且第 3 步的端到端测试要的正是这样三个版本,一个 fixture 两用 | +| 2026-10-24 | 第 1 步完成(In Progress) | 定向测试通过:`UnobservablePresenceTests` 3 个、`ABISnapshotDocumentTests` 与 `ABIDifferAlgorithmTests` 共 14 个、`ExportedSymbolFactsTests` 5 个,以及受 printer 改动影响的导出注释与 `--exported-only` 套件,原始退出码 0。真实数据核对:此前导出的 nlist 里,12.7 与 15.0 的 SwiftUI 各有 149,409 与 167,325 个 local `_$s` 符号,13.0 与 14.8 一个都没有 | +| 2026-10-24 | 规则集中在 `UnobservablePresence.swift`,evolution 与 diff 共用 | 「看不见」的判定(`MemberRecord` / `ContainerSnapshot.needsLocalSymbolsToBeSeen`)、逐版本观测与按两侧推断(`PresenceObservation`、`PresenceResolution`)只写一份,两版本时两条路径不可能给出不同结论 | +| 2026-10-24 | 模型另加两个可选字段 `ABIEvolution.versionIndicesWithoutLocalSwiftSymbols` 与 `MemberLineage.latestSignature`,以及报告共用的 `UnobservedSpan` 和版本区间的标签函数 | 方案没写到。图例与报告要知道哪些版本没有 local Swift 符号;只为看不见的版本才收录、没有事件的 lineage 没有地方带签名,报告只能印出 mangled key。新字段都是可选的,值为空时不编码,所以没有被剥版本的轴,`evolution --json` 输出逐字节不变(测试钉住) | +| 2026-10-24 | diff 把看不见的东西放进 `ABIDiff.unobservableDeclarations`;看不见的容器连同它的成员一起列出 | 两版本的 evolution 会给容器和每个成员各留一条「看不见」的 lineage,diff 列出同样的集合,一致性测试据此比对。列表为空时同样不编码 | +| 2026-10-24 | 报告的 Transitions 段把区间事件计入首次观测到它的那一步,下面另起一行注明其中几条发生在哪两个版本之间 | 与兼容性判定的归属一致,又不让人误以为变化就发生在那一步 | +| 2026-10-24 | 第 2 步完成 | SwiftDiffing 108 个测试全过(新增 19 个),原始退出码 0;变异检验:去掉「两侧都在则推断存在」、让导出成员也算看不见,新测试有 7 个变红(退出码 1),还原后转绿。SwiftSectionKitTests 65 个、SwiftSectionCommandTests 106 个、SwiftInterfaceTests 317 个全过 | +| 2026-10-24 | `@available` 遇到任何一个「看不见」的版本就不发,推断存在照常算存在 | 方案只写了区间事件;实现时发现挨着轴端的看不见版本同样会让边界不成立(`[●◌]` 会被读成 `obsoleted:`),按同一原则一并排除 | +| 2026-10-24 | 着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain | 方案没写到。原规则把不含 `removed in` / `modified in` 的注释一律当新增,`removed between` 会被染成新增 | +| 2026-10-24 | 第 3 步完成 | 定向测试 `UnobservablePresenceTests`(新增 5 个端到端用例)、`EvolutionMarkingTests`(新增 7 个)、`InterfaceAnnotationStyleTests`(新增 1 个)全过;SwiftInterfaceTests 329 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个、SwiftDiffingTests 108 个全过,原始退出码 0。变异检验:去掉 `@available` 的边界判断、把着色默认值改回新增,3 个测试变红,还原后转绿。CLI 冒烟:对现编的三版 dylib(第二版 `strip -x`)跑 `evolution --interface --emit-available`、文本报告与 `diff`,输出与设计一致 | +| 2026-10-25 | 实数据核对后收紧两处:只因容器看不见、或只在两侧都不在的区段看不见的成员,不再因此收录,diff 里看不见的容器也只列容器本身;两侧都不在的区段不写短语,也不拦 `@available` | 第一次重跑 51 版 SwiftUI 时,新输出多了 21,805 条 `not observable in …`、`@available` 少了约 2.2 万行,抽样发现两类:容器自己已有注解(类型在 13.0 出现、15.0 迁去 SwiftUICore,或 extension 整体看不见),它的成员却跟着各标一次,与增删容器的成员一贯不标注的规则不一致;以及 12.4 就删掉的成员在 13.0–14.8 两侧都不在,什么都说不出,却写了短语、丢了本来成立的 `obsoleted:`。收紧后另有 169 条只剩位图、没有短语的成员注解随之消失 | +| 2026-10-25 | 第 4 步完成,实数据结果 | 同一命令(release 版 CLI,`--dyld-shared-cache -p …/SwiftUI --interface --emit-available`,51 份归档 cache)在 `next` 与本分支上各跑一次。`next` 的输出与 0073 之前生成的那份只差 0073 修好的 20 行。本分支对 `next`:208,706 行代码逐行相同;42,517 条注解不变,30,229 条只有 13.0–14.8 那几位变了,没有一条观测到的位置被改,也没有注解丢失;新增 151 条注解,全部是此前被容器的假缺口挡住的跨段增删。两端都在、中间缺席的 5,189 条里 5,097 条(98.2%)整段变成推断存在;`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条(类型的真实删除、丢了 discriminator 的私有类型,以及几条公开 `static let` 在被剥前后由不同的访问器撑起,属方案列出的范围外情形);`removed in 13.0` 从 18,293 降到 1,700、`added in 15.0` 从 19,596 降到 4,472,其余换成 2,084 / 2,065 / 17 条 `removed` / `added` / `modified between 12.7 and 15.0` 与 17,684 条 `not observable in …`(多是容器在 13.0 出现或 15.0 搬走、成员自己说不清何时增删的情形)。`@available` 行从 66,711 降到 48,214,去掉的都是边界不确定的。峰值内存占用(peak memory footprint)4.46 GB 对 `next` 的 4.41 GB,多 58 MB(约 1.3%,新增的导出判定与逐版本状态);RSS 两边都是 12.8 GB,多是只读映射的 cache 页。这台 28 核机器上 release 版用时 216 秒 | +| 2026-10-25 | 实现完成,待合并 | 全量 `swift test --skip IntegrationTests`(收紧前的第 3 步代码)2,578 个测试全过,原始退出码 0;收紧后重跑受影响的 SwiftDiffingTests 110 个、SwiftInterfaceTests 330 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个,全过。每次收紧都做了变异检验(改回原规则,对应的新测试变红,还原后转绿);最终提交上再跑一次全量,2,581 个测试全过,原始退出码 0。没有跑渲染 A/B:单版本的 `dump` / `interface` 只动了 printer 里导出判定的一处等价改写,相关的导出注释与 `--exported-only` 套件都过了。不另写使用指南或实现说明:规则与取舍写在 `ABIEvolutionDesign.md` 第六批与本提案;新术语 unobservable 已登记 | +| 2026-10-29 | 合入 `next`,取号 0081,状态改 Implemented | 用户决定先把本分支合进 `next`,再在合并后的 `next` 上做多 image 演进,两者改的是同一批文件。把 `next` 合进分支时解了四处冲突:快照格式版本(`next` 上 0077 已占用 8,本案改为 9)、两份文档索引、skill 里的格式说明(写明 8 和 9 都随 0.25.0 发布,8 只在开发分支上存在过)。`next` 后来加的 `AbbreviatedIdentifierScanTests` 抓到本案代码里的 `lhs` / `rhs`,改名为 `left` / `right`。合并结果在 JHs-Mac-Studio-Ultra 上验证(Xcode 26.6,远端依赖:MachOObjCSection 0.8.204、MachOKit 0.55.100、MachOKitExtensions 1.3.0、swift-demangling 0.7.2、swift-semantic-string 0.5.0;fixture 用 0.24.0 发版审计时编的那份,此后 fixture 源码只改过注释):全量 `swift test --skip IntegrationTests` 2,700 个测试、514 个套件,只有这条扫描失败;改名后重跑扫描与 SwiftDiffingTests,112 个测试全过,原始退出码 0 | +| 2026-10-29 | 不另写使用指南或实现说明,不新增术语 | 规则与取舍已写在 `ABIEvolutionDesign.md` 第六批与本提案;unobservable 已在 10-25 登记进术语表 | diff --git a/Documentations/Evolutions/0082-image-group-evolution.md b/Documentations/Evolutions/0082-image-group-evolution.md new file mode 100644 index 000000000..06aca8253 --- /dev/null +++ b/Documentations/Evolutions/0082-image-group-evolution.md @@ -0,0 +1,65 @@ +# 0082 - 一个版本由一组 image 组成的演进 + +- **状态**: Implemented +- **创建日期**: 2026-10-29 +- **最后更新**: 2026-10-29 +- **所属愿景**: 无 +- **关联提案**: [0013](0013-swift-evolution-interface-builder.md)(evolution 联合接口)、[0081](0081-evolution-unobservable-presence.md)(看不见的版本)、MachOObjCSection 的 `0016-objc-evolution-image-groups`(ObjC 侧,随 MachOObjCSection 0.8.205 发布) +- **实现分支 / PR**: `feature/image-group-evolution`(worktree `.worktrees/MachOSwiftSection-ImageGroupEvolution`,基于 `next` e1221a02),2026-10-29 合入 `next` +- **配套文档**: [ABIEvolutionDesign.md](../Internal/ABIEvolutionDesign.md) 第七批、[Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md)(`InterfaceVersionGroupUnit`) + +## 摘要 + +evolution 一个版本只读一个 image。Apple 拆框架时声明会在 image 之间搬家:AppKit 的东西挪进 UIFoundation、CollectionViewCore、CoreAutoLayout,macOS 15 起 SwiftUI 的大批类型挪进 SwiftUICore(带 `@_originallyDefinedIn(module: "SwiftUI")`,mangled name 不变)。单 image 的演进把搬走的报成 removed、搬来的报成 added,其实它们没有消失。本案让一个版本由一组 image(image group)组成:组里的声明合成一个 API 面来比较,组内搬家不再报成增删,而是单独记成 moved(`> moved in 15.0: SwiftUI → SwiftUICore`);lineage 报告、JSON 与联合接口都支持。顺带修掉一个单 image 就有的缺口:SwiftUI 二进制里给 SwiftUICore 类型加的成员,mangling 里没有 extension 上下文,索引器只在类型自己的 image 里收这类成员,结果 SwiftUI 的 dump、interface 与快照里它们整个消失(macOS 26.7 的 SwiftUI interface 里就没有 `Text.accessibilityTextContentType(_:)`)。ObjC 侧的同一功能由 MachOObjCSection 的会话实现,两边约定同一套模型与文案。 + +## 方案 + +**第一步:索引漏收的成员**(已完成,单独提交)。`SwiftDeclarationIndexer.indexExtensions()` 另外收「类型不在本 image、mangling 里也没有 extension 上下文」的成员(allocator、函数、计算属性、下标、静态存储属性;实例存储属性除外),当作该类型的 extension 成员,进 `extension <类型>`。三条判据同时成立才收:上下文是「模块 → struct、class、enum 一路下来」;那个模块是本 image 自己的类型或协议所在的 Swift 模块(`__C` 除外);类型与协议的名字不在本 image 的定义里(用的是定义收成员时用的同一个名字)。单 image 的 interface 从此能看到这些成员(dump 不经这条路径,不变);ABI 快照的格式版本从 9 升到 10,旧基线会把它们全报成新增。 + +这样收到的不只是拆分出去的类型的成员:同一模块里没有类型描述符的类型(编译器把只当命名空间用的内部 enum 的描述符删掉了)的成员、定义按名字收不到的成员,原先同样被丢掉,现在也一并出现在 `extension <类型>` 里。它们都是本模块真实的成员,只是先前看不见。渲染 A/B 在 Ultra 上跑,差异逐类核对后写进本提案。 + +**第二步:SwiftDiffing 的 image 组**(已完成)。 + +- 输入:每个版本一个有序的单 image 快照列表,主 image 在前:`ABIImageSnapshot(imageName:snapshot:)`;入口 `ABIEvolutionBuilder().evolution(ofImageGroups: [[ABIImageSnapshot]], versions: [ABIVersionDescriptor])`。单 image 快照与它的文档格式不变,image 名由调用方给出。组为空就当这个版本什么都没有。 +- 合并:types、protocols、globals 直接拼接,同 key 的只比较组里第一个 image 的,其余走现有的 key collision 报出;四个 extension 桶里同 key 的容器合成一个,成员按组顺序拼接。组里定义了的类型,它的普通 extension 容器(没有协议、没有 `where`、不是 retroactive)并回类型本体:单 image 时这些成员本来就算在类型本体里,跨 image 才分出去,不并回就会在搬家那一版报成「类型里删掉、extension 里新增」。 +- 看不见的版本:组里任一 image 没有 local Swift 符号,这个版本就按没有 local Swift 符号处理,宁可多标看不见,不误报删除。 +- 搬家:一个声明在跳变两侧都观测到在场、两侧所在的 image 集合不同,就记一条 `ImageMove(versionIndex:oldImageNames:newImageNames:earliestVersionIndex:)`;中间隔着看不见的版本时比较两侧最近的观测,`earliestVersionIndex` 标出起点。成员只在旧集合 ≠ 新集合、并且 (旧, 新) 与所属容器的不同时才记,整个类型搬走时不给每个成员都记一遍。只有搬家的 lineage 也要收录;没有事件的成员 lineage 用 0081 加的 `latestSignature` 带签名。搬家不进兼容性判定:旧 image 有没有 re-export 新 image,快照里没有这个事实,只报不判。 +- 模型只增不改:`ABIVersionDescriptor.imageNames`、`ContainerLineage.imageMoves`、`MemberLineage.imageMoves`、`ABIKeyCollision.droppedImageNames`,值为空时不编码,单 image 的 `evolution --json` 逐字节不变。 +- 报告:头部那行下面紧跟 `Image group:` 与每个 image 的在场位图(按在轴上首次出现的顺序),`--summary-only` 也带;跳变摘要多一项 `N moved`;事件行与搬家行按版本合并排序,同一版本里事件在前:`> moved in 15.0: SwiftUI → SwiftUICore`、`> moved between 12.7 and 15.0: …`,集合用 ` + ` 连接;collision 警告写成 `dropped: <签名> (SwiftUICore)`。 + +**第三步:联合接口的 image 组**(已完成)。`SwiftEvolutionInterfaceImage(imageName:machO:)` 与 `AnySwiftEvolutionInterfaceBuilder(…, imageGroups:labels:…)`。内部一个版本由几个单 image 的渲染单元组成,每个声明交给索引它的那个 image 的打印器:容器按定义的身份找,成员跟着所属容器走,全局声明按 image 逐个列。并回类型本体的 extension 成员在类型体里渲染,与 evolution 的口径一致。注解多一种短语 `moved in 15.0: SwiftUI → SwiftUICore`,与其他短语按版本顺序用 ` · ` 连接;图例在位图位置那行之后加 `// Image group:` 与每个 image 的位图,放在 `@available` 说明之前。单 image 的构造与输出不变。 + +**第四步:集成测试与文档**(已完成)。`MachOImageName` 加 UIFoundation、CollectionViewCore、CoreAutoLayout;`ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests` 加 `cacheImageNames`(默认只有主 image)和逐版本的 image 组,主 image 在场才上轴,其余在场才加入;Swift 侧新增 SwiftUI + SwiftUICore 的报告与联合接口套件(默认三版本轴与 51 版归档轴);ObjC 的报告与联合接口套件(`ObjCAPIEvolutionTestSuite`、`ObjCEvolutionInterfaceTestSuite`)各加 AppKit + UIFoundation + CollectionViewCore + CoreAutoLayout 与 SwiftUI + SwiftUICore 两组,同样分默认三版本轴与归档轴,MachOObjCSection 的依赖下限随之抬到 0.8.205。产物文件名用组里的 image 名以 `+` 连接。文档同批更新 `ABIEvolutionDesign.md`、`Modules/SwiftInterface.md`、术语表(image group)与演进账本,agent 插件的 skill 只改快照格式那一段。 + +**没问就定下的假设**: + +- 命令行这次不接,`evolution` 不加选项。 +- 两版本的 `ABIDiffer.diff` 不加 image 组入口。 +- 组里定义了的类型,它的普通 extension 容器不论 mangling 带不带 extension 上下文都并回类型本体;这只影响成员列在哪个容器下,不影响身份。 + +**测试**:第一步用现编的两 image fixture(`ProbeCore` 定义带 `@_originallyDefinedIn(module: "Probe")` 的类型,`Probe` 给它加成员),验证单 image 索引收到这些成员、带 extension 上下文的跨模块成员照旧;第二步用手工快照覆盖合并规则、并回、搬家(容器、成员、只跟着容器走的不记、隔着看不见的版本)、collision 的 image 名、单 image JSON 不变与两个文本报告;第三步用同一 fixture 的多个版本做联合接口端到端,并在 `EvolutionMarkingTests` 覆盖新短语与图例。测试一律在 JHs-Mac-Studio-Ultra 上跑。 + +**后续项**: + +- 命令行入口:`evolution` 接收一组 image(这次按假设不接,有需要再提)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-29 | Created as Draft,用户批准开工(Accepted) | 用户要 ObjC 演进的集成套件支持多个 image:AppKit 的东西搬进 UIFoundation、CollectionViewCore,SwiftUI 的搬进 SwiftUICore,只看一个 image 发现不了;库里的快照与演进模型都只认一个版本一个 image,用户决定直接实现 | +| 2026-10-29 | ObjC 侧交给 MachOObjCSection 的会话,本库做 Swift 侧与集成测试 | 用户的分工。两边约定同一套输入形状、搬家记录与文案;ObjC 侧另有 protocol 副本去重、同名 category 合并两条规则 | +| 2026-10-29 | 先把 `feature/evolution-unobservable-presence` 合进 `next` 再切本分支 | 一轮提问定案。两者改的是同一批文件(演进模型、builder、报告、接口注解),那个分支 10-25 起就是「实现完成,待合并」;已作为 0081 落地 | +| 2026-10-29 | 报告、JSON 与联合接口都做,命令行不接 | 一轮提问定案 | +| 2026-10-29 | 单 image 漏收成员这次一起修,作为第一步单独提交 | 核实时发现 SwiftUI 给 SwiftUICore 类型加的、没有 extension 上下文的成员在单 image 索引里整个消失(宿主 26.7 的 SwiftUI interface 里没有 `Text.accessibilityTextContentType(_:)`),不修的话 image 组里它们照样在 15.0 报成 removed;用户选择这次一起修 | +| 2026-10-29 | 成员搬家的签名放在 lineage 的 `latestSignature` 上,`ImageMove` 只记版本与两侧的 image;Swift 侧多一个 `earliestVersionIndex` | 0081 已经给没有事件的成员 lineage 加了 `latestSignature`;隔着看不见的版本时,搬家只能落在两次观测之间。ObjC 侧照同样的分工改了 | +| 2026-10-29 | 第一步的判据收紧:只认上下文是「模块 → struct、class、enum 一路下来」的成员,并排除本 image 定义的协议名 | 第一版只按类型名排除。全量测试里 SymbolTestsCore 的 interface 快照抓到误收:协议 `BasicDefaultProtocol` 的两个默认实现被列了两遍,带约束 extension 里三个嵌套类型的存储属性访问器成了 extension 成员。这些符号的上下文与本 image 的定义对不上名字,但它们都不属于别的 image | +| 2026-10-29 | 第一到第三步完成(Draft → Accepted → In Progress) | 在 JHs-Mac-Studio-Ultra 上验证(Xcode 26.6,远端依赖:MachOObjCSection 0.8.204、MachOKit 0.55.100、MachOKitExtensions 1.3.0、swift-demangling 0.7.2、swift-semantic-string 0.5.0):复现测试在修复前 3 处失败、修复后通过;全量 `swift test --skip IntegrationTests` 2,729 个测试、518 个套件全部通过,原始退出码 0;IntegrationTests 编译通过,按项目规定不运行 | +| 2026-10-29 | ObjC 的两个集成套件等 MachOObjCSection 发版后再接 | ObjC 侧的 API 只在 MachOObjCSection 本地 `next`(118e8db)上,那边的提案还在等用户审。IntegrationTests 随全量一起编译,Ultra 与 CI 都按远端版本解析依赖,提前接会让 `next` 编不过 | +| 2026-10-29 | 第一步再加一条判据:成员所在类型的模块必须是本 image 自己的类型或协议所在的 Swift 模块(`__C` 除外) | 第一次渲染 A/B(基线 `next` e1221a02,候选 f97ba3b2;归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器、进程内)所有 dump 一致,interface 在 SwiftUI、SwiftUICore、Combine 有差异。其中一部分是别的模块的成员:标准库内联进来的代码(`Swift.Array._endMutation()`、`Swift.String._copying(_:)`)、ClangImporter 给导入的 C 枚举合成的 `init?(rawValue:)`(`__C.UIButtonType`)、SwiftUI 里带进来的 `Foundation` 与 `Combine` 成员。它们不是本模块的 API,判据把它们排除;回归测试在 fixture 里调用 `ComparisonResult(rawValue:)`,修复前变红 | +| 2026-10-29 | 本模块里定义收不到的成员照样收进 `extension <类型>` | 同一次 A/B 里另一部分是本模块的成员:没有类型描述符的内部命名空间(`SwiftUI.Accessibility`、`Combine.CombineFeatures` 的静态成员)与定义按名字收不到的成员(如 iOS 15.5 SwiftUI 里 `ConicGradient` 的一个内部初始化器)。它们在单 image 里与拆分出去的类型的成员分不开,原先同样被丢掉;收进来是更完整的接口,不是误报 | +| 2026-10-29 | 第二次渲染 A/B 通过核对 | 基线 `next` e1221a02,候选 a0a7dc27,JHs-Mac-Studio-Ultra,Xcode 26.6,两侧共用一份 `Package.resolved`。96 对里 77 对逐字节一致,所有 dump 一致;差异只在 SwiftUI、SwiftUICore 与 Combine 的 interface,全部只增不减(每对删除 0 行),新出现的 extension 全在本 image 自己的模块上,别的模块的 extension 块两侧逐字节一致。规模:macOS 26.6 cache 的 SwiftUI +1,222 行、52 个新 extension(`Text.accessibilityTextContentType(_:)` 等,基线里没有),SwiftUICore +102 行、23 个;iOS 26.5 模拟器的 SwiftUI +1,336 行、69 个;iOS 15.5 模拟器(拆分之前)的 SwiftUI +191 行、35 个,都是没有类型描述符的内部命名空间之类本模块原先丢掉的成员;Combine 各场景 +3 行,即 `Combine.CombineFeatures` 的一个静态成员 | +| 2026-10-29 | 搬家按集合比较;被丢记录的文案收成 `ABIKeyCollision.droppedRecordDescriptions` 一处 | MachOObjCSection 的会话对照两边实现核对出两处不一致:联合接口末尾的 collision 警告没写 image 名,而报告写了;搬家按数组比较,调用方在两个版本里把同一组 image 换个顺序列,同时在两个 image 里的声明会被报成搬家。两条回归测试在修复前变红;两版本 diff 的报告也改用同一处文案。随后又按 ObjC 侧的做法补了一处:image 名与签名数量对不上时(只有手工构造或改过的 JSON 才会这样)只列签名,不再被 `zip` 悄悄截掉多出来的签名 | +| 2026-10-29 | 合入 `next`,取号 0082,状态改 Implemented | 先在本地合进常驻检出给用户看(3c4356cf;跨端核对的修复之后又合一次,1ed65d32),用户看过后正式收尾。最终代码 fa33331a(之后只改文档)在 JHs-Mac-Studio-Ultra 上全量 `swift test --skip IntegrationTests`:2,734 个测试、518 个套件全过,原始退出码 0(Xcode 26.6;远端依赖 MachOObjCSection 0.8.204、MachOKit 0.55.100、MachOKitExtensions 1.3.0、swift-demangling 0.7.2、swift-semantic-string 0.5.0)。渲染 A/B 沿用 a0a7dc27 上的第二次结果:此后的三处修复只改 evolution 的搬家判定与 collision 文案,单版本的 `dump` / `interface` 不经过它们。ObjC 的两个集成套件与命令行入口记为后续项 | +| 2026-10-29 | 不另写使用指南;术语已登记 | 实现说明在 `ABIEvolutionDesign.md` 第七批与 `Modules/SwiftInterface.md`。没有面向调用方的公开文档讲 evolution 的库 API(`SwiftSectionKit.md` 只讲命令对应的请求,这次没接命令行),所以不另写使用指南。image group 与 move 已登记进术语表 | +| 2026-10-29 | 接上 ObjC 的两个集成套件,MachOObjCSection 的下限抬到 0.8.205 | MachOObjCSection 0.8.205(它的提案 0016)发布了 image 组的 API。`ObjCAPIEvolutionTestSuite` 与 `ObjCEvolutionInterfaceTestSuite` 各加 AppKit + UIFoundation + CollectionViewCore + CoreAutoLayout、SwiftUI + SwiftUICore 两组,默认三版本轴与归档轴各一套;按 `objc` 子命令的方式建 indexer 的几行收成一个共用函数,单 image 的套件也改用它。在 JHs-Mac-Studio-Ultra 上只把 MachOObjCSection 解析到 0.8.205、其余依赖不变,全量 2,734 个测试、518 个套件全过,原始退出码 0;IntegrationTests 编译通过(按项目规定不运行)。后续项只剩命令行入口 | diff --git a/Documentations/Evolutions/0083-exported-only-marking-mode.md b/Documentations/Evolutions/0083-exported-only-marking-mode.md new file mode 100644 index 000000000..b306cc576 --- /dev/null +++ b/Documentations/Evolutions/0083-exported-only-marking-mode.md @@ -0,0 +1,46 @@ +# 0083 - 导出过滤进入标记模式,C 导入类型不再判成未导出 + +- **状态**: Implemented +- **创建日期**: 2026-10-30 +- **最后更新**: 2026-10-31 +- **关联提案**: [0016](0016-exported-only-interface.md)(导出过滤)、[0024](0024-exported-declaration-flag.md)(类型 / 协议的 `exportStatus`)、[0056](0056-visibility-regions.md)(标记模式);RuntimeViewer 的 `draft-exported-declarations-filter`(使用方) +- **实现分支 / PR**: `feature/exported-only-marking-mode`(worktree `.worktrees/MachOSwiftSection-ExportedOnlyMarkingMode`,基于 `next` e4b5595c),2026-10-31 合入 `next` + +## 摘要 + +RuntimeViewer 要加「只看导出的声明」:侧栏按 `exportStatus` 筛掉未导出的类型与协议,内容区、批量导出与 Find 删掉导出类型里未导出的成员。内容区打开 `printExportedDeclarationsOnly` 就行,Find 却不行:它的语料用标记模式打印——全量打一遍,受选项控制的内容标上可见条件,搜索时按当前选项投影——而 0056 把导出过滤明确留在了标记模式之外,开着这个选项 Find 照样搜得到未导出的成员。本提案让标记模式覆盖导出过滤。 + +排查中还发现一处裁决错误。C 导入类型(`__C.CGSize` 一类)的描述符是每个用到它的模块各自生成的一份副本:编译器对 Clang 声明一律给 `PublicNonUnique` 链接(`swift/lib/SIL/IR/SIL.cpp` 的 `getDeclLinkage`),副本从不进导出表,所以它的 `exportStatus` 读成 `.notExported`。可本镜像给它写的扩展可以是公开 API(SwiftUI 的 `extension CGSize: VectorArithmetic`)。RuntimeViewer 开着 `showCImportedTypes`,并把这类扩展并进 C 类型的条目,按类型筛会把它们一起藏掉;打印器的 `ExportFilterScope` 也会把这些类型收进「未导出」集合,开了 `--show-c-imported-types` 的 `--exported-only` 因此很可能删掉这些扩展(读代码推断,由第 1 步的测试确认)。 + +## 方案 + +1. **C 导入类型不裁决**(已完成)。`ExportStatus` 加一个不给结论的 case `declarationIsCImported`:`ExportStatus.resolve` 遇到 `isCImportedContextDescriptor` 为真(模块是 `__C` 或 `__C_Synthesized`)的描述符直接返回它,`isExported` 为 `nil`,`isDefinitelyNotExported` 为 `false`。两个 `resolve` 入口因此改为接收描述符本身(原先只收 offset),类型与协议走同一条规则。于是 `ExportFilterScope` 不再收这些类型,它们的扩展照常按成员裁决,`--exported-only --show-c-imported-types` 也不再删 C 类型本身,ExportedOnlyInterfaceFiltering.md「已知降级」里的那一条随之撤掉。 + - 复现测试:现场编译的 fixture(当时在 `ExportedOnlyLibraryEvolutionFixtureTests` 里,第 2 步挪成共享的 `ExportedOnlyFixture`)加了 `CGPoint` 的公开扩展与对 `PublicContract` 的 conformance,`cImportedTypeIsNotRuledOnAndItsPublicExtensionsAreKept` 以 `showCImportedTypes: true` 打印 `--exported-only`。修复前它的四条断言全红:`CGPoint` 判成未导出,类型本身、conformance 扩展与公开扩展一起被删,扩展那一腿的推断成立。`ExportStatusTests.cImportedTypeIsNotRuledOn` 在 SymbolTestsCore 唯一的 C 导入类型 `CMTimeFlags`(描述符是 private external)上钉住新 case。 +2. **标记模式覆盖导出过滤**(已完成)。`SwiftVisibilityOption` 加 `printExportedDeclarationsOnly`(原始值 `swift.printExportedDeclarationsOnly`),`isVisibilityOptionEnabled` 认它。标记模式下,过滤器原本不输出的每一处——类型、协议、扩展三个打印入口,被清空的普通扩展,成员循环,存储属性的预筛,以及 `printRoot` 的两个全局块与 ObjC category conformance 块——改为照常输出,标上 `.disabled("swift.printExportedDeclarationsOnly")`。判定沿用同一组 `isExcludedByExportFilter`,标记模式下不看开关本身的取值(`evaluatesExportFilter`),每处都问 `exportFilterVisibility(excluded:)` 要「输出 / 略过 / 标记」;已经打好的 `SemanticString` 用 `visible(under:)`(即 `markAtoms(from:visibleUnder:)`)补标。`ExportFilterScope` 照旧要由宿主装上,`printRoot()` 在标记模式下也装。conformance 扩展被清空后印成 `{}`、相邻声明之间不多出空行,交给 swift-semantic-string 的容器把成员的条件带到分隔符上,与其他选项一样;容器管不到的只有 `DeclarationBlock` 闭合 `}` 前的换行(见决策日志),由打印器补:类型与扩展 body 里嵌套定义之后的声明全被过滤时,标记模式下去掉那部分最后的换行(`bodyAfterNestedDefinitions(of:content:)`)。普通模式的输出逐字节不变。 + - 测试:现场编译的模块挪进 `MachOTestingSupport` 成为共享的 `ExportedOnlyFixture`,另加五个定义:嵌套类型保留、之后的声明全被过滤的类型(`Holder`)、存储属性是 internal 的类型(`FieldHolder`)、无 case 的枚举(`Namespace`)、别的模块类型的扩展(`extension Int`),以及什么都不剩的 `Hidden`。`VisibilityRegionProjectionTests` 的每个打印器都装同一个 scope,选项组合里多了这个选项:SymbolTestsCore 进程内全关、全开与每个选项单开单关(24 组),从文件打印仍只变动布局选项;`ExportedOnlyFixture` 逐个定义按开关开、关投影(`exportedOnlyFixturePrintsProjectToTheFilterBothWays`),整份 `printRoot()` 也投影一次(`exportedOnlyFixtureRootPrintProjectsToTheFilterBothWays`)。两个探针确认测试会红:标记模式退回不管导出过滤时三条投影测试都红;不去掉 body 末尾的换行时,上述四种形态投影到开关打开都印成 `}}`。 +3. **宿主须知**(已完成,随第 2 步提交)写进 `marksOptionalContent` 与 `installExportFilterScope` 的文档注释:标记打印同样要先装 scope,否则扩展这一腿全部保留。 + +不做: + +- 成员不加模型上的导出标志。宿主按每个类型或协议自己的 `exportStatus` 筛就够;导出类型里未导出的成员由打印器删,RuntimeViewer 的成员搜索读的是投影。(起草时的理由是「类型或协议没导出,它的成员与嵌套类型必然也没导出」,按有效访问级别推得;实现后发现系统框架的导出表由导出清单决定、不跟访问级别走,这个前提不成立,但结论不受影响,见决策日志。) +- `printExportStatus`(`// not exported` 标注)、dump 路径、ObjC 一侧都不动。 + +兼容性:给 `ExportStatus` 加 case 会让宿主里穷举的 `switch` 编译不过;RuntimeViewer、MachOKitUI、MachOViewer、swift-decompiler 目前都没有用它,0024 选枚举时也为新增结局留了位置。`SwiftVisibilityOption` 加 case 同理,这四个仓库都没有穷举它:RuntimeViewer 只经 `isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)` 投影,会自动认出新选项。`--exported-only` 的说明本来就写着「没有导出证据的一律保留」,C 类型落进这一条,flag 文案与 agent 插件 skill 不用改。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-30 | Created as Draft | RuntimeViewer 要过滤未导出的类型与成员,Find 依赖的标记模式不覆盖导出过滤;排查中发现 C 导入类型被判成未导出,会连带藏掉本镜像给它写的公开扩展。用户批准分两份提案推进:本库一份,RuntimeViewer 一份。 | +| 2026-10-30 | 成员级的导出判断不下沉到模型 | 类型或协议没导出时,它的成员与嵌套类型必然没导出(编译器按所在类型限制成员的有效访问级别)。还需要成员级判断的只剩导出类型内部、别的模块类型的扩展与全局声明,这些都由打印器处理,RuntimeViewer 读投影即可。 | +| 2026-10-30 | C 导入类型在裁决源头改为不给结论,不在扩展那一腿特判 | 错在裁决本身:描述符副本的导出状态说明不了类型能否被外部使用。改在源头,宿主的侧栏、过滤范围与 `exportStatus` 的其他读者一起正确。 | +| 2026-10-30 | Draft → Accepted | 用户批准,开始实现。 | +| 2026-10-30 | Accepted → In Progress;新 case 定名 `declarationIsCImported` | 实现在 `feature/exported-only-marking-mode`。暂名 `cImportedDeclaration` 改成与同枚举的 `declarationHasNoSymbol` 同一句式(主语 + 谓语),读作「这个声明是 C 导入的」,`exportStatus == .declarationIsCImported` 在调用处读得通。 | +| 2026-10-30 | 协议描述符也走 C 导入检查 | 规则针对的是描述符而不是种类:Clang 的协议在 Swift 里没有协议描述符,这条检查在协议上不会命中,但两个入口共用一条规则,以后出现例外也不会漏。代价是每个协议多读一次上下文链。 | +| 2026-10-30 | `DeclarationBlock` 闭合换行由打印器补,不改 swift-semantic-string | 方案原以为分隔符全交给容器即可。`DeclarationBlock` 是例外:它按全量打印的 body 最后一个字节决定补不补闭合换行,swift-semantic-string 的设计记录把这列为已知限制。别的选项只控制注释,从不改变 body 的最后一个字节;导出过滤会删掉整段声明,body 留着嵌套类型、之后的声明全被过滤时,投影到开关打开就印成 `}}`。在容器里修要给条件加取反、发新版再抬依赖,超出本提案范围;打印器知道哪些声明被过滤,在标记模式下去掉那部分最后的换行,交给块自己补一个条件为「body 任一部分可见」的换行,各种投影下都对。 | +| 2026-10-30 | `printRoot` 的全局块与 ObjC category conformance 块一并标记 | 方案列的是打印器的入口,但原则是「过滤器原本不输出的每一处」。这两处也会删内容,不标就会让 `printRoot()` 的标记打印投影出错。逐个定义打印的 RuntimeViewer 用不到,但 `printRoot` 的契约要和逐个定义的一致。 | +| 2026-10-30 | 现场编译的模块挪进 `MachOTestingSupport` | 投影测试与原来的过滤测试要用同一份模块,照 `ModuleSelectorFixture` 的样子做成共享的 `ExportedOnlyFixture`,每个进程只编一次。 | +| 2026-10-30 | 实现完成,待用户看过后收尾 | 三步都已提交。验证(JHs-Mac-Studio-Ultra):全量 2,738 个测试、518 个套件只红 `ThunkOnlyObjCMemberTests` 4 条,`next` 快照在同一工具链下同样红、换 Xcode 26.6 则绿,是现场编译 fixture 随编译器漂移的既有问题;Xcode 26.6 下编译通过、相关 9 个套件全过;临时探针在本机 dyld cache 的 Combine、SwiftUICore、AppKit 上逐个定义比对标记打印的投影,848 / 14,086 / 2,879 个定义全部一致。普通打印的路径在构造上逐字节不变、SymbolTestsCore 的 interface 快照通过,不算大重构,未跑渲染 A/B。文档:不另写使用指南或实现说明,ExportedOnlyInterfaceFiltering.md 加了「C 导入类型不裁决」与「标记模式」两节,术语表的 marking mode 与 exported-only 过滤两条已更新、没有新术语,演进账本按日期占位,节号落地时取。 | +| 2026-10-31 | 「类型没导出则嵌套类型必然没导出」不成立;成员不下沉到模型的结论不变 | RuntimeViewer 接入时在 Foundation 碰到 `LocalePreferences` 没导出、它嵌套的 `LocalePreferences.ICUSymbolsAndStrings` 却导出了(类型描述符、元数据访问器与元数据都在导出表里)。swift-foundation 源码里两者都是 `package`,苹果构建系统框架时按导出清单决定导出什么,与访问级别无关。结论仍成立:每个类型与协议带的是它自己的 `exportStatus`,宿主按它筛、打印器也按它裁决,没有哪里依赖「随外层」。 | +| 2026-10-31 | 嵌套定义区域契约在这里写明一个例外,不改标记方式 | 同一例子下,标记模式的 `marksNestedDefinitions` 契约不成立:父定义被过滤、整段带着「开关关着才可见」,从中取出的导出子定义比它单独打印多了这个条件。父定义投影到开关打开时必须整段不可见,子定义单独打印又必须可见,同一段原子带不了两种条件;要在取出区域时去掉祖先加的条件,得改 swift-semantic-string 的区域编码,超出本提案。所以在 `marksNestedDefinitions` 的文档里写明:宿主对「自己没被过滤、外层被过滤」的嵌套定义单独打印——RuntimeViewer 已经这样做。`ExportedOnlyFixture` 用链接器的 `-unexported_symbol` 造出同样的形态(`UnexportedParent.ExportedNested`),契约测试把这个区域按例外严格检查;去掉例外判定时它报的正是 RuntimeViewer 那一处。普通打印下这个导出的嵌套类型随外层一起被 `--exported-only` 删掉,是 0016 起就有的行为,记入 ExportedOnlyInterfaceFiltering.md 的已知降级。 | +| 2026-10-31 | 合入 `next`,取号 0083,状态改 Implemented | 先在本地合进常驻检出给用户看(ad95cacd;嵌套定义区域契约的例外之后又合一次,3323c163),用户看过后正式收尾。最终代码在 JHs-Mac-Studio-Ultra 上验证:与 opaque 层号的修复(ProjectEvolutionLog 第 118 节)一起合进本地 `next`(d20ba205)后,全量 `swift test --skip IntegrationTests` 2,743 个测试、519 个套件,只红 `ThunkOnlyObjCMemberTests` 4 条,原始退出码 1,与 `next` 基线 e4b5595c 相同,Xcode 26.6 下这 4 条是绿的;合并结果(09684869)用 Xcode 26.6(Swift 6.3.3)连同测试目标编译通过,原始退出码 0。RuntimeViewer 接入后核对:打开 `printExportedDeclarationsOnly` 时,3,996 个 Swift 条目的标记打印投影与内容区直接打印逐字一致,Find 只在开关关着时搜得到未导出的成员。没有未做完的项。文档:不另写使用指南或实现说明(ExportedOnlyInterfaceFiltering.md 的两节已覆盖),没有新术语 | diff --git a/Documentations/Evolutions/0084-comment-structure.md b/Documentations/Evolutions/0084-comment-structure.md new file mode 100644 index 000000000..1eb9ae5f1 --- /dev/null +++ b/Documentations/Evolutions/0084-comment-structure.md @@ -0,0 +1,234 @@ +# 0084 - 注释结构标记:打印器给每条注释标出种类和各段角色 + +- **状态**: Implemented +- **创建日期**: 2026-10-31 +- **最后更新**: 2026-10-31 +- **所属愿景**: 无 +- **关联提案**: [0068-nested-definition-regions](0068-nested-definition-regions.md) 与 [0056-visibility-regions](0056-visibility-regions.md)(同一手法:标记写在原子的 `identifier` 里,冻结后分离成一张表);RuntimeViewer 的 `draft-source-editor-comment-annotations`(使用方:SourceEditor 面板把注释画成标签,字段偏移树与枚举布局可折叠);swift-semantic-string 0.6.0 新增的注释区域组件(载体);MachOObjCSection 的同名开关(ObjC 一侧,同一套约定) +- **实现分支 / PR**: `feature/comment-structure`(worktree `.worktrees/MachOSwiftSection-CommentStructure`,基于 `next` 849a0b21),2026-10-31 合入 `next`;swift-semantic-string 的注释区域组件随它的 0.6.0 发布 +- **配套文档**: [术语表](../Glossary.md)的「comment structure」条目;[`Internal/Modules/SwiftInterface.md`](../Internal/Modules/SwiftInterface.md) 的「注释结构标记」一段 + +## 摘要 + +RuntimeViewer 要在 SourceEditor 面板里把 interface 的注释画成圆角标签(不显示 `// `、`/* */` 和标点,标签名与数值分色),把字段偏移树做成可折叠的大纲,把枚举布局的摘要和逐 case 说明拆成标签并可折叠。用户在 RuntimeViewer 会话里定了:注释的结构由生成器输出,RuntimeViewer 不解析注释文本。今天做不到,因为每条注释在 `SemanticString` 里只是一个 `.comment` 原子,枚举逐 case 的说明甚至是一个多行原子,种类、段、树的层级都没有留下。本提案给 `SwiftDeclarationPrintConfiguration` 加一个默认关的开关 `marksCommentStructure`:打开时,打印器把输出的每一条注释包进 swift-semantic-string 新增的注释区域(`AnnotationRegion`),标出它的种类(本库在 `AnnotationRegion.Kind` 上扩展的一组常量)和每一段的角色(marker、label、value……),字段偏移树与枚举布局用区域的嵌套表达层级;关着时输出与今天逐原子相同。 + +## 方案 + +### 改动位置 + +- **swift-semantic-string**(另一个仓库,由它的会话设计与实现,0.6.0 发布,见下文「依赖」):`AnnotationRegion`(带一个 kind 的区域)、`AnnotationSegment`(带一个角色的段)、`AnnotatedAtom`(「不打标记时的一个原子」拆成几片打印,分离时并回一个 span)。标记写在原子的 `identifier` 上,不改文本;`separatingAnnotationRegions()` 分离出干净文本和一张表(区域的 kind、UTF-8 范围、深度、直接外层区域,段的角色、范围与所在区域)。 +- **MachOSwiftSection**: + - `SwiftDeclarationPrintConfiguration`(`SwiftDeclarationPrintConfiguration.swift:149` 起,与 `marksOptionalContent`、`marksNestedDefinitions` 并列)加 `public var marksCommentStructure: Bool = false`。 + - `DeclarationRenderConfiguration`(`DeclarationRenderConfiguration.swift:54`)加一个 package 级的同名属性,只由打印器在 `renderModelFields`(`SwiftDeclarationPrinter+Headers.swift:392`)里设置。 + - 在 `AnnotationRegion.Kind` 上扩展 Swift 的种类(公开),新增 `StructuredComment`(package,一条注释的种类与段),都放在 `Sources/Output/SwiftDeclarationRendering/`。 + - interface 路径上全部注释输出点改为经 `StructuredComment` 输出,逐处见下表「出处」一列。 + - `EnumLayoutCalculator.LayoutResult.summaryDescription`(`EnumLayoutCalculator.swift:295`)改为由策略名和一组事实拼出,文字不变,标记时用同一组事实分段。 + - `bodyAfterNestedDefinitions`(`SwiftDeclarationPrinter+VisibilityRegions.swift:78`)判断 body 末尾的换行时改为认 `BreakLine` 原子,理由见「依赖」。 +- **不动**:dump 的输出(`SwiftDump` 的各个 Dumper、`DumpRequest`);diff 与 evolution 渲染器自己的注释(`EvolutionMarking.swift`);CLI 的选项与输出;开关关着时的全部输出。 + +### 开关与契约 + +1. **关着**:dump 与 interface 的输出与今天逐原子相同——文本、原子、span、identifier 都不变,一个原子都不多拆。 +2. **打开**:把打印结果冻结,用 `separatingAnnotationRegions()` 分离出注释表之后,得到的冻结串与关着时完全相同——文本、span、identifier 逐个相等。为了标出段,一条注释会拆成几个 `.comment` 原子,但拆开的片都在一个 `AnnotatedAtom` 里,分离时并回原来的一个 span;装了 transformer 的注释不拆。RuntimeViewer 能接受的底线更宽:文本与每个字节的语义类型、identifier 相同,span 边界可以不同。万一 swift-semantic-string 最终不提供 `AnnotatedAtom`,契约退到这条底线。 +3. **不漏标**:interface 路径上每一个 `.comment` 字节都落在某个注释区域里。测试用这一条找漏掉的输出点。 +4. **与另外两种标记组合**:与 `marksOptionalContent` 一起打开时,按任一配置投影后再分离,得到的注释表与「用该配置打印、只开本开关」得到的相同;与 `marksNestedDefinitions` 一起打开时,嵌套定义那段切出、去缩进后分离出的注释表,与单独打印它得到的相同。 + +### 种类 + +种类是 `AnnotationRegion.Kind` 的静态成员,原始字符串与成员名相同;`note` 由 swift-semantic-string 自带,其余由本库扩展。清单以 RuntimeViewer 转来的起点清单为底,按实际输出补全: + +| kind | 例 | 出处 | +|---|---|---| +| `memberAddress` | `// Address: 0x135DC`、`// Address (getter): 0x135DC`、`// Address (destructor): 0x…` | `SemanticComponents.swift:30` 的 `AddressComment`,用在 `SwiftDeclarationPrinter.swift:752`、`:755`、`:803`、`:806`、`:853`、`:899`、`:929` | +| `vtableOffset` | `// VTable offset: 12`、`// VTable offset (setter): 13` | `SemanticComponents.swift:57`(`SwiftDeclarationPrinter.swift:850`、`:896`、`:926`);存储属性的访问器走 `DeclarationRenderConfiguration.swift:266`(`SwiftDeclarationPrinter+Headers.swift:490`) | +| `pwtOffset` | `// PWT offset: 0x18` | `SemanticComponents.swift:7` 前缀为 `PWT offset` 时(协议成员);`SwiftDeclarationPrinter.swift:465`(被剥掉符号的协议需求) | +| `fieldOffset` | `// Field offset: 0x8` | `DeclarationRenderConfiguration.swift:213`(两个布局后端的存储字段);`SemanticComponents.swift:7` 前缀为 `Field offset` 时;`SwiftDeclarationPrinter+ObjCImplementation.swift:15`(`@objc @implementation` 的 ivar) | +| `fieldOffsetUnknown` | `// Field offset: unknown (generic parameter not substituted)` | `DeclarationRenderConfiguration.swift:229` | +| `fieldLayoutNode` | `// │ ├── _countAndFlagsBits (Swift.UInt64): 0x8` | `DeclarationRenderConfiguration.swift:239`,两棵树的递归在 `StaticFieldLayoutBackend.swift:189` 与 `RuntimeFieldLayoutBackend.swift:250` | +| `typeLayout` | `// Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647)`;进程内路径上元组类型的字段是一个多行块 | `DeclarationRenderConfiguration.swift:352`(文件路径)、`MetadataWrapper+Dump.swift:9`(进程内路径) | +| `typeLayoutElement` | 元组块里一个元素的 `// Type: …` 与 `// Layout: (…)` 两行 | `MetadataWrapper+Dump.swift:15` | +| `enumLayoutSummary` | `/* Tagged Multi-Payload (tag bytes after the payload area) — cases: 3 (2 payload + 1 empty); tag values used: 3; tag bits: 8; tag region: offsets 24..<25 (8 bits); leftover extra inhabitants for an outer enum: 253 */` | `DeclarationRenderConfiguration.swift:332` | +| `enumLayoutCase` | `/* Enum Layout */` 加这个 case 的整个说明块 | `StaticFieldLayoutBackend.swift:225`、`RuntimeFieldLayoutBackend.swift:178`,说明块是 `DeclarationRenderConfiguration.swift:308` | +| `enumLayoutCaseHeader` | `// Case 1 (0x01) `withPair` — payload case #1` | 同上,说明块的第一行 | +| `enumLayoutCaseEncoding` | `// encoding: tag byte(s) after the payload area = 1; …` | 同上 | +| `enumLayoutCaseNote` | `// note: the exact bytes depend on …` | 同上,只在离线路径解不出 extra inhabitant 的具体字节时出现 | +| `enumLayoutCaseFixedBytes` | `// fixed bytes: byte[0x18] = 0x1 (0b00000001)` | 同上 | +| `enumLayoutCaseByte` | `// offset 0x18 = 0x01 (0b00000001)`,每个字节一行 | 同上 | +| `exportStatus` | `// not exported` | `SemanticComponents.swift:96`(成员)、`DeclarationRenderConfiguration.swift:203`(存储属性,`SwiftDeclarationPrinter+Headers.swift:507`)、`SwiftDeclarationPrinter.swift:953`(全局声明) | +| `protocolExtensionDefault` | `// protocol-extension default` | `SwiftDeclarationPrinter.swift:861`、`:904`、`:934` | +| `privateDeclarationSource` | `// EnabledKey is declared in Enabled.swift of module SwiftUICore` | `SwiftDeclarationPrinter.swift:292`、`:447`、`:534`、`:843`、`:879`、`:918`,`SwiftInterfaceBuilder.swift:186`、`:202`;文字由 `PrivateDeclarationSourceFiles.swift:81` 拼出 | +| `conditionalWitness` | `// Body is picked at run time by an availability check (SE-0360):` 加它下面的分支行 | `SwiftDeclarationPrinter+Headers.swift:316` | +| `conditionalWitnessBranch` | `// macOS 26.0 or later: some SwiftUI.View`,每个分支一行 | 同上 | +| `strippedSymbolicRequirement` | `// Kind: Method, isAsync: false, isInstance: true` | `StrippedSymbolicRequirement.swift:52` | +| `note` | 其余说明性注释,见下 | 见下 | + +归为 `note` 的:局部类型的上下文(`SwiftDeclarationPrinter.swift:281`)、`@_rawLayout` 来自 builtin 描述符的说明(`:335`)、推断出的 `@objc @implementation` 证据(`:610`,行内注释)、由后备存储合成的包装属性(`SwiftDeclarationPrinter+Headers.swift:532`)、没有名字的枚举元素(`SwiftDeclarationPrinter+Members.swift:81`、`:131`)、`/* type not recoverable */`(`SwiftDeclarationPrinter+ObjCImplementation.swift:67`)、类型还原不出的 ivar(`:108`)、ObjC 协议的三种说明(`SwiftDeclarationPrinter+ObjCProtocols.swift:95`、`:98`、`:103`)、interface 文件头的每一行(`InterfaceHeader.swift:233`)。 + +起点清单里的 `spareBits`、`deletedMethodSlot`、`ambiguousAttribution` 不进对外清单:interface 路径不输出它们。`SwiftDeclarationPrintConfiguration` 没有 spare-bit 选项(`renderModelFields` 建的渲染配置里 `printSpareBitAnalysis` 恒为 `false`),另两种只由 `ClassDumper` 输出。它们的 helper 也改走 `StructuredComment`(见「实现」),种类先定为 package 级,等哪天 dump 也要标记时再公开。 + +### 段 + +角色沿用三方约定:`marker`(注释符号)、`label`、`qualifier`、`separator`、`key`、`value`、`name`、`type`、`treePrefix`、`text`。两条通用规则: + +- 续行里注释符号后面用来对齐的空格算进 marker(`// `、`// `)。RuntimeViewer 隐藏 marker 后按区域的层级自己排版,不靠这些空格。 +- 代码缩进、换行不属于任何段。多行块内部的代码缩进与换行在块区域之内、行区域之外。 + +各种类的段(`·` 分隔,引号里是原文,空格照原样): + +``` +memberAddress / vtableOffset / pwtOffset / fieldOffset + marker "// " · label "Address" · separator ": " · value "0x135DC" + 带访问器:marker "// " · label "Address" · separator " (" · qualifier "getter" · separator "): " · value "0x135DC" + vtableOffset 的 label 是 "VTable offset"、value 是十进制槽号;pwtOffset、fieldOffset 的 label 是 "PWT offset"、"Field offset" + +fieldOffsetUnknown + marker "// " · label "Field offset" · separator ": " · value "unknown" · separator " (" · text "generic parameter not substituted" · separator ")" + +fieldLayoutNode + marker "// " · treePrefix "│ ├── " · name "_countAndFlagsBits" · separator " (" · type "Swift.UInt64" · separator "): " · value "0x8" + 没有类型名时:… name "_value" · separator ": " · value "0x8" + +typeLayout + marker "// " · label "Type Layout" · separator ": (" · key "size" · separator ": " · value "16" · separator ", " · key "stride" · … · separator ")" + 元组块: + "/* Type Layout */" marker "/* " · label "Type Layout" · marker " */" + "// Type: Swift.Int" marker "// " · label "Type" · separator ": " · type "Swift.Int" + "// Layout: (…)" 同 typeLayout,label "Layout" + "// Total: " marker "// " · label "Total" · separator ": " + +enumLayoutSummary + marker "/* " · label "Tagged Multi-Payload (tag bytes after the payload area)" · separator " — " + · key "cases" · separator ": " · value "3 (2 payload + 1 empty)" · separator "; " · key "tag values used" · … · marker " */" + +enumLayoutCase + "/* Enum Layout */" marker "/* " · label "Enum Layout" · marker " */" + Header marker "// " · label "Case" · separator " " · value "1" · separator " (" · value "0x01" · separator ") `" + · name "withPair" · separator "` — " · key "payload case" · separator " #" · value "1" + 没有声明名时 value "0x01" 后面是 separator ") — ";单载荷枚举的载荷 case 只有 key "payload case" + Encoding marker "// " · label "encoding" · separator ": " · text "tag byte(s) after the payload area = 1; …" + Note marker "// " · label "note" · separator ": " · text "…" + FixedBytes marker "// " · label "fixed bytes" · separator ": " · value "byte[0x18] = 0x1 (0b00000001)" + 每个连续字节段一个 value,之间 separator ", ";"none — …"、"not computed" 这几种说法是 text + Byte marker "// " · label "offset" · separator " " · key "0x18" · separator " = " · value "0x01" · separator " (" · value "0b00000001" · separator ")" + 只固定部分位的字节:"offset 0x00: fixed bits 0b11000000 = 0b10000000 (the other bits hold payload storage)" → + … key "0x00" · separator ": " · label "fixed bits" · separator " " · value "0b11000000" · separator " = " · value "0b10000000" + · separator " (" · text "the other bits hold payload storage" · separator ")" + +exportStatus / protocolExtensionDefault + marker "// " · label "not exported"(或 "protocol-extension default") + +privateDeclarationSource + marker "// " · name "EnabledKey" · separator " " · text "is declared in" · separator " " · value "Enabled.swift" · separator " " · text "of module" · separator " " · name "SwiftUICore" + 没有名字时以 text "Declared in" 开头;文件名没恢复出来时 text "is declared in a source file whose name could not be recovered" + · separator " (" · key "private discriminator" · separator " " · value "_…" · separator ")";编译器合成的文件是 text "is declared in the file the compiler synthesized for" · separator " " · value 文件名 + +conditionalWitness + 第一行 marker "// " · name "Body" · separator " " · text "is picked at run time by an availability check (SE-0360)" · separator ":" + Branch marker "// " · qualifier "macOS 26.0 or later" · separator ": "(冒号加对齐用的空格) · type "some SwiftUI.View";无条件的分支 qualifier 是 "always" + +strippedSymbolicRequirement + marker "// " · key "Kind" · separator ": " · value "Method" · separator ", " · key "isAsync" · separator ": " · value "false" · … + +note + marker "// " · text "…";行内注释是 marker "/* " · text "…" · marker " */" +``` + +### 结构 + +- **字段偏移树**:`fieldOffset` 区域覆盖 `// Field offset: 0x8` 那一行和它下面整棵树;每个 `fieldLayoutNode` 区域覆盖它自己那一行和它全部后代的行。所以只看嵌套就知道每个节点的深度、所在行和子树的末行,不用猜后面的同级区域算不算它的孩子。展开偏移树在自己的可见性区域里(`printExpandedFieldOffsets`),投影掉以后根区域只剩自己那一行。 +- **枚举**:`enumLayoutSummary` 在类型的 case 之前,每条事实拆成 key / value 段。`enumLayoutCase` 覆盖 `/* Enum Layout */` 与这个 case 的全部说明行,每行一个子区域:`enumLayoutCaseHeader`、`enumLayoutCaseEncoding`、`enumLayoutCaseNote`、`enumLayoutCaseFixedBytes`,以及每个字节一个 `enumLayoutCaseByte`。载荷 case 前面的 `// Type Layout: …` 是独立的 `typeLayout` 区域,两块之间的空行不属于任何区域。 +- **元组的 Type Layout**(只在进程内路径):`typeLayout` 区域覆盖整块,每个元素一个 `typeLayoutElement` 子区域,`// Total: ` 与它下面那行属于整块、不另设区域。 +- **条件 witness**:`conditionalWitness` 区域覆盖说明行与全部分支行,每个分支一个 `conditionalWitnessBranch` 子区域。 +- 其余种类各占一行,一条注释一个区域。 +- 表里报出的区域范围从第一段开始、到最后一段结束:行首的缩进与行尾的换行不算在内,多行区域内部的缩进与换行算在内。这由 swift-semantic-string 在分离时保证:它裁掉区域首尾那些不属于任何段、每个字节都是空白的原子或片,段从不裁。需要这一条,是因为字段偏移树的根区域在根那一行与树之间必须包住根自己的换行,而树所在的可见性区域一个原子都不能挪——挪了,标记模式下那个换行字节的可见性标记就与不开时不同——所以投影掉树以后,根区域以换行结尾,裁剪后就只剩根那一行。也因此,现有 helper 输出的「缩进 + 注释 + 换行」可以整个包进区域,不必重排原子。 + +### 装了 transformer 的注释 + +`fieldOffsetTransformer`、`vtableOffsetTransformer`、`typeLayoutTransformer`、`expandedFieldOffsetTransformer`、`enumLayoutTransformer`、`enumLayoutCaseTransformer` 的闭包返回任意 `SemanticString`,打印器不知道里面怎么分段。开关打开时,闭包的输出整个包进该种类的区域,它的原子全部记为 `text` 段,不再细分,也没有子区域——枚举 case 块只剩 `enumLayoutCase` 一层,RuntimeViewer 折叠到块的第一行。字段偏移树的嵌套不受影响:递归在打印器里,每一行闭包的输出照样包进 `fieldLayoutNode` 区域。 + +`applyTransformers(_:)` 装上的库自带模板也一样处理。按占位符标出代入的值要另做一套带段的模板渲染(每个模块的 `transform` 改成按占位符逐段输出,枚举 case 模板还要处理条件行与自动补行),而且打印器拿到的只是闭包,还得先知道它来自哪个模板模块,留给后续提案。 + +### 实现 + +- **种类常量**:公开地扩展在 `AnnotationRegion.Kind`(swift-semantic-string 的 struct 加静态成员)上。种类会随新注释增加,宿主遇到不认识的种类按 `note` 处理即可。MachOObjCSection 在同一个类型上扩展它自己的六个,两份清单互不重叠;两边都要用的种类放进 swift-semantic-string,免得 RuntimeViewer 同时 import 两个库时出现同名的静态成员。 +- **`StructuredComment`**:一条注释的段(角色加文字),种类在加区域时由调用点给出——一个区域的种类未必只属于一行注释(字段偏移的根区域包着整棵树,枚举 case 的区域包着标题行与说明块)。不标记时渲染成一个 `.comment` 原子,文字是各段拼接,与今天的原子相同;标记时渲染成 `AnnotationRegion(kind) { AnnotatedAtom(type: .comment) { AnnotationSegment(role) { 文字 } … } }`,每段一片,分离时并回那一个原子。每处输出点只描述一次文字,两种渲染都从它来,两边不会写走样。关着时每条注释比今天多建一个段数组;第 5 步量过这部分开销,SwiftUI 打开全部注释选项生成 interface 时 instructions retired 多 0.7%,可以忽略,所以没有改成直接拼字符串。一条注释无论拆成几个原子都仍是容器里的一个元素:`Rows`、`MemberList` 一个元素一行,拆散了成员前的注释会各占一行。 +- **例外是枚举逐 case 的说明块**:关着时仍走 `EnumCaseProjection.description(indent:prefix:)`(`Transformer+EnumLayoutProjection.swift:86`,它是公开 API,模板引擎与 dump 共用),打开时由同一组 `Transformer.SwiftEnumLayout.CaseInput` 字段按行组装。两边一致靠契约测试覆盖 fixture 里的每个枚举,另用合成的投影做单元测试:只固定部分位的字节、离线解不出的 extra inhabitant、单载荷、没有声明名的 case。 +- **dump 不标记**:`DeclarationRenderConfiguration` 里的共享 helper 都改走 `StructuredComment`(包括只有 dump 用的 `memberAddressComment`、`deletedMethodSlotComment`、`ambiguousAttributionComment`、`spareBitAnalysisComment`、`privateDeclarationSourceFileComments`),但它们的开关只由打印器设置,dump 建的配置从不设,所以 dump 输出不变、也不带标记。 +- **防漏标**:一个源码扫描测试,在 interface 路径的模块(`SwiftDeclarationRendering`、`SwiftPrinting`、`SwiftInterface`、`SwiftDeclaration`)里,除 `StructuredComment` 自身外不许再直接构造 `Comment(`、`InlineComment(`、`MultipleLineComment(` 或类型为 `.comment` 的原子;`EvolutionMarking.swift` 进白名单。仓库里已有同类扫描(`ReaderKindCastScanTests`、`CommandLineStreamWriteScanTests`)。 + +### 依赖 swift-semantic-string + +API 以它的会话定稿为准,随它的 0.6.0 发布,说明在它的 `docs/AnnotationRegions.md`。它满足本库提的要求: + +- 区域可以嵌套(同 kind 也行),原样保留内容的元素结构(同 `DefinitionRegion`),起止可以落在一个 `AnnotatedAtom` 内部;相邻的两个同 kind 区域读回为两个。 +- 边界不靠编号:每层区域在每个原子上记一个只取决于区域自身内容的阶段(锚点之前、锚点、锚点之后),所以去缩进、投影、切出定义区域都改不动它。0068 的「内联与单独打印逐个相同」、「标记模式投影到某个配置再分离 = 用该配置打印再分离」都成立,`content(ofDefinitionRegion:)` 与 `removingIndentation(levels:)` 不用改。 +- 区域包住带 identifier 的原子时,原 identifier 留在最里层,分离时原样还原。 +- 段的十种角色定义在 swift-semantic-string(`AnnotationSegment.Role`),两个生产方共用。 + +本库后来补提的几条,它也已确认: + +- 表里报出的区域范围裁掉首尾那些不属于任何段、每个字节都是空格、制表符或换行的原子或片(见「结构」)。判断以原子为单位,被冻结切成几片的长原子按整个原子判断;只含这种原子的区域不进表。只看原子自身的字节,所以去缩进与投影都改变不了结果。 +- `AnnotatedAtom` 的输出可以再被外层的可见性、定义、注释区域包住,由外层给每一片加同一个标记,`marksOptionalContent` 下照常并回一个 span。 +- 不在 `AnnotatedAtom` 里的段可以包住任意原子:不同语义类型、带 identifier、带可见性或定义标记都行,只是段里不能再有段或注释区域。transformer 闭包的输出因此可以整个包成一个 `text` 段;哪天宿主自己也用注释区域标它的输出,就只包区域、不加段。 +- 内容为空的段、区域、`AnnotatedAtom` 什么都不记,不 trap。 + +草图里的「一次扫描的模板代入函数」本库第一版不用,它已从提案里删掉。它列出的已知限制「分离之前看到的是拆开的片」,本库打印路径上按原子判断的有两处。`DeclarationBlock` 看最后一个原子的末字节,片拼起来末字节不变,不受影响。`bodyAfterNestedDefinitions`(`SwiftDeclarationPrinter+VisibilityRegions.swift:78`)判断最后一个原子是不是 `"\n"`,而枚举块拆开后最后一片正是 `"\n"`;今天块后面总跟着 case 声明,块不会是 body 的最后一项,但这条前提不该靠顺序维持。这处判断改为「最后一个原子是 `BreakLine`」:字符串是 `"\n"` 且类型是 `.standard`。拆出的片类型是 `.comment`,不会被认错;不开标记时没有哪个 `.comment` 原子恰好是 `"\n"`,行为不变。 + +本库依赖的下限抬到 0.6.0,带注释区域的第一个版本(之前是 0.5.0)。 + +### 落地步骤 + +1. **单一来源**(不依赖 swift-semantic-string;已完成):新增 `StructuredComment`,这一步只有不标记的渲染。角色先用 package 级的过渡类型 `StructuredComment.Role`,成员名与 swift-semantic-string 草图里的 `AnnotationSegment.Role` 相同,段写成 `.label("Address")`,以后换类型时调用点不用动。interface 路径的全部注释输出点与 `DeclarationRenderConfiguration` 的共享 helper 改走它,`summaryDescription` 改为由事实拼出,加上源码扫描测试。这一步还没有开关,输出必须逐字节不变:全量测试与基线逐条一致,另用单元测试钉住每种注释的文字与段。 +2. **接上 swift-semantic-string**(已完成):依赖暂时指向它的 `next` 分支;删掉过渡类型,角色改用 `AnnotationSegment.Role`,种类常量公开地扩展在 `AnnotationRegion.Kind` 上。 +3. **开关与标记渲染**(已完成):`marksCommentStructure`、`StructuredComment` 的标记渲染、枚举 case 块的分段组装、字段偏移树与枚举与元组与条件 witness 的区域结构、transformer 闭包的包装、`bodyAfterNestedDefinitions` 的判断。 +4. **测试**(已完成,与第 3 步同一个提交):契约测试、结构测试、少见种类所在套件里的断言、单元测试。 +5. **文档与完整验证**(已完成):模块文档、术语表、演进账本与 AGENTS.md 的规则行;全量测试、渲染 A/B、性能对比;依赖下限随 swift-semantic-string 发版抬到 0.6.0。 + +### 验证 + +- **契约测试**(SwiftInterfaceTests,新套件):SymbolTestsCore,进程内与文件两种读取方式,四种配置——全部注释选项打开的默认渲染;再开 `marksOptionalContent` 并挂 opaque 解析器,逐个投影核对契约第 4 条前半;装上 `applyTransformers(_:)` 的全部模板;再开 `marksNestedDefinitions`,核对契约第 4 条后半。每种配置都核对契约第 2、3 条。 +- **结构测试**:在 SymbolTestsCore 上断言具体形状——带 `String` 字段的结构体(树的嵌套、每个节点覆盖的行),多载荷枚举(摘要的 key / value,case 块的五种子区域与字节行的段),类的 getter / setter 地址与 vtable 槽(qualifier),`fieldOffsetUnknown`,`exportStatus`,进程内路径上的元组 Type Layout 块。 +- **少见的种类**:条件 witness、ObjC 相关的说明、局部类型、`@_rawLayout`、合成的包装属性、没有名字的枚举元素、私有声明来源、被剥掉符号的协议需求,各自的套件已经现场编译了能产生它们的 fixture;在这些套件里加上契约第 2、3 条的断言(共用一个 helper),不改 SymbolTestsCore(改它会牵动全部基线)。 +- **单元测试**:`StructuredComment` 不标记时的文字与今天逐字相同(按种类列表驱动);枚举 case 块的分段组装与 `description(indent:prefix:)` 逐字相同(合成投影)。 +- **开关关着**:现有快照测试与全量测试原样通过;渲染 A/B 逐字节一致(AGENTS.md 规定的大改后必跑项:每处注释的构造都换了写法)。 +- **性能**:Ultra 上对 SwiftUI 生成打开全部注释选项的 interface,开关关着,改动前后各量一次 `time -l` 的 instructions retired。 +- swift-semantic-string 的组件、分离与组合由它自己的测试覆盖。 + +### 没有询问就采用的假设 + +- 只标单版本打印(`SwiftDeclarationPrinter` 与 `SwiftInterfaceBuilder.printRoot`);dump、diff、evolution 的注释不标。 +- 装了 transformer 的注释整条记为一个 `text` 段,按占位符分段留给后续提案。 +- 区域第一版不带属性:RuntimeViewer 第一版不用,需要的文字都在段里。 +- 每条注释的文字只写在 `StructuredComment` 一处,关着时由各段拼接,所以改动会经过默认输出路径,靠渲染 A/B 证明逐字节不变;只有枚举逐 case 块保留原实现、另写分段组装。 +- 不加 CLI 选项:CLI 只输出文本,注释表没有落点。 +- 实现等 swift-semantic-string 的组件在分支上可用后开始,开发期依赖它的 `next` 分支,它发版后改回版本号(原定用本地兄弟依赖,改法见决策日志)。 + +### 顺带发现 + +interface 路径从不使用 `SwiftDeclarationPrintConfiguration.memberAddressTransformer`:成员地址由 `AddressComment`(`SemanticComponents.swift:30`)输出,它没有 transformer 参数,`renderModelFields` 建渲染配置时也没把这个闭包传下去。所以 RuntimeViewer 设置里的成员地址模板对 interface 不起作用;那个闭包的输入只有偏移,接上了也会丢掉 `(getter)` 这类标注。与本提案无关,另行处理。 + +thunk 读取器不解析两个分支各自直接加载一个类型的可用性条件 witness。`if #available(macOS 26, *) { return 1 } else { return "one" }` 这样的 `some` 结果,编译器(Swift 6.3 与 6.4,`-O` 与 `-Onone` 都一样)把 thunk 编成一次 `__isPlatformVersionAtLeast` 调用加一条 `csel`,在 `$sSiN` 与 `$sSSN` 两个地址之间选,没有分支;读取器只认分支,这个 witness 就打印成 `typealias Body = accessor function at …`,也不出 SE-0360 那条注释。两个分支都要调用取 metadata 的函数时(`[1]` 与 `["one": 1]`)thunk 有分支,读得出来。与本提案无关,另行处理。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-31 | Created as Draft | RuntimeViewer 要在 SourceEditor 面板把注释画成标签,字段偏移树与枚举布局可折叠;用户在 RuntimeViewer 会话里定了由生成器输出注释的结构、RuntimeViewer 不解析注释文本。RuntimeViewer 会话把本仓库这一份转了过来,连同三方共用的约定草案(载体在 swift-semantic-string,ObjC 一侧由 MachOObjCSection 做)。只起草,用户批准之前不写实现。 | +| 2026-10-31 | 开关命名 `marksCommentStructure`,与 MachOObjCSection 同名 | 与 `marksOptionalContent`、`marksNestedDefinitions` 用同一个动词。ObjC 一侧放在 `ObjCInterfaceBuilder` 的构造参数上。 | +| 2026-10-31 | 契约按 RuntimeViewer 的修订:文本与每个字节的语义类型、identifier 相同,span 边界可以不同 | 冻结时一个原子一个 span,相邻原子从不合并(swift-semantic-string 的 `FrozenSemanticString+Freezing.swift:25`),拆段必然多出 span。已请 swift-semantic-string 在能便宜做到时把同一原子的片并回一个 span,做到了测试就按完全相等断言。 | +| 2026-10-31 | `spareBits`、`deletedMethodSlot`、`ambiguousAttribution` 不进对外清单;补上 `typeLayoutElement`、`conditionalWitness`、`conditionalWitnessBranch`、`strippedSymbolicRequirement` | 前三种 interface 路径不输出;后四种是实际输出里有结构、起点清单没列到的注释。 | +| 2026-10-31 | 区域第一版不带属性 | RuntimeViewer 第一版不用;名字、类型、偏移都已是段。 | +| 2026-10-31 | RuntimeViewer 确认照用本提案的种类清单与段的切法 | 它的画法:认不出的 kind 按 `note` 画;藏起 marker 与 separator(separator 里的空格留作间距);treePrefix 画成透明,在 `├── ` 那格画展开三角;`fieldOffset` 与 `fieldLayoutNode` 区域的末尾就是折叠的终点;枚举 Header 的两个 value 按「序号」与「序号的十六进制」显示,不当 tag 值。`memberAddressTransformer` 在 interface 路径不生效与本提案无关,RuntimeViewer 这条线不依赖它。 | +| 2026-10-31 | 采用 swift-semantic-string 的 API 草图(`AnnotationRegion` / `AnnotationSegment` / `AnnotatedAtom`);种类改为扩展 `AnnotationRegion.Kind`,不另建 `SwiftCommentKind` | 两个生产方与 RuntimeViewer 用同一个类型。ObjC 一侧也改为扩展它,两份清单互不重叠,共用的种类放进 swift-semantic-string。 | +| 2026-10-31 | 契约第 2 条恢复为完全相等 | 拆开的片都在 `AnnotatedAtom` 里,分离时并回原来的一个 span。RuntimeViewer 放宽后的条件留作底线。 | +| 2026-10-31 | 请 swift-semantic-string 裁掉区域首尾的空白原子;它提议的模板代入函数第一版不用 | 前者让字段偏移树不必重排原子,标记模式下换行字节的可见性标记也就不变。后者要先解决「打印器怎么知道闭包来自哪个库自带模板」,留给后续提案。 | +| 2026-10-31 | swift-semantic-string 接受裁剪,确认组合、闭包输出成段、空段静默丢弃三点;`bodyAfterNestedDefinitions` 的判断改为认 `BreakLine` 原子 | 它的草稿已同步更新(仍待它的用户批准)。判断加上类型条件后,开标记时不再依赖「枚举块不会是 body 最后一项」这条前提;不开标记时行为不变。 | +| 2026-10-31 | 落地步骤拆成五步,第 1 步不依赖 swift-semantic-string | 它的组件还只是草图,要等它的用户批准后才实现。第 1 步(注释文字的单一来源)只动默认输出的构造方式,能单独构建与验证,先做;第 2 步起等它的组件在分支上可用。 | +| 2026-10-31 | 用户批准,开始实现 | 状态改为 Accepted。 | +| 2026-10-31 | In Progress;第 1 步落地,与原方案有四处出入 | 一,第 1 步不建种类的过渡类型:一个区域的种类未必只属于一行注释(字段偏移的根区域包着整棵树,枚举 case 的区域包着标题行与说明块),所以种类在第 3 步加区域时由调用点给出,`StructuredComment` 只记段。二,关着时每条注释多建一个段数组,没有做成「关着直接拼字符串」;开销留给第 5 步的性能对比,量出来不可忽略再改。三,返回字符串的现有接口都保留原签名,改为由段拼出:公开的 `ConditionalWitnessComment.lines`,package 级的 `PrivateDeclarationSourceFileComments.line` / `lines` 与 `conditionalWitnessCommentLines`(dump 与测试在用);打印器改用新增的结构化形式。四,续行的注释符号写成两个相邻的 marker 段(`// ` 与对齐用的空格),说明性注释开头的空格同样归 marker;第 3 步标记时把相邻的同角色段并成一段,表里仍是一个 `// `。另外两个新套件 `StructuredCommentTests`、`CommentConstructionScanTests` 进了 CI 的筛选清单,AGENTS.md 的打印器一节加了一行规则。 | +| 2026-10-31 | 第 2 步:开发期依赖 swift-semantic-string 的 `next` 分支,只换这一个依赖 | 它的组件已落进 `next`(`2698750`),还没发版。不用 `USING_LOCAL_DEPENDENCIES=1`:那会把 MachOKit、MachOObjCSection 等兄弟库也一起换成它们 `next` 上未发版的内容,测试与 A/B 就不再只差本提案的改动。`Package.swift` 里 `Semantic` 的远端要求暂时写成 `branch: "next"`,落地前改回它发版后的版本号;解析结果只有这一项与基线不同。 | +| 2026-10-31 | 第 3、4 步落地,合成一个提交;与原方案有四处出入 | 第 3 步没有自己的测试,而且它让 `StructuredComment` 自己的文件构造 `.comment` 原子(`AnnotatedAtom(type: .comment, …)`),源码扫描测试要同时放行这些文件,单独提交的话中间那个提交的测试是红的。一,契约第 4 条后半(与 `marksNestedDefinitions` 组合)放进 `NestedDefinitionRegionContractTests` 新增的一个变体,并比较分离出的注释表,不在新套件里重复它切区域、去缩进的那套比较;新套件 `CommentStructureContractTests` 管第 2、3 条与第 4 条前半,另加整个 interface 的 `printRoot`(含文件头)。二,条件 witness 没有现成的现场编译 fixture(唯一的 SE-0360 测试读宿主 cache 里的 SwiftUI),新加套件 `ConditionalWitnessCommentStructureTests` 现场编一个小 dylib;两个分支返回 `[1]` 与 `["one": 1]`,原因见「顺带发现」。三,判漏标的覆盖检查只看非空白的注释字节,与区域首尾裁掉空白的规则一致。四,整个 import `Semantic` 的测试文件里,它的 `Error` 组件会遮住 `Swift.Error`,这些文件改为按名字只 import 用到的类型。三个新套件进了 CI 的筛选清单;条件 witness 那个 fixture 用 Xcode 26.6(Swift 6.3)编出来同样读得出两个分支。 | +| 2026-10-31 | 第 5 步完成验证;关着时保留「每条注释建一个段数组」 | 全量测试与 `next` 849a0b21 一致(只红默认 Xcode 27.2 下既有的 `ThunkOnlyObjCMemberTests` 4 条),Xcode 26.6 下受影响的套件全过,渲染 A/B 96 对逐字节一致。性能:SwiftUI 打开全部注释选项生成 interface,instructions retired 平均多 0.7%,峰值内存不变,开销可以忽略,所以不改成关着时直接拼字符串。数字记在演进账本第 119 节。 | +| 2026-10-31 | 实现完成,待用户看过后收尾 | 剩下的只有依赖下限:swift-semantic-string 发版后,把 `Semantic` 的要求从 `branch: "next"` 改回版本号,再落进 `next`。 | +| 2026-10-31 | RuntimeViewer 端到端核对通过 | 它对着本地合并后的 `next`(b6c37d31,加 swift-semantic-string 2698750、MachOObjCSection 635fe17)用测试包里的嵌套 struct、多载荷 enum、open class 核对:开关开与关的文本、span、identifier 完全相等,每条注释都在表里、从注释符号开始,区域层层嵌套,出现的 kind 与 role 都在约定清单里;字段树和 case 块在它的 App 里都能收起。 | +| 2026-10-31 | 依赖改回 `from: "0.6.0"`;Implemented,取号 0084 | 用户决定先请 swift-semantic-string 发版再落地,不带着分支依赖进 `next`。它发布的 0.6.0(`fd7e93c`)相对 `2698750` 只改了 README 与 `docs/AnnotationRegions.md` 各一行,所以改 pin 后只重跑受影响的 17 个套件(147 个测试全过,原始退出码 0),全量、A/B 与性能沿用第 5 步的结果。文档:术语表与模块文档在第 3、4 步已写好,不另写使用指南——开关只是一个布尔值,属性的文档注释写明了契约,宿主怎么读注释表由 swift-semantic-string 的 `docs/AnnotationRegions.md` 说明。 | diff --git a/Documentations/Evolutions/0085-abi-flag-words-bit-field.md b/Documentations/Evolutions/0085-abi-flag-words-bit-field.md new file mode 100644 index 000000000..749029f52 --- /dev/null +++ b/Documentations/Evolutions/0085-abi-flag-words-bit-field.md @@ -0,0 +1,102 @@ +# 0085 - ABI 层的 flag word 改用 `@BitField`,修掉三个读错位的访问器 + +- **状态**: Implemented +- **创建日期**: 2026-11-05 +- **最后更新**: 2026-11-05 +- **所属愿景**: 无 +- **关联提案**: FrameworkToolbox 的 [0015-bit-field-macro](https://github.com/Mx-Iris/FrameworkToolbox/blob/main/Documentations/Evolutions/0015-bit-field-macro.md)(宏本身,以本仓库为第一个使用方) +- **实现分支 / PR**: `feature/abi-flag-words-bit-field`(worktree `.worktrees/MachOSwiftSection-ABIFlagWordsBitField`,基于 `next` 463b2209),2026-11-05 合入 `next`;MachOKitUI 的对应改动 `feature/optional-flag-word-kinds` 同日合入它的 `main` +- **配套文档**: 无 + +## 摘要 + +ABI 层照 Swift 运行时的 C++ 头文件(`swift/ABI/MetadataValues.h`)手写了 24 个 flag word 类型。其中 17 个在一个整数里同时装着单个的标志位和多位字段,手写成四种风格:`OptionSet` 加 static、仓库自己的 `FlagSet` 协议加 `Bits` 常量、私有掩码常量、每个 case 是一个掩码的枚举。三个访问器把位读错了: + +- `ExistentialTypeFlags.classConstraint` 只掩码、不移位,读到 `Any` 这类不限定 class 的 existential 就崩(`InProcessMetadataPicker` 的注释专门交代测试要绕开它)。 +- `ProtocolDescriptorFlags.classConstraint` 同样漏了移位,那一位是 1 时就崩。 +- `FunctionTypeFlags.convention` 既不掩码也不移位,把整个 flag word 直接转成 `UInt8`:不超过 255 时读到的是参数个数那几位,超过 255 就崩。 + +三处从 2025-10 首次提交起就在,本仓库的生产代码没有调用方,但都是公开 API。FrameworkToolbox 的提案 0015 加了 `@BitField`,即 C++ `FLAGSET_DEFINE_FLAG_ACCESSORS` / `FLAGSET_DEFINE_FIELD_ACCESSORS` 在 Swift 里的对应物:属性上只写占哪几位,移位、掩码和类型转换由宏与重载决议生成。本提案把这 17 个类型的访问器改成 `@BitField` 声明,三个 bug 随之修掉(先写复现测试);另把 `ClassFlags` 与 `InvertibleProtocolSet` 改用 `@FlagSet`。 + +## 方案 + +以下都是未经询问就采用的假设,错了在批准前指出即可。 + +**前提**:FrameworkToolbox 发出同时包含 `@FlagSet` 与 `@BitField` 的版本(下一个是 0.17.0),本仓库 `Package.swift` 的下限从 `from: "0.4.0"` 抬到这个版本,`Package.resolved` 跟着更新。 + +**先写复现测试,再迁移。** 三个 bug 各一条测试,修复前会崩(单独运行确认),修复后通过,永久保留: + +- `ExistentialTypeFlags`:读 `Any.self` 的 metadata,`classConstraint` 是 `.any`。同时删掉 `InProcessMetadataPicker` 与 `ExistentialTypeFlagsBaselineGenerator` 里「必须改用 `AnyObject.self`」的绕路说明。 +- `ProtocolDescriptorFlags`:原始值 `0x2` 读成 `.any`。 +- `FunctionTypeFlags`:分别读一个 Swift 闭包、`@convention(c)` 与 `@convention(block)` 函数的 metadata,`convention` 与之相符。 + +**迁移范围。** 每个访问器只剩 `@BitField(bits: …)` 加原来的名字与类型,位置照抄现在的掩码;17 个类型的每个位都已对照过 Swift 6.4 的 C++ 头文件,除上面三处外没有错位。 + +| 类型 | 迁移后 | +|---|---| +| `ContextDescriptorFlags` | kind、version、kind-specific flags 的原始值与三个 Bool;三个 `OptionSet` static 保留 | +| `TypeContextDescriptorFlags` | 全部;新增 `metadataInitialization` 字段,三个 `has…MetadataInitialization` 由它推出 | +| `ProtocolContextDescriptorFlags`、`AnonymousContextDescriptorFlags`、`ExtraClassDescriptorFlags` | 全部 | +| `MethodDescriptorFlags`、`ProtocolRequirementFlags`、`GenericRequirementFlags` | kind 与各个位;`isCoroutine`、`isAsync` 这类推导属性照旧手写 | +| `ProtocolConformanceFlags`、`GenericEnvironmentFlags`、`ExistentialTypeFlags`、`ProtocolDescriptorFlags`、`FunctionTypeFlags` | 全部 | +| `FunctionParameterTypeFlags`、`FunctionTypeExtendedFlags`、`ValueWitnessFlags`、`GenericMetadataPatternFlags`、`KeyPathComponentHeader` | 字段与位;哨兵值、按值比较的推导属性照旧手写 | + +**公开 API 的变化:非可选的枚举字段。** 13 个字段现在是 `Kind(rawValue: …)!` 强制解包,`@BitField` 不接受「认不得就崩」,必须二选一: + +- 会随编译器增长的 kind 改成可选:`MethodDescriptorFlags.kind`、`ProtocolRequirementFlags.kind`、`GenericRequirementFlags.kind`、两个 `TypeReferenceKind` 字段、`specialProtocol` / `specialProtocolKind`、`dispatchStrategy`、`convention`。本仓库约 30 处调用跟着改:`switch` 补一个 `nil` 分支,写清认不得的 kind 怎么办(dump 里照实印出原始值,不猜);`== .sameType` 这类比较不用改。 +- 只有一位、两种取值都已定义的三个 `classConstraint` 写 `default:`,类型不变。 +- `ContextDescriptorFlags.kind` 现在就回落到 `.unknown`,写成 `default: ContextDescriptorKind.unknown`,类型不变。 +- 下游:MachOKitUI 约 5 处要改,其中 `"\(requirement.flags.kind)"` 改成可选后会印出 `Optional(…)`,要显式处理;RuntimeViewer 与 swift-decompiler 没有直接用到这些字段。 + +**`@FlagSet` 的两处。** + +- `ClassFlags`:从「每个 case 是一个掩码的枚举」改成 `OptionSet`,装得下多个位的组合。`ClassFlags.hasCustomObjCName.rawValue` 这类写法照旧编得过;对它的 `switch` 与可失败的 `init(rawValue:)` 不再成立,本仓库没有这样的用法。 +- `InvertibleProtocolSet`:`InvertibleProtocolKind` 挪进结构体成为 `Flag`,旧名留一个 typealias;`hasCopyable` / `hasEscapable` 保留。 +- `@FlagSet` 生成的 static 不在源码里,按语法扫描公开成员的覆盖率检查看不到它们,`CoverageAllowlistEntries` 与相关 baseline 里登记的名字跟着改。`@BitField` 不受影响:属性声明还在源码里。 + +**不迁移。** + +- `MetadataRequest`:它要 setter,宏的第一版不生成;现在的手写版没有问题。 +- 存储不叫 `rawValue` 的四处(`GenericParamDescriptor`、`EnumDescriptor`、`BuiltinTypeDescriptor`、`MultiPayloadEnumDescriptor`):宏只读 `rawValue`。 +- 已经正确的三个纯单比特 `OptionSet`(`FieldRecordFlags`、`GenericContextDescriptorFlags`、`AccessibleFunctionFlags`)。 +- 仓库自己的 `FlagSet` / `MutableFlagSet` 协议保留:迁移后的类型照旧声明遵循,`flag(bit:)` 的调用方不受影响,`MetadataRequest` 还在用 `MutableFlagSet`。 + +**顺手记下、不在这次范围。** `ProtocolConformanceFlags.hasNonDefaultSerialExecutorIsIsolatingCurrentContext` 读的第 20 位只在 2025 年 3–4 月的 Swift 主线上存在过,6.1 到 6.3 的正式版头文件里都没有,读出来永远是 0:保留这个公开属性,在文档注释里写明。`ProtocolRequirementFlags` 缺 C++ 有的 `extraDiscriminator`;`TypeContextDescriptorFlags.classAreImmdiateMembersNegative` 的名字拼错了,改名要走废弃流程。 + +**验证。** 全量测试在 Ultra 上跑;渲染 A/B 验证(读取栈的大改动之后必须做)预期逐字节一致——三个读错的访问器都不在 `dump` / `interface` 的输出路径上,认不得的 kind 在系统框架里也不该出现。 + +**文档。** 演进账本记一节;`CLAUDE.md` 里 ABI 层那一段加一条「flag word 的访问器用 `@BitField` 声明,不手写掩码」;`SelfContainedABILayer.md` 判断要不要提一句。 + +## 落地步骤 + +每一步各自能构建、测试通过,单独提交。 + +- [x] 1. 依赖下限抬到包含两个宏的 FrameworkToolbox 版本;三条复现测试,确认修复前失败。 +- [x] 2. 迁移 17 个类型,三个 bug 随之修掉;改成可选的字段的调用方跟着改;覆盖率清单与 baseline。 +- [x] 3. `ClassFlags`、`InvertibleProtocolSet` 改用 `@FlagSet`;覆盖率清单。 +- [x] 4. 全量测试与渲染 A/B;文档;给 MachOKitUI 提一份对应的改动。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | Created as Draft | 调研 ABI 层能否用宏收掉样板时发现:17 个混排 flag word 手写成四种风格,三个访问器读错位;能表达这种形状的 `@BitField` 已在 FrameworkToolbox 0015 落地 | +| 2026-11-05 | 三个读错位的访问器不单独修,随迁移一起修 | 用户选定。迁移后它们由宏生成,单独修一遍等于改两次;在那之前它们没有生产调用方 | +| 2026-11-05 | `@FlagSet` 只用在 `ClassFlags` 与 `InvertibleProtocolSet` | 用户选定。`ClassFlags` 现在装不下组合,`InvertibleProtocolSet` 的种类枚举与集合是两处定义;另外三个纯单比特类型现在就是对的,改了只是统一写法,还要改覆盖率清单 | +| 2026-11-05 | 宏放在 FrameworkToolbox,不放本仓库的 `MachOMacros` | 用户选定。MachOObjCSection 等仓库也在读二进制里的 flag word | +| 2026-11-05 | 会随编译器增长的 kind 改成可选,三个 `classConstraint` 与 `ContextDescriptorFlags.kind` 写 `default:` | 用户选定。认不得的值不再让读取它的程序崩溃;代价是本仓库约 30 处、MachOKitUI 约 5 处调用跟着改。另一条路是私有的可选属性外包一层手写的强制解包,调用方不用改,但认不得的值照旧崩,没选 | +| 2026-11-05 | 前提已就位:FrameworkToolbox 发出 0.17.0 | 用户批准发版。0.17.0 同时包含 `@FlagSet`(0014)与 `@BitField`(0015) | +| 2026-11-05 | 用户批准,开始实现 | — | +| 2026-11-05 | 实测三条复现测试在修复前都让进程停下 | 在 Ultra 上用 Xcode 26.6 逐条跑:`ExistentialTypeFlags` 与 `FunctionTypeFlags` 报 `Not enough bits to represent the passed value`,`ProtocolDescriptorFlags` 报强制解包遇到 `nil`;迁移后三条都通过 | +| 2026-11-05 | `GenericRequirementDescriptor.content` 与 `ProtocolConformanceDescriptor.typeReference` 遇到认不得的 kind 照旧停下,改成带说明的 `preconditionFailure` | 两者的返回类型(`GenericRequirementContent`、`TypeReference`)没有能装下未知 kind 的 case,以前是 `kind` 的强制解包在这里停,现在 `kind` 本身能安全读取,停在真正无法往下的地方。要让它们也不停,得给两个枚举加分支,是另一次改动 | +| 2026-11-05 | `ExistentialTypeMetadata.representation` 把 `case .none` 写成 `case .some(.none)` | `SpecialProtocolKind` 自己有 `none` case,字段改成可选后,裸写的 `.none` 会被编译器当成 `nil`,只给警告、语义悄悄变了;全仓库只有这一处 | +| 2026-11-05 | dump 里认不得的方法 kind 印成 `[unknown kind, flags 0x…]`;协议要求的 kind token 认不得时是 `unknown` | 不猜,照实印出原始的 flag word;kind token 以前遇到这种情况会崩,所以没有已持久化的 key 用到它 | +| 2026-11-05 | baseline 生成器对改成可选的字段强制解包,baseline 文件不变 | fixture 里只有本库认得的 kind;生成器是维护者手动跑的工具,遇到认不得的值当场停下比写进一个哨兵值好查 | +| 2026-11-05 | 改了公开属性的类型之后先清掉构建产物再编 | 增量构建没有重编源码没变、却用到 `MethodDescriptorFlags.kind` 的 `VTableSlotAttributionTests.swift`,链接时还在找旧的非可选 getter;与 `CLAUDE.md` 里「改了 MachOSymbols 的结构布局要 clean」同一类 | +| 2026-11-05 | `InvertibleProtocolKind` 成为 `InvertibleProtocolSet.Flag` 的 typealias,raw value 从 `UInt8` 变成 `UInt16` | `@FlagSet` 生成的 `rawValue` 取 `Flag` 的原始类型,而集合存的是 16 位;唯一的调用方 `SymbolicDemangler` 经 `UInt64(…rawValue)` 读它,不受影响 | +| 2026-11-05 | `InvertibleProtocolSet` 的 Suite 只登记 `hasCopyable` / `hasEscapable` | `rawValue`、`init(rawValue:)` 与两个 static 改由 `@FlagSet` 生成,不在源码里,按语法扫描的覆盖率检查找不到它们,登记了就报「登记了不存在的成员」;Suite 里对它们的测试照旧保留、照旧运行 | +| 2026-11-05 | MachOKitUI 的对应改动放在它的 `feature/optional-flag-word-kinds`,经一个 `kindDescription` 帮手显示,认不得时写 `unknown` | 那 6 处都是把 kind 直接插进字符串,改成可选后不会编译失败,只会印出 `Optional(…)`;帮手收的是 `Kind?`,非可选的值会自动提升,所以对新旧两版 MachOSwiftSection 都能编。在 Ultra 上用只放这两个仓库的沙盒(`git archive`,`USING_LOCAL_DEPENDENCIES=1`,MachOSwiftSection 解析为本地 `fileSystem`)编过 `MachOKitUICore`(`--traits SwiftSection`);MachOKitUI 还没有 `.worktrees/` 的忽略规则,加在本地的 `.git/info/exclude`,不改它受版本控制的 `.gitignore` | +| 2026-11-05 | 文档:演进账本记一节,`AGENTS.md` 的 ABI 层一段加了 flag word 的规则;`SelfContainedABILayer.md` 不改 | ABI 层早就经 MachOBase → Utilities 引入 FrameworkToolbox 的宏(`@CaseCheckable`、`@AssociatedValue`),这次没有新的依赖边;没有新术语 | +| 2026-11-05 | 不另写使用指南或实现说明 | 宏的用法与契约在 FrameworkToolbox 的 `BitField.md`;本仓库要遵守的写法(可选的 kind、`default:`、`.some(.none)`、改类型后先清构建产物)已写进 `AGENTS.md`,没有别的维护者会踩、代码里又看不出的决策 | +| 2026-11-05 | 实现完成,待用户看过后收尾 | 都在 Ultra 上用 Xcode 26.6 跑:全量 `swift test --skip IntegrationTests` 2,784 个测试全过;渲染 A/B 96 对逐字节一致,覆盖归档 cache、模拟器文件、进程内 `MachOImage` 三条读取路径;两份手改的 baseline 经 `regen-baselines` 重新生成后没有差异;MachOKitUI 对本分支编过 | +| 2026-11-05 | 落地,编号 0085,状态改 Implemented | 用户决定直接收尾,合入 `next` 时远端没有新提交,沿用上一行那次验证。摘要承诺的都已做到;留作后续的只有 `GenericRequirementDescriptor.content` 与 `ProtocolConformanceDescriptor.typeReference` 遇到认不得的 kind 仍会停下(见上文)。可选字段里裸写 `.none` 的陷阱同时补进了 FrameworkToolbox 的 `BitField.md`,那是宏的调用方都会踩的;不另配指南或实现说明、没有新术语的判断不变 | diff --git a/Documentations/Evolutions/0086-shared-dependency-openings.md b/Documentations/Evolutions/0086-shared-dependency-openings.md new file mode 100644 index 000000000..8ff0eb86b --- /dev/null +++ b/Documentations/Evolutions/0086-shared-dependency-openings.md @@ -0,0 +1,43 @@ +# 0086 - 依赖定位器共享同一路径的打开,不再按根重开 cache 与显式文件 + +- **状态**: Implemented +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **所属愿景**: 无 +- **关联提案**: 无。起因见演进账本第 122 节的后续第一条;当时不共享的理由见第 120 节;落地记在第 124 节 +- **实现分支 / PR**: `feature/shared-dependency-openings`,已合进 `next` +- **配套文档**: [Modules/MachODependencies.md](../Internal/Modules/MachODependencies.md) + +## 摘要 + +`FileDependencyLocator` 每建一个,就把搜索路径里的 dyld cache(`.dyldSharedCache(path:)`,根所在的那份与 `cachedHost` 除外)整个打开一次(`FullDyldCache(url:)`,macOS 27 是八十几个文件),把每个 `.machOFile(path:)` 文件也打开一次。定位器又是按根建的:静态布局、索引器的共享闭包、thunk 分析、ObjC 祖先、属性包装器目录、interface 依赖,最多六个使用方各建一个。打开数于是随根数成倍增长:DockHelper 配对一份归档的 macOS 27.0 cache 跑一次 `interface --emit-offset-comments`,那份 cache 的 80 个文件峰值共开着 369 个描述符,单个文件最多 7 个。RuntimeViewer 离线读一个配对非本机 cache 的 bundle 时,每个 bundle 镜像都是一个根,倍数还要再乘上去。改成同一路径在进程里只打开一次,还有人在用就复用。 + +## 方案 + +- **cache**:MachODependencies 内部加一张按路径共享打开的表。键是主 cache 文件的标准化路径加文件身份(设备号、inode、大小、修改时间;文件被换掉就开新的),值弱引用 `FullDyldCache`。定位器遇到 `.dyldSharedCache(path:)` 先查表:那份还活着(还有镜像引用它)就用它;否则开一份,先把它不加锁的懒状态读好(映射表、带滑动信息的映射表、symbol cache,与 `cachedHost` 的做法相同)再放进表。 +- **显式文件**:`.machOFile(path:)` 与系统根下的文件同理,按标准化路径、文件身份和首选 CPU 共享挑好的那个 slice,弱引用。**分两步落地**:cache 这一半先做;显式文件等 MachOKit 去掉独立文件的 `cache` 探测(`fix/standalone-file-cache-probe`)发版之后再做。 +- **不变的**:查找顺序与结果,`cachedHost` 与根所在 cache 的特例,`DyldCacheImageDirectory` 的数据目录;`FileDependencyLocator` 与 `DependencySearchPath` 的公开接口不变,下游不用改。 +- **没问就定的假设**: + - **弱引用,不常驻。** 定位器建完闭包就释放,缓存定位器没用,要缓存的是打开本身;常驻又会让 `evolution` 跨几十份 cache 时每份都一直开着(第 80 节常驻过 51 份宿主 cache、4,182 个文件)。 + - **共享 `MachOFile` 是安全的。** 读取走 MachOKit 的内存映射,并发读没问题;cache 里的镜像在构造时就给了 `_cache`,之后不再写懒状态。独立文件的 `cache` 探测原先会写 `_cache`,MachOKit 0.55.101(`fix/standalone-file-cache-probe`)去掉了这个探测,显式文件的共享排在它之后落地。 + - **RuntimeViewer 的目录照旧自己开配对的 cache。** 定位器之间共用一份之后,一个进程里这份 cache 最多开两次(目录一次、定位器一次),不值得为省这一次加公开 API。 +- **验证**:上面那条命令,这份 cache 上同时开着的描述符 369 → 205,单个文件最多 7 → 4(MachOKit 的打开、Swift 与 ObjC 读取层的映射;预估的「3 个以内」偏少,见决策日志),输出逐字节一致;新测试:两个根各自的依赖闭包里,同一个 cache 镜像来自同一个 `FullDyldCache`,同一路径的显式文件是同一个实例;放掉全部引用后再查,会重新打开。 +- **落地步骤**: + 1. ✅ cache 这一半:`SharedDyldCacheOpeningTests` 先红(两个定位器共用一份打开;六个定位器在 256 个描述符下都能定位到镜像),再在 MachODependencies 加共享打开表(`SharedDyldCacheOpenings`)、`FileDependencyLocator` 改用它;`Modules/MachODependencies.md` 与账本同批。 + 2. ✅ 显式文件这一半:`SharedMachOFileOpeningTests` 先红(两个定位器各拿一个实例;300 个定位器在 256 个描述符下有的打不开文件),再加 `SharedMachOFileOpenings`,`.machOFile(path:)` 与系统根下的文件都改用它;文档同批。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-06 | 创建为 Draft | 修描述符耗尽时横向排查到的同类问题:依赖定位器按根重开配对的 cache 与显式文件。用户要求另起一批、先给方案 | +| 2026-11-06 | 共享表放在 MachODependencies 内部,不做成 MachOKitExtensions 的公开 API | 用户选定。不加公开接口、RuntimeViewer 不用改;配对的 cache 在一个进程里最多开两次,可以接受 | +| 2026-11-06 | cache 先做,显式文件等 MachOKit 的独立文件探测修复发版后再做 | 用户选定。cache 这一半不依赖那个修复;共享独立文件的 `MachOFile` 要等它去掉并发时会写共享状态的探测 | +| 2026-11-06 | 用户批准,开始实现 cache 这一半 | 叠在本地 `next`(0bdfd80d)上:它含描述符耗尽的修复与 MachOKit 0.55.101 / MachOKitExtensions 1.3.1,都还没推送。同日 MachOKit 0.55.101 已发,显式文件那一半的前提满足,开不开工另问用户 | +| 2026-11-06 | 同一个定位器的搜索路径里同一份打开只加一次 | 两次点名同一个 cache 文件,原先各开一份、各查一遍,结果相同;共用之后是同一个实例,查一遍即可 | +| 2026-11-06 | 实测:每个文件最多 4 个描述符,不是预估的 3 个以内 | DockHelper 配对归档的 27.0 cache 跑一次 `interface`:这份 cache 上同时开着的描述符 369 → 205,单个文件最多 7 → 4(改动前 4–7,改动后 2–4),输出逐字节一致。这次运行只建了两个定位器(静态布局、ObjC 祖先解析),改动前它们各开一份,改动后共用一份;剩下的是 MachOKit、Swift 读取层与 ObjC 读取层各自的映射。根越多,省得越多 | +| 2026-11-06 | cache 这一半实现完成,待用户看过后收尾 | 全量 2,793 个测试只红既有的 `ThunkOnlyObjCMemberTests` 4 条;分支变基到已推送的 `next` 4b08e02a 上。显式文件那一半的前提(MachOKit 0.55.101)已满足,开工另问用户 | +| 2026-11-06 | 用户同意开工显式文件这一半 | MachOKit 0.55.101 去掉了独立文件的 `cache` 探测,共享独立文件的 `MachOFile` 不再有并发写 | +| 2026-11-06 | 显式文件按文件身份加 CPU 的原始值取键;挑 slice 的规则搬进共享表;系统根下的文件一并共享 | 原始值做键,只差能力位的两个 CPU 会各开一份,只是少共享;同一个文件挑出的 slice 只取决于 CPU,所以挑 slice 放在共享表里。系统根文件与显式文件是同一种「按路径读 Mach-O」,分开处理只会留下同类问题 | +| 2026-11-06 | 显式文件这一半实现完成,待用户看过后收尾 | `MachODependenciesTests` 38 条全过;全量见账本 | +| 2026-11-06 | 落地为 0086,状态改 Implemented | 用户在 RuntimeViewer 里离线打开 Dock.app 验证通过。两步都已实现,没有后续项。不另写使用指南或实现说明:公开接口不变,没有调用方要守的新约定,设计与取舍已写进配套的 Modules/MachODependencies.md 第 3 节;没有新术语 | diff --git a/Documentations/Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md b/Documentations/Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md new file mode 100644 index 000000000..c4cac6b54 --- /dev/null +++ b/Documentations/Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md @@ -0,0 +1,37 @@ +# 0087 - `@ResolvableLocatableLayoutWrapper`:样板宏改名并补上遵循 + +- **状态**: Implemented +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **关联提案**: [0027-locatable-layout-wrapping-macro](0027-locatable-layout-wrapping-macro.md)(引入这个宏;本提案推翻它「宏不生成遵循」的决定) +- **实现分支 / PR**: `refactor/resolvable-locatable-layout-wrapper-macro` + +## 摘要 + +0027 引入的 `@LocatableLayoutWrapping` 只生成 `layout` / `offset` / `init(layout:offset:)` 三项存储,遵循仍要在声明处手写 `: ResolvableLocatableLayoutWrapper`。98 个贴了宏的 struct 都是 `ResolvableLocatableLayoutWrapper`(直接写的 51 个,经 `MetadataProtocol`、`ContextDescriptorProtocol`、`TopLevelDescriptor` 这类子协议遵循的 46 个,还有一个只写了 `LocatableLayoutWrapper`),宏与遵循从来成对出现,分开写只是多一处要记住的样板。本提案让宏同时补上遵循,并把它改名为 `@ResolvableLocatableLayoutWrapper`:宏名就是它带来的遵循,和 `@Observable` 宏对 `Observable` 协议是一个思路。 + +## 方案 + +- **宏实现**(`Sources/Support/MachOMacros/ResolvableLocatableLayoutWrapperMacro.swift`,由 `LocatableLayoutWrappingMacro.swift` 改名):在原有的 member 角色之外加一个 extension 角色。编译器只把类型**还缺**的协议交给扩展宏,所以宏照单生成 `extension X: <缺的协议> {}`,一个都不缺时什么也不生成。member 角色的行为不变:访问级别跟随宿主,宿主已手写的成员跳过并发 warning,贴在非 struct 上报 error(extension 角色此时静默返回,不重复报错)。 +- **宏声明**从 `Utilities`(`Sources/Support/Utilities/Macros/LocatableLayoutWrapping.swift`)搬到 `MachOSwiftSection`,与 `ResolvableLocatableLayoutWrapper` typealias 放在同一个文件。扩展宏要在声明里写出要补的协议,它们分别在 MachOKitExtensions、MachOResolving 与 MachOKit(经它转出口的 `LayoutWrapper`),`Utilities` 看不到。宏与 typealias 同名不冲突:宏只在 `@` 后面查找。`MachOSwiftSection` target 直接声明对 `MachOMacros` 的依赖(此前经 `Utilities` 间接拿到)。 +- **`conformances:` 写出整条协议链**:`LocatableLayoutWrapper, Resolvable, LayoutWrapper, Equatable, Sendable`,不只写顶上两个。只写两个时,`LayoutWrapper` 只是经 `LocatableLayoutWrapper` 隐含,Swift 6.3 下 `TypeMetadataRecord.layoutSize` 在 `MachOFile+Swift.swift` 里报「requires that 'TypeMetadataRecord' conform to 'LayoutWrapper'」,同一行在 `MachOImage+Swift.swift` 里却编过;`FullMetadata.layoutSize` 同样。写出 `LayoutWrapper` 后这几处都编过。`Equatable`、`Sendable` 同理一并写出,不留只靠隐含的遵循。 +- **宿主文件都要 `import MachOKit`**:展开出来的扩展写着 `LayoutWrapper`,这个名字只有 MachOKit 转出口,`MachOBase` 不转。98 个宿主分布在 97 个文件里,有 33 个原来只 import 了 `MachOBase`(或什么都没 import),补上 `import MachOKit`;漏了时报「cannot find type 'LayoutWrapper' in scope」,位置指在宏展开里。AGENTS.md 的那条规则写明了这一点。 +- **98 处用法**:`@LocatableLayoutWrapping` 换成 `@ResolvableLocatableLayoutWrapper`。直接写了 `: ResolvableLocatableLayoutWrapper` 的 51 处删掉它(`BuiltinTypeDescriptor` 留下 `TopLevelDescriptor`),`GlobalActorReference` 删掉 `: LocatableLayoutWrapper`;经子协议遵循的 46 处声明不动——子协议还带着 `where Layout: …` 约束与关联类型,删不得。 +- **覆盖率扫描器**(`PublicMemberScanner`)按新宏名认出宿主、补上 `layout` / `offset` 两个成员,覆盖率契约与 baseline 不变。 +- **不变的**:每个类型生成的存储成员逐字相同,读取行为不变,所以不跑渲染 A/B。下游仓库(RuntimeViewer、MachOObjCSection、MachOKitUI、swift-decompiler 等)没有一处用到旧宏名,改名不留 deprecated 别名。 +- **没问就定的假设**: + - `GlobalActorReference`、`MetadataBounds`、`ClassMetadataBounds` 此前不是 `Resolvable`,改后多出这个遵循。`Resolvable` 的默认实现就是按布局整块读,三者都没有自己的 `resolve`,行为不变;只是公开 API 多了一个遵循,属于增量变化。 + - 0027 当初保留声明处协议名的两条理由不再成立:宏名就是协议名,`grep ResolvableLocatableLayoutWrapper` 仍能找到全部遵循者;多重遵循的类型现在把其余协议写在声明处、这一个交给宏,宏只补缺的,不会重复。 + - 历史文档(0027 正文、2026-09-11 的任务报告、演进账本的旧章节)保持原样,它们记的是当时的事实;只在 0027 的决策日志末尾追加一行指向本提案。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-06 | Created as Draft | 宏与 `ResolvableLocatableLayoutWrapper` 遵循总是成对出现,用户要求把遵循收进宏并给宏改名 | +| 2026-11-06 | 宏名取 `@ResolvableLocatableLayoutWrapper` | 用户在三个候选里选定:与它补上的遵循同名,搜索协议名仍能找到所有遵循者 | +| 2026-11-06 | 按轻量档写精简提案;状态 Draft → Accepted → In Progress | 用户批准方案;提案随功能分支的第一个提交落盘,不先单独提交进 `next`:`next` 的检出里有别处未提交的改动,其中包括提案索引所在的 `Documentations/README.md` | +| 2026-11-06 | `conformances:` 由两个协议改为整条协议链 | 只写两个时,两处对隐含协议 `LayoutWrapper` 的静态成员引用编不过,且同一行在另一个文件里能编过,取决于编译顺序;写出 `LayoutWrapper` 后编过 | +| 2026-11-06 | 33 个宿主文件补 `import MachOKit` | 扩展里要写出 `LayoutWrapper` 这个名字,只有 MachOKit 转出口它;中途一度怀疑是编译器丢了遵循、改成无视编译器给的缺失清单,查明是名字不可见后撤回,宏仍只补编译器报缺的协议 | +| 2026-11-06 | 实现完成,待用户看过后收尾 | Ultra 上 Xcode 26.6 全量 2,793 个测试全过,原始退出码 0,覆盖率不变式通过、baseline 零改动。文档:AGENTS.md 的 ABI 层规则改写(含 `import MachOKit` 的要求),演进账本加一节,0027 决策日志补一行;不另写实现说明,宏的文档注释已说明协议链与 import 的原因;没有新术语,术语表不动 | +| 2026-11-06 | 落地:取号 0087,状态 In Progress → Implemented | 合进 `next` 前远端已落地 0086 与演进账本第 124、125 节,本提案顺延为 0087、账本第 126 节;与远端 `next` 合并后在 Ultra 上用 Xcode 26.6 重跑全量:2,796 个测试、532 个套件全过,原始退出码 0。配套文档的判断不变:不另写实现说明与使用指南,没有新术语 | diff --git a/Documentations/Evolutions/0088-machofile-performance.md b/Documentations/Evolutions/0088-machofile-performance.md new file mode 100644 index 000000000..be426fb06 --- /dev/null +++ b/Documentations/Evolutions/0088-machofile-performance.md @@ -0,0 +1,131 @@ +# 0088 - 离线读取追平进程内:去掉 MachOFile 独有的开销,再压两边共用的部分 + +- **状态**: Implemented +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-08 +- **关联提案**: [0086-shared-dependency-openings](0086-shared-dependency-openings.md)(依赖定位器按路径共享 cache 与 Mach-O 文件的打开,本提案的依赖镜像索引建在它之上) +- **实现分支 / PR**: 本库 `perf/machofile-performance`(已合进 `next`,演进账本第 127 节);MachOObjCSection、MachOKit fork 各开同名分支;swift-demangling 另有提案与分支(`perf/demangler-self-copy`) + +## 摘要 + +RuntimeViewer 离线(`MachOFile`)读二进制的 Swift 部分比进程内(`MachOImage`)慢。上一轮修掉了独立文件每读一次就重开文件等四处根因之后,本机 dyld cache 里的 SwiftUI 打开全部布局注释(RuntimeViewer 的默认)生成 interface,离线仍要约 27.8 秒 CPU,进程内约 15.9 秒。采样显示差距几乎全在离线独有的计算上:静态布局引擎给依赖镜像建索引 12 秒,在 cache 里定位 ObjC 方法表 1.7 秒,读取原语约 1.4 秒。本提案分两期:第一期去掉这三块,目标是追平进程内;第二期压两种读取器共用的部分(主镜像符号索引、统计模块名、索引与打印的热点),RuntimeViewer 的加载也随之变快。另加一个开发用的基准程序,用来在同一进程里比较两种读取器。所有改动输出逐字节不变、公开 API 不变。 + +## 方案 + +### 基线 + +release 构建,Mac Studio Ultra(macOS 27.2),`sample` 按阶段采样,单位是忙碌样本对应的 CPU 秒。 + +本机 cache 里的 SwiftUI,`interface` 打开五类布局注释(字段偏移、成员地址、vtable 偏移、类型布局、枚举布局),命令行共 27.8 秒: + +| 部分 | CPU 秒 | 只有离线才有 | +|---|---|---| +| 给依赖镜像建索引(`ImageReference.init`,算跨模块字段布局用) | 12.0 | 是 | +| 在 cache 里定位 ObjC 方法表(MachOObjCSection `DyldCache._machO(at:)`) | 1.7 | 是 | +| 读取原语(取映射、地址换算、拷贝、取 identifier) | 约 1.4 | 是 | +| 统计模块名(`SwiftInterfaceBuilder.collectModules`,只有命令行走) | 2.1 | 否 | +| 主镜像符号索引、索引器 `prepare`、其余打印 | 约 10.6 | 否 | + +- **依赖镜像索引为什么贵**:`ImageReference.init` 一次建齐七张表。其中给类型起名要走 `SymbolicDemangler.demangleContext`,碰到匿名上下文(私有类型、局部类型)就去查符号,于是为每个依赖镜像建一整张符号索引,这一项 7.7 秒。`BuiltinTypeLayoutIndex` 4.8 秒,ObjC 协议名 2.6 秒(与前者有重叠)。依赖按顺序折叠,一次名字未命中就把剩下的传递依赖全部建一遍。`ImageReference` 也不跨 universe 共用:每个打印器建一个 universe,RuntimeViewer 换一个镜像就把共同的依赖(SwiftUICore、Foundation……)再建一遍。 +- **单个文件也一样**:iOS 18.5 模拟器的 SwiftUI 带上运行时根目录做依赖搜索路径时共 19 秒,不带只要 11.7 秒,多出的部分同样是依赖镜像索引。 +- **进程内对照**:同一份 SwiftUI 经 `MachOImage` 约 15.9 秒,量自 `RenderingVerificationTests`,已扣掉下一条所说的开销。 +- **为什么不用渲染对照测试的墙钟**:测试进程里 swift-dependencies 每取一次 `@Dependency` 就调 `TestContext.current`,后者用 `dlsym` 查一个不存在的符号,查不到不缓存,占采样忙碌时间 45–60%。墙钟两次运行能差一倍。 + +### 测量:开发用基准程序 + +新增可执行 target `reader-benchmark`(`Sources/Executables/reader-benchmark`,不作为 product 对外)。它在普通进程里按同一份配置分别经 `MachOImage`(`dlopen` 后取镜像)与 `MachOFile`(本机 cache 或给定文件加依赖搜索路径)跑 `prepare()` 与 `printRoot()`,分段报告 CPU 时间、墙钟与 instructions retired(`proc_pid_rusage`);`--mode index` 只跑 `SwiftDeclarationIndexer.prepare()`,即 RuntimeViewer 加载镜像时等的那一步。每一步改动前后各量一次。 + +基准程序量出的基线(release,本机 cache 里的 SwiftUI,CPU 秒 / instructions retired,两次运行的范围): + +| 场景 | `MachOImage` | `MachOFile` | +|---|---|---| +| 只建索引 | 4.8–5.1 / 67 G | 6.0–6.4 / 86 G | +| interface 准备 | 7.1–7.8 / 111 G | 8.4–9.0 / 131 G | +| interface 打印(五类布局注释) | 5.1–5.6 / 69 G | 20.1–22.0 / 304 G | + +iOS 18.5 模拟器的 SwiftUI(单个文件,运行时根目录作依赖搜索路径):只建索引 6.9–7.2 / 100 G,准备 9.1–10.0 / 139 G,打印 8.0–8.5 / 111 G。 + +### 第一期:去掉离线独有的开销 + +1. **依赖镜像索引**(MachOSymbols:`SymbolIndexStore`;SwiftLayout:`ImageReference`、`ImageUniverse`) + - 符号索引分两段:第一段只收符号表、按偏移的行索引、`_symbolic` 表与导出事实,不 demangle;把每个名字还原成节点树的第二段在第一次有查询要用树时才建。给依赖镜像的私有类型起名只查「这个地址上的符号」,从此不再 demangle 整个依赖镜像。**已完成**:打印 304 G → 200 G。 + - 七张表各自按需建,用到哪张建哪张;四种查找(类型、协议、ObjC 类、assocty witness)各自折叠依赖,类型查找不再顺带读路过的每个镜像的 ObjC 协议表。读失败的表当空表,不再连累整个镜像。**已完成**。 + - `ImageReference` 按镜像进 `SharedCache`(淘汰组 `layoutImageIndexes`;它不指向别的组的存储,所以不跟随任何组),所有 universe 共用一份。**已完成**:与上一条合计,打印 200 G → 153 G。 + - 按模块名直接找到依赖镜像,名字未命中时不再把剩下的依赖全部折叠一遍:待前几步做完后按采样再定。 +2. **cache 里按地址、按序号找镜像**(MachOObjCSection) + - `DyldCache.machO(containing:)` 每次调用都把 cache 里的全部镜像逐个构造出来、逐段比较地址(macOS 27 的 cache 约四千个镜像),读协议列表、类与 category 时每个指针调一次;`DyldCacheLoaded` 的同名函数(进程内)也一样。改为每个 cache 只建一次按地址排序的区间表,二分查找,同一地址落在几个镜像里时仍取原来遍历顺序里的第一个。 + - `DyldCache._machO(at:)` 每次调用都重建整张 header info 列表、线性查找、再逐个子 cache 尝试构造镜像;改为每个 cache 只建一次「镜像序号 → 镜像」的对照表。 + - **已完成**(MachOObjCSection 分支 `perf/machofile-performance`):文件一侧的表挂在 cache 文件打开的 file handle identity 上,进程内的表随进程存活(已加载的 shared cache 从不卸载)。只建索引 86 G → 79 G,准备 131 G → 124 G,打印 153 G → 118 G。 +3. **读取层**(MachOKit fork、本库 MachOReading) + - `MachOFile` 的读取直接从 MachOKit 打开文件时做的那份映射里按偏移取值(fork 新增 `@_spi(Support) fileBytes`):不再另外映射一遍文件(`SharedFileMapping` 删除),不再每读一次就查一次关联对象、做一次动态类型转换、分配一个 `Data`。**已完成**:准备 117 G → 116 G,打印 111 G → 107 G,只建索引 72 G → 71 G。 + - 原计划的「地址区间表、段表各算一次」与「`identifier` 存在实例上」不做:采样显示从完整 cache 枚举出的镜像本来就带着自己文件的 `DyldCache`,`cacheAndFileOffset` 只是每次读取走一遍已记住的映射表,剩下的这几项合计不到 1%。 + +### 第二期:两种读取器共用的部分 + +4. **统计模块名**(SwiftInterface):把节点池扫一遍,不再对每个符号的整棵树做一次泛型遍历(每次调用都要向运行时实例化一次 opaque 类型)。**已完成**:`SymbolIndexStore.moduleNamesInAllSymbols(in:)` 在节点池里前序遍历、共享子树只进一次,名字与首次出现的顺序不变;interface 准备阶段 116 G → 70 G,与只建索引持平。 +5. **主镜像符号索引**(MachOSymbols):把符号名还原成节点树这一步分到多个线程做,再按原顺序驻留,索引内容与顺序不变。**已完成**:每批最多 16 × 512 行,提前一批分给各线程还原,驻留与分类留在建索引的线程上按行号顺序做。只建索引的墙钟 6.6 秒 → 3.7 秒。swift-demangling 0.7.2 的 `Demangler` 在 `require(pop())` 上会整份复制自身,多线程同时复制节点栈时抢引用计数,CPU 时间一度升到约 11.4 秒;用户批准后在 swift-demangling 修掉(它的提案 0018,随 0.7.3 发布),CPU 回到约 6.3 秒,指令数也少了约 6 G。 +6. **索引器与打印的热点**:按前几步做完后的采样逐个处理,方向是减少临时分配、去掉热循环里没有特化的泛型调用。**已做两处**:`MangledName.resolve` 不再每个字符调一次 `String(format: "%c")`(离线打印约 4.6%,进程内约 1.8%);类约束泛型参数的替身 `Swift.AnyObject` 的 assocty witness 查找直接答没有(它是 SwiftUI 布局里唯一一次查不到的 witness 查找,却让 552 个依赖镜像全部建了 witness 表)。打印阶段 107 G → 92 G。另在 swift-demangling 0.7.3 里让 `Remangler` 的节点哈希缓存不再逐格销毁(进程内打印约 6%)。剩下的大头:类型查找为找到第 33、46、56、59 个依赖镜像里的四个类型,把前面的镜像全建了类型表(约占离线打印 4%,其中三分之二是为给依赖镜像的匿名上下文起名而建整张符号表第一段),记为后续项。 + +第二期之后(release,上游用发布版:MachOKit 0.55.102、MachOObjCSection 0.8.206、swift-demangling 0.7.3;instructions retired / 墙钟,三份 interface 与基线逐字节相同): + +| 场景 | 基线 `MachOFile` | 现在 `MachOFile` | 现在 `MachOImage` | +|---|---|---|---| +| 本机 cache 的 SwiftUI:只建索引 | 86 G / 6.4 秒 | 64 G / 3.8 秒 | 59 G / 3.1 秒 | +| 同上:interface 准备 | 131 G | 64 G | 60 G | +| 同上:interface 打印(五类布局注释) | 304 G / 21 秒 | 86 G / 6.2 秒 | 61 G / 4.5 秒 | +| iOS 18.5 模拟器的 SwiftUI:只建索引 | 100 G | 71 G | — | +| 同上:interface 准备 / 打印 | 139 G / 111 G | 73 G / 70 G | — | + +只建索引的 CPU 时间约 6.3 秒(单线程时约 5.2 秒),多出的是各线程分批还原树的开销。 + +### 不变的部分 + +- `dump` 与 `interface` 的输出逐字节不变,以渲染 A/B 验证。 +- 公开 API 不变;新增的只有上游仓库的 SPI。 +- CLI 的 flag 与行为不变。 + +### 落地步骤 + +1. 基准程序,记录基线(本库)。**已完成** +2. 依赖镜像索引,按上面四条依次做,每条各量一次(本库)。前三条已完成,第四条(类型查找按模块定向)记为后续项。 +3. cache 里按地址、按序号找镜像(MachOObjCSection)。**已完成**,随 0.8.206 发布。 +4. 读取层(MachOKit fork → 本库)。**已完成**,fork 随 0.55.102 发布;MachOKitExtensions 不用改。 +5. 统计模块名(本库)。**已完成**。 +6. 主镜像符号索引多线程(本库)。**已完成**。 +7. 索引器与打印的热点(本库)。做了两处,其余见上。 + - 期间查出 MachOKit 的竞态(fork 修复,见决策日志):`DyldCache`、`FullDyldCache`、`MachOFile` 把算过的映射表、main cache、full cache、symbol cache 记在不加锁的存储属性里,两个线程第一次同时读同一个镜像时会 use-after-free。 +8. 收尾:全量测试、渲染 A/B、Xcode 26.6 编译检查;上游按依赖顺序发版(MachOKit fork、MachOKitExtensions、MachOObjCSection),本库抬依赖下限;更新演进账本与相关模块文档。**已完成**:上游发版 MachOKit fork 0.55.102、MachOObjCSection 0.8.206、swift-demangling 0.7.3(MachOKitExtensions 不用改),本库已抬下限;演进账本记在第 127 节。 + +开发期间本库经 `swift package edit` 指向上游的功能分支,不动任何共享检出的依赖链接。 + +### 采用的假设 + +- 进程内的数字以基准程序为准;渲染对照测试只用来做 A/B。 +- 第二期第 5 项若发现节点驻留无法安全分线程,就只把还原节点树分出去、驻留留在单线程,并在决策日志里记下。 +- 测试进程里那次 `dlsym` 不在本提案范围内,记为后续项。 + +### 后续项 + +- 测试进程里 swift-dependencies 的 `TestContext.current` 每次都 `dlsym`:拖慢所有经 `@Dependency` 的测试,可在测试支撑里预先建立依赖上下文,或向上游提修复。 +- 类型查找按模块定向(第 2 项第四条):查一个名字时只折叠类型表里可能有这个模块前缀的镜像。每个镜像的前缀集合可以不建整张表就算出来——各类型描述符祖先里的模块名,加上嵌套类型所在扩展的被扩展类型的模块;只含标识符的名字才走定向查找(局部类型的键带 ` #`、括号,不会与之相等)。收益有限:Foundation、SwiftUICore 都扩展了 `Swift` 里的类型,查 `Swift.*` 时它们仍要建表;RuntimeViewer 在各个根之间共享依赖镜像的表,只有头一两个根受益。做之前要先在真实镜像上钉住「每个只含标识符的键的前缀都在集合里」。 +- 依赖镜像的符号表第一段只为给匿名上下文起名而建:可以再拆出只按偏移查的一段,跳过按名字排序、去重哈希与导出 trie 遍历。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-06 | 创建为精简提案,用户批准:两期都做,加开发用基准程序,MachOObjCSection、MachOKitExtensions、MachOKit fork 可以改并各自发版(MachOKit 只进 fork);状态 Accepted | 上一轮修复后离线仍慢约 1.75 倍,采样显示差距几乎全在离线独有的计算上 | +| 2026-11-06 | 基准程序落地、记下干净基线;状态 In Progress | 测试进程的墙钟被 `dlsym` 污染,普通进程里两种读取器才可比 | +| 2026-11-06 | 依赖镜像起名改为「符号索引分两段」,不再「沿描述符父链自己拼名字」 | 自己拼名字要逐条复刻 `demangleContext` 的规则(C 导入类型的 TypeImportInfo、扩展上下文、私有类型的 discriminator),依赖镜像的私有类型又确实会被按名字查到(依赖类型的字段经 symbolic reference 指向它);分两段后起名只查一个地址上的符号,贵的部分(demangle 整个镜像)已经去掉,名字仍由同一套代码给出,查找两侧必然一致 | +| 2026-11-06 | 依赖镜像的表按需建、按查找种类分开折叠、按镜像共享 | 各种查找折叠的镜像与顺序和原来相同,每次查找答案不变;共享的 `ImageReference` 只含值类型,不指向别的淘汰组的存储 | +| 2026-11-06 | `DyldCache.machO(containing:)` 与 `DyldCacheLoaded` 的同名函数并入第 2 项 | 符号索引分两段后重新采样,它是依赖镜像索引里剩下的最大一块(读 ObjC 协议列表时每个协议都要遍历 cache 的全部镜像) | +| 2026-11-06 | 读取改走 MachOKit 自己的映射,删掉 `SharedFileMapping` 与 `ConcurrentFileMappingTests`;`SharedFileMappingTests` 改名 `FileMappingTests`,「删掉的文件读取要抛错」改为「照样读得到」,另加越界读取抛错;CI 套件列表随之换名 | 映射在打开文件时就已建好且按打开共享,读取不再有「第一次读时映射」这一步,竞态与映射失败两种情形都不存在了;描述符反而少了一份 | +| 2026-11-06 | 第 3 项缩小为只做 `fileBytes`,MachOKitExtensions 不改 | 采样修正了「每次访问 `cache` 都新建 `DyldCache`」的判断:cache 里的镜像创建时就带着自己文件的 `DyldCache`,余下几项合计不到 1% | +| 2026-11-06 | 第 5 项按计划做:demangle 一批批分给多线程,驻留与分类留在单线程按行号顺序 | 节点序号就是驻留顺序,打印与快照依赖它;一行的树只由名字决定,分线程不改变结果 | +| 2026-11-06 | 并行 demangle 的 CPU 开销来自 swift-demangling:`try require(pop())` 这类写法里 `require` 不是 `mutating`,编译器先整份复制 `Demangler` 再求参数,之后每次 `pop()` 都写时复制节点栈 | 采样:并行时还原树的一半 CPU 在这份复制引起的 retain/release 上,单线程时也占 demangle 时间约三分之一。swift-demangling 不在已批准可改的上游里,改不改、发不发版由用户决定;本库先保留并行(墙钟减半),决策日志记下代价 | +| 2026-11-06 | 第 4 项改为在节点池里遍历,共享子树只进一次 | 结果、首次出现顺序与符号数都和逐棵树遍历相同(`moduleNamesMatchAWalkOfEveryTree` 钉住) | +| 2026-11-06 | 第 7 项先做 `MangledName.resolve` 与类约束替身的 witness 查找 | 前者逐字节核对过 `%c` 与按 Latin-1 标量追加在 0x20–0xFE 上结果相同;后者经临时插桩确认:整次运行只有这一次 witness 查不到,代价是 552 个依赖镜像的 witness 表 | +| 2026-11-06 | 修 MachOKit fork 的竞态:两张映射表在打开 cache 时就读好、改为常量;镜像组装时就带的 `DyldCache` 改为常量;其余懒得出的引用(main cache、full cache、symbol cache)经 `MemoizedReference` 加锁读写,锁外计算、只在仍为空时发布 | SwiftInterfaceTests 约一半的运行在 `mappingInfo(for:)` 里 SIGSEGV(lldb 抓栈)。缓存是上游 2026-06 加的,第 4 步之前的读取路径也走它;第 2 步让依赖镜像的表在所有 universe 间共享、`LazilyBuiltIndex` 又在锁外建表,两个测试会同时给同一个镜像建同一张表,才变得常见。热路径上的两处改成常量而不是加锁,读取不多一次加锁 | +| 2026-11-07 | 用户批准:swift-demangling 也改并发版(修 `Demangler` 的自我复制,顺带看 `Remangler` 销毁替换表的开销),走它自己的提案与语料对照测试,本库抬依赖下限;MachOKit 的竞态修复只留在 fork,不提上游;类型查找按模块定向记为后续项 | 前者让两种读取器建索引都少约 5% 指令、并行时的 CPU 从约 2.3 倍降到约 1.25 倍;后两项按用户的取舍 | +| 2026-11-07 | 实现完成,待用户看过后收尾 | 全量测试约 2800 个,只有 ThunkOnlyObjCMemberTests 的 4 条在默认 Xcode 27.2 下红,用 Xcode 26.6 跑同一套 8 个全过(现场编译 fixture 的工具链差异,基线就有),这一步同时是本库的 Xcode 26.6 编译检查;渲染 A/B(基线为本分支切出时的 `next` 并固定在旧的上游版本,候选用新发布的上游)三条读取路径 96 对全部逐字节相同。AGENTS.md 里「`MachOFile` 不能并行打印是因为读取共用 `FileHandle`」的理由已不成立,改为如实说明尚未验证、规则不变。文档:MachOSymbols、SwiftInterface、SwiftLayout、MachOCaches 的模块文档已随各步同步;不另写使用指南或实现说明;新术语无。 | +| 2026-11-08 | 用户看过后落地:合进 `next`,取号 0088,状态 Implemented,演进账本第 127 节 | 收尾前在本分支切出时的 `next` 上用默认 Xcode 27.2 复跑 `ThunkOnlyObjCMemberTests`:红的是同样 4 条、断言位置相同,确认不是本次引入。此后只改了文档,其余验证沿用上一行。使用指南、实现说明与新术语的判断同上一行,都不需要;后续项照旧三条。 | diff --git a/Documentations/Evolutions/0089-swift-objc-interop-module.md b/Documentations/Evolutions/0089-swift-objc-interop-module.md new file mode 100644 index 000000000..ec6022c3e --- /dev/null +++ b/Documentations/Evolutions/0089-swift-objc-interop-module.md @@ -0,0 +1,288 @@ +# 0089 - 把 SwiftInspection 的 ObjC 部分拆成 SwiftObjCInterop 模块 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-09 +- **所属愿景**: 无 +- **关联提案**: [0055-group-sources-by-layer](0055-group-sources-by-layer.md)(上一次整理 target 的位置,新模块沿用它的 `Sources/<层>/` 布局);[0018-self-contained-abi-layer](0018-self-contained-abi-layer.md)(把符号归属定在 SwiftInspection,后来的 ObjC 功能以此为由就近落户);要搬的代码出自 [0046](0046-objc-implementation-class-recognition.md)、[0047](0047-objc-ancestor-override-recovery.md)、[0048](0048-objc-member-selector-recovery.md)、[0049](0049-objc-ancestor-dependency-closure.md)、[0052](0052-objc-custom-class-name.md)、[0078](0078-objc-classes-without-class-objects.md)、[0079](0079-swift-declared-objc-protocols.md);[0057-reading-context-migration](0057-reading-context-migration.md)(0.25.0 删除废弃的读取转发,本提案随同一个破坏性版本发布) +- **实现分支 / PR**: `refactor/swift-objc-interop-module`(worktree `.worktrees/MachOSwiftSection-SwiftObjCInterop`);RuntimeViewer 一侧是 `feature/swift-objc-interop-module`(worktree `RuntimeViewer/.worktrees/RuntimeViewer-SwiftObjCInterop`) +- **配套文档**: 模块参考 [Modules/SwiftObjCInterop.md](../Internal/Modules/SwiftObjCInterop.md) + +## 摘要 + +SwiftInspection 的 39 个源文件里有 19 个、约 6100 行(整个模块的一半)讲的是 Swift 类型在 Objective-C 一侧的样子:Swift 类的 class object、`@objc @implementation` 类、Swift 里声明的 `@objc` 协议、ObjC 方法表与祖先链、从 ClangImporter 移植的命名规则。本提案把这 19 个文件整块搬进新模块 `SwiftObjCInterop`(`Sources/Analysis/SwiftObjCInterop/`),它在依赖层级上紧挨在 SwiftInspection 之上、在 SwiftLayout 与 SwiftThunkAnalysis 之下。类型名、访问级别、日志的 subsystem 与 category、缓存淘汰分组的名字一律不变,只换所在模块;SwiftInspection 从此不再依赖 MachOObjCSection。这是源码层面的破坏性改动:直接用到这些公开类型的下游要多写一行 `import SwiftObjCInterop`,RuntimeViewer 的两处在同一批改好。dump 与 interface 的输出不变。 + +## 动机 + +SwiftInspection 的定位是 Swift runtime metadata 分析:带 symbolic reference 的 demangle、enum 布局、泛型参数分层、in-process metadata 构建。可今天它有一半代码在读 `__objc_classlist`、`class_ro_t`、`protocol_t` 和 ObjC 方法表,模块名已经说不清模块里装着什么: + +- **一项模块依赖只为这一半而存在**。SwiftInspection 里 import MachOObjCSection 的 8 个文件全在 ObjC 一侧,另一半一个都不用它(`Package.swift:521`)。 +- **入口文档失去主题**。`AGENTS.md` 里 SwiftInspection 的条目约 4400 个字符,是所有模块条目里最长的(第二长的 SwiftThunkAnalysis 约 2800),大半篇幅在讲 ObjC 索引;模块参考 `Internal/Modules/SwiftInspection.md` 至今「待写」,一个模块装着两个主题,很难写成一篇。 +- **这种混杂是一份份提案就近累积出来的,没有人通盘决定过**。0046 的决策日志写的理由是「它已经依赖 MachOObjCSection 与 MachOFoundation,位于 SwiftDump 与 SwiftDeclaration 之下,两条路径共用」(`0046-objc-implementation-class-recognition.md:126`);此后 0047、0048、0049、0052、0078、0079 都以「与已有的 ObjC 索引同层同模式」跟进。新模块同样位于 SwiftDump 与 SwiftDeclaration 之下,同样满足这个理由;但只要 ObjC 代码还留在 SwiftInspection,下一个 ObjC 功能还会照这个理由放进去。 + +## 前期调研 + +### 要搬的 19 个文件 + +全部在 `Sources/Analysis/SwiftInspection/`,括号里是 `next` 当前的行数: + +| 主题 | 文件 | +|------|------| +| Swift 类在 ObjC 一侧的样子 | `SwiftClassObjectIndex.swift`(237)、`SwiftClassWithoutClassObjectIndex.swift`(454)、`CustomObjCClassName.swift`(38)、`ObjCRuntimeNames.swift`(79)、`ClassHierarchyDumper.swift`(81) | +| `@objc @implementation` 类 | `ObjCImplementationClassIndex.swift`(740)、`ObjCImplementationClassFacts.swift`(208) | +| ObjC 协议 | `SwiftDeclaredObjCProtocolIndex.swift`(289)、`ObjCProtocolAdoptionIndex.swift`(283)、`ObjCProtocolRecord.swift`(213)、`ObjCProtocolRequirements.swift`(424) | +| 成员与祖先链 | `ObjCClassMethodIndex.swift`(641)、`ObjCClassHierarchy.swift`(257)、`ObjCAncestorResolver.swift`(286)、`ObjCMember.swift`(193)、`ObjCMemberShape.swift`(433) | +| 命名规则与类型编码 | `ObjCImporterNaming.swift`(924)、`ObjCImporterVerbs.swift`(88)、`ObjCTypeEncoding.swift`(274) | + +合计 6142 行;留下的 20 个文件约 6000 行。 + +`ClassHierarchyDumper` 是 in-process 专用的调试工具(`@_spi(Internals)`),沿 Swift 类的 metadata 一路走进 ObjC 父类,用的是 MachOObjCSection 的 `ObjCClass64`,并在同一个文件里给 `ObjCClass64` 补了几个 retroactive conformance。它若留下,SwiftInspection 就得为这 81 行继续依赖 MachOObjCSection,所以一起搬。 + +### 依赖方向只有一个 + +- **ObjC 一侧用到核心的只有三样,都已经是 `public` 或 `package`**:`SymbolicDemangler.demangleTypeUncached(for:in:)` 与 `demangleContext(for:in:)`(`public`,`SymbolicDemangler.swift:327`、`:342`)、`NodeTypeNaming`(`package`,`NodeTypeNaming.swift:53`–`:130`)、`GenericParameterDepthLayout.make(for:in:)`(`public`,`GenericParameterDepthLayout.swift:87`)。搬过去不需要放宽任何访问级别。调用点:`ObjCProtocolAdoptionIndex.swift:245`、`ObjCRuntimeNames.swift:73`、`SwiftClassObjectIndex.swift:175`、`SwiftClassWithoutClassObjectIndex.swift:339`、`:389`、`:425`、`ObjCClassMethodIndex.swift:557`、`ObjCImporterNaming.swift:270`、`ObjCMemberShape.swift:428`、`SwiftDeclaredObjCProtocolIndex.swift:268`。 +- **核心不用 ObjC 一侧的任何东西**。只有两个共用文件里夹着 ObjC 一侧的声明:`SharedCacheEvictionGroup+SwiftInspection.swift` 五个分组里的 `objcImplementationClasses`、`objcHierarchy`、`objcAncestorResolver`,以及 `Extensions/MachORepresentableWithCache+ReaderKinds.swift:28` 的 `objcImplementationClassReader`。 +- `RuntimeMetadataTypeBuilder.swift` 的 `import ObjectiveC` 是系统的 ObjC runtime 模块(in-process 构建 metadata 时用),与 MachOObjCSection 无关,留在原处。 + +### 包内的消费方 + +37 个源文件提到要搬的类型,分布在 8 个模块:SwiftDeclaration 19、SwiftDump 7、SwiftIndexing 4、SwiftLayout 2、SwiftThunkAnalysis 2、SwiftDeclarationRendering 1、SwiftPrinting 1、SwiftSectionKit 1。其中 3 个只在文档注释里提到(`SwiftDeclarationIndexConfiguration.swift`、`StandInMemberSymbolBuilder.swift`、`SwiftIndexEvents.swift`),真正要加 import 的是 34 个。CrossReferenceAnalysis 只用 `SymbolicDemangler`,不受影响;TestSupport、Executables、Plugins 一处都没用到。 + +### 测试 + +20 个测试文件用到要搬的类型: + +- SwiftInspectionTests 里 5 个纯 ObjC 的套件:`ObjCImporterNamingTests`、`ObjCProtocolRequirementBuilderTests`、`SwiftClassObjectIndexTests`、`SwiftClassWithoutClassObjectIndexTests`、`SwiftDeclaredObjCProtocolIndexTests`。 +- SwiftInspectionTests 里 4 个两边都测的套件:`AnonymousContextPrivateDiscriminatorTests`、`DyldCacheTwinImageTests`、`MalformedSymbolValueTests`、`SymbolicManglingIndexTests`。其中 `AnonymousContextPrivateDiscriminatorTests` 与 `SymbolicManglingIndexTests` 经 `internal` 的协议 `ObjCImplementationClassReading` 读 ObjC class。 +- 其余 11 个分布在 SwiftDumpTests、SwiftInterfaceTests、SwiftIndexingTests、SwiftDeclarationRenderingTests、SwiftSectionCommandTests、SwiftSectionKitTests、IntegrationTests。SwiftSectionCommandTests 与 SwiftSectionKitTests 的那两个只用到同名的 dump 段名字 `objcImplementationClasses`(不是淘汰分组),不需要 import,所以要加 import 的测试文件是 13 个,要加依赖的测试 target 是 6 个。 + +CI 按套件名过滤(`.github/workflows/macOS.yml:123` 的 `\.(…)(/|$)`),套件换了测试 target 照样匹配;名单里的 `MalformedSymbolValueTests` 本来也留在原处。没有源码扫描测试写死 `SwiftInspection` 的路径。 + +### 下游 + +- **RuntimeViewer** 有两处:`RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/ObjC/RuntimeObjCSection.swift:67`(`ObjCImplementationClasses.all(in:)`)与 `RuntimeViewerCore/Sources/RuntimeViewerCore/Images/RuntimeLoadedImageReading.swift:29`(SPI 的 `ClassHierarchyDumper`)。RuntimeViewerCore 在 `USING_LOCAL_DEPENDENCIES=1`(写在它的 `.package.env` 里)时经 `../../MachOSwiftSection` 直接读本库的集成 worktree,否则跟远端的 `next` 分支(`RuntimeViewerCore/Package.swift:128`),所以本库一合进 `next`,这两处就编不过。 +- **MachOKitUI**(`MachOSwiftSectionDetailBuilder.swift`)与 **REAgent**(`StaticAnalysisSwiftSession.swift`)import SwiftInspection,但不用要搬的类型。swift-decompiler、MachOViewer 不 import SwiftInspection。 + +### 留不了过渡别名 + +新模块依赖 SwiftInspection,SwiftInspection 就不能反过来写 `public typealias ObjCMember = SwiftObjCInterop.ObjCMember`,那是循环依赖。`@_originallyDefinedIn` 只服务于带平台可用性标注的二进制框架,对 SwiftPM 源码包不起作用。所以没有废弃过渡期,只能直接搬。 + +### 输出不会变 + +要搬的文件里没有 `Error` 类型,也没有 `String(reflecting:)`、`localizedDescription`、`type(of:)` 这类会把模块名带进输出的写法;改动只是文件位置和 import。 + +### 日志 + +要搬的类型里有 6 个用 `@Loggable(.private, subsystem: "com.machoswiftsection.swift-inspection", category: "<类型名>")`。`AGENTS.md` 规定 subsystem 与 category 跨重构保持稳定(RuntimeViewer 按它们过滤日志流),所以搬过去照旧写 `swift-inspection`。 + +## 提议方案 + +新增 target `SwiftObjCInterop`(`Sources/Analysis/SwiftObjCInterop/`)与同名 library product,把上表 19 个文件原样搬进去(`git mv`,只改 import),两个共用文件里 ObjC 一侧的声明拆到新模块的文件里。SwiftInspection 去掉对 MachOObjCSection 的依赖。8 个消费方模块在 `Package.swift` 里加上对新模块的依赖,34 个源文件各加一行 import。 + +测试照同一条分界:5 个纯 ObjC 套件搬进新的测试 target `SwiftObjCInteropTests`(`Tests/SwiftObjCInteropTests/`),其余用到这些类型的测试文件留在原处,加一行 import。 + +RuntimeViewer 同批改:两个文件各加一行 import,`RuntimeViewerCore/Package.swift` 加上这个 product。本库先合进 `next`,RuntimeViewer 紧接着合进它自己的 `next`。 + +没有询问就采用的假设: + +- 新模块和 SwiftInspection 一样平铺,只有一个 `Extensions/` 子目录,不按主题再分:19 个文件名本身已按主题成组。 +- 现行文档里写着「在 SwiftInspection」的地方全部改成新模块;带日期的记录(TaskReports、Roadmaps、Reviews、已落地的提案、ProjectEvolutionLog、Changelogs)保留当时的写法——与 [0055](0055-group-sources-by-layer.md) 同一条规则。 + +### 非目标 + +- 不改任何类型名、签名、访问级别或逻辑;日志的 subsystem 与 category、缓存淘汰分组的字符串都不变。 +- 不搬 SwiftThunkAnalysis 的 `ObjCMembers/`:`ObjCMethodThunkReferences.swift:87` 用 Capstone 解码 thunk,搬进新模块会让 SwiftLayout 间接依赖 Capstone,而 SwiftThunkAnalysis 单独成 target 正是为了把 Capstone 挡在其他模块之外(`Package.swift:590`)。 +- 不搬 SwiftLayout 自己的 `ObjCClassIndex` / `ObjCProtocolIndex`,也不碰 CrossReferenceAnalysis 的 `ObjectiveCClassIndex`。它们各自服务于布局与交叉引用,要不要与新模块的索引合并是另一个问题。 +- 不整理 `Tests/` 的其他部分。 +- CLI 不变,`AgentPlugins/` 里的 skill 不用改。 + +## 详细设计 + +### `Package.swift` + +新 target 放在 SwiftInspection 之后: + +```swift + /// The Objective-C side of Swift types: the class objects of Swift + /// classes, `@objc @implementation` classes, `@objc` protocols declared + /// in Swift, ObjC method tables and ancestor chains, and the + /// ClangImporter's naming rules (evolution proposal + /// `swift-objc-interop-module`). Sits directly above `SwiftInspection`, + /// whose demangler it uses; this is where `MachOObjCSection` enters the + /// Swift-facing stack. + static let SwiftObjCInterop = Target.target( + name: "SwiftObjCInterop", + dependencies: [ + .product(.MachOKit), + .product(.MachOObjCSection), + .product(.Demangling), + .product(name: "FoundationToolbox", package: "FrameworkToolbox"), + .target(.Utilities), + .target(.MachOCaches), + .target(.MachOFoundation), + .target(.MachOSwiftSection), + .target(.SwiftInspection), + ], + path: "Sources/Analysis/SwiftObjCInterop", + ) +``` + +其余改动: + +- `SwiftInspection` 的依赖去掉 `.product(.MachOObjCSection)`。 +- `SwiftLayout`、`SwiftThunkAnalysis`、`SwiftDeclarationRendering`、`SwiftDump`、`SwiftDeclaration`、`SwiftIndexing`、`SwiftPrinting`、`SwiftSectionKit` 各加 `.target(.SwiftObjCInterop)`。 +- products 在 `.library(.SwiftInspection)` 之后加 `.library(.SwiftObjCInterop)`。 +- 新测试 target: + + ```swift + static let SwiftObjCInteropTests = Target.testTarget( + name: "SwiftObjCInteropTests", + dependencies: [ + .target(.MachOSwiftSection), + .target(.MachOTestingSupport), + .target(.MachOFixtureSupport), + .target(.SwiftInspection), + .target(.SwiftObjCInterop), + ], + swiftSettings: testSettings, + ) + ``` + +- 直接 import 新模块的其他测试 target(SwiftInspectionTests、SwiftDumpTests、SwiftInterfaceTests、SwiftIndexingTests、SwiftDeclarationRenderingTests、IntegrationTests)各加 `.target(.SwiftObjCInterop)`。 + +### 依赖层级 + +`AGENTS.md` 的层级图在 SwiftDump 与 SwiftInspection 之间加一层: + +``` + └── SwiftDump + └── SwiftObjCInterop (the Objective-C side of Swift types — MachOObjCSection enters here) + └── SwiftInspection + └── MachOSwiftSection (ABI model — depends on MachOBase ONLY) +``` + +SwiftThunkAnalysis 与 SwiftLayout 依赖 SwiftObjCInterop;CrossReferenceAnalysis 仍只依赖 SwiftInspection。 + +### 拆开两个共用文件 + +- `SharedCacheEvictionGroup+SwiftInspection.swift` 留下 `symbolicMangling` 与 `demangleMemo`。`objcImplementationClasses`、`objcHierarchy`、`objcAncestorResolver` 连同各自的文档注释搬到新文件 `Sources/Analysis/SwiftObjCInterop/SharedCacheEvictionGroup+SwiftObjCInterop.swift`,构造时传的字符串不变。这正是 `AGENTS.md` 的约定:每个模块在自己的 `SharedCacheEvictionGroup+.swift` 里声明分组。 +- `objcImplementationClassReader` 搬到新模块的 `Extensions/MachORepresentableWithCache+ObjCReaderKinds.swift`,原文件的文档注释里讲 ObjC 那一半的段落随它走;`swiftSectionReader` 只有 Swift 一侧在用,留在 SwiftInspection。 + +### import 的写法 + +消费方文件照原来 import SwiftInspection 的方式加一行: + +```swift +import SwiftInspection +import SwiftObjCInterop +``` + +用到 SPI 的(目前只有 `ClassHierarchyDumper`)写 `@_spi(Internals) import SwiftObjCInterop`;`package` 级的类型在同一个包内照常可见;测试里用到 `internal` 的 `ObjCImplementationClassReading` 的写 `@testable import SwiftObjCInterop`。 + +## 替代方案考量 + +1. **只在 SwiftInspection 里分一个 `ObjC/` 子目录**。零破坏,下游一行都不用改。否决(用户选定拆模块):模块边界与对 MachOObjCSection 的依赖都不变,入口文档仍是一个模块两个主题,下一个 ObjC 功能还会以「同层同模式」放进 SwiftInspection。 +2. **模块名用 `SwiftObjCInspection`**。与 SwiftInspection 对称,一眼看出两者是一对。否决(用户选定 `SwiftObjCInterop`):「ObjC interop」是编译器(`-enable-objc-interop`)与本库 ABI 层(`ClassMetadataObjCInterop`)已有的说法,正好描述「Swift 类型在 ObjC 一侧」这件事;`Swift` 前缀也与包内其他 Swift 侧模块一致。 +3. **再细拆成两个模块**(不读 Mach-O 的命名规则与类型编码一个,按镜像建的索引一个)。否决:命名规则那几个文件也要用 SwiftInspection 的 `NodeTypeNaming`(`ObjCImporterNaming.swift:270`、`ObjCMemberShape.swift:428`),细拆之后依赖并不减少,却在同一个功能区里多出一道模块边界。 +4. **并进 MachOObjCSection**。做不到:这些代码读 Swift metadata(descriptor、`SymbolicDemangler`),而 MachOObjCSection 不依赖本库,反过来依赖就成了跨包循环。 +5. **新模块放在 SwiftThunkAnalysis 之上,连 `ObjCMembers/` 一起收进来**。否决:SwiftLayout 要用 `SwiftClassObjectIndex` 与 `SwiftDeclaredObjCProtocolIndex`,那样它会经 SwiftThunkAnalysis 间接依赖 Capstone。 +6. **在 SwiftInspection 留 typealias 过渡一个版本**。做不到,见前期调研「留不了过渡别名」。 +7. **`ClassHierarchyDumper` 留在 SwiftInspection**。否决:为一个 81 行的 in-process 调试工具保留整项 MachOObjCSection 依赖,拆分就不完整。 +8. **RuntimeViewer 等升级到 0.25.0 再改,本库只在发版说明里写迁移**。否决(用户选定同批改):RuntimeViewer 的本地构建直接读本库的集成 worktree,远端依赖又跟 `next` 分支,本库一合入它就编不过。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏。** 下列 13 个公开类型换到 `SwiftObjCInterop` 模块,名字与形状都不变:`CustomObjCClassName`、`ObjCAncestorResolver`、`ObjCAncestorResolverStore`、`ObjCClassHierarchy`、`ObjCClassHierarchyProviding`、`ObjCClassHierarchyProviderStore`、`ObjCClassHierarchies`、`ObjCImplementationClassFacts`、`ObjCImplementationClasses`、`ObjCMember`、`ObjCMemberTable`、`ObjCMemberShape`,以及 SPI 的 `ClassHierarchyDumper`。其余要搬的类型是 `package` 级,只影响本包。 + +调用方若在只 import 了 SwiftInspection 的文件里直接写到这些类型——或在开启 `MemberImportVisibility` 时访问它们的成员,例如经 `VariableDefinition.objcMember`、`ExtensionDefinition.unrepresentedObjCImplementationInstanceVariables` 拿到的值——就会编不过。改法是加一行 import,并在 SwiftPM 清单里加上 product: + +```swift +// Before +import SwiftInspection + +let classNames = ObjCImplementationClasses.all(in: machO).map(\.className) +``` + +```swift +// After +import SwiftInspection +import SwiftObjCInterop + +let classNames = ObjCImplementationClasses.all(in: machO).map(\.className) +``` + +```swift +// The consumer's Package.swift +.product(name: "SwiftObjCInterop", package: "MachOSwiftSection"), +``` + +用 `@available(*, deprecated, renamed:)` 平滑过渡不可行:类型名没变,变的是所在模块,而旧模块无法再声明指向新模块的别名(循环依赖)。 + +### ABI 兼容性 + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +本仓库内:上述 8 个源码模块与 6 个测试 target 加依赖、加 import;SwiftInspection 去掉一项依赖;CrossReferenceAnalysis 不受影响。 + +下游仓库: + +- **RuntimeViewer**:`RuntimeObjCSection.swift` 加 `import SwiftObjCInterop`,`RuntimeLoadedImageReading.swift` 加 `@_spi(Internals) import SwiftObjCInterop`,`RuntimeViewerCore/Package.swift` 加 product。与本库同批合入 `next`。 +- **MachOKitUI、REAgent**:import SwiftInspection,但不用要搬的类型,不受影响。 +- **swift-decompiler、MachOViewer**:不 import SwiftInspection。 + +### 文档与示例 + +- `AGENTS.md`:层级图加一层;SwiftInspection 条目删去 ObjC 那部分,Swift 一侧原样保留(它没有模块参考可承接细节);新的 SwiftObjCInterop 条目只列组成部分和三条最容易做错的事实,细节进模块参考;SwiftLayout 的 peer 说明与缓存规则里的模块归属改成新模块。 +- 新写模块参考 `Documentations/Internal/Modules/SwiftObjCInterop.md`,登记进 `Modules/README.md` 与 `Documentations/README.md`。它串起已有的六篇专题文档(`ObjCImplementationClassRecognition.md`、`ObjCMemberRecovery.md`、`ThunkOnlyObjCMembers.md`、`CustomObjCClassNames.md`、`ClassesWithoutClassObjects.md`、`SwiftDeclaredObjCProtocols.md`),不复述它们。 +- 改写写着「在 SwiftInspection」的现行文档:`Glossary.md`(7 处)、`Documentations/README.md`(2 处)、`SwiftDeclaredObjCProtocols.md`、`StaticFieldOffsetComputation.md`、`ClassesWithoutClassObjects.md`、`ObjCImplementationClassRecognition.md`、`CustomObjCClassNames.md`、`ObjCMemberRecovery.md`、`ReadingContextAbstraction.md`、`Modules/SwiftLayout.md`、`Modules/SwiftDeclaration.md`、`Modules/MachODependencies.md`、`Modules/SwiftSectionKit.md`、`Modules/SwiftThunkAnalysis.md`、`ProjectMap.md` 的模块分层表;代码里两处讲模块归属的注释(`ObjCMembers.swift`、`SwiftDeclarationIndexer.swift`)。 +- 根目录 `README.md`(英文公开文档):模块表加 `SwiftObjCInterop` 一行,`ClassHierarchyDumper` 从 SwiftInspection 的介绍里移出,import 说明改成 `@_spi(Internals) import SwiftObjCInterop`。 +- `Changelogs/0.25.0.md` 写明搬迁与改法。项目惯例是发版时才写 Changelog,所以迁移说明先记在 ProjectEvolutionLog 本节的「对应版本」里,发版时照着写。 + +## API 演进与废弃策略 + +- 旧位置不保留废弃别名(做不到,见上),直接搬。 +- 随 0.25.0 发布。这一版已计划删除 [0057](0057-reading-context-migration.md) 留下的废弃读取转发,本来就是破坏性版本;放在同一版里,下游只经历一次破坏。 +- 0.x 版本的次版本号可以带破坏性改动,不需要跳主版本号。 + +## 落地步骤 + +1. 从 `next` 切出 worktree `.worktrees/MachOSwiftSection-SwiftObjCInterop` 与分支 `refactor/swift-objc-interop-module`,fixture 只链 `DerivedData/SymbolTests`。(已完成) +2. `Package.swift`:新 target、product、测试 target;SwiftInspection 去掉 MachOObjCSection;8 个消费方模块加依赖。(已完成,`d5a9f332`) +3. `git mv` 19 个文件,拆开两个共用文件,34 个源文件加 import;编译整个库,原始退出码为 0。(已完成,`d5a9f332`) +4. 测试:5 个套件搬进 `Tests/SwiftObjCInteropTests/`,其余 13 个测试文件加 import,6 个测试 target 加依赖;编译全部测试 target。(已完成,`d5a9f332`) +5. 在 Ultra 上跑 `swift test --skip IntegrationTests`,以原始退出码为准。(已完成:2804 个测试全部通过,原始退出码 0) +6. 在 Ultra 上跑渲染 A/B(`Scripts/run-rendering-ab-verification.py`,基线是合入前的 `next`):三条读取路径的 dump 与 interface 逐字节一致。(已完成:96 对全部一致) +7. 文档:按「文档与示例」一节改;提案状态与决策日志同批更新。(已完成,`f7d77dd6`) +8. RuntimeViewer 照跨仓库的流程单独建 worktree 与分支 `feature/swift-objc-interop-module`,改两个文件与清单。验证在 Ultra 的沙盒里做:把 RuntimeViewerCore 与本分支各导出一份放在一起,只有 MachOSwiftSection 走本地、其余依赖照常解析远端的 `next`,编译 RuntimeViewerCore。通过后两边各自在本地合进集成 worktree 的 `next`(不推送);之后推送时本库在前。(已完成:RuntimeViewer `e7e5a1b1`,沙盒编译通过) + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 新模块的模块参考就是配套文档,登记到头部;预计不另写实现说明或使用指南:搬迁本身没有代码里看不出来的决策,迁移改法写进 Changelog。 +- **有没有引入新术语** —— 预计没有:`SwiftObjCInterop` 是模块名,不是术语。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-09 | Created as Draft | 用户指出 SwiftInspection 里 ObjC 的内容太多。调研确认 39 个源文件里有 19 个(约 6100 行)属于 ObjC 一侧,且只单向依赖模块的其余部分,可以拆出去而不成环 | +| 2026-11-09 | 按完整档处理 | 模块拆分属于架构改动,公开类型换模块是破坏性的 API 改动 | +| 2026-11-09 | 拆成独立模块,不只在模块内分子目录 | 用户选定。只分子目录虽然零破坏,但模块边界与对 MachOObjCSection 的依赖都不变,之后的 ObjC 功能仍会以同样的理由落进 SwiftInspection | +| 2026-11-09 | 模块名定为 `SwiftObjCInterop` | 用户选定,没选 `SwiftObjCInspection`:沿用编译器与 ABI 层已有的「ObjC interop」说法,`Swift` 前缀与包内其他 Swift 侧模块一致 | +| 2026-11-09 | RuntimeViewer 同批改 | 用户选定,没选「只在发版说明里写迁移」:RuntimeViewer 的本地构建直接读本库的集成 worktree,远端依赖跟 `next` 分支,本库一合入它就编不过 | +| 2026-11-09 | 默认做法定稿 | 用户确认:只换模块,类型名、访问级别、日志 subsystem 与 category、缓存淘汰分组名都不变;`ClassHierarchyDumper` 一起搬;5 个纯 ObjC 测试套件搬进新测试 target,4 个两边都测的留在原处;`ObjCMembers/` 与 SwiftLayout 自带的 ObjC 索引不动;验收含全量测试与渲染 A/B,都在 Ultra 上跑;新写模块参考、缩短 `AGENTS.md` 的条目;随 0.25.0 发布。提问到此结束 | +| 2026-11-09 | Draft → Accepted | 用户批准,开始实现 | +| 2026-11-09 | Accepted → In Progress | 从 `next` 切出分支 `refactor/swift-objc-interop-module` 与 worktree `.worktrees/MachOSwiftSection-SwiftObjCInterop` | +| 2026-11-09 | 加 import 的文件数按实际用法核定:源码 34 个、测试 13 个、测试 target 6 个 | 调研时按名字出现次数数的。3 个源文件只在文档注释里提到要搬的类型;SwiftSectionCommandTests 与 SwiftSectionKitTests 里的 `objcImplementationClasses` 是同名的 dump 段名字,不是淘汰分组。正文的数字已改成实际值 | +| 2026-11-09 | 消费方源码一律加不带属性的 `import SwiftObjCInterop`;测试照搬原来那行 `import SwiftInspection` 的 `@testable` / `@_spi(Internals)` | 源码里没有用到新模块的 SPI(`ClassHierarchyDumper` 只有 RuntimeViewer 与 IntegrationTests 用);测试照搬属性,原来经 SwiftInspection 能访问的 `internal` 与 SPI 成员搬过去后照样能访问 | +| 2026-11-09 | `AGENTS.md` 的 SwiftInspection 条目只删 ObjC 部分,Swift 一侧原样保留;SwiftObjCInterop 条目保留三条最容易做错的事实 | 原定两条都缩到「一两行加链接」。SwiftInspection 没有模块参考可以承接删掉的细节(`Modules/README.md` 仍记为待写),删了就没有去处;SwiftObjCInterop 那三条(`@objc` 协议没有协议描述符、ObjC 协议遵循没有 conformance record、按名字查 Swift 类查不到时回退 `SwiftClassObjectIndex`)是 agent 默认会做错的,其余细节都进了模块参考 | +| 2026-11-09 | Changelog 留到发版时写 | 项目惯例是 `release:` 提交里才写 `Changelogs/<版本>.md`;迁移说明先记在 ProjectEvolutionLog 本节的「对应版本」里 | +| 2026-11-09 | RuntimeViewer 单独建 worktree 与功能分支,验证改在 Ultra 的沙盒里做 | 原定在 RuntimeViewer 的集成 worktree 里改、用本机的本地依赖编译。改成照跨仓库流程各建各的分支;编译放到 Ultra,因为本机只改代码、构建与测试都去 Ultra,而本机的集成 worktree 在推送之前 Ultra 看不到,所以沙盒里只把 MachOSwiftSection 换成本分支的副本,其余依赖走远端的 `next` | +| 2026-11-09 | 沙盒里 `swift-helper-service` 与 `swift-injection-peer` 也走本地 | 它们的发布版本依赖只有分支版本的包,纯远端解析不出来;RuntimeViewer 平时就从兄弟目录取这两个,沙盒里照样链到 Ultra 上的检出。沙盒第一次解析把 MachOKit 的 `next` 定在 Ultra 上 SwiftPM 缓存里的旧提交(缺 `fileBytes`),`swift package update` 之后取到远端最新的 `next` 才编过——与本次改动无关 | +| 2026-11-09 | 实现完成,待用户看过后收尾 | 全部在 Ultra 上验证:全量 `swift test --skip IntegrationTests`(Xcode 26.6)2804 个测试、534 个套件全部通过,原始退出码 0;渲染 A/B 96 对逐字节一致(归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器文件、进程内 `MachOImage`);RuntimeViewerCore 在沙盒里编译通过。配套文档只有新模块的模块参考,已登记到头部,不另写实现说明或使用指南:搬迁本身没有代码里看不出来的决策,迁移改法记在 ProjectEvolutionLog 本节、发版时写进 Changelog。没有新术语:`SwiftObjCInterop` 是模块名 | +| 2026-11-09 | In Progress → Implemented | 用户看过后收尾:本库合进 `next` 并推送,提案编号 0089,ProjectEvolutionLog 记为第 128 节。RuntimeViewer 一侧的改动在功能分支 `feature/swift-objc-interop-module` 上,已在本地合进它的 `next`;那个 `next` 里还有别的会话没推送的合并,所以这次没有推 RuntimeViewer 的 `next`。在它推上去之前,远端的 RuntimeViewer 跟远端的本库 `next` 编不过,这是留下的后续项 | +| 2026-11-09 | RuntimeViewer 的后续项完成 | 用户选定只推这三行:在 RuntimeViewer 的远端 `next` 上单独提交(cherry-pick,`cf32c2e7`),别的会话合进它本地 `next`、还在等用户看的 Tuist 改动不跟着推。提交里的 RuntimeViewerCore 与沙盒里编过的完全相同。本地 `next` 经合并带着同一份改动,以后整合远端时两边相同、不会冲突 | diff --git a/Documentations/Evolutions/0090-objc-imported-declarations.md b/Documentations/Evolutions/0090-objc-imported-declarations.md new file mode 100644 index 000000000..f75f2285b --- /dev/null +++ b/Documentations/Evolutions/0090-objc-imported-declarations.md @@ -0,0 +1,159 @@ +# 0090 - ObjC 类、category 与协议按 ClangImporter 的规则建成 Swift 声明 + +- **状态**: Implemented +- **创建日期**: 2026-11-10 +- **最后更新**: 2026-11-10 +- **关联提案**: [0079-swift-declared-objc-protocols](0079-swift-declared-objc-protocols.md)(Swift 定义的 `@objc` 协议:本提案把它为协议要求移植的命名规则与类型桥接推广到类、category 与任意协议)、[0048-objc-member-selector-recovery](0048-objc-member-selector-recovery.md)(ObjC 成员表:按 selector 把 ObjC 方法联结到 Swift 成员,本提案靠它把 Swift 实现的成员换成真实声明)、[0046-objc-implementation-class-recognition](0046-objc-implementation-class-recognition.md)(识别 `@objc @implementation` 类);下游是 RuntimeViewer 的提案 0084-objc-generated-interface +- **实现分支 / PR**: `feature/objc-imported-declarations`(自 `next` 切出,已合入 `next`) +- **配套文档**: [Modules/SwiftObjCInterop.md](../Internal/Modules/SwiftObjCInterop.md)(第 6 个子系统与两条契约)、[Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)「ObjC 声明按 Swift 导入的样子」、[ObjCCommandLine.md](../ObjCCommandLine.md)「The Swift view」 + +## 摘要 + +本库只把 Swift 声明打印成 Swift 接口,ObjC 类、category 与协议只有 MachOObjCSection 打出的 ObjC 头文件。RuntimeViewer 要做 Xcode 的 Generated Interface——把一个 ObjC 类显示成 Swift 导入它之后的样子——需要本库给出这种声明。0079 已经为 Swift 定义的 `@objc` 协议移植过 ClangImporter 的命名规则(`omitNeedlessWords`、初始化器、error 约定、subscript)与类型桥接,但只用在协议要求上。本提案把它推广到镜像里任意的 ObjC 类、category 与协议,建成三种新的声明模型,交给 `SwiftDeclarationPrinter` 打印。成员由 Swift 实现时(桥接出去的 Swift 类、`@objc @implementation` 类、Swift 写的 category),经 0048 的 ObjC 成员表联结到那个 Swift 成员,照抄它的真实声明,不再按规则推导。 + +## 方案 + +### 三种声明 + +| ObjC 一侧 | 打印成 | 新模型 | +|---|---|---| +| 类 | `class Name: Superclass, Protocol… { … }` | `ObjCImportedClassDefinition` | +| category | `extension Name: Protocol… { … }`,category 名写进注释 | `ObjCImportedCategoryDefinition` | +| 协议 | `protocol Name: Inherited… { … }`,optional 要求打 `optional` | `ObjCImportedProtocolDefinition` | + +- 不打访问级别,推导出的成员也不打 `@objc`:本库打印的 Swift 接口一律不打访问级别,而这里的每个成员本来就是 ObjC 成员。只在编译器从打印出的名字推不回原 selector 时打 `@objc(selector)`。 +- 类读的是类自己的方法表、属性表与协议表。dyld cache 会把 category 预先附加到类上(类的表变成「多张表的表」,别的镜像的 category 也在里面,类自己的那张排在本镜像的最后),这些 category 不算类的成员,与头文件里类的 `@interface` 一致。 +- 链接器会把同一镜像里给本镜像的类写的 category 并进类自己的表,`__objc_catlist` 里不再有它们。所以 category 声明只出现在给别的镜像的类写的 category 上;Swift 给本镜像的 ObjC 类写的 `extension`、`@objc(Name) @implementation extension` 的成员都是类的成员。 +- 协议沿用 0079 的 `ObjCProtocolRequirementBuilder`,加一个参数区分协议是 Swift 还是 ObjC 声明的(`DeclaringLanguage`):ObjC 声明的协议,属性名照 importer 的属性规则改写,也不去掉 Swift 推导 selector 时插入的 `With`。 +- 类名与协议名的换算沿用 0079 的 `ObjCRuntimeNames`:Swift 类按 `_TtC…` demangle,改过运行时名的经 `SwiftClassObjectIndex` 换回 Swift 名。ObjC 声明的类与协议保持 `__C` 下的 ObjC 名,与 mangling 一致;Swift 里改了名的(`NSObject` 协议是 `NSObjectProtocol`,与同模块某个类同名的协议加 `Protocol` 后缀)照本库的惯例交给打印时的类型名提供者,本提案不在模型里改名。 +- C struct 与 union 不在本提案内。 + +### 成员 + +- **属性**:读属性表的特性串。`R` 打 `{ get }`,否则 `{ get set }`;类属性打 `class var`。所有权只打 Swift 写得出来的:`W` 打 `weak`;`C` 只在属性类型是 Swift 导入成类的类型时打 `@NSCopying`(`NSString`、`NSArray` 这类导入成值类型的不打);可读写、又不是 `&` / `C` / `W` 的对象属性打 `unowned(unsafe)`;只读属性的特性串不记所有权,什么都不打。`BOOL` 属性有自定义 getter 时 Swift 名取 getter 的名字(`hidden` 打成 `isHidden`,`ImportName.cpp` 的 `isBoolType` 分支)。名字开头的缩写词改小写(`CGPath` 打成 `cgPath`),再照 importer 对属性名做删减:属性类型与所在的类相同时删掉名字里重复的类型名(`NSColor` 的类属性 `blackColor` 打成 `black`),属性类型来自特性串。属性的 getter 与 setter 不再单列成方法,属性排在 getter 在方法表里的位置。 +- **方法**:实例方法打 `func`,类方法打 `class func`。名字照 `ObjCImporterNaming`:`init` 家族成初始化器(可空性未知,打 `init!`),`objectAtIndexedSubscript:` 等四个 selector 成 subscript。error 约定只认 selector 里名为 `error` 的那一段(或以 `AndReturnError`、`WithError` 结尾的基名):编码里的 `^@` 也可能是 `NSDictionary **`,`initWithRTF:documentAttributes:` 不能打成 `init(rtf:)`。 +- **工厂方法**(`+colorWithRed:green:blue:alpha:`):importer 只在返回 `instancetype` 时才把它转成 `convenience init(red:green:blue:alpha:)`,而类的方法编码只记 `@`,看不出来。见下文「没问就定的假设」。 +- importer 不导入的 selector 不打:`.cxx_construct`、`.cxx_destruct`、`dealloc`,以及 ARC 下禁用的 `retain`、`release`、`autorelease`、`retainCount`。 + +### 类型从哪来 + +参数与返回值的类型按下面的顺序取,取到即止: + +1. **联结上的 Swift 成员**(见「与 Swift 合并」):精确,含可空性。 +2. **类采纳的协议**(含协议的继承链)里同一 selector 的扩展类型编码:带类名与 block 签名(`@"NSString"`、`@?`)。clang 在每个引用某协议的镜像里都放一份它的 `protocol_t`,所以本镜像里就有。参数个数与 selector 的冒号数对不上的编码不用,退回方法表自己的编码;两者都对不上的方法不打,免得把名字配给错的类型。 +3. **属性的特性串**(`T@"NSString"`):给这个属性的 getter 与 setter。 +4. **都没有**:`id` 与不知道类名的 `@` 打 `Any`;对象一律 `T!`,这正是 importer 对没有可空性标注的声明的做法。 + +第 4 档推出的名字会走偏:importer 靠参数的类名删掉多余的词,而类的方法编码只记 `@`。例如 `convertPoint:fromView:` 的第二个参数丢了类名 `NSView`,推出 `convert(_:fromView:)`,Swift 里的真名是 `convert(_:from:)`。所以推导出的成员沿用 0079 的做法:编译器从打印出的 Swift 名推出的 selector 与实际不同时,打 `@objc(selector)` 钉住原 selector。 + +### 与 Swift 合并 + +打印器打印每个成员之前,先在实现这个类或 category 的 Swift 定义里找回答同一 selector 的成员:用 0048 记在每个 Swift 成员上的 `objcMember`(selector 与是否类方法),属性先按 getter、再按 setter 找,工厂方法按类方法找。找到就打印那个 Swift 成员的声明,找不到的才按上面的规则推导。证据先认 IMP 处的 `To` 符号与反汇编 thunk 找到的调用目标;这两档都没有时,也认只按名字的第三档(0048 只给覆写算这一档):参与配对的定义就是实现这个类的那些,类方法表里的方法总有一个成员实现,名字对得上的就是它。配对在打印时做,模型里的成员不记来源。三种情形: + +- **桥接出去的 Swift 类**(class data 的 Swift 位为 1):类声明来自 Swift 的 `TypeDefinition`,与 Swift 一侧的 interface 相同。同一模块里 extension 的成员在 mangling 里就记成类自己的成员,已经在类里;本镜像里另外的 extension(带约束的、遵循协议的)跟在类后面打印。方法表里没有 Swift 成员回答的方法另列在一个 `extension` 里,按规则推导并注明。 +- **`@objc @implementation` 类**:类头(父类、协议)来自 ObjC 记录,成员来自 `@implementation` extension 里配上的成员。这些 Swift 名就是编译器导入头文件时得到的名字,所以这种类的输出与 Xcode 的 Generated Interface 一致。 +- **Swift 给 ObjC 类写的 extension**(`extension NSView { @objc func … }`、`@objc(Name) @implementation extension`):类在本镜像里时,链接器已把它编成的 category 并进类的表,成员就打在类里;类在别的镜像里时是一个 category 声明。两种都从本镜像那个 `extension __C.NSView` 里配成员。 + +### API 形状 + +照 0079 的 `ObjCProtocolDefinition` 与 `printObjCProtocolDefinition(_:level:)`:模型放 SwiftDeclaration,由 `SwiftDeclarationIndexer` 按名字现建(ObjC 类动辄上千个,不随索引一次建完;镜像里的类与 category 记录按镜像缓存),第一次打印时索引自己,打印器打印。category 按 MachOObjCSection 的 `uniqueName` 取,与 `ObjCInterfaceBuilder.categoryInterface(uniqueName:)` 一致。 + +```swift +// 最简单:一个纯 ObjC 类 +if let definition = indexer.objcImportedClassDefinition(named: "NSView") { + let interface = try await printer.printObjCImportedClassDefinition(definition) +} + +// 常见:桥接出去的 Swift 类,成员自动换成 Swift 声明,不需要调用方做什么 +let contentView = indexer.objcImportedClassDefinition(named: "_TtC8MyModule11ContentView") + +// category 与协议 +let category = indexer.objcImportedCategoryDefinition(uniqueName: categoryUniqueName) +let dataSource = indexer.objcImportedProtocolDefinition(named: "NSTableViewDataSource") + +// 镜像里有哪些 +let classNames = indexer.objcImportedClassRuntimeNames +let categoryNames = indexer.objcImportedCategoryUniqueNames +``` + +成员模型 `ObjCImportedMemberDefinition` 照 `ObjCProtocolRequirementDefinition` 的形状:`kind`(方法、初始化器、工厂初始化器、属性、subscript)、`node`、`selector`、`setterSelector`、`isClassMember`、`ownership`、`hasExplicitSelector`、`typeEncoding`。协议要求直接用 `ObjCProtocolRequirementDefinition`,不另建类型。类定义带上 Swift 一侧:`swiftClassDefinition`(桥接出去的 Swift 类)与 `swiftExtensions`(本镜像里这个类的 Swift extension),category 定义带 `swiftExtensions`。 + +`swift-section objc interface` 加一个 `--swift` 开关(SwiftSectionKit 里是 `ObjCInterfaceRequest.printsSwiftImport`),打印这种 Swift 声明而不是 ObjC 头文件;类、category 与协议才有,struct 与 union 没有。 + +### 落地步骤 + +1. **准确率测量**(已完成,结果见下一节):以 macOS 27.2 的 AppKit 为样本,从 SDK 取每个公开 ObjC 成员的 Swift 名(它的 USR 带 selector,例如 `c:objc(cs)NSView(im)convertPoint:fromView:`),再用已有的 `ObjCImporterNaming` 只凭运行时元数据推导,统计一致的比例,并按原因归类。 +2. 三种模型、属性与方法的规则、类型的四档来源(已完成)。 +3. 与 Swift 合并(已完成)。 +4. 打印器与 `swift-section` 开关(已完成)。 +5. 测试(已完成):命名规则的期望值取自 SDK 里真正的 ClangImporter 给出的名字(第一步测量用的同一批 AppKit 成员),不再另跑 `swift-synthesize-interface`;记录读取与成员构建对进程内的 AppKit 测;与 Swift 合并、打印对 `@objc @implementation` 夹具测(纯 ObjC 类、`@implementation` 类、桥接出去的 Swift 类、Swift 声明的 `@objc` 协议,以及单独发布的 dylib 里给 `NSObject` 写的 category)。 + +### 第一步的测量结果 + +2026-11-10 在 Mac Studio Ultra(macOS 27.2,Xcode 27.2 27B52)上测。SDK 一侧用 `swift-symbolgraph-extract` 导出 AppKit 的符号图(连同 `AppKit@Foundation` 扩展图),以其中每个 ObjC 成员 USR 里的 selector 与它的 Swift 名为准;运行时一侧把 AppKit 载入进程,只读运行时的方法表与属性表,不发消息、不触发 `+initialize`。测量程序在临时分支 `probe/objc-importer-naming-accuracy`(`Sources/Executables/objc-importer-naming-probe`),不合并;逐个成员的结果表留在 Ultra 的 `/Volumes/DerivedData/Agents.noindex/claude/Probes/ObjCImporterNamingAccuracy/AppKit.tsv`。 + +比对了 6,937 个成员,另有 422 个在运行时找不到(实现在别的镜像,或只在头文件里声明)。每个方法按三种类型信息推导:只用运行时编码(对象都只是 `@`)、再加类采纳的协议里同一 selector 的扩展编码(协议成员用协议自己的扩展编码)、把 `@` 换成 SDK 声明的类型(类型信息能达到的上限)。 + +| 类别 | 个数 | 只用运行时编码 | 加协议的扩展编码 | 换成 SDK 的类型 | +|---|---|---|---|---| +| 实例方法 | 2,508 | 66.4 % | 66.7 % | 80.9 % | +| 类方法 | 177 | 53.7 % | 54.2 % | 67.2 % | +| 初始化器 | 428 | 56.3 % | 56.3 % | 58.2 % | +| 属性 | 2,726 | 94.5 % | 94.5 % | 94.5 % | +| 协议方法 | 1,023 | 76.7 % | 92.4 % | 91.6 % | +| 协议属性 | 75 | 100 % | 100 % | 100 % | +| 合计 | 6,937 | 78.4 % | 80.8 % | 86.3 % | + +加上协议的扩展编码之后仍有 1,331 个对不上,其中 639 个只差参数标签。按 SDK 能说明的原因归类,一个成员可以属于几类: + +- 换上 SDK 的类型就对(参数或返回值的类名丢了):415。 +- API notes 改过名:343。只按成员所在的类查,实际更多:父类的改名也管到子类重新声明的同一方法。例如 `NSResponder` 在 API notes 里把 `tryToPerform:with:` 定为 `tryToPerform(_:with:)`,`NSApplication.h` 重新声明了这个方法,于是 `NSApplication` 的这个方法也叫这个名字;推导出的 `try(toPerform:with:)` 正是 Swift 3 时代 API notes 里的旧名。 +- 工厂方法被导入成初始化器:165。 +- 属性名被 importer 缩短(`blackColor` 成 `black`):117。 +- 头文件里有 `NS_SWIFT_NAME`(文本搜索,只作参考):49。 +- 以上都不是:283。其中 113 个带整型参数,多半是枚举或选项集的类型名丢了(参数类型是 `NSEventMask` 时,`matchingMask:` 会被删成 `matching:`);18 个带集合参数,元素类型丢了(`NSSet` 让 `…AtIndexPaths:` 删成 `…At:`)。 + +另外两处是移植本身的缺口:26 个属性只差开头缩写词的大小写(`CGPath` 对 `cgPath`),20 个方法把 `^@` 当成了 error 参数(`initWithRTF:documentAttributes:` 推成 `init(rtf:)`)。 + +对方案的影响: + +1. 协议的扩展编码最关键(协议方法从 76.7 % 升到 92.4 %),照计划用。类方法借采纳协议的编码只多对了 7 个,因为这一档便宜、命中时又精确,仍然保留。 +2. 「成员」一节补上三条:属性名开头的缩写词改小写、照 importer 删减属性名、error 约定只认名为 `error` 的那一段。工厂方法照原假设按 `instancetype` 推测,正好覆盖那 165 个。四条做完,估计合计能到 85 % 左右。 +3. 剩下的差异靠运行时信息补不上:API notes 与 `NS_SWIFT_NAME`、枚举与选项集的类型名、集合的元素类型、由可空性推出的默认参数(`orderFrontStandardAboutPanelWithOptions:` 的 `With` 就是因为参数有默认值才被删掉),以及参数名(importer 不拆参数名为 `sender` 的方法)。这些只有查 SDK 才能拿到,照原假设留给以后的提案;推导出的名字照方案用 `@objc(selector)` 钉住原 selector。 + +### 没问就定的假设 + +- 工厂方法:选择子开头能与类名末尾对上(`matchFactoryAsInitName` 的规则)、返回对象的类方法,按返回 `instancetype` 处理,打成 `convenience init`。不逐个注明是推测:成员列表开头的注释已经说明这些名字是按 importer 的规则推出的。 +- 不打 `async` 版本:importer 会给带 completion handler 的方法另打一个 `async` 版本,但类的方法编码里 block 没有签名,推不出结果类型。与 0079 一致,只打 completion handler 形式。 +- 公开 API 不查 SDK:经 SourceKit 读 SDK 头文件能给公开 API 换上精确的名字,但要装 Xcode、只能在 macOS 上用,留作以后的提案。 +- 发版:新增公开 API,随下一个小版本发布;RuntimeViewer 抬 pin 后接入。 + +## 后续项 + +- `objc interface --swift` 接上 `--resolve-c-module-names` 的类型名提供者:`NSObject` 协议才会打成 `NSObjectProtocol`,`CF…Ref` 才会去掉 `Ref`。 +- 类型名提供者补上 ClangImporter 的一条规则:与同一模块里别的实体重名的协议加 `Protocol`(`NSAccessibilityElementProtocol` 这类)。TypeDatabase 现在只认 API notes 与 CF 规则,Swift 一侧的接口也受影响。 +- `TypeDefinition.extensions` 从来没有人填:填上,或者删掉。 +- 剥掉本地符号的镜像(dyld cache 里的 AppKit)中,`@objc @implementation` 类没有 Swift 符号的成员仍按规则推导,例如 `NSGlassEffectView` 的 `init(frame:)`。 +- 查 SDK 拿精确名字(API notes、`NS_SWIFT_NAME`、枚举与选项集的类型名、可空性),带 completion handler 的方法的 `async` 版本,C struct 与 union 的 Swift 视图:都留给以后的提案。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-10 | Created as Draft | RuntimeViewer 要做 Xcode 的 Generated Interface,把 ObjC 对象显示成 Swift 接口;由 Swift 实现的类要与 Swift 一侧的信息合在一起 | +| 2026-11-10 | 在本库扩展已有的 ClangImporter 移植,不在运行时调用编译器 | 用户选定。纯 Swift,离线文件、iOS 与命令行都能用;调用 `swift-synthesize-interface` 要装 Xcode、每次几秒,而且输入缺的信息一样缺 | +| 2026-11-10 | 按轻量档写精简提案,与 RuntimeViewer 的草案各管一个仓库 | 用户选定;准确率测量放进落地第一步 | +| 2026-11-10 | 用户批准,开始实现;先做落地第一步的准确率测量,测量程序写完给用户看过再跑 | 用户批准时指定的顺序;按全局规则,自己写的脚本先给用户看 | +| 2026-11-10 | 第一步完成:只凭运行时元数据,AppKit 的公开成员有 80.8 % 与 SDK 的 Swift 名一致;「成员」一节补三条规则(属性缩写词小写、属性名删减、error 约定只认 `error` 段),状态改 In Progress | 用户看过测量程序后批准在 Ultra 上运行;三条都是移植的缺口,测量里分别对应 26、117、20 个成员。其余差异要 SDK 才能补,按原假设留给以后的提案 | +| 2026-11-10 | 用户批准接着实现第二到第五步,在 Ultra 上构建与测试,做完在本地合进 `next` | 用户选定 | +| 2026-11-10 | 类只读自己的表,不读 dyld cache 预先附加的 category | 起初读全部表,NSColor 打出了别的镜像的 category 成员与协议;头文件里类的 `@interface` 也只有类自己的成员 | +| 2026-11-10 | category 声明只覆盖给别的镜像的类写的 category;给本镜像的类写的 Swift extension 与 `@implementation` category 的成员打在类里 | 夹具实测:链接器把同镜像的 category 全部并进类的表,`__objc_catlist` 整段不存在,事后分不出哪些成员来自 category | +| 2026-11-10 | 不打访问级别,推导出的成员不打 `@objc`;原方案的 `open` / `public` / `@objc optional` 不用 | 本库的 Swift 接口一律不打访问级别;成员本来就是 ObjC 成员,`@objc` 只在要钉住 selector 时有信息量 | +| 2026-11-10 | 所有权只打 Swift 写得出来的:只读属性什么都不打,`@NSCopying` 只给导入成类的类型 | 只读属性的特性串不记所有权,按原规则会打出 `unowned(unsafe)`;`copy` 的 `NSString` 在 Swift 里是 `String`,`@NSCopying` 写不上去 | +| 2026-11-10 | 与 Swift 合并在打印器里做,成员模型不记 `Origin`;只按名字的第三档在前两档都没有时也认 | Swift 成员已经有自己的模型,再存一份是重复;参与配对的定义就是实现这个类的那些,第三档的成员只能是实现那个 selector 的成员。不认它时,thunk 被优化掉的覆写会按规则再打一遍 | +| 2026-11-10 | 协议要求复用 `ObjCProtocolRequirementBuilder`,加 `DeclaringLanguage` 区分 Swift 与 ObjC 声明的协议 | 两者只差属性名的规则与是否去掉 Swift 插入的 `With`,不值得另建一套 | +| 2026-11-10 | `Protocol` 后缀不在模型里做,节点保持 `__C` 下的 ObjC 名 | 本库的节点与 mangling 一致,Swift 里改了名的 `__C` 名由打印时的类型名提供者(`--resolve-c-module-names`)改写;`objc interface --swift` 还没接它,留作后续 | +| 2026-11-10 | 第五步不另跑 `swift-synthesize-interface`,命名规则的期望值取自 SDK 里 importer 给出的名字 | 第一步已经用 SDK 的符号图对过 6,937 个成员,同一来源更全,也不用在测试里依赖工具链 | +| 2026-11-10 | 实现完成,待用户看过后收尾 | 第二到第五步都已落地,SwiftObjCInteropTests 与新的 ObjCImportedDefinitionTests 在 Ultra 上通过 | +| 2026-11-10 | 用户看过后批准收尾;按本库 CLI 的规定补上请求与命令两侧的 `--swift` 测试,随库发布的 agent 插件 skill 同批写上 `--swift` | 本库规定新开关在请求与命令两侧各有一个测试,改 CLI 要同批更新插件 skill | +| 2026-11-10 | 落地编号 0090,状态改 Implemented。不另写实现说明与使用指南:维护者要知道的契约与坑写进 SwiftObjCInterop、SwiftDeclaration 两份模块参考,用法写进命令行指南的「The Swift view」一节;新术语「ObjC imported declaration」「category merging」登记进术语表 | 模块参考已经覆盖实现里看不出来的取舍,再写一篇实现说明只会复述;没做的几项记进「后续项」 | diff --git a/Documentations/Evolutions/0091-export-verdict-without-local-symbols.md b/Documentations/Evolutions/0091-export-verdict-without-local-symbols.md new file mode 100644 index 000000000..de7649bab --- /dev/null +++ b/Documentations/Evolutions/0091-export-verdict-without-local-symbols.md @@ -0,0 +1,50 @@ +# 0091 - 没有本地符号的镜像里,扩展中的类型与私有 `@objc` 协议也给出导出结论 + +- **状态**: Implemented +- **创建日期**: 2026-11-10 +- **最后更新**: 2026-11-10 +- **所属愿景**: 无 +- **关联提案**: [0016](0016-exported-only-interface.md)(重整名一腿拒绝扩展上下文的由来)、[0024](0024-exported-declaration-flag.md)(`exportStatus` 的来历)、[0083](0083-exported-only-marking-mode.md)(标记模式) +- **实现分支 / PR**: `feature/export-verdict-without-local-symbols`(从 `next` 切) + +## 摘要 + +RuntimeViewer 的侧栏把「Not Exported」设为排除后,AppKit 里仍列出几十个带私有鉴别器的类型,例如 `NSView._HitTestMap`、`NSGlassEffectContainerView.GlassGroup`。原因在 `ExportStatus` 的判定:描述符地址上没有符号时,第二条腿把名字重新 mangle 后查导出表,但名字里只要有扩展上下文就放弃,给出 `.descriptorSymbolNameUnresolvable`。macOS 27.2 的共享缓存里,AppKit 没有本地符号(`dump` 里私有成员符号 0 个;Foundation 153 个,SwiftUI 676 个),而 Swift 写在 ObjC 类里的类型必然经过扩展上下文(`(extension in AppKit):__C.NSView`)。所以 AppKit 里这类未导出的类型全部判不出:约 45 个,其中 33 个的名字带私有声明。`swift-section interface --exported-only` 同样把其中 25 个私有类型留在了输出里,Foundation、SwiftUI、SwiftUICore 则一个都没有。另外,Swift 声明的 `@objc` 协议一律不判(`.declarationHasNoSymbol`),AppKit 的 5 个私有协议因此也一直留着。本提案让这两类声明拿到结论。 + +## 方案 + +1. ✅ **第二条腿只在遇到带约束的扩展时放弃。** 0016 拒绝扩展上下文的理由只对带约束的扩展成立:编译器只把扩展自己的要求 mangle 进上下文,模型的名字却带着完整签名。不带约束的扩展节点只有模块和被扩展的类型两个子节点,重新 mangle 与编译器的拼写一致(`$s10Foundation15AttributeScopesO6AppKitE0dE10AttributesV010AttachmentB0OMn` 经 `swift-demangle -test-remangle` 原样往返)。`containsExtensionContext(_:)` 改为只认带泛型签名的扩展节点。协议走的是同一条路,一并修好。 +2. ✅ **私有声明与局部类型没有符号可判时,判为未导出(第三条腿)。** 编译器给私有、fileprivate 与局部声明的链接不是 public,它们不会进导出表。用 `-enable-private-imports` 编出的镜像会导出私有声明,但那时第一条腿已在描述符上找到导出符号,走不到这里。认法有两种,任一成立即可: + - 名字的上下文链里有私有声明或局部类型:看自己的名字、外层类型、扩展所扩展的类型;不看泛型实参、扩展的要求和函数签名(`isPrivateOrLocal(_:)`)。 + - 描述符外层有匿名上下文(`isEnclosedByAnonymousContext(_:in:)`):编译器给私有声明与局部声明套的就是这一层。什么符号都没留的镜像里匿名上下文没有名字,私有类型的名字里就没有鉴别器,只有这一种认得出。 + + 用在两处:第 1 步之后仍判不出的类型与协议(带约束扩展里的私有类型),以及 `ObjCProtocolDefinition.exportStatus`(它没有描述符,只看名字;原来恒为 `.declarationHasNoSymbol`)。只在镜像有导出信息时判为 `.notExported`,否则是 `.imageHasNoExportInformation`;为此 `SymbolIndexStore` 加了包内接口 `hasExportInformation(in:)`。 +3. ✅ **打印器照常过滤。** `printObjCProtocolDefinition` 像 Swift 协议一样经过 `exportFilterVisibility(excluded:)`:`--exported-only` 时去掉,标记模式下标成「开关关闭时才可见」。协议的默认实现扩展随协议一起打印,不另外进 `ExportFilterScope`,公开 API 不变。ObjC 类别(category)遵循的协议全是本镜像未导出的 `@objc` 协议时,这条 conformance 也去掉,同 Swift 类型遵循未导出协议的 conformance 一样;还遵循了别的协议的,整条保留。 +4. ✅ **测试。** 新建现编夹具 `ExtensionContextExportFixture`(不开 `-enable-testing`),里面有:嵌在 `extension Int` 和 `extension NSObject` 里的 public、internal、private 类型,私有类型里的嵌套类型,扩展里的协议和局部类型,带约束扩展里的 public、internal 与 private 类型,public 与 private 的 `@objc` 协议,以及只遵循私有协议、同时遵循两种协议的两个 Foundation 类别。它出三个变体,各用自己的模块名分别编译:未剥离、只留 `_symbolic` 符号(AppKit 的形状)、`strip -x`。 + - 两个剥离变体上,扩展里 internal、private 与局部的声明判 `.notExported`,public 的判 `.exported`。修复前前者是 `.descriptorSymbolNameUnresolvable`。 + - 未剥离变体上,凡经过不带约束扩展的名字,重新 mangle 的结果与描述符上的符号逐字相等。这证明第 1 步放开之后不会拼错名字、误删导出的类型。 + - 带约束扩展里,internal 的类型仍判不出,private 的判 `.notExported`(`strip -x` 变体上靠匿名上下文认出)。 + - 私有 `@objc` 协议判 `.notExported`,public 的仍是 `.declarationHasNoSymbol`;`--exported-only` 的 interface 里没有私有协议,也没有只遵循它的类别。原 `SwiftDeclaredObjCProtocolsFixture` 上同样断言;`ObjCProtocolDefinitionIndexingTests` 原来断言所有 `@objc` 协议都是 `.declarationHasNoSymbol`,随之改为私有的那个是 `.notExported`。 + - `ExportStatusTests.remanglingRefusesAConstrainedExtensionContext` 保留不动。 +5. ✅ **文档。** `ExportStatus` 的文档注释补上 AppKit 这个反例和第三条腿;`Internal/ExportedOnlyInterfaceFiltering.md`、`Internal/Modules/SwiftDeclaration.md` 与术语表里「重整名拒绝扩展上下文」的说法同批改掉;`--exported-only` 的帮助文字、`InterfaceRequest` 的注释和 README 原写「没有导出证据的一律保留」,补上私有与局部声明这个例外。 + +下游:RuntimeViewer 抬 pin 之后,侧栏对类型自动生效;它构造 `@objc` 协议条目时现在不读 `exportStatus`,要改一行。它自己逐条打印 ObjC 类别的 conformance,第 3 步的类别规则也要照做一遍。并在 RuntimeViewer 的 ResolvedIssues 里记下这次问题。 + +没有询问就采用的假设: + +- 第 2 步的推断不只用在 `@objc` 协议上,也用在带约束扩展里的私有类型上:理由相同,而要解决的就是「排除未导出之后不应再看到私有声明」。 +- RuntimeViewer 里用户手动做出的特化不在本提案范围。它的私有声明来自泛型实参,描述符属于原型,沿用原型的结论本来就对。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-10 | Created as Draft | RuntimeViewer 把未导出的类型设为排除后,仍显示带私有鉴别器的 AppKit 类型;调查定位到本库的导出判定。用户选定在本库修,并决定私有的 `@objc` 协议也当作未导出。 | +| 2026-11-10 | 用户批准,开始实现 | 在功能分支 `feature/export-verdict-without-local-symbols` 上实现;构建与测试按惯例放到 JH's Mac Studio Ultra 上跑。 | +| 2026-11-10 | 夹具出三个变体,每个用自己的模块名分别编译 | 只做 `strip -x` 覆盖不到 AppKit:AppKit 留着 `_symbolic` 符号,私有鉴别器还原得出,所以另做一个只留 `_symbolic` 的变体。起初从一次编译复制出三份,测试却在剥离副本的描述符上查到了本地符号:各镜像的缓存按 `LC_UUID` 认文件,复制品共用一个 UUID,剥离副本读到的是未剥离那份的符号索引。 | +| 2026-11-10 | 第三条腿除了看名字,也看描述符外层有没有匿名上下文 | `strip -x` 的变体里匿名上下文没有名字,带约束扩展里的私有类型名字中没有鉴别器,光看名字判不出;匿名上下文是编译器给私有与局部声明套的,结构上就在。 | +| 2026-11-10 | 只遵循私有 `@objc` 协议的 ObjC 类别也在 `--exported-only` 时去掉 | 修复后用新编的 swift-section 跑 AppKit,私有类型与扩展都没了,只剩 `extension __C.NSTextList: AppKit._TitleProviding {}`。Swift 类型遵循未导出协议的 conformance 本来就会去掉,这里同样处理;类别还遵循了别的协议时整条保留,不靠猜删。 | +| 2026-11-10 | 新增包内接口 `SymbolIndexStore.hasExportInformation(in:)`,不公开 | 第三条腿要分清镜像有没有导出信息,只有本库自己用。 | +| 2026-11-10 | 全量测试的 43 个失败判为基线既有,不在本分支处理 | 在 JH's Mac Studio Ultra(macOS 27.2,Xcode 27.2)上,`SymbolTestsCore` 按 CI 的方式(ad-hoc 签名)现编,`swift test --skip IntegrationTests` 有 43 个测试失败,全是 ABI 层描述符偏移与基线不等一类(另有 `KeyPathComputedPropertyBodyTests`、`ThunkOnlyObjCMemberTests`)。在 `next`(`bd1df364`)上用同一份夹具跑同一批测试,失败的测试一个不差、也没有多出来,与本改动无关。 | +| 2026-11-10 | 实现完成,待用户看过后收尾 | 验证都在 JH's Mac Studio Ultra 上:撤掉判定修复时,扩展中的类型、私有 `@objc` 协议与往返重整共 8 组测试变红,恢复后全绿;单撤类别规则时只有它那一条变红。最终提交上 `SwiftInterfaceTests`、`SwiftIndexingTests` 与 `SwiftSectionKitTests` 只剩 4 个失败,都在上一行的基线集合里。用新编的 swift-section 对 macOS 27.2 的 AppKit 跑 `interface --exported-only --emit-private-source-files`:修复前留下 25 个私有类型、32 个扩展,修复后一个带私有鉴别器的声明都不剩,`NSTextList` 遵循 `_TitleProviding` 的类别也不在了。没有另写实现说明或使用指南:实现说明 `Internal/ExportedOnlyInterfaceFiltering.md` 已同批更新;没有新术语,术语表只改了已有词条。 | +| 2026-11-10 | 落地:编号 0091,演进账本第 130 节,状态改为 Implemented | 用户批准收尾。这期间 `next` 已推上 0090(ObjC imported declarations),所以取 0091;合并只在两份索引表冲突,两边都保留,合并结果推送前在 Ultra 上重跑了验证。第 1–5 步与方案一致,没有没做完的项;RuntimeViewer 一侧的跟进另做。指南与术语的判断见上一行。 | diff --git a/Documentations/Evolutions/0092-existential-any.md b/Documentations/Evolutions/0092-existential-any.md new file mode 100644 index 000000000..7a8953dfe --- /dev/null +++ b/Documentations/Evolutions/0092-existential-any.md @@ -0,0 +1,89 @@ +# 0092 - interface 与 dump 给 existential 写上 `any`,并修好 constrained existential 字段的类型 + +- **状态**: Implemented +- **创建日期**: 2026-11-11 +- **最后更新**: 2026-11-11 +- **关联提案**: swift-demangling 的提案 `0020-existential-any`(`Evolutions/0020-existential-any.md`),加 `DemangleOptions.useExistentialAny`。同一套做法的先例是 [0064-module-selectors](0064-module-selectors.md) 与 swift-demangling 的 `0017-module-selectors`。 +- **实现分支 / PR**: 本库与 swift-demangling 都是 `feature/existential-any` + +## 摘要 + +本库印 existential 类型时不写 `any`:`any P` 印成 `P`,`(any Error)?` 印成 `Swift.Error?`,`(any P).Type` 印成 `P.Protocol`,只有带 primary associated type 实参的 `any P` 带 `any`。编译器从 SE-0335 起写 `.swiftinterface` 时,除了 `Any` 和 `AnyObject` 都写 `any`,Swift 6.4 也没有关掉它的选项(macOS 27.2 SDK 的 Foundation 接口里有 550 处);`Collection` 这类有 associated type 的协议不写 `any`,编译器还会警告 "use of protocol 'Collection' as a type must be written 'any Collection'"。本提案让 interface 与 dump 默认照编译器的规则写 `any`。顺带修一个印错类型的 bug:存储属性 `any Boxed` 在 interface 里印成 `Swift.Int`,在 dump 里印成 `symbolic existential type (non-unique) 0x0 `,看不出是哪个协议。 + +## 方案 + +**写法**照编译器(`ExistentialType::get`、`TypePrinter::visitAnyMetatypeType`、`isSimpleUnderPrintOptions`): + +| 源码 | 现在 | 改后 | +|---|---|---| +| `any P`、`any P & Q` | `P`、`P & Q` | `any P`、`any P & Q` | +| `any C & P`、`any P & AnyObject` | `C & P`、`P & Swift.AnyObject` | `any C & P`、`any P & Swift.AnyObject` | +| `Any`、`AnyObject` | `Any`、`Swift.AnyObject` | 不变 | +| `(any P)?`、`(any P.Type)?` | `P?`、`P.Type?` | `(any P)?`、`(any P.Type)?` | +| `any P.Type`、`any (P & Q).Type` | `P.Type`、`P & Q.Type` | `any P.Type`、`any (P & Q).Type` | +| `Any.Type`、`AnyObject.Type` | `Any.Type`、`Swift.AnyObject.Type` | `any Any.Type`、`any Swift.AnyObject.Type`(编译器就这么写,SDK 里有 16 处 `any Any.Type`) | +| `(any P).Type` | `P.Protocol` | `(any P).Type` | +| `any P` | 已带 `any` | 不变;在元类型里写成 `any P.Type`,不重复写 `any` | + +**swift-demangling**:新选项 `DemangleOptions.useExistentialAny`,命名照 `useModuleSelectors`,取自 SE-0335 的 upcoming feature `ExistentialAny`。不进任何预设,预设的输出仍与 Apple 的 demangler 逐字节一致。`NodePrinter` 按上表处理 `protocolList`、`protocolListWithClass`、`protocolListWithAnyObject`、`existentialMetatype`、`metatype` 与 `constrainedExistential`;选项打开时,可选类型与元类型的括号按带 `any` 的写法判断。发版后本库抬依赖下限。 + +**interface**: + +- `SwiftDeclarationPrintConfiguration.usesExistentialAny`,默认打开;`InterfaceRequest.usesExistentialAny` 同名;CLI 用 `interface --no-existential-any` 关闭。 +- 打印上下文照 `usesModuleSelectors` 的路子在创建时读一次;`TypeNodePrintable` 与 `BoundGenericNodePrintable` 按上表改;委托给上游打印器的地方带上新选项。 +- `OpaqueTypeResolving.opaqueType(forNode:index:usesModuleSelectors:)` 的布尔参数换成一个 `DemangleOptions`(`spellingOptions:`),只认拼写类选项——集合 `DemangleOptions.interfaceSpellingOptions`,即 `useModuleSelectors` 与 `useExistentialAny`。opaque type 约束里的实参由 provider 自己打印,这样 `some Sequence` 里的 `any` 才印得出来,以后再加拼写开关也不用再改签名;协议名本身只认模块选择器。这是源码不兼容的改动,但实现方只有本库的 provider,RuntimeViewer 只构造它。`SwiftDeclarationPrinter` 上同名的公开方法保留旧签名,标为废弃并转发到新签名。 + +**dump**:CLI 默认带上 `useExistentialAny`,`--disable-existential-any` 关闭;与其他 demangle 选项一样走 `DemangleOptionGroup`,三个预设都生效。`DumpRequest.demangleOptions` 的默认值同步加上,测试用的 `DemangleOptions.test` 也加上,dump 快照因此记录新写法。dump 里的 constrained existential 沿用上游的写法 `any …Boxed`,与 dump 里符号那几行一致;interface 仍写成 `any …Boxed`。 + +**bug 修复**:字段记录里的 `any Boxed` 是一个 `symbolicExtendedExistentialType`,由 shape(`any Boxed<τ_0_0>`)和实参列表 `[Int]` 组成,两个打印器都只印了实参。改为在 `SymbolicDemangler` 解出类型之后,用 `GenericArgumentBinding` 把实参代回 shape,得到与 getter 符号里一样的 `constrainedExistential` 节点,dump、interface、ABI diff 拿到的都是正确的类型。连带: + +- 原先协议不同、实参相同的两个字段在 ABI diff 里文字完全一样(都是 `symbolic existential type … `),字段换了协议查不出来;修复后能分开。 +- ABI 快照里这类字段的文字变了,`ABISnapshotDocument.currentFormatVersion` 升到 12;旧快照读入时报版本不符,要重新生成。 +- 静态布局引擎改为直接认 `constrainedExistential`(原先从 `symbolicExtendedExistentialType` 里往下找),布局数值不变。 +- shape 读不出来时保留原节点,行为与现在一样。 + +**不动**:查找用的 key(固定预设打印,不带新选项);ABI diff / snapshot / evolution 的写法(用 `.default` 预设,只有上面 bug 修复带来的字段文字变化);TypeIndexing。RuntimeViewer 不用改代码,它取打印配置的默认值,升级后直接显示 `any`;要加设置项另议。 + +**测试与验证**: + +- bug 先写复现测试,确认修复前失败。 +- 新建现编 fixture(照 `ModuleSelectorFixture`),覆盖上表每一行,外加有 associated type 的 `any Collection`、`any Boxed` 字段、`(any Boxed)?` 与 `some Sequence`;interface 与 dump 各一组测试,开关关掉时输出与现在相同。 +- swift-demangling 为每种节点补开关两种状态下的打印测试。 +- 重新生成受影响的快照基线;全量测试在 Ultra 上跑。 +- 渲染 A/B 跑两遍:候选关掉开关,应逐字节一致(constrained existential 字段那几行逐条核对);打开开关,抽查差异只在 existential 的写法。候选一侧关开关,需要给 A/B 脚本和 MachOImage 那条腿各加一个入口;改完脚本重跑它自己的单元测试。 +- CLI 加了 flag,同批更新 `AgentPlugins/swift-section` 的 skill。 + +**落地步骤**(每步各自构建通过、相关测试通过后提交): + +1. ✅ swift-demangling:`DemangleOptions.useExistentialAny` 与 `NodePrinter` 的改动、打印测试、该仓库的精简提案(`feature/existential-any`)。全量 651 个测试在 Ultra 上跑,与官方 demangler 逐字节对照的语料测试全过;只有新测试里 5 个可选类型用例的期望写错(`.default` 不合成 `?`),改用 `.interface` 并补两个 `XSq` 用例后通过。 +2. ✅ bug 修复:`ConstrainedExistentialFieldTests`(interface、ABI 快照)与 `ConstrainedExistentialFieldDumpTests` 修复前 3 个测试全部失败,症状正是 `var boxed: Swift.Int` 与 `symbolic existential type (non-unique) 0x0 `;修复后相关的 43 个套件、209 个测试只剩两份快照不符,差异正好是这两个字段,已更新。 +3. ✅ interface:打印配置、打印上下文、`TypeNodePrintable` / `BoundGenericNodePrintable`、opaque type provider 的拼写参数、`InterfaceRequest` 与 CLI 开关。 +4. ✅ dump:`DemangleOptionGroup` 的开关、`DumpRequest` 与测试预设的默认值。 +5. ✅ 现编 fixture `ExistentialAnyFixture` 与 `ExistentialAnyInterfaceTests`(26 个形状 × 开关两种状态)、`ExistentialAnyDumpTests`,命令映射测试。第一轮全量测试 2842 个测试 / 543 个套件:新测试全过,失败的是 12 份 fixture 快照、`FinalKeywordICFRegressionTests` 里 SourceEditor 的 `languageService`(协议类型,现在写 `any`),以及 `FileMappingTests.readersOfOneCacheFileShareOneMapping`。12 份快照重新录制,共 202 行变化,去掉 `any`、括号并把 `.Protocol` 当 `.Type` 之后与旧快照逐字节相同;SourceEditor 的期望改成 `any`。`readersOfOneCacheFileShareOneMapping` 是全量并发下的偶发:基线与候选单独跑都通过(候选连跑三次),与本改动无关。另补 `constrainedExistentialMetatypeIsLaidOutAsAMetatype`:把三处修复文件换回修复前的版本,它报 40 字节(值容器),修复后是 16 字节。 +6. ✅ 验证与文档,都在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上跑;本库只让 swift-demangling 走本分支的本地副本,其余依赖两侧解析成同一份远端发布版(MachOKit 0.55.102、MachOKitExtensions 1.3.3、MachOObjCSection 0.8.206、swift-semantic-string 0.6.0)。 + - 全量 `swift test --skip IntegrationTests`:2843 个测试 / 543 个套件。失败只有两条,单独跑都通过:`FileMappingTests.readersOfOneCacheFileShareOneMapping` 在基线(`next` 577eadf2 + swift-demangling `next` 6489476)的全量里同样失败,是基线已有的并发偶发;`BoundedConcurrentMapTests.cancellationStopsSubmittingPendingElements` 只在三个任务同跑、负载 60 以上那一轮超出它一分钟的时限,前两轮候选与基线的全量都通过。 + - 渲染 A/B,基线同上,各预构建一次 release 后带 `--skip-build` 跑,96 对(归档 cache 15.5 与 26.6、iOS 16.4–26.5 模拟器、MachOImage 腿)。候选关掉 `any`(`--disable-existential-any` / `--no-existential-any` / `bareExistentials`)时 42 对逐字节一致,54 对共 185 行不同,全部来自 constrained existential 的修复:基线把这类字段印成实参(ActivityKit 的 `[Swift.String : Foundation.DataSwift.Never]`、SwiftUICore 的 `var base: A`),候选印出 `any Combine.Subject`、`any SwiftUI.Keyframes`,另有 SwiftUICore 三处 `any AnimationFinishingDefinition.Type` 的布局注释由 40 字节改为 16 字节。候选打开 `any` 再跑一遍,与关掉时相比改动 50207 行,去掉 `any`、括号并把 `.Protocol` 当 `.Type` 之后 96 对逐字节相同。 + - 关掉 `any` 那一轮暴露一处缺括号:可选的 constrained existential 元类型印成 `any ….Type?`,已改为 `(any ….Type)?` 并加测试。 + - A/B 脚本自己的单元测试 17 个全过(含新加的两个)。 + - 文档:演进账本、`Modules/SwiftInterface.md`、`StaticLayoutEngine.md`、`SystemFrameworkRenderingVerification.md`、`AGENTS.md`、`AgentPlugins/swift-section` 的 skill(其中点名的开关逐个对过各子命令的 `--help`)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-11 | Created as Draft | 用户确认 interface 与 dump 都改成写 `any`,并修好 `any Boxed` 字段印成 `Swift.Int` 的 bug | +| 2026-11-11 | 默认打开,配置与 CLI 都留关闭的开关 | 用户要的是改掉现在的写法;Swift 6.4 的编译器写接口文件时总是写 `any`,没有关掉的选项。0064 的模块选择器默认关闭,是因为那是 Swift 6.4 才有的新写法,SwiftUI 自己也关掉了 | +| 2026-11-11 | bug 在解析阶段修,不在两个打印器里各修一遍 | 改一处,dump、interface、ABI diff 与布局引擎拿到同一个正确的节点,还让 ABI diff 分得开协议不同的字段;代价是 ABI 快照格式升版 | +| 2026-11-11 | `Any.Type` 写成 `any Any.Type` | 照编译器,SDK 接口里就是这么写的 | +| 2026-11-11 | opaque type 的拼写参数并成一个 `DemangleOptions` | 两个布尔开关并成选项集合,以后再加拼写开关不用改签名 | +| 2026-11-11 | Draft → Accepted:用户批准,开始实现;补上落地步骤 | 精简提案原先没有拆步骤,按方案拆成六步,每步各自能构建、能测 | +| 2026-11-11 | 两个打印器里,「外层已经写了 `any`」的位置(existential 元类型的实例、`any P` 的协议列表)直接印协议成员,不经带缓存的 `printName` | 两个打印器都按节点身份缓存打印片段,而 `any` 是唯一取决于父节点的写法:同一个 protocol list 节点在别处带 `any`、在这里不带,经 `printName` 会互相串用缓存。swift-demangling 有测试覆盖两种顺序 | +| 2026-11-11 | swift-demangling 的 `nestedNameOptions`(特化参数、宏名里的嵌套名字)也透传 `useExistentialAny` | 与 `useModuleSelectors` 同理,一行里不该混两种写法 | +| 2026-11-11 | dump 里的 constrained existential 用上游写法 `any …Boxed`,与同一份 dump 里 getter 符号那行一致 | 代回实参后的节点与 getter 符号里的节点同形,上游打印器对两者给出同一种写法 | +| 2026-11-11 | 静态布局引擎原先给 `any P.Type` 的分支永远走不到(先找到的是内层的 constrained existential),会按值容器而不是元类型布局;随修复改为按元类型布局 | 修复后字段直接是 `existentialMetatype(constrainedExistential)`,走普通的元类型路径;`extendedExistentialLayout` 只留给没经过 `SymbolicDemangler` 的树,并复用同一个解析函数 | +| 2026-11-11 | interface 打印器遇到没解析出类型的 shape,交给上游打印器原样写出,不再印实参 | 把实参当成类型印出来是一个看起来对、实际错的类型;上游的原文至少名副其实 | +| 2026-11-11 | 特化器的诊断文字(`displayName(of:)`)也写 `any` | 它的约定是「照 interface 的写法」,interface 默认写 `any` 了 | +| 2026-11-11 | 两处已知缺口留作后续,这次不改:未展开 opaque 引用拼成 `@_opaqueReturnTypeOf("$s…", n) __<…>` 时,尖括号里的实参按 `.default` 打印;「展开的字段偏移」注释里嵌套字段的类型名在离线与进程内两条路径上都按 `.default` 打印 | 两处都不跟打印配置的拼写走,模块选择器当初同样没接;一处只在独立文件里 opaque 引用展开失败、实参又是 existential 时才碰到,另一处是注释里的类型名而不是声明本身。要接得把拼写选项一路传进 `OpaqueReferenceSpelling` 与 SwiftLayout 的 `NestedFieldOffsetTree`,超出这次的范围 | +| 2026-11-11 | 开关关掉时,可选的 constrained existential 元类型也加括号:`(any P.Type)?` | constrained existential 无论开关都写 `any`,它的元类型同样以 `any` 开头;A/B 里 SwiftUICore 的 `finishingDefinition` 印成 `any ….Type?`,不是合法的 Swift。上游打印器在选项关闭时保持与官方 demangler 一致,不改 | +| 2026-11-11 | 实现完成,待用户看过后收尾。配套文档:不另写使用指南或实现说明,写法规则在提案与 swift-demangling 的 README,实现要点在 `AGENTS.md` 与模块文档;新术语:无 | 落地步骤六步全部完成并验证 | +| 2026-11-11 | In Progress → Implemented,编号 0092 | 用户要求收尾。本库与 swift-demangling(提案 0020)的 `next` 都已推送;swift-demangling 没有发版,本库 `Package.swift` 对它的下限仍是 `0.7.3`,所以走远端依赖的构建要等它发版、本库抬下限后才编得过。验证沿用最终代码上的那轮全量与两轮渲染 A/B(之后只改了文档)。按共享分支编号:origin/next 最大 0091,origin/main 最大 0075;演进账本第 131 节 | diff --git a/Documentations/Evolutions/0093-observable-macro-folding.md b/Documentations/Evolutions/0093-observable-macro-folding.md new file mode 100644 index 000000000..daf8dbca6 --- /dev/null +++ b/Documentations/Evolutions/0093-observable-macro-folding.md @@ -0,0 +1,172 @@ +# 0093 - 识别 `@Observable` 宏:interface 默认折叠它的展开 + +- **状态**: Implemented +- **创建日期**: 2026-11-11 +- **最后更新**: 2026-11-12 +- **实现分支**: `feature/observable-macro` +- **配套文档**: [Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)(模型与识别)、[Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md)(折叠、展开与分块的打印) + +## 摘要 + +用 `@Observable` 写的类,编译后二进制里只剩宏展开的结果:每个被跟踪的属性 `x` 变成 private 的存储字段 `_x` 加一组 computed accessor(getter / setter / `_modify` / init accessor),另外多出存储字段 `_$observationRegistrar`、方法 `access(keyPath:)`、`withMutation(keyPath:_:)`、四个 `shouldNotifyObservers(_:_:)` 重载,以及一个 `extension X: Observation.Observable {}`。interface 今天把这些原样印出来,读起来和源码对不上。本提案让库识别出这样的类:模型上标出它带 `@Observable`(`prepare()` 之后就能读到,宿主可以在类型列表里标出来),interface 默认印成源码的样子(类型上写 `@Observation.Observable`,被跟踪的属性写成普通的 `var x: T`,宏生成的成员与 conformance 不印),打开新开关 `expandsMacros` 则和今天逐字节相同。起因是 RuntimeViewer 要在侧边栏标出这类类型,并让用户在折叠与展开两种形态之间切换。 + +## 方案 + +### 改动位置 + +- 识别规则(新文件):`Sources/Analysis/SwiftInspection/ObservableMacroRecognition.swift`,只读字段记录,供下面两处调用。 +- 模型:新类型 `SwiftAttachedMacro`(`Sources/Declaration/SwiftDeclaration/Model/SwiftAttachedMacro.swift`);`TypeDefinition.attachedMacros` 在 `TypeDefinition.init(type:in:)`(`Model/Definitions/TypeDefinition.swift:230`)里赋值,specialization 构造的定义沿用泛型定义的值;`TypeDefinition.observableMacroExpansion` 由新的索引步骤 `Indexing/TypeDefinition/TypeDefinition+ObservableMacro.swift` 产出,接在 `TypeDefinition+Indexing.swift:97` 的 `recoverWrappedProperties(in:)` 之后;`ExtensionDefinition.generatingMacro` 在 `SwiftDeclarationIndexer` 建 conformance extension 时(`SwiftDeclarationIndexer.swift:791` 一带)赋值。 +- 打印:`SwiftDeclarationPrintConfiguration.expandsMacros`;`SwiftVisibilityOption.expandsMacros`;新文件 `SwiftDeclarationPrinter+ObservableMacro.swift`,照 `SwiftDeclarationPrinter+PropertyWrapperSynthesis.swift` 的做法算一份每次打印用的视图,接进字段块(`SwiftDeclarationPrinter+Headers.swift:471`)、成员块(`SwiftDeclarationPrinter.swift:765`、`:804`)、导出过滤(`SwiftDeclarationPrinter+ExportFilter.swift:218`)、类型头与 extension 的打印。 +- dump:`ClassDumper.declaration`(`Sources/Output/SwiftDump/Dumper/ClassDumper.swift:57`)在类头前加 `@Observation.Observable`。 +- CLI 与 Kit:`InterfaceRequest.expandsMacros`、`interface --expand-macros`,以及 `AgentPlugins/swift-section` 的 skill。 + +明确不动的地方:`fields` / `variables` / `functions` 保持二进制里的原样,ABI diff、snapshot、evolution 的记录不变;diff 与 evolution 的 interface 一律印展开形态(它们比较的是 ABI 事实);property wrapper 的还原不变;不涉及 swift-demangling 与 swift-semantic-string。 + +### 识别规则 + +在 Ultra 上用 Swift 6.4.2 编了探针(debug、release、release 加 `strip -x` 三种),规则按实测定: + +- 必须是 class,并且有一个名叫 `_$observationRegistrar`、类型正是 `Observation.ObservationRegistrar` 的存储字段。字段记录在剥掉符号之后仍在,所以剥过的二进制同样认得出。 +- 有 `_$backingData` 字段的不算:SwiftData 的 `@Model` 也生成同名同类型的 registrar 字段(探针实测),它要另作识别,不在本提案内。 +- 不要求有 `Observation.Observable` 的 conformance record:一个 `@Observable` 类继承另一个 `@Observable` 类时,宏不再生成 conformance(实测子类没有这条记录)。 + +### 被跟踪的属性怎么认 + +每个存储字段 `_x`(`var`,名字不以 `_$` 开头,没被 property wrapper 还原认领)先排除一种情况:类型里有成员变量 `x`、但类型与 `_x` 不同(`weak` 之类的引用存储先剥掉再比),那 `_x` 存的就不是 `x`。`sending` 不算不同:编译器 mangle 声明自身的函数类型时不写 `sending`(`ASTMangler::appendDeclType`,加上它不改符号),字段记录照写,`var make: () -> sending T` 的 accessor 符号读出 `() -> T`、存储读出 `() -> sending T`。其余的依次看下面的证据,第一条成立的为准;每个被跟踪的属性都记下认定它的证据(`ObservableMacroExpansion.TrackedProperty.Evidence`): + +1. `x` 有 init accessor(`Model.count.init`):只有被宏挪走存储的属性才有。 +2. 镜像里的成员变量 `x` 有 setter 或 `_modify`,类型与 `_x` 相同。 +3. `_x` 自己有初始值表达式(`variable initialization expression of Model._cache`):它是手写的存储属性,不认。 +4. 初始值表达式挂在 `x` 名下(`… of Model.count`):源码把初始值写在 `x` 上,宏只挪走了存储。 +5. `_x` 有自己的 accessor 而 `x` 一个都没有:宏的存储与它的 computed 属性要么一起被 vtable 留住,要么一起被剥掉,所以这是手写的存储属性,不认。 +6. 都没有:只凭存储字段名认作被跟踪,证据记为 `backingFieldName`。 + +带本地符号也不能当作「缺了就是没有」:系统框架链接时 dead-strip,没人引用的 init accessor、final 类 internal 属性的 accessor 都会被去掉(SwiftUI 实测,fixture 用 `-dead_strip` 变体复现)。剩下的误判只有一种:用 `@ObservationIgnored` 声明、名字以下划线开头的 `var _y`,镜像里既没有它自己的初始值表达式、也没有它自己的 accessor 时,会被读成被跟踪的 `y`。初始值表达式只在前两条都不成立时才按类型查一次。 + +成员变量 `x` 在镜像里时来源记为 `declaredMember`,否则记为 `synthesized`:从 `_x` 合成 `var x: T`,打印时照 property wrapper 合成的先例在上方加一行 note 注释,写明是从存储字段 `_x` 合成的。 + +其余存储的 `var`(`@ObservationIgnored` 声明的)在折叠形态里加上 `@Observation.ObservationIgnored`:不加的话,读者分不出哪些属性被跟踪。`let` 不加,宏本来就不跟踪它。 + +### 折叠形态长什么样 + +```swift +@Observation.Observable +class InternalModel { + var value: Swift.Int + var optionalText: Swift.String? + @Observation.ObservationIgnored var cacheHits: Swift.Int + let constant: Swift.Int + + init() + + deinit +} +``` + +- 被跟踪的属性印在 `_x` 的位置,也就是源码里的位置;`_x` 的字段偏移与布局注释照旧挂在它上面(那就是它的存储)。 +- 不印:`_$observationRegistrar`、`declaredMember` 来源的 computed `x`、宏生成的 `access(keyPath:)`、`withMutation(keyPath:_:)`、`shouldNotifyObservers(_:_:)`,以及宏生成的 `Observation.Observable` conformance(extension 里没有别的内容时整个 extension 不印)。 +- 宏与属性名按节点打印,module selector 照常生效(`@Observation::Observable`),不拼字符串。 +- `marksOptionalContent` 打开时两种形态都印:折叠的内容在 `.disabled(expandsMacros)` 区域里,展开的内容在 `.enabled(expandsMacros)` 区域里,按任一取值投影都与直接用该取值打印逐字节相同。RuntimeViewer 用这个在两种形态之间切换而不必重印,展开的那部分就是被折叠的成员。 + +### API + +宿主的调用点: + +```swift +// 侧边栏:prepare() 之后就能读,不需要先索引这个类型。 +if typeDefinition.attachedMacros.contains(.observable) { + properties.insert(.isObservable) +} + +// interface:默认折叠;要看二进制里的展开就打开。 +configuration.expandsMacros = true +``` + +- `public struct SwiftAttachedMacro: Hashable, Sendable`:`static let observable`,带 `name` 与 `moduleName`。用 struct 加静态成员而不用 enum,以后识别 `@Model` 之类不会破坏下游的穷举 `switch`。 +- `TypeDefinition.attachedMacros: Set`:构造时算出,和 `exportStatus` 一样在 `prepare()` 返回时就有。 +- `TypeDefinition.observableMacroExpansion: ObservableMacroExpansion?`:`index(in:)` 之后才有,列出被跟踪的属性(`name`、`backingFieldName`、`origin`)、加 `@ObservationIgnored` 的存储属性和宏生成的方法。 +- `ExtensionDefinition.generatingMacro: SwiftAttachedMacro?`:这个 extension 是哪个宏生成的;宿主把 extension 当独立对象显示时,凭它在折叠形态里隐藏。 +- `SwiftDeclarationPrintConfiguration.expandsMacros: Bool = false`、`SwiftVisibilityOption.expandsMacros`、`InterfaceRequest.expandsMacros`、CLI `interface --expand-macros`。关掉折叠(`expandsMacros = true`)时输出与今天逐字节相同。 + +### 宿主的内联展开 + +RuntimeViewer 要像 Xcode 的 Expand Macro 那样,在 `@Observation.Observable` 那一行下面单独显示宏生成的声明。为此再加两样,打印规则仍只在本库一处: + +```swift +// 宏生成的声明成块打印:成员在类型成员的缩进上,extension 在类型自己的缩进上。 +let expansion = try await printer.printMacroExpansion(of: .observable, attachedTo: typeDefinition) + +// 折叠形态里给宏属性打上定位标记,separatingAnnotationRegions() 读回。 +configuration.marksAttachedMacros = true +// region.kind == .attachedMacro(.observable) +``` + +- `SwiftDeclarationPrinter.printMacroExpansion(of:attachedTo:level:)`:印出 registrar、每个被跟踪属性的存储 `_x`、每个被跟踪属性的 computed `x`(照宏的写法 `{ get set }`,镜像剥掉了 accessor 也印,上方加 note 注释)、`access(keyPath:)`、`withMutation(keyPath:_:)`、镜像里留下的 `shouldNotifyObservers(_:_:)`,最后是 `extension X: Observation.Observable {}`。存储和方法带着展开形态里同样的注释,用的是同一套打印代码,computed `x` 带镜像里它的 accessor 注释(地址、vtable 槽位、导出结论);导出过滤照常生效。类型没带这个宏时印出空串。 +- `SwiftDeclarationPrintConfiguration.marksAttachedMacros`:折叠形态里每个宏属性包在 `AnnotationRegion` 里,种类是 `AnnotationRegion.Kind.attachedMacro(_:)`(`attachedMacro.Observation.Observable`),一个宏一个种类,宿主不必读文字就知道是哪个宏。默认关,关着时输出逐字节不变。 +- `SwiftDeclarationPrinter.printMacroExpansionParts(of:attachedTo:)`:照 Xcode 展开 attached macro 的位置把展开拆成几块(`MacroExpansionPart`),每块不带自身缩进、首尾不带换行:每个被跟踪属性一块,放在它折叠出的声明下方,先是宏生成的 accessor 块(总是 `get`、`set`,不看镜像里还剩哪些 accessor),再是存储 `_x`;registrar 与生成的方法一块,放在类型闭合括号上方;生成的 conformance 一块,放在闭合括号下方。`marksAttachedMacros` 打开时,每个被跟踪属性折叠出的声明包在 `AnnotationRegion.Kind.attachedMacroTrackedProperty(_:named:)` 的区域里,`MacroExpansionPart.anchorKind` 与它相等;闭合括号不另做标记,它是类型 `DefinitionRegion` 的最后一行(或打印的那个定义的最后一行),不必改 swift-semantic-string。 + +### dump + +dump 照旧印出二进制里的全部成员,只在类头前加 `@Observation.Observable`,与 `@objc @implementation` 类在 dump 里的写法一致。 + +### 测试与验证 + +- 新的现场编译 fixture `ObservableMacroFixture`(照 `ClassesWithoutClassObjectsFixture` 的写法),四个变体:debug、release、release 加 `-dead_strip` 链接、release 加 `strip -x`;覆盖 final、open、internal、子类、泛型、带 property wrapper 的类、属性类型是带 `sending` 的函数类型的类,一个只手写 conformance 的类,以及一个手写出 `_$backingData` 与 registrar 字段、代替 `@Model` 的类。 +- 断言:识别结果、每个变体的折叠与展开输出、`marksOptionalContent` 下两种投影与直接打印逐字节相同、dump 类头、CLI 开关、Kit 字段。 +- 渲染 A/B:候选侧加 `--expand-macros` 的 interface 应与基线逐字节相同;dump 的差异只能是 `@Observable` 类的类头行,逐条核对。测试与 A/B 都在 Ultra 上跑。 + +### 发版 + +RuntimeViewer 的 release 构建按版本解析,要等本库发版。`next` 上 existential-any 用了 swift-demangling 未发布的选项,所以顺序是先发 swift-demangling,再发本库(带上这两项)。 + +### 落地步骤 + +每一步单独构建通过、相关测试通过后提交并推送;测试在 Ultra 上跑。 + +1. [x] 识别与模型标记:`ObservableMacroRecognition`、`SwiftAttachedMacro`、`TypeDefinition.attachedMacros`(含 specialization 沿用)、`ExtensionDefinition.generatingMacro`;新 fixture `ObservableMacroFixture` 与识别的测试。 +2. [x] 索引期的展开分析:`ObservableMacroExpansion`、`TypeDefinition.observableMacroExpansion`;各变体下被跟踪属性、来源、`@ObservationIgnored` 属性与生成方法的测试。 +3. [x] interface 折叠:`expandsMacros`、`SwiftVisibilityOption.expandsMacros`、类型头属性、字段块与成员块、导出过滤、conformance extension、`marksOptionalContent` 下的两种形态,以及 `printMacroExpansion(of:attachedTo:level:)` 与 `marksAttachedMacros`;输出与投影一致性的测试。 +4. [x] dump 类头的 `@Observation.Observable` 与测试。 +5. [x] `InterfaceRequest.expandsMacros`、`interface --expand-macros`、`AgentPlugins/swift-section` 的 skill,以及两侧的测试。 +6. [x] 文档(模块文档、术语表、`AGENTS.md`、A/B 流程、演进账本第 132 节与文档索引)、全量测试与渲染 A/B。 +7. [x] 用户批准后追加:分块展开 `printMacroExpansionParts` 与被跟踪属性的定位标记;accessor 块照宏的写法印。 + +### 验证 + +在 JHs-Mac-Studio-Ultra(macOS 27.2、Xcode 26.6)的沙盒里跑,swift-demangling 用它 `next` 的 8809c1b 作本地兄弟依赖(existential-any 的选项还没发版)。 + +- 全量测试:2879 个测试、548 个套件,只剩 `FileMappingTests.readersOfOneCacheFileShareOneMapping` 一条;分支起点上跑全量同样只这一条失败,是基线已有的。 +- 全量中途暴露并修好的两件事:`TypeDefinition` 实例大小超过提案 0002 的守卫(456 > 448,展开描述改为装箱,回到 440);fixture 在静态初始化里同步编四个变体,编译期间占住协作线程(改为在独立线程编译、访问器改成 async)。当时把 `BoundedConcurrentMapTests` 的一分钟时限超时也归到它头上,后来查明这条在没有本分支改动的全量里也会超时,见下一条。 +- 分块的展开(`printMacroExpansionParts`)加入后再跑全量:2884 个测试,三条失败,都不是本次引入的。`FileMappingTests` 是基线已有的。`BoundedConcurrentMapTests.cancellationStopsSubmittingPendingElements` 的时限超时在 Ultra 上其他会话不含本分支的全量里也出现过(2026-11-11 的两次)。`SharedCacheTests.differentKeysParallelViaAsyncLet` 要两个 detached task 在 30 秒内同时拿到协作线程,而 Ultra 的全量自始至终占满协作线程池,排在前面的测试都要等 800 秒以上才结束。这两条在日志里都是在任何新测试开始之前就已经失败的,分块的代码也只在新测试里执行。 +- 渲染 A/B(96 对,基线是分支起点,候选侧加 `--expand-macros` 与 `RV_OPTS` 的 `expandsMacros`):interface 全部逐字节一致;dump 有 10 对不同,去掉 `@Observation.Observable ` 前缀后都逐字节一致,进程内一侧标出 SwiftUI、SwiftUICore、SwiftData 共 28 个类。A/B 跑在 dead-strip 修复之前的提交上;之后的改动只动折叠形态(A/B 里关着)、只在 `marksAttachedMacros` 打开时才有的标记、新加的分块 API 和测试支持代码,展开形态与 dump 不受影响,没有重跑。 +- 真实框架:用修复后的 CLI 渲染 macOS 27.2 的 SwiftUI,`Immersion`、`WindowVisibilityState`、`SearchEnvironmentStorage` 等都折叠对了;剩下印 `@Observation.ObservationIgnored var _x` 的当时都判为手写写法(存储与同名属性类型不同,或同名的是方法)。其中三个类的 `makeFileCoordinator` 判错了:类型只差一个 `sending`,见决策日志。修好后用新旧两个 CLI 渲染 SwiftUI、SwiftUICore、SwiftData 的折叠形态逐字比较,只有这三处变了,都折叠成 `var makeFileCoordinator: @Sendable () -> sending NSFileCoordinator`(其中一处属性名本身带下划线)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-11 | Created as Draft | RuntimeViewer 要在侧边栏标出 `@Observable` 类,并在 interface 里提供折叠与展开两种形态,请本库识别这个宏 | +| 2026-11-11 | 识别结果在构造时算出,不等 `index(in:)` | RuntimeViewer 的侧边栏在索引任何类型之前就建好,与 `exportStatus` 的情形相同 | +| 2026-11-11 | 有 `_$backingData` 的类不认作 `@Observable` | SwiftData 的 `@Model` 生成同名同类型的 registrar 字段(探针实测) | +| 2026-11-11 | 关掉折叠时输出与今天逐字节相同,类头也不加属性 | 与 `usesExistentialAny`、`usesModuleSelectors` 的先例一致,A/B 能用它做逐字节对照 | +| 2026-11-11 | accessor 被剥掉时也合成被跟踪的属性,上方加 note 注释 | 剥过符号的 App 里 internal 的 view model 是常态;先例是 property wrapper 的合成,note 写明来源字段 | +| 2026-11-11 | interface 默认折叠 | 用户选定:interface 的目标是读起来像源码,要看二进制里的展开就加 `--expand-macros` | +| 2026-11-11 | 用户批准,开始实现;补上落地步骤 | 精简提案原本没有分步,按方案拆成六步,每步能单独构建与验证 | +| 2026-11-11 | 带本地符号的镜像只认 init accessor;剥过符号的镜像依次看导出的 accessor、初始值表达式、存储字段名,每个属性记下证据 | 探针实测 debug 与 release 都保留每个被跟踪属性的 init accessor;手写的 `_y` 在这样的镜像里没有 `y` 的 init accessor,不会误认。只有全剥的 internal 类才需要推断 | +| 2026-11-11 | 加入展开块的打印与宏属性的定位标记 | RuntimeViewer 要做 Xcode 式的内联展开,用户批准把这两项加进本提案;由本库打印,宿主不必再写一遍打印规则 | +| 2026-11-11 | 嵌套类型的宏属性靠 `marksNestedDefinitions` 对应到定义:最内层的 `DefinitionRegion` 就是它的类型,不另加 API | 一次打印会内联嵌套类型,宿主要知道每个属性区域属于哪个定义;类型的属性行本来就印在它自己的定义区域里,复用现成机制比复刻打印顺序可靠 | +| 2026-11-11 | 折叠出的 `var x` 用 computed `x` 的 `final`、导出结论与 accessor 注释(vtable 槽位、地址),字段的偏移与布局注释照旧 | 存储字段 `_x` 是 private,它的 `final` 与导出结论说的是存储,不是属性;`x` 的槽位与代码地址才是宿主要找的入口 | +| 2026-11-11 | `@Observation.Observable` 从 `Observation.Observable` 协议的名字节点打印,`@Observation.ObservationIgnored` 从结构体节点打印;两者都是静态节点 | 打印器按节点身份缓存片段,节点要活过打印;协议节点不会被写上 `any`,属性还能链到同名协议 | +| 2026-11-11 | 展开块一行一条声明、不留空行,交给 `Rows` 组合 | 每条声明自带缩进,`Rows` 按两侧是否可见放换行,标记打印投影后也不会多出空行或首尾换行 | +| 2026-11-11 | 标记打印里,只属于展开形态的声明在「类型体最后一个换行」的判断里算作可能看不见 | 投影到折叠形态加只印导出时,嵌套类型之后可能什么都不剩,闭合括号会粘成 `}}`;与导出过滤用同一个机制处理 | +| 2026-11-11 | dump 只在类头加属性,不加关闭开关;渲染 A/B 的进程内一侧加 `RV_OPTS` 的 `expandsMacros` | dump 以信息最大化为目标,A/B 里它的差异只有类头行,人工核对;interface 有 `--expand-macros`,进程内一侧照样需要能关掉折叠 | +| 2026-11-11 | 证据规则不再按镜像有没有本地符号分流:init accessor、成员的 setter 或 `_modify`、挂在 `x` 名下的初始值表达式在任何镜像里都算,只有 `_x` 自己的初始值表达式、或 `_x` 有 accessor 而 `x` 没有,才把它排除 | 用修好的 CLI 渲染真实 SwiftUI 时发现 `Immersion` 等类没折叠对:SwiftUI 带本地符号,但 dead-strip 去掉了 init accessor,旧规则把 `_amount` 读成手写字段。fixture 加 `-dead_strip` 变体复现,修复前的 CLI 在它上面错得一样 | +| 2026-11-11 | fixture 改在独立线程编译,访问器改成 async | 几个套件同时要 fixture 时,同步编译占住多条协作线程,全量里 `BoundedConcurrentMapTests` 两次超时,分支起点上没有;改后全量通过 | +| 2026-11-11 | 实现完成,待用户看过后收尾 | 文档:模块文档(SwiftDeclaration、SwiftInterface)写实现说明,术语表登记 macro folding,插件 skill 写 CLI 用法;不另写使用指南,CLI 的 `--help` 与 skill 已够;演进账本一节、取号与文档索引留给正式收尾 | +| 2026-11-12 | 加入分块的展开 `printMacroExpansionParts` 与被跟踪属性的定位标记;闭合括号用类型的定义区域定位 | RuntimeViewer 改为 Xcode 式的分散展开,用户批准在正式收尾前加上;给 `DeclarationBlock` 的闭合括号打标记要改 swift-semantic-string 并先发版,类型的定义区域已经给出它的范围 | +| 2026-11-12 | 分块里属性的 accessor 块单独打印,由测试逐行对照展开形态的同一块 | 分块要的是不带声明头的块,变量打印器只会连声明一起印;init accessor 提案正在给展开形态的块加 `init` 一行,对照测试保证分块跟着加,而不是悄悄少一行 | +| 2026-11-12 | 更正 2026-11-11 那一行:`BoundedConcurrentMapTests` 的超时不是 fixture 同步编译造成的,独立线程编译照旧保留 | Ultra 上其他会话不含本分支的全量里这条也超时;同步编译占住协作线程是真问题,但当时「改后全量通过」只是一次运气 | +| 2026-11-12 | 比对 `_x` 与 `x` 的类型时撇开 `sending`,类型照旧读 getter 的符号;wrapped property 的属性写法改用同一个比较 | 编译器 mangle 声明自身的函数类型时不写 `sending`,字段记录照写;SwiftUI 三个类的 `makeFileCoordinator` 因此被当成「另一种类型的成员」,存储被印成 `@ObservationIgnored`。init accessor 的符号同样不写 `sending`,改读它没有用。getter 被 `@_silgen_name` 钉成旧 mangling 的情形不处理(init accessor 会话指出的 SwiftUICore `_GeometryActionModifier2.value`):宏生成的 accessor 加不了这个属性 | +| 2026-11-12 | 「关掉折叠时输出逐字节不变」以本提案之前的输出为准 | init accessor 提案([0094-init-accessor-recovery](0094-init-accessor-recovery.md))让展开形态里每个被跟踪属性的 accessor 块多印 `@storageRestrictions(initializes: _x) init` 一行,分块里的块跟着印;那一行是那份提案带来的变化 | +| 2026-11-12 | 分块与整块展开里,被跟踪属性的 accessor 块一律照宏的写法印 `{ get set }`,不看镜像里还剩哪些 accessor;`--expand-macros` 的展开形态仍照镜像。取代前面「逐行对照展开形态」那一行,对照测试改为钉住宏的写法 | 用户批准(RuntimeViewer 提出):macOS 27.2 的 AppKit 剥光了 `ColorSliderModel` 的 accessor,分块里只剩存储,看不出属性变成了 computed;SwiftUI 的 `_makeFileCoordinator` 只剩 getter,分块只印 `{ get }`。宏生成的块是固定的,跟着识别结果走;init accessor 那份改动落地后,这个块再加 `@storageRestrictions(initializes: _x) init` 一行 | +| 2026-11-12 | 落地:取号 0093,状态改 Implemented。不另写使用指南,术语表不加新词 | 用户看过后批准收尾。配套文档是 SwiftDeclaration 与 SwiftInterface 两份模块文档,CLI 用法在 `--help` 与插件 skill 里,`macro folding` 已登记。后续项:getter 被 `@_silgen_name` 钉成旧 mangling 时不折叠(已裁决不处理);完全剥光符号的 internal 类会把 `@ObservationIgnored var _y` 读成被跟踪属性;`@Model` 等别的宏还没有识别;发版要先发 swift-demangling | diff --git a/Documentations/Evolutions/0094-init-accessor-recovery.md b/Documentations/Evolutions/0094-init-accessor-recovery.md new file mode 100644 index 000000000..0280a22b1 --- /dev/null +++ b/Documentations/Evolutions/0094-init-accessor-recovery.md @@ -0,0 +1,128 @@ +# 0094 - 还原 SE-0400 的 init accessor + +- **状态**: Implemented +- **创建日期**: 2026-11-12 +- **最后更新**: 2026-11-12 +- **实现分支**: `feature/init-accessor-recovery`(RuntimeViewer 一侧是同名分支,见落地步骤 1) +- **配套文档**: [Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)(accessor 种类、索引步骤与推断规则)、[Modules/MachOSymbols.md](../Internal/Modules/MachOSymbols.md)(分桶前的 `isMember` 名单)、[Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md)(宏展开里 accessor 块的 `init` 一行) + +## 摘要 + +SE-0400 让 computed property 带一个 `init` accessor:初始化器给这个属性赋值时,由它初始化 `@storageRestrictions(initializes:)` 列出的 stored property。二进制里只留下这个 accessor 的符号(后缀 `vi`),`@storageRestrictions` 的名单和参数名都不留。库今天把这个符号整个丢掉:dump 不列它,interface 只印 `get` / `set`,ABI diff 也看不到它。本提案把 init accessor 当成所属属性的一个 accessor 建进模型:dump 列出它的符号,ABI diff 把它算进 accessor 集合,interface 在 accessor block 里印出 `init`;`initializes:` 的名单按「同名的 `_x`、类型与属性相同」推断,推不出就用注释说明二进制没有记录。起因是 SwiftUICore 导出的 `_GeometryActionModifier2.value.init`:编译器自己的 `.swiftinterface` 把它印成 `@storageRestrictions(initializes: _value) init(initialValue)`,我们的 interface 只有 `{ get set }`;`@Observable` 的展开形态也因此缺了每个被跟踪属性的 init accessor。 + +## 方案 + +### 二进制里有什么 + +调研对照了 Swift 6.4 的编译器源码,并在 Ultra 上用 Swift 6.4.2 编了探针:六种写法,debug、release、debug 加 dead-strip、release 加 dead-strip 四种构建。 + +- 符号是 `<属性>vi`,例如 `$s7SwiftUI24_GeometryActionModifier2V5valueyxAA0C5ProxyVYbcvi`(`SwiftUI._GeometryActionModifier2.value.init`)。swift-demangling 已经认得(`Node.Kind.initAccessor`),不用改。 +- 编译器把 init accessor 的访问级别写死为 `internal`(`lib/AST/AccessRequests.cpp`,理由是它只在本模块里被调用)。只有标了 `@usableFromInline` 的才导出,这也是官方 `.swiftinterface` 印出 init accessor 的唯一情况;macOS 27.2 SDK 的 `.swiftinterface` 里只有 SwiftUICore 一处。其余的都是本地符号:前三种构建里六个都在,release 加 dead-strip 之后只剩导出的那个(初始化器把它内联掉了,再没有引用)。 +- `initializes:` 的每一项变成一个 indirect result,`accesses:` 的每一项变成一个 `inout` 参数(`lib/SIL/IR/SILFunctionType.cpp` 的 `getSILFunctionTypeForInitAccessor`)。指针直接指向那块存储,看不出是哪个字段:探针里 `Pair.point.init` 的全部机器码是 `str x2, [x0]; str x3, [x1]; ret`,能数出它初始化两块存储,认不出是 `_x` 和 `_y`。参数名不进 mangling,不写时默认叫 `newValue`。 +- 有 `…vi` 符号不等于有 init accessor:SwiftUICore 的 `_GeometryActionModifier.value` 已经改回 stored property,为了兼容旧客户端内联进去的调用,用 `@_silgen_name` 留了一个同名的 mutating 函数。 + +### 改动位置 + +1. 模型:`Sources/Declaration/SwiftDeclaration/Model/Kinds/AccessorKind.swift:1` 加 `case initAccessor`,`addressLabel` 为 `init`;`Model/Members/Accessor.swift:36` 之后加 `hasInitAccessor`;`Model/Members/VariableDefinition.swift` 加 `initializedFieldNames: [String]?`,存推断出的名单,`nil` 表示镜像里看不出来。 +2. 符号分桶:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift:1164` 把 `.initAccessor` 并进 getter / setter 那一支,进成员桶 `.variable`;`:1938` 的 `isAccessor` 加上它,否则 init accessor 的节点会被当成「没有 accessor」。 +3. accessor 种类:`Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift:14` 加上映射。不加的话种类落到 `.none`,`isStored`(`Accessor.swift:19`)会把整个属性当成 stored property。 +4. 建成员:`Indexing/Building/MemberDefinitionBuilder.swift:50` 把 init accessor 排在同名那一组的最后,`accessors.first` 不变;声明节点照旧取 getter 或 borrow(`:62`),只有 init accessor 的组照旧不建成属性(今天也不建)。 +5. 成员顺序:`Model/Members/OrderedMember.swift:22` 的 `minSymbolOffset` 跳过 init accessor,成员顺序和今天一样。 +6. 推断:新文件 `Sources/Analysis/SwiftInspection/InitAccessorFieldInference.swift`,放在 dump 和模型都够得着的一层,和 `ObservableMacroRecognition` 同一个位置。比较类型用的两个函数搬进同一层的 `StoredTypeMatching.swift`:`ObservableMacroExpansionRecovery.referencedTypeNode(ofStoredType:)`(剥掉 `weak` / `unowned`)与 `WrappedPropertyRecovery.declaredType(_:matchesStoredType:)`(撇开 `sending`),`@Observable` 展开的恢复、wrapper attribute 的写法与本推断三处共用。新的索引步骤 `Indexing/TypeDefinition/TypeDefinition+InitAccessors.swift`,接在 `TypeDefinition+Indexing.swift:47` 的 `foldStoredPropertyAccessors` 之后、`:88` 收集 `orderedMembers` 之前(后者拷贝成员的值,晚了就写不进去)。 +7. interface:`Sources/Output/SwiftPrinting/NodePrinter/AccessorBlockKeywords.swift` 加上 `init` 那一行,`NodePrintables/MemberDeclarationNodePrintable.swift:167` 的 `printAccessorBlock` 把它印在 `get` 之前。推不出时的注释走 `Sources/Output/SwiftDeclarationRendering/StructuredComment+Factories.swift` 里的新工厂 `initAccessorFieldsNotRecorded`,配新的注释种类 `AnnotationRegion.Kind.initAccessorFields`(`AnnotationRegionKind+SwiftComments.swift`),由 `SwiftDeclarationPrinter.renderMember` 印在声明的上一行。 +8. dump:`Sources/Output/SwiftDump/Dumper/StructDumper.swift:154` 与 `ClassDumper.swift:471` 一带的成员循环。init accessor 进桶之后自动列出,带地址和导出状态;每一条前面再加一行推断结果。 +9. ABI diff:`Sources/Output/SwiftDiffing/MemberRecord.swift:322` 给 `.initAccessor` 一个 token `init`;`ABISnapshotDocument.swift:90` 的格式版本从 12 升到 13,因为带 init accessor 的属性的 `|acc:` 标签变了,旧基线会把它们全报成改动。 +10. RuntimeViewer:`RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:1952` 的 `kindString` 对 `AccessorKind` 穷举 `switch`,要补一行 `case .initAccessor`,和本库合进 `next` 放在同一批,否则它直接编不过。它的注释种类是按字符串比较的 struct,新的注释种类不用改代码,按普通注释的样式显示。 + +### 明确不动的地方 + +- `@Observable` 的识别:证据照旧按 kind 查 `symbols(of: .initAccessor)`。按 kind 的索引对每个符号都记一行(`SymbolIndexStore.swift:1035`),进不进成员桶都不影响它;折叠形态整块不印被跟踪属性背后的 computed property,不会出现 accessor block。 +- 导出判定:成员的导出结论是「任一 accessor 导出即导出」(`SymbolIndexStore.swift:1445`),加进一个不导出的 init accessor 不改变任何结论,`--exported-only` 也一样。 +- 属性的声明节点、名字和类型,property wrapper 的还原。 +- `final` 的推断结论不变:它把「有 accessor 符号、却都没有 vtable descriptor」当证据,而 init accessor 从不进 vtable,所以证据里不算它(`TypeDefinition+FinalRecovery.swift` 的两处判据、dump 那条路的 `ClassDumper.storedAccessorFieldNames`)。不排除的话,SwiftUICore 那种兼容函数放在 class 的 stored property 上,会让它单凭这一个符号被判成 `final`。 +- `accesses:` 和参数名一律不印;`propertyWrappedFieldInitAccessor`(mangling 里的 `fF`)不在范围内;swift-demangling 不改。 + +### 推断规则 + +属性有 init accessor,并且类型里有一个名叫 `_<属性名>`、类型与属性相同(先剥掉 `weak` / `unowned`)的 stored property,`initializedFieldNames` 就是 `["_<属性名>"]`;否则为 `nil`。这条规则对得上 `@Observable` 的展开、SwiftUICore 那一例和手写的 `_x` 写法;对不上探针里的 `Angle`(初始化的是 `degrees`)、`Pair`(一个属性同时初始化 `_x` 和 `_y`)和只写 `accesses:` 的写法。要求类型相同,是因为只看名字会把类型不同的 `_x` 也认进来:SwiftData `@Model` 的 `_name` 是占位类型,它的 init accessor 真正写入的是 `_$backingData`。 + +比较用的「属性的类型」取 init accessor 自己符号里写的那个,不取声明(getter)的:SwiftUICore 用 `@_silgen_name` 把 `_GeometryActionModifier2.value` 的 getter 和 setter 钉在类型改成 `@Sendable` 之前的旧 mangling 上,只有 init accessor 的符号写着字段 `_value` 的类型。模型与 dump 都经 `InitAccessorFieldInference.initializedFieldNames(ofInitAccessorSymbol:)` 读同一个符号,结论一致。init accessor 的符号同样是声明自身的 mangling,不写 `sending`(`ASTMangler::appendDeclType` 不递归),字段记录写,所以 `_make: () -> sending A` 对 `make: () -> A` 也算类型相同,比较照 `StoredTypeMatching.declaredType(_:matchesStoredType:)` 撇开 `sending`。 + +### 输出的样子 + +推得出时,照编译器的写法把属性和 `init` 写在同一行: + +```swift +struct FrozenBox { + var _value: A + init(value: A) + var value: A { + @storageRestrictions(initializes: _value) init + get + set + } +} +``` + +推不出时只印 `init`,声明上一行用注释说明: + +```swift +struct Angle { + var degrees: Swift.Double + init(radians: Swift.Double) + // init accessor: the binary does not record which stored properties it initializes + var radians: Swift.Double { + init + get + set + } +} +``` + +- 带 `…vi` 符号的 stored property(SwiftUICore 那个兼容函数)照旧按 stored property 印,输出和今天完全一样:stored property 只给 accessor 印 vtable 槽注释,init accessor 没有槽。 +- 开着成员地址注释时,computed property 和 `@Observable` 折叠形态里的被跟踪属性都多一行 `init` 的地址;`expandsMacros` 的展开形态在每个被跟踪属性的 accessor block 里多出 `@storageRestrictions(initializes: _x) init`(照镜像里有的 init accessor);`printMacroExpansion` 与 `printMacroExpansionParts` 照宏的写法总是印这一行,不看镜像留没留它。 +- dump 在类型的 variable 符号里多列一条 `X.value.init : A`,前面一行写推断结果:推出的名单,或者二进制没有记录。 + +### 测试与验证 + +- 新的现编 fixture `InitAccessorFixture`(`Sources/TestSupport/MachOTestingSupport/`),照 `ObservableMacroFixture` 分四个变体:debug、release、release 加 dead-strip、release 加 `strip -x`。源码是探针的六种写法(`Model` 多一个 `weak` 存储的属性),加上 SwiftUICore 的两种写法(stored property 上的兼容函数 `ShimmedBox`、getter 钉在旧 mangling 上的 `SendableUpgrade`)和 SwiftData 那种 `_name` 类型不同的 `PersistedLookalike`;编译照它的做法放在协作线程池之外,带 library evolution,与 SwiftUICore 一样。 +- 模型、interface、dump、ABI diff 各一组测试,覆盖推得出、推不出、兼容函数,以及 dead-strip 之后只剩导出的那一个;`ObservableMacroInterfaceTests` 里展开形态的期望补上 `init` 那一行。 +- 在 Ultra 上跑全量测试和渲染 A/B(改动碰了索引和打印,按规定必须跑)。差异只允许出现在带 `…vi` 符号的属性上。 + +### 落地步骤 + +每一步单独能构建、相关测试能过,做完各提交一次。 + +1. (已完成)模型与分桶:改动位置 1 到 5 里除 `initializedFieldNames` 以外的部分,ABI diff 的 token 与快照格式 13(改动位置 9),RuntimeViewer 的 `kindString`(改动位置 10,RuntimeViewer 仓库里单独的分支);新的 `InitAccessorFixture`,以及模型、dump(init accessor 自动列出)、ABI diff 的测试。这一步之后 interface 还不印 `init`,只有成员地址注释多出 `init` 的地址。 +2. (已完成)推断:`InitAccessorFieldInference`(连同挪过来的 `referencedTypeNode(ofStoredType:)`)、新的索引步骤与 `initializedFieldNames`,以及模型测试。 +3. (已完成)interface:`init` 那一行、推得出时的 `@storageRestrictions`、推不出时的注释(新工厂与新注释种类);interface 测试,`ObservableMacroInterfaceTests` 里展开形态的期望。 +4. (已完成)dump:每条 init accessor 前的推断结果,以及 dump 测试。 +5. (已完成)文档与验证:改动位置之外的文档同步(见下一节最后一条),Ultra 上的全量测试与渲染 A/B。 + +### 没有询问就采用的假设 + +- 推得出的名单在 interface 里默认就印,不加开关,也不标「推断」:同名且同类型的证据比只看 selector 名字强得多,所以不照 `--infer-objc-overrides` 默认关掉的做法;证据写在 dump 里。代价是带 `accesses:` 的少见写法会印得不全。 +- 推不出时的注释总是印,不设开关;只有带 init accessor 的属性才会有,量很小。 +- `init` 一律不带参数名:省略参数名是合法写法,参数名本来也不属于接口。 +- 文档同批更新:`Documentations/Internal/Modules/SwiftDeclaration.md`(accessor 种类和新的索引步骤;第 86 行「init accessor 不进成员桶」的说法要改)、`ProjectEvolutionLog.md`、`AgentPlugins/swift-section` 的 skill(输出里多了推断出来的名单)。`@Observable` 提案如果那时还没落地,在它的决策日志里补一行「展开形态多出 `init`」;已经落地就只记在本提案里。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-12 | Created as Draft | 调研确认二进制只留 init accessor 的符号、不留 `@storageRestrictions`;用户选定写轻量提案:dump、interface、ABI diff 都认出 init accessor,名单只按同名同类型的 `_x` 推断,推不出就注明 | +| 2026-11-12 | 在 `AccessorKind` 上加 case,不在 `VariableDefinition` 上另挂一个字段 | 和 SE-0507 的 `borrow` / `mutate` 一致;dump 的成员循环、地址注释、ABI diff 都沿着 `accessors` 自动带上它。代价是 RuntimeViewer 的穷举 `switch` 要同批补一行 | +| 2026-11-12 | 不从机器码推 `initializes:` / `accesses:` | 能数出 indirect result 和 `inout` 参数各有几个,但指针直接指向存储,看不出是哪个字段;只有个数印不成合法的 Swift | +| 2026-11-12 | 推断要求类型相同 | 只看名字会把类型不同的 `_x` 也认成被初始化的存储,SwiftData `@Model` 就是这样 | +| 2026-11-12 | 用户批准,开始实现;补上落地步骤 | 原稿只列了改动位置,按能各自构建的顺序拆成五步 | +| 2026-11-12 | `final` 推断不把 init accessor 当证据 | 实现时发现 `final` 的证据门槛是「有任意 accessor 符号」,init accessor 进了 `accessors` 之后会被算进去;它从不经 vtable 派发,什么也证明不了。排除之后所有结论与今天相同 | +| 2026-11-12 | 落地步骤 1、2 完成 | Ultra 上相关的 14 个套件(新增的三组、`ABIDifferTests`、`@Observable` 的各组)80 个测试全过。第一次跑时 init accessor 一个都没进成员桶:分桶之前还有一道 `isMember` 名单(`SymbolIndexStore.swift:1878`),补上之后全绿 | +| 2026-11-12 | 推不出时的注释印在声明上一行,不放在 `init` 行尾 | accessor block 由节点打印器写出,那里没有带注释种类的注释通道;声明上一行是地址、导出状态等成员注释共用的位置,走 `comment(_:as:)` 就能被 `marksCommentStructure` 标出来 | +| 2026-11-12 | 落地步骤 3、4 完成;`init` 那一行抽成 `AccessorBlockKeywords.InitAccessorLine.write(into:)` | Ultra 上 interface、dump、printing、rendering、indexing、diffing 六个测试目标 913 个测试全过。`@Observable` 那边新加的 `printMacroExpansionParts` 自己拼 accessor block、不经 `printAccessorBlock`,抽出来以后两处共用同一份渲染 | +| 2026-11-12 | 推断比较的类型改取 init accessor 自己的符号 | 第一轮渲染 A/B 的差异全是新增行,但 SwiftUICore 的 `_GeometryActionModifier2.value` 在 dump 里推出了 `_value`、在 interface 里却印成「没有记录」:模型拿的是 getter 的类型,而这个 getter 被 `@_silgen_name` 钉在没有 `@Sendable` 的旧 mangling 上。fixture 加了同样写法的 `SendableUpgrade`,修复前三个测试变红,修复后模型与 dump 走同一个入口 | +| 2026-11-12 | 合进 `next` 上的 `@Observable` 分段打印,`accessorBlock(of:)` 改用 `InitAccessorLine` | 它在 `printAccessorBlock` 之外自己拼 accessor block;合并后、改动前,它的 `aTrackedPropertysAccessorBlockIsTheExpandedFormsBlock` 三个用例全红,改成共用同一份渲染 | +| 2026-11-12 | 比较撇开 `sending`;比较类型的两个函数搬到 SwiftInspection 的 `StoredTypeMatching` | `@Observable` 会话在 SwiftUI 里查到:声明自身的 mangling 不写 `sending`,字段记录写,`() -> sending T` 的存储因此对不上自己的属性;init accessor 的符号同样如此。fixture 加 `SendingResult`,修复前模型、interface、dump 都漏推。对方的比较函数原在 SwiftDeclaration 的 `WrappedPropertyRecovery`,dump 够不着,经对方同意搬下去,三处共用 | +| 2026-11-12 | 渲染 A/B 通过(以本地 `next` 54c3b9ef 为基线) | 96 对里 80 对逐字节相同;16 对不同的全是新增行,没有一行被删改,内容只有 init accessor 的符号行、推断注释、`init` 那一行和它的地址注释。interface 里 SwiftUICore 的 `_GeometryActionModifier2.value` 印成 `@storageRestrictions(initializes: _value) init`,与官方 `.swiftinterface` 只差参数名;进程内 SwiftUICore 推出 `ReorderableStyleConfiguration.ContainerState.placeholder` 的 `_placeholder`;进程内 SwiftUI 有 4 个属性推不出(`taskState`、两个 `previousSnapshot`、`results`),按规则注明。合并 `sending` 修复之前在 0bcfe627 上跑的全量 2903 个测试,只红了 Ultra 上已知的 3 条(`FileMappingTests` 每次都红,两条满负载下偶发);合并之后相关的 19 个套件全过,全量留到最后一次合并之后再跑 | +| 2026-11-12 | 合进 `next` 上宏形状的 accessor block,`init` 那一行照宏的写法总是印 | `@Observable` 那边按 RuntimeViewer 的要求,让 `printMacroExpansion` 与 `printMacroExpansionParts` 照宏的写法印被跟踪属性的 accessor block、不再照镜像,`accessorBlock(of:)` 随之删掉。宏总会为被跟踪属性生成初始化 `_x` 的 init accessor,所以这个固定的块也印 `@storageRestrictions(initializes: _x) init`,经 `InitAccessorLine` 渲染;`--expand-macros` 照旧按镜像 | +| 2026-11-12 | 实现完成,待用户看过后收尾 | 最终提交 b0ff1597 的全量测试 2908 个,红了 5 条:`FileMappingTests` 在 Ultra 上每次都红,`SharedCacheTests` 一条与 `BoundedConcurrentMapTests` 三条是满负载下超时,单独重跑这两个套件 20 个测试全过。RuntimeViewerCore 带上 `kindString` 那一行、对着本分支编译通过。文档已同步:两份模块说明(SwiftDeclaration、MachOSymbols)、SwiftInterface 的宏折叠一段、agent skill;演进账本一节与总索引的条目留到正式收尾取号时写 | +| 2026-11-12 | 落地:取号 0094,状态改 Implemented,与 0093 一起推进 `next` | 用户看过后批准收尾。实现叠在 `@Observable` 的改动上(`StoredTypeMatching` 与宏形状的 accessor 块),两份提案只能一起推,编号按合进 `next` 的先后,0093 在前。收尾时核对:最终全量红的 5 条,在不含本分支的 `@Observable` 全量(2883 个测试)里都同样出现。配套文档是三份模块文档,不另写使用指南,输出的变化写在插件 skill 里;术语表不加新词(init accessor 是 Swift 自己的术语);`AGENTS.md` 不用改,分桶前的 `isMember` 名单写在 MachOSymbols 的模块文档里。插件 skill 的快照格式说明改到 13,顺带补上格式 12 漏写的那一条。后续项:一个属性初始化几块存储、初始化的不是 `_x`、只写 `accesses:` 的写法推不出,只印 `init` 加注释;`propertyWrappedFieldInitAccessor`(`fF`)不在范围内;旧的 ABI 快照要用新版重新生成;RuntimeViewer 的 `kindString` 那一行随 RuntimeViewer 那边 `@Observable` 的改动一起推 | diff --git a/Documentations/Evolutions/0095-observable-nested-expansion.md b/Documentations/Evolutions/0095-observable-nested-expansion.md new file mode 100644 index 000000000..0471184cc --- /dev/null +++ b/Documentations/Evolutions/0095-observable-nested-expansion.md @@ -0,0 +1,78 @@ +# 0095 - `@Observable` 的展开分两层:先出 `@ObservationTracked`,再展开它 + +- **状态**: Implemented +- **创建日期**: 2026-11-12 +- **最后更新**: 2026-11-12 +- **实现分支**: `feature/observable-nested-expansion` +- **配套文档**: [Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md)(两层分块与折叠形态的写法) + +## 摘要 + +提案 [0093](0093-observable-macro-folding.md) 的分块展开(`printMacroExpansionParts`),把每个被跟踪属性的 accessor 块与存储 `_x` 直接算作展开 `@Observable` 的结果。Swift 源码里这是两层。`ObservableMacro` 是 MemberAttributeMacro,只给每个被跟踪属性加一个 `@ObservationTracked`,此外写出成员与 conformance;accessor 块与存储是 `ObservationTrackedMacro` 的 accessor 与 peer 两个角色写的。Xcode 也是在展开结果里再展开一次 `@ObservationTracked`,才看到这两样。RuntimeViewer 要照这个分层显示,用户定由本库印出两层,RuntimeViewer 只负责摆放。 + +同一轮里还有一处折叠形态的格式改动,也并进本提案:`@Observation.ObservationIgnored` 原先和声明挤在同一行,SwiftUI 里类型长的属性因此行行折行;现在它单独占一行,放在声明上方。 + +## 方案 + +改动位置: + +- `Sources/Output/SwiftPrinting/MacroExpansionPart.swift:11` 有三处改动。 + - `Placement` 加 `.trackedPropertyAttribute(named:)`,放在属性折叠出的声明上方。 + - 加 `nestedExpansions: [NestedExpansion]`。`NestedExpansion` 有三个字段:嵌套宏的属性在 `content` 里的 UTF-8 范围(`attributeUTF8Range`)、宏(`macro`),以及展开它的分块(`parts`)。 + - `anchorKind` 改成存储属性。两层的分块都指向同一个折叠声明的区域 `attachedMacroTrackedProperty(.observable, named:)`。 +- `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObservableMacro.swift:318`(`printIncludedObservableMacroExpansionParts`):每个被跟踪属性改出一块 `.trackedPropertyAttribute(named:)`,内容是那个属性,写作 `@Observation.ObservationTracked`(打开 module selector 时是 `@Observation::ObservationTracked`)。它的 `nestedExpansions` 只有一项,宏是 `.observationTracked`,分块就是今天的 `.trackedProperty(named:)`:先是 accessor 块(含 init 行),再是存储,内容一字不改。成员块与 conformance 块不变。 +- `Sources/Declaration/SwiftDeclaration/Model/SwiftAttachedMacro.swift:30` 加 `SwiftAttachedMacro.observationTracked`。`Sources/Analysis/SwiftInspection/ObservableMacroRecognition.swift:97` 旁边加它的静态名字节点,因为打印器按节点身份缓存片段。 + +折叠形态的格式(用户追加): + +- `SwiftDeclarationPrinter+ObservableMacro.swift` 的 `observationIgnoredAttribute(level:)`:属性后面不再接空格,改为换行加声明的缩进。字段与成员两条打印路径都经过它。 +- 被忽略的 wrapped property,wrapper 的属性也单独占一行。成员路径经 `printThrowingVariable` 的内部重载 `placesWrapperAttributeOnItsOwnLine`,公开签名不变;合成路径经 `printThrowingSynthesizedWrappedProperty` 的 `placesAttributeOnItsOwnLine`。 +- `lazy` 是声明的一部分,留在声明那一行。 + +明确不动: + +- 折叠形态里除上面这条以外的部分。 +- `--expand-macros` 的展开形态。 +- 定位标记。 +- 整块展开 `printMacroExpansion`:仍是两层合起来的样子。它印的是一块独立的声明,挂在别的声明上的 `@ObservationTracked` 放不进去。 + +没问就采用的假设: + +- `.trackedProperty(named:)` 只出现在嵌套展开里,顶层不再有。分块 API 还没发版,RuntimeViewer 跟着改。 +- 第一层属性块的可见性与它锚定的折叠声明一致,和今天的 accessor 块是同一条规则。 +- 第一层分块的内容就是这个属性本身,所以嵌套宏的范围覆盖整块内容。 + +### 落地步骤 + +每一步单独构建通过、相关测试通过后提交并推送;测试在 Ultra 上跑。 + +1. [x] `SwiftAttachedMacro.observationTracked` 与它的名字节点;`MacroExpansionPart` 的 `.trackedPropertyAttribute(named:)`、`NestedExpansion` 与存储的 `anchorKind`;`printMacroExpansionParts` 出两层;分块测试改成两层。 +2. [x] 文档:`Modules/SwiftInterface.md`、`AGENTS.md` 里分块的说明;全量测试。 +3. [x] 折叠形态里 `@Observation.ObservationIgnored` 与被忽略的 wrapper 属性各占一行;测试、模块文档与插件 skill。 + +测试: + +- 第一层每个被跟踪属性一块,内容是属性,带一项嵌套展开,范围覆盖属性文本。 +- 嵌套分块与今天的 `.trackedProperty` 分块逐字节相同。 +- fixture 的四个变体都要过。 + +### 验证 + +在 JHs-Mac-Studio-Ultra(macOS 27.2、Xcode 26.6)的沙盒里跑,swift-demangling 用它 `next` 的 8809c1b 作本地兄弟依赖。 + +- 两层展开:相关套件(`@Observable` 与 init accessor 的测试、投影、注释结构与嵌套定义区域的契约)88 个测试全过;全量 2909 个测试,只有 `FileMappingTests.readersOfOneCacheFileShareOneMapping` 一条失败,基线上同样失败。 +- 加上 `@Observation.ObservationIgnored` 单独占一行之后:相关套件(另加 property wrapper 的测试)106 个测试全过;全量 2909 个测试有两条失败。一条是 `FileMappingTests`;另一条是 `BoundedConcurrentMapTests` 的时限超时,是 Ultra 全量下的既有偶发,失败在任何新测试开始之前。 +- 分块 API 的改动不影响输出。折叠形态只改了 `@Observation.ObservationIgnored` 那几行的换行,渲染 A/B 的候选一侧带 `--expand-macros`,比较不到折叠形态,所以不跑渲染 A/B。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-12 | Created as Draft | RuntimeViewer 要照 Swift 源码的两层展开 `@Observable`,用户定由本库印两层 | +| 2026-11-12 | 第一层的属性写作 `@Observation.ObservationTracked`,经类型打印器印出 | 用户选定:与折叠形态的 `@Observation.Observable`、`@Observation.ObservationIgnored` 一致,module selector 也照样生效;宏源码写的是不带模块名的 `@ObservationTracked` | +| 2026-11-12 | 用户批准,开始实现;补上落地步骤 | 精简提案原本没有分步 | +| 2026-11-12 | 被导出过滤排除的属性两层都不出;属性块里不放标记区域 | 两层都摆在折叠声明旁边,声明被排除时宿主找不到锚点;嵌套宏的范围已经由 `attributeUTF8Range` 给出,不必再用 `marksAttachedMacros` 的区域 | +| 2026-11-12 | 两层展开实现完成 | 文档:`Modules/SwiftInterface.md` 与 `AGENTS.md` 已写两层;术语表不加新词 | +| 2026-11-12 | 折叠形态里 `@Observation.ObservationIgnored` 单独占一行,并进本提案;被忽略的 wrapped property 的 wrapper 属性也单独占一行,`lazy` 留在声明行;只改带 `@Observation.ObservationIgnored` 的属性,别处的 wrapper 属性照旧与声明同行 | 用户在 RuntimeViewer 里看 SwiftUI 时提出:类型长的属性行行折行。用户定:并进正在做的提案一起收尾;wrapper 属性也各占一行 | +| 2026-11-12 | 实现完成,待用户看过后收尾 | 文档:`Modules/SwiftInterface.md` 写了两层与属性换行,`AGENTS.md` 写了两层,插件 skill 写了 `@Observation.ObservationIgnored` 单独占一行;术语表不加新词 | +| 2026-11-12 | 落地:取号 0095,状态改 Implemented。不另写使用指南,术语表不加新词 | 用户看过后批准收尾。配套文档是 SwiftInterface 模块文档,分块 API 的用法在 `MacroExpansionPart` 的文档注释里。后续项:整块展开 `printMacroExpansion` 仍是两层合起来的样子;`@Model` 等别的宏还没有识别 | diff --git a/Documentations/Evolutions/0096-swift-first-imported-declarations.html b/Documentations/Evolutions/0096-swift-first-imported-declarations.html new file mode 100644 index 000000000..0950258ef --- /dev/null +++ b/Documentations/Evolutions/0096-swift-first-imported-declarations.html @@ -0,0 +1,304 @@ + + + + + +0096 - Swift 实现的类,导入声明以 Swift 一侧为准 + + + +

+ +

0096 - Swift 实现的类,导入声明以 Swift 一侧为准

+

本页是提案 0096-swift-first-imported-declarations.md 的网页版,对应提案「最后更新」2026-11-18。两者对不上时以提案为准。

+ + + + + + + + + + +
+ +

摘要

+

RuntimeViewer 的 Generated Interface 显示 macOS 27.2 共享缓存里 SceneHosting 的 SHScenePresentation(一个 @objc @implementation 类)时,只有 5 个成员用上了 Swift 声明,其余都按 ClangImporter 的规则从 selector 推导,例如 func isHostingSceneLayer(_: Any!) -> Swift.Bool,而同一镜像的 Swift 一侧就有 func isHosting(sceneLayer: __C.FBSceneLayer) -> Swift.Bool。原因在 0090 的配对只认符号证据:系统框架剥掉了 To thunk 的符号,-O 又把 Swift 函数体整段内联进 thunk(-[SHScenePresentation isHostingSceneLayer:] 的实现不再调用 isHosting(sceneLayer:)),第二档找不到引用;只按名字配的第三档在 0048 里只算 override,0090 接上的也只有这一部分。

+

本提案让 Swift 实现的类以 Swift 一侧为准:Swift 一侧有的成员照它的声明打印,ObjC 一侧只补 Swift 一侧没有的。头文件标了 NS_REFINED_FOR_SWIFT、在 Swift 里改成 __ 开头的成员,两边都标出来:Swift 视图写出它的 __ 声明,ObjC 头文件打上这个宏。这一项跨三个库:本库判定哪些成员改了名,MachOObjCSection 在头文件里打宏,RuntimeViewer 把两者接起来。

+ +

三个库各做什么

+
+ + + + + + + + + MachOSwiftSection (this library) + ~ ObjCImplementingSwiftMembers + pair by name, "__" prefix, type check + ~ @objc @implementation: Swift-first body + + query: members refined for Swift + + // NS_REFINED_FOR_SWIFT: var __x: … + + + MachOObjCSection + + Swift import notes (API-notes shape) + isSwiftPrivate → NS_REFINED_FOR_SWIFT + ~ ObjCInterfaceBuilder.classInterface + + notes parameter, default empty + no notes: output byte-for-byte same + + + RuntimeViewer (service process) + ~ Generated Interface: picks up MSS changes + ~ ObjC header & Find corpus: members → notes + ~ lockfile: bump both revisions (branch: next) + + + Swift view, refined members + + + import notes + + + header + macro + +
+ 新增~ 修改
+
+ +
    +
  • MachOObjCSection:头文件渲染接受宿主按成员给出的 Swift 导入标注,形状照 Clang 的 API notes——方法以 selector 加实例/类方法为键,属性以名字加实例/类属性为键,每项是一个可以加属性的值类型。现在只有 isSwiftPrivate(API notes 的 SwiftPrivate,即 NS_REFINED_FOR_SWIFT),日后的 NS_SWIFT_NAME 是再加一个 swiftName。ObjCInterfaceBuilder 打印类的两个入口(classInterface、markedClassInterface)多一个参数,默认为空;宏打在属性与方法声明的分号前、行尾注释之前。不传时输出逐字节不变。只接类,category 与协议先不接。 +
    // 类型与参数的名字实现时定
    +var notes = ObjCSwiftImportNotes()
    +notes[.property(named: "settings")] = .init(isSwiftPrivate: true)
    +let header = builder.classInterface(named: "SHScenePresentation", options: options, swiftImportNotes: notes)
    +
  • +
  • 本库:上面的配对、打印形状、存储属性两条,以及一个查询:一个类里哪些 ObjC 成员是 NS_REFINED_FOR_SWIFT。查询用本库自己的类型——本库按版本依赖 MachOObjCSection,直接用它的新类型就得先等它发版、再抬下限。
  • +
  • RuntimeViewer:抬锁文件里两个库的修订号(两个都按 branch: "next" 依赖,不等发版),Generated Interface 由此得到改动。服务进程打印一个 ObjC 类的头文件之前,向同一镜像的 Swift section 要这个类改了名的成员,转成 MachOObjCSection 的标注;镜像没有 Swift section、或这个类没有 Swift 参与时不传。Find 语料里的头文件同样带上,与显示逐字一致——Find 按位置高亮结果。标注只在服务进程里用,请求与回复没有新字段,混版本不受影响。
  • +
+ +

方案

+ +

打印形状

+
    +
  • @objc @implementation 类(类的 Swift extension 里有 0046 认出的 @implementation 主体)改成与桥接出去的 Swift 类同一种形状:类头仍取 ObjC 记录的父类与协议;类体是 Swift 一侧 interface 里 @implementation extension 的内容,存储属性、final 的纯 Swift 成员都在;本镜像里这个类的其余 Swift extension 跟在类后面;ObjC 方法表里没有 Swift 成员回答的,按规则推导、加注明,放在类体最后——推断出改了名的属性除外,它的注释挂在占了它原名的 Swift 属性正上方(见「改了 Swift 名字的成员」)。
  • +
  • 桥接出去的 Swift 类形状不变。ObjC 实现、只被 Swift 扩展的类(夹具里的 ClangWidget)与 category 仍逐个成员替换。三种都用下面的配对:Swift 类末尾那个「没有 Swift 成员回答」的 extension 会少掉误列的成员。
  • +
+ +

配对:哪个 ObjC 成员有 Swift 成员回答

+

前两档(IMP 处的 To 符号、thunk 引用到的实现)不变。两档都没配上的 ObjC 成员,到实现这个类的 Swift 定义里、还没配上的成员中按名字找:

+
    +
  • 不再只限 override。在打印时做(ObjCImplementingSwiftMembers),不改 0048 在索引期记下的事实,dump 与 Swift 一侧的 interface 不受影响。
  • +
  • 名字判据沿用 ObjCMemberShape.isConsistent(withSelector:isClassMethod:),加一条:认 NS_REFINED_FOR_SWIFT 加的 __ 前缀(属性名、方法基名、初始化器的第一个标签)。同一个 selector 既对得上 __layerFilter、又对得上纯 Swift 的 layerFilter 时取前者:头文件标了 NS_REFINED_FOR_SWIFT 的才是 ObjC 那个成员。
  • +
  • 类型明显对不上的不配:ObjC 一侧是对象(@),Swift 成员的类型却是 Swift 与 Foundation 之外定义的 struct 或 enum;或者 ObjC 一侧是标量,Swift 成员却是类或 existential。宁可漏配,不配错,与 0048 一致。
  • +
  • 仍然只在恰好一个候选时配。
  • +
+ +

改了 Swift 名字的成员(NS_REFINED_FOR_SWIFT)

+

只看 @implementation 类与被本镜像 Swift extension 扩展的 ObjC 类;桥接出去的 Swift 类没有头文件,不涉及。两种判定:

+
    +
  • 有凭据:ObjC 成员配上的是 __ 开头的 Swift 成员(layerFilter ↔ __layerFilter)。
  • +
  • 推断:ObjC 属性没配上,而 Swift 一侧有同名属性、类型明显对不上(settings 对上本模块的 struct ScenePresentationSettings)。Swift 不允许一个类型里有两个同名属性,ObjC 那个只能是在 Swift 里改了名。只用于属性:方法可以按参数类型重载,同名说明不了改过名。
  • +
+

两边怎么标:

+
    +
  • Swift 视图(Generated Interface):有凭据的照 Swift 一侧打(var __layerFilter: …)。推断的没有 Swift 符号可抄,打一条结构化注释(StructuredComment),内容是按 importer 规则推出的 __ 声明,压成一行: +
      +
    • 位置:@objc @implementation 类里,挂在占了它原名的那个 Swift 属性正上方(var settings: ScenePresentationSettings 的上一行),排在那个属性自己的注释(地址、偏移)之前,不再进类体末尾那组;那组因此变空时,那行说明也不打。类体里没有那个 Swift 属性时留在原处:ObjC 实现、只被 Swift 扩展的类,类体按 ObjC 方法表逐个打,纯 Swift 属性不在里面;导出过滤(--exported-only)滤掉那个 Swift 属性时也一样,免得注释随它一起消失。
    • +
    • 分段:注释里的声明按结构分段,宿主可以像字段偏移树的行那样分色。NS_REFINED_FOR_SWIFT 是 .label,后面的 : 是 .separator;声明里属性名 __settings 是 .name,类型 __C.SHScenePresentationSettings! 是 .type;var 、声明里的 : 、 { get set } 不带角色——宿主会藏起 .separator 里的标点,声明里的冒号不能是 separator。各段取自结构,不切打印出的文字:名字与修饰词取自声明打印出的组件(名字是语义类型为 .variable 的那个),类型由 TypeNodePrinter 单独打印属性的类型节点,访问器块取自 AccessorBlockKeywords。
    • +
    +
  • +
  • ObjC 头文件:两种都在声明的分号前打 NS_REFINED_FOR_SWIFT。头文件由 MachOObjCSection 打印,由宿主告诉它哪些成员要打(见「三个库各做什么」)。
  • +
+ +

Swift 一侧缺、ObjC 一侧有的事实

+
    +
  • @implementation 的存储属性没有 setter 符号时,现在一律打 let,可 -O 下 setter 常被内联进 thunk、不留符号。改为 ObjC 属性可写就打 var,特性串带 W 就加 weak:scene 由 let scene: FBScene? 变成 weak var scene: FBScene?。Swift 一侧的 interface 同样生效。
  • +
  • 只剩 ivar、Swift 类型还原不出的存储属性(observers、_isActive):Generated Interface 里有同名 ObjC 属性时,在原位置打这个属性的导入形式(var observers: Any!),代替注释。Swift 一侧的 interface 照旧打注释——那里要的是 Swift 的类型,ObjC 的类型不是它。
  • +
+ +

以 SHScenePresentation 为例

+

Generated Interface,现在(节选):

+
class SHScenePresentation: __C.NSObject {
+    var settings: __C.SHScenePresentationSettings! { get set }
+    weak var scene: __C.FBScene! { get set }
+    var layerFilter: __C.SHSceneLayerFilter! { get set }
+    @objc var priority: Swift.Int { get set }
+    func isHostingSceneLayer(_: Any!) -> Swift.Bool
+}
+

改后(节选;注释的措辞实现时定):

+
class SHScenePresentation: __C.NSObject {
+    var observers: Any! { get set }
+    // stored property layerController: Swift type not recoverable (ObjC ivar, …)
+    weak var scene: __C.FBScene?
+    var __layerFilter: __C.SHSceneLayerFilter { get set }
+    var layerFilter: SceneHosting.SceneLayerFilter { get set }
+    @objc var priority: Swift.Int { get set }
+    // NS_REFINED_FOR_SWIFT: var __settings: __C.SHScenePresentationSettings! { get set }
+    var settings: SceneHosting.ScenePresentationSettings { get set }
+    func isHosting(sceneLayer: __C.FBSceneLayer) -> Swift.Bool
+
+    // Objective-C methods of the class that no Swift member answers to. …
+}
+

ObjC 头文件,改后(节选):

+
@property (nonatomic, strong) SHSceneLayerFilter *layerFilter NS_REFINED_FOR_SWIFT; // getter IMP: …
+@property (nonatomic, strong) SHScenePresentationSettings *settings NS_REFINED_FOR_SWIFT; // getter IMP: …
+ +

没问就定的假设

+
    +
  • 纯 Swift 成员(final、@nonobjc)照打:Swift 一侧有的就以它为准。
  • +
  • @objc 照 Swift 一侧原样打:符号证据配上的成员带,名字配上的不带。
  • +
  • category 不改成 Swift 优先,也不标 NS_REFINED_FOR_SWIFT:同一个类的几个 category 共用这个镜像里这个类的全部 Swift extension,分不清哪个成员属于哪个 category。
  • +
  • 镜像里根本没有 Swift 符号的成员(0090 后续项里 NSGlassEffectView 的 init(frame:))仍按规则推导:Swift 一侧确实没有它。
  • +
  • __ 名字照 importer 的规则推:属性名与方法基名加 __,初始化器加在第一个标签上。
  • +
  • 本库的公开 API 只多「一个类哪些成员是 NS_REFINED_FOR_SWIFT」这一个查询;Swift 优先的打印在打印器内部,ObjCImportedClassDefinition 已带着 swiftExtensions。
  • +
  • NS_SWIFT_NAME 不在本提案,见后续项。
  • +
+ +

落地步骤

+
    +
  1. (已完成)MachOObjCSection:头文件渲染接受宿主给的 Swift 导入标注、打出 NS_REFINED_FOR_SWIFT;测试覆盖属性、实例方法、类方法,不传标注时输出逐字节不变,marked 形式投影后与普通形式一致;文档写进它的使用指南「库调用方」一节与下一个版本的 Changelog。
  2. +
  3. (已完成)本库测试先红:夹具加一个照 SHScenePresentation 写的 @implementation 类,成员 public,像系统框架那样留下导出符号——一个头文件用 NS_SWIFT_NAME 改了 Swift 名的方法(isHosting(sceneLayer:) 那种)、一对 NS_REFINED_FOR_SWIFT 属性加同名的纯 Swift 属性(一个留下 __ 成员的符号、一个不留)、一个 weak 可写存储属性、一个只留 ivar 的存储属性。在 .optimizedStripped 变体上断言 Generated Interface 与改名查询的结果,先确认它们在改动前失败。
  4. +
  5. (已完成)本库实现:配对、打印形状、改了 Swift 名字的成员(判定、Swift 视图的注释、给宿主的查询)、存储属性的两条。
  6. +
  7. RuntimeViewer:(已完成)ObjC 头文件的显示与 Find 语料带上标注,测试接线;(已完成)用户在 App 里看过 SHScenePresentation;(收尾时,由 RuntimeViewer 一侧做)两个库落地进各自的 next 后,抬锁文件里的修订号。
  8. +
  9. (已完成)文档:模块参考 SwiftObjCInterop 与 SwiftDeclaration 里「ObjC 声明按 Swift 导入的样子」、命令行指南的「The Swift view」、演进账本、术语表;插件 skill 里讲 objc interface --swift 输出的地方一并核对。
  10. +
+ +

后续项

+
    +
  • NS_SWIFT_NAME:配上的 Swift 成员的名字与 importer 推出的名字不同时,头文件里打 NS_SWIFT_NAME(…)。SHScenePresentation 的 isHosting(sceneLayer:) 就是这样:夹具实测 importer 自己只给 isHostingSceneLayer(_:),参数是 FXSceneLayer 这种带前缀的类也一样,这个名字只能来自头文件的 NS_SWIFT_NAME。比较要用上 Swift 成员的参数类型——只凭 @ 推出的名字本来就偏。MachOObjCSection 的标注已为它留了位置。
  • +
  • swift-section objc interface 与 objc dump 也打这个宏:要 MachOObjCSection 先发带新接口的版本,本库再抬依赖下限。
  • +
+ +

决策日志

+
+展开 14 条决策 + + + + + + + + + + + + + + + + +
日期决定理由
2026-11-17Created as DraftRuntimeViewer 的 Generated Interface 里,系统框架中的 @objc @implementation 类大多数成员仍是按 selector 推导的名字与 Any!;用户要求 Swift 实现的类以 Swift 一侧的类型与签名为准,只有 Swift 一侧没有的才用 ObjC 一侧的
2026-11-17ObjC 属性与 Swift 一侧的属性同名而类型对不上时(settings),Swift 视图用结构化注释写出它的 __settings 声明,ObjC 头文件给它标 NS_REFINED_FOR_SWIFT;MachOObjCSection 现在不会打这个宏,要给它加上,接口为日后的 NS_SWIFT_NAME 留好位置用户选定。两边各用自己的语言说同一件事,与 SDK 里头文件和它导入后的样子一致
2026-11-17本库用自己的类型给出改了名的成员,由 RuntimeViewer 转成 MachOObjCSection 的输入;swift-section 的 ObjC 头文件暂不打这个宏本库按版本依赖 MachOObjCSection,直接用它的新类型就得先发版、再抬下限;RuntimeViewer 按分支依赖两个库,不用等
2026-11-17三个库共用这一份提案,另两个仓库的提案索引各加一行 cross-repository draft一次改动一份提案;MachOObjCSection 的索引里已有这种跨仓库草案的先例
2026-11-17用户批准,开始实现按 MachOObjCSection → 本库 → RuntimeViewer 的顺序做,三个仓库各一条 feature/swift-first-imported-declarations
2026-11-17构建与测试改在 JHs-MacBook-Pro 上跑JHs-Mac-Studio-Ultra 当天连不上 GitHub(22 与 443 端口都在本地被断开),代码只经 GitHub 同步,网络设置不动
2026-11-17本库按 USING_LOCAL_DEPENDENCIES=1 配 swift-demangling next 的同级检出来编本库 next 用到 swift-demangling 还没发版的 DemangleOptions.useExistentialAny,按发布版 0.7.3 编不过;锁文件不进 git,CI 以外都这样编
2026-11-17RuntimeViewer 的功能分支接在 origin/next 上本地 next 有 6 个别处还没推的提交(与本改动无关的文件),推功能分支会把它们带上 GitHub
2026-11-17只剩 ivar 的存储属性,找它的 ObjC 属性先认 V<ivar>,再认同名夹具编出的 ObjC 属性特性串不写 V,SceneHosting 的写;两种都要认
2026-11-17NS_REFINED_FOR_SWIFT 注释把声明压成一行({ get set })原样打印时访问器块占好几行,只有第一行在注释里
2026-11-17夹具照编译器的要求写:改名属性的实现写成 @objc(name) var __name;isHostingSceneLayer: 的 Swift 名由头文件的 NS_SWIFT_NAME 给,实现写 @objc(isHostingSceneLayer:)编译器拒绝不写 selector 的 __name(它从 Swift 名推出 __name,头文件里没有),也从 isHosting(sceneLayer:) 推出 isHostingWithSceneLayer:;importer 自己不会把 isHostingSceneLayer: 拆成 isHosting(sceneLayer:),参数类带前缀也一样,所以 SceneHosting 的这个名字来自 NS_SWIFT_NAME,后续项据此更正
2026-11-17实现完成,待用户看过后收尾三个库在 JHs-MacBook-Pro(macOS 27.2,Xcode 27.2)上验证:MachOObjCSection 的 ObjCInterfaceTests 与 ObjCDeclarationRenderingTests 全过;本库新测试改动前失败、改动后通过,相关套件全过,全量(跳过 IntegrationTests)与不含改动的 next 失败点完全相同(167 处,SymbolTests 夹具的 ABI 基线按 Xcode 26.6 录、模拟器 runtime 缺文件);RuntimeViewerCore 的新测试与 Generated Interface 测试全过。RuntimeViewer 锁文件里两个库的修订号留到正式收尾再抬:两个库的改动那时才进各自的 next。不另写实现说明与使用指南:契约写进了两份模块参考、命令行指南与 MachOObjCSection 的使用指南;新术语「改名成员」与 MachOObjCSection 的「Swift 导入标注」已登记
2026-11-17推断出改了名的属性,注释挂到占了它原名的 Swift 属性正上方(排在那个属性自己的注释之前);注释里的声明分段:属性名 .name、类型 .type,var 、声明里的冒号和访问器块不带角色。类体里没有那个 Swift 属性、或导出过滤滤掉了它时,注释留在原处用户在 RuntimeViewer 里看过效果后定的:注释放在类体末尾,离它说的那个属性太远;整条声明是一个 .value 段,宿主只能整段一个颜色。宿主会藏起 .separator 里的标点,所以声明里的冒号不能标成 separator
2026-11-18Implemented,取号 0096,合进 next 并推送用户在 RuntimeViewer 里看过注释的新位置与分段着色,同意收尾。追加的两处在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2)上验证:两个新用例改动前失败、改动后通过,相关的 9 个套件 73 个测试全过。仍不另写实现说明与使用指南:位置与分段写进了命令行指南的「The Swift view」、插件 skill 与术语表的「改名成员」,没有新术语。NS_SWIFT_NAME 与 swift-section 的 ObjC 头文件打宏两项留作后续项
+
+ +
+ + diff --git a/Documentations/Evolutions/0096-swift-first-imported-declarations.md b/Documentations/Evolutions/0096-swift-first-imported-declarations.md new file mode 100644 index 000000000..be299433f --- /dev/null +++ b/Documentations/Evolutions/0096-swift-first-imported-declarations.md @@ -0,0 +1,145 @@ +# 0096 - Swift 实现的类,导入声明以 Swift 一侧为准 + +- **状态**: Implemented +- **创建日期**: 2026-11-17 +- **最后更新**: 2026-11-18 +- **关联提案**: [0090-objc-imported-declarations](0090-objc-imported-declarations.md)(本提案改它的「与 Swift 合并」)、[0048-objc-member-selector-recovery](0048-objc-member-selector-recovery.md)(把 ObjC 方法联结到 Swift 成员的三档证据)、[0046-objc-implementation-class-recognition](0046-objc-implementation-class-recognition.md)(认出 `@objc @implementation` 类);RuntimeViewer 的提案 0084(Generated Interface) +- **跨仓库**: 本提案是三个库共用的唯一提案,MachOObjCSection 与 RuntimeViewer 的提案索引各有一行 cross-repository draft 指向这里;各库的部分见「三个库各做什么」 +- **实现分支 / PR**: 三个仓库都是 `feature/swift-first-imported-declarations`(从各自的 `next` 切出),本地合进各自的 `next`,没开 PR +- **网页版**: [0096-swift-first-imported-declarations.html](0096-swift-first-imported-declarations.html) + +## 摘要 + +RuntimeViewer 的 Generated Interface 显示 macOS 27.2 共享缓存里 SceneHosting 的 `SHScenePresentation`(一个 `@objc @implementation` 类)时,只有 5 个成员用上了 Swift 声明,其余都按 ClangImporter 的规则从 selector 推导,例如 `func isHostingSceneLayer(_: Any!) -> Swift.Bool`,而同一镜像的 Swift 一侧就有 `func isHosting(sceneLayer: __C.FBSceneLayer) -> Swift.Bool`。原因在 0090 的配对只认符号证据:系统框架剥掉了 `To` thunk 的符号,`-O` 又把 Swift 函数体整段内联进 thunk(`-[SHScenePresentation isHostingSceneLayer:]` 的实现不再调用 `isHosting(sceneLayer:)`),第二档找不到引用;只按名字配的第三档在 0048 里只算 override,0090 接上的也只有这一部分。 + +本提案让 Swift 实现的类以 Swift 一侧为准:Swift 一侧有的成员照它的声明打印,ObjC 一侧只补 Swift 一侧没有的。头文件标了 `NS_REFINED_FOR_SWIFT`、在 Swift 里改成 `__` 开头的成员,两边都标出来:Swift 视图写出它的 `__` 声明,ObjC 头文件打上这个宏。这一项跨三个库:本库判定哪些成员改了名,MachOObjCSection 在头文件里打宏,RuntimeViewer 把两者接起来。 + +## 方案 + +### 打印形状 + +- **`@objc @implementation` 类**(类的 Swift extension 里有 0046 认出的 `@implementation` 主体)改成与桥接出去的 Swift 类同一种形状:类头仍取 ObjC 记录的父类与协议;类体是 Swift 一侧 interface 里 `@implementation` extension 的内容,存储属性、`final` 的纯 Swift 成员都在;本镜像里这个类的其余 Swift extension 跟在类后面;ObjC 方法表里没有 Swift 成员回答的,按规则推导、加注明,放在类体最后——推断出改了名的属性除外,它的注释挂在占了它原名的 Swift 属性正上方(见「改了 Swift 名字的成员」)。 +- 桥接出去的 Swift 类形状不变。ObjC 实现、只被 Swift 扩展的类(夹具里的 `ClangWidget`)与 category 仍逐个成员替换。三种都用下面的配对:Swift 类末尾那个「没有 Swift 成员回答」的 extension 会少掉误列的成员。 + +### 配对:哪个 ObjC 成员有 Swift 成员回答 + +前两档(IMP 处的 `To` 符号、thunk 引用到的实现)不变。两档都没配上的 ObjC 成员,到实现这个类的 Swift 定义里、还没配上的成员中按名字找: + +- 不再只限 override。在打印时做(`ObjCImplementingSwiftMembers`),不改 0048 在索引期记下的事实,dump 与 Swift 一侧的 interface 不受影响。 +- 名字判据沿用 `ObjCMemberShape.isConsistent(withSelector:isClassMethod:)`,加一条:认 `NS_REFINED_FOR_SWIFT` 加的 `__` 前缀(属性名、方法基名、初始化器的第一个标签)。同一个 selector 既对得上 `__layerFilter`、又对得上纯 Swift 的 `layerFilter` 时取前者:头文件标了 `NS_REFINED_FOR_SWIFT` 的才是 ObjC 那个成员。 +- 类型明显对不上的不配:ObjC 一侧是对象(`@`),Swift 成员的类型却是 Swift 与 Foundation 之外定义的 struct 或 enum;或者 ObjC 一侧是标量,Swift 成员却是类或 existential。宁可漏配,不配错,与 0048 一致。 +- 仍然只在恰好一个候选时配。 + +### 改了 Swift 名字的成员(`NS_REFINED_FOR_SWIFT`) + +只看 `@implementation` 类与被本镜像 Swift extension 扩展的 ObjC 类;桥接出去的 Swift 类没有头文件,不涉及。两种判定: + +- **有凭据**:ObjC 成员配上的是 `__` 开头的 Swift 成员(`layerFilter` ↔ `__layerFilter`)。 +- **推断**:ObjC 属性没配上,而 Swift 一侧有同名属性、类型明显对不上(`settings` 对上本模块的 struct `ScenePresentationSettings`)。Swift 不允许一个类型里有两个同名属性,ObjC 那个只能是在 Swift 里改了名。只用于属性:方法可以按参数类型重载,同名说明不了改过名。 + +两边怎么标: + +- **Swift 视图**(Generated Interface):有凭据的照 Swift 一侧打(`var __layerFilter: …`)。推断的没有 Swift 符号可抄,打一条结构化注释(`StructuredComment`),内容是按 importer 规则推出的 `__` 声明,压成一行: + - **位置**:`@objc @implementation` 类里,挂在占了它原名的那个 Swift 属性正上方(`var settings: ScenePresentationSettings` 的上一行),排在那个属性自己的注释(地址、偏移)之前,不再进类体末尾那组;那组因此变空时,那行说明也不打。类体里没有那个 Swift 属性时留在原处:ObjC 实现、只被 Swift 扩展的类,类体按 ObjC 方法表逐个打,纯 Swift 属性不在里面;导出过滤(`--exported-only`)滤掉那个 Swift 属性时也一样,免得注释随它一起消失。 + - **分段**:注释里的声明按结构分段,宿主可以像字段偏移树的行那样分色。`NS_REFINED_FOR_SWIFT` 是 `.label`,后面的 `: ` 是 `.separator`;声明里属性名 `__settings` 是 `.name`,类型 `__C.SHScenePresentationSettings!` 是 `.type`;`var `、声明里的 `: `、` { get set }` 不带角色——宿主会藏起 `.separator` 里的标点,声明里的冒号不能是 separator。各段取自结构,不切打印出的文字:名字与修饰词取自声明打印出的组件(名字是语义类型为 `.variable` 的那个),类型由 `TypeNodePrinter` 单独打印属性的类型节点,访问器块取自 `AccessorBlockKeywords`。 +- **ObjC 头文件**:两种都在声明的分号前打 `NS_REFINED_FOR_SWIFT`。头文件由 MachOObjCSection 打印,由宿主告诉它哪些成员要打(见「三个库各做什么」)。 + +### Swift 一侧缺、ObjC 一侧有的事实 + +- `@implementation` 的存储属性没有 setter 符号时,现在一律打 `let`,可 `-O` 下 setter 常被内联进 thunk、不留符号。改为 ObjC 属性可写就打 `var`,特性串带 `W` 就加 `weak`:`scene` 由 `let scene: FBScene?` 变成 `weak var scene: FBScene?`。Swift 一侧的 interface 同样生效。 +- 只剩 ivar、Swift 类型还原不出的存储属性(`observers`、`_isActive`):Generated Interface 里有同名 ObjC 属性时,在原位置打这个属性的导入形式(`var observers: Any!`),代替注释。Swift 一侧的 interface 照旧打注释——那里要的是 Swift 的类型,ObjC 的类型不是它。 + +### 以 `SHScenePresentation` 为例 + +Generated Interface,现在(节选): + +```swift +class SHScenePresentation: __C.NSObject { + var settings: __C.SHScenePresentationSettings! { get set } + weak var scene: __C.FBScene! { get set } + var layerFilter: __C.SHSceneLayerFilter! { get set } + @objc var priority: Swift.Int { get set } + func isHostingSceneLayer(_: Any!) -> Swift.Bool +} +``` + +改后(节选;注释的措辞实现时定): + +```swift +class SHScenePresentation: __C.NSObject { + var observers: Any! { get set } + // stored property layerController: Swift type not recoverable (ObjC ivar, …) + weak var scene: __C.FBScene? + var __layerFilter: __C.SHSceneLayerFilter { get set } + var layerFilter: SceneHosting.SceneLayerFilter { get set } + @objc var priority: Swift.Int { get set } + // NS_REFINED_FOR_SWIFT: var __settings: __C.SHScenePresentationSettings! { get set } + var settings: SceneHosting.ScenePresentationSettings { get set } + func isHosting(sceneLayer: __C.FBSceneLayer) -> Swift.Bool + + // Objective-C methods of the class that no Swift member answers to. … +} +``` + +ObjC 头文件,改后(节选): + +```objc +@property (nonatomic, strong) SHSceneLayerFilter *layerFilter NS_REFINED_FOR_SWIFT; // getter IMP: … +@property (nonatomic, strong) SHScenePresentationSettings *settings NS_REFINED_FOR_SWIFT; // getter IMP: … +``` + +### 三个库各做什么 + +- **MachOObjCSection**:头文件渲染接受宿主按成员给出的 Swift 导入标注,形状照 Clang 的 API notes——方法以 selector 加实例/类方法为键,属性以名字加实例/类属性为键,每项是一个可以加属性的值类型。现在只有 `isSwiftPrivate`(API notes 的 `SwiftPrivate`,即 `NS_REFINED_FOR_SWIFT`),日后的 `NS_SWIFT_NAME` 是再加一个 `swiftName`。`ObjCInterfaceBuilder` 打印类的两个入口(`classInterface`、`markedClassInterface`)多一个参数,默认为空;宏打在属性与方法声明的分号前、行尾注释之前。不传时输出逐字节不变。只接类,category 与协议先不接。 + + ```swift + // 类型与参数的名字实现时定 + var notes = ObjCSwiftImportNotes() + notes[.property(named: "settings")] = .init(isSwiftPrivate: true) + let header = builder.classInterface(named: "SHScenePresentation", options: options, swiftImportNotes: notes) + ``` + +- **本库**:上面的配对、打印形状、存储属性两条,以及一个查询:一个类里哪些 ObjC 成员是 `NS_REFINED_FOR_SWIFT`。查询用本库自己的类型——本库按版本依赖 MachOObjCSection,直接用它的新类型就得先等它发版、再抬下限。 +- **RuntimeViewer**:抬锁文件里两个库的修订号(两个都按 `branch: "next"` 依赖,不等发版),Generated Interface 由此得到改动。服务进程打印一个 ObjC 类的头文件之前,向同一镜像的 Swift section 要这个类改了名的成员,转成 MachOObjCSection 的标注;镜像没有 Swift section、或这个类没有 Swift 参与时不传。Find 语料里的头文件同样带上,与显示逐字一致——Find 按位置高亮结果。标注只在服务进程里用,请求与回复没有新字段,混版本不受影响。 + +### 没问就定的假设 + +- 纯 Swift 成员(`final`、`@nonobjc`)照打:Swift 一侧有的就以它为准。 +- `@objc` 照 Swift 一侧原样打:符号证据配上的成员带,名字配上的不带。 +- category 不改成 Swift 优先,也不标 `NS_REFINED_FOR_SWIFT`:同一个类的几个 category 共用这个镜像里这个类的全部 Swift extension,分不清哪个成员属于哪个 category。 +- 镜像里根本没有 Swift 符号的成员(0090 后续项里 `NSGlassEffectView` 的 `init(frame:)`)仍按规则推导:Swift 一侧确实没有它。 +- `__` 名字照 importer 的规则推:属性名与方法基名加 `__`,初始化器加在第一个标签上。 +- 本库的公开 API 只多「一个类哪些成员是 `NS_REFINED_FOR_SWIFT`」这一个查询;Swift 优先的打印在打印器内部,`ObjCImportedClassDefinition` 已带着 `swiftExtensions`。 +- `NS_SWIFT_NAME` 不在本提案,见后续项。 + +### 落地步骤 + +1. (已完成)MachOObjCSection:头文件渲染接受宿主给的 Swift 导入标注、打出 `NS_REFINED_FOR_SWIFT`;测试覆盖属性、实例方法、类方法,不传标注时输出逐字节不变,marked 形式投影后与普通形式一致;文档写进它的使用指南「库调用方」一节与下一个版本的 Changelog。 +2. (已完成)本库测试先红:夹具加一个照 `SHScenePresentation` 写的 `@implementation` 类,成员 `public`,像系统框架那样留下导出符号——一个头文件用 `NS_SWIFT_NAME` 改了 Swift 名的方法(`isHosting(sceneLayer:)` 那种)、一对 `NS_REFINED_FOR_SWIFT` 属性加同名的纯 Swift 属性(一个留下 `__` 成员的符号、一个不留)、一个 `weak` 可写存储属性、一个只留 ivar 的存储属性。在 `.optimizedStripped` 变体上断言 Generated Interface 与改名查询的结果,先确认它们在改动前失败。 +3. (已完成)本库实现:配对、打印形状、改了 Swift 名字的成员(判定、Swift 视图的注释、给宿主的查询)、存储属性的两条。 +4. RuntimeViewer:(已完成)ObjC 头文件的显示与 Find 语料带上标注,测试接线;(已完成)用户在 App 里看过 `SHScenePresentation`;(收尾时,由 RuntimeViewer 一侧做)两个库落地进各自的 `next` 后,抬锁文件里的修订号。 +5. (已完成)文档:模块参考 SwiftObjCInterop 与 SwiftDeclaration 里「ObjC 声明按 Swift 导入的样子」、命令行指南的「The Swift view」、演进账本、术语表;插件 skill 里讲 `objc interface --swift` 输出的地方一并核对。 + +## 后续项 + +- `NS_SWIFT_NAME`:配上的 Swift 成员的名字与 importer 推出的名字不同时,头文件里打 `NS_SWIFT_NAME(…)`。`SHScenePresentation` 的 `isHosting(sceneLayer:)` 就是这样:夹具实测 importer 自己只给 `isHostingSceneLayer(_:)`,参数是 `FXSceneLayer` 这种带前缀的类也一样,这个名字只能来自头文件的 `NS_SWIFT_NAME`。比较要用上 Swift 成员的参数类型——只凭 `@` 推出的名字本来就偏。MachOObjCSection 的标注已为它留了位置。 +- `swift-section objc interface` 与 `objc dump` 也打这个宏:要 MachOObjCSection 先发带新接口的版本,本库再抬依赖下限。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-17 | Created as Draft | RuntimeViewer 的 Generated Interface 里,系统框架中的 `@objc @implementation` 类大多数成员仍是按 selector 推导的名字与 `Any!`;用户要求 Swift 实现的类以 Swift 一侧的类型与签名为准,只有 Swift 一侧没有的才用 ObjC 一侧的 | +| 2026-11-17 | ObjC 属性与 Swift 一侧的属性同名而类型对不上时(`settings`),Swift 视图用结构化注释写出它的 `__settings` 声明,ObjC 头文件给它标 `NS_REFINED_FOR_SWIFT`;MachOObjCSection 现在不会打这个宏,要给它加上,接口为日后的 `NS_SWIFT_NAME` 留好位置 | 用户选定。两边各用自己的语言说同一件事,与 SDK 里头文件和它导入后的样子一致 | +| 2026-11-17 | 本库用自己的类型给出改了名的成员,由 RuntimeViewer 转成 MachOObjCSection 的输入;`swift-section` 的 ObjC 头文件暂不打这个宏 | 本库按版本依赖 MachOObjCSection,直接用它的新类型就得先发版、再抬下限;RuntimeViewer 按分支依赖两个库,不用等 | +| 2026-11-17 | 三个库共用这一份提案,另两个仓库的提案索引各加一行 cross-repository draft | 一次改动一份提案;MachOObjCSection 的索引里已有这种跨仓库草案的先例 | +| 2026-11-17 | 用户批准,开始实现 | 按 MachOObjCSection → 本库 → RuntimeViewer 的顺序做,三个仓库各一条 `feature/swift-first-imported-declarations` | +| 2026-11-17 | 构建与测试改在 JHs-MacBook-Pro 上跑 | JHs-Mac-Studio-Ultra 当天连不上 GitHub(22 与 443 端口都在本地被断开),代码只经 GitHub 同步,网络设置不动 | +| 2026-11-17 | 本库按 `USING_LOCAL_DEPENDENCIES=1` 配 swift-demangling `next` 的同级检出来编 | 本库 `next` 用到 swift-demangling 还没发版的 `DemangleOptions.useExistentialAny`,按发布版 0.7.3 编不过;锁文件不进 git,CI 以外都这样编 | +| 2026-11-17 | RuntimeViewer 的功能分支接在 `origin/next` 上 | 本地 `next` 有 6 个别处还没推的提交(与本改动无关的文件),推功能分支会把它们带上 GitHub | +| 2026-11-17 | 只剩 ivar 的存储属性,找它的 ObjC 属性先认 `V`,再认同名 | 夹具编出的 ObjC 属性特性串不写 `V`,SceneHosting 的写;两种都要认 | +| 2026-11-17 | `NS_REFINED_FOR_SWIFT` 注释把声明压成一行(`{ get set }`) | 原样打印时访问器块占好几行,只有第一行在注释里 | +| 2026-11-17 | 夹具照编译器的要求写:改名属性的实现写成 `@objc(name) var __name`;`isHostingSceneLayer:` 的 Swift 名由头文件的 `NS_SWIFT_NAME` 给,实现写 `@objc(isHostingSceneLayer:)` | 编译器拒绝不写 selector 的 `__name`(它从 Swift 名推出 `__name`,头文件里没有),也从 `isHosting(sceneLayer:)` 推出 `isHostingWithSceneLayer:`;importer 自己不会把 `isHostingSceneLayer:` 拆成 `isHosting(sceneLayer:)`,参数类带前缀也一样,所以 SceneHosting 的这个名字来自 `NS_SWIFT_NAME`,后续项据此更正 | +| 2026-11-17 | 实现完成,待用户看过后收尾 | 三个库在 JHs-MacBook-Pro(macOS 27.2,Xcode 27.2)上验证:MachOObjCSection 的 `ObjCInterfaceTests` 与 `ObjCDeclarationRenderingTests` 全过;本库新测试改动前失败、改动后通过,相关套件全过,全量(跳过 IntegrationTests)与不含改动的 `next` 失败点完全相同(167 处,SymbolTests 夹具的 ABI 基线按 Xcode 26.6 录、模拟器 runtime 缺文件);RuntimeViewerCore 的新测试与 Generated Interface 测试全过。RuntimeViewer 锁文件里两个库的修订号留到正式收尾再抬:两个库的改动那时才进各自的 `next`。不另写实现说明与使用指南:契约写进了两份模块参考、命令行指南与 MachOObjCSection 的使用指南;新术语「改名成员」与 MachOObjCSection 的「Swift 导入标注」已登记 | +| 2026-11-17 | 推断出改了名的属性,注释挂到占了它原名的 Swift 属性正上方(排在那个属性自己的注释之前);注释里的声明分段:属性名 `.name`、类型 `.type`,`var `、声明里的冒号和访问器块不带角色。类体里没有那个 Swift 属性、或导出过滤滤掉了它时,注释留在原处 | 用户在 RuntimeViewer 里看过效果后定的:注释放在类体末尾,离它说的那个属性太远;整条声明是一个 `.value` 段,宿主只能整段一个颜色。宿主会藏起 `.separator` 里的标点,所以声明里的冒号不能标成 separator | +| 2026-11-18 | Implemented,取号 0096,合进 `next` 并推送 | 用户在 RuntimeViewer 里看过注释的新位置与分段着色,同意收尾。追加的两处在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2)上验证:两个新用例改动前失败、改动后通过,相关的 9 个套件 73 个测试全过。仍不另写实现说明与使用指南:位置与分段写进了命令行指南的「The Swift view」、插件 skill 与术语表的「改名成员」,没有新术语。`NS_SWIFT_NAME` 与 `swift-section` 的 ObjC 头文件打宏两项留作后续项 | diff --git a/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.html b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.html new file mode 100644 index 000000000..347ab8a95 --- /dev/null +++ b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.html @@ -0,0 +1,960 @@ + + + + + +0097 - 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache + + + +
+ +

0097 - 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache

+
+ 状态:Implemented + 对应提案最后更新:2026-11-19 + 作者:JH + 创建:2026-11-18 + 所属愿景:不依赖 IDA 的逆向(第 1 阶段) +
+

本页是 0097-offline-cross-references-and-symbolication.md 的网页版,两者对不上时以 Markdown 原文为准。

+ + + +

摘要

+

CrossReferenceAnalysis 今天只能分析当前进程映射进来的镜像,读不了磁盘上的 app、也读不了 /Volumes/DyldSharedCaches 下归档的各版本 cache,而且没有命令行入口。本提案做六件事:

+
    +
  1. 把分析器里「直接读进程内存」的地方收进一个读取抽象,新增从 FullDyldCache 和一组 MachOFile 构造分析器的入口,槽里的值改由 fixup 解码得到;
  2. +
  3. 把交叉引用按层拆成三个模块:与语言无关的核心 CrossReferenceCore(指令扫描、函数表、桩与槽、字符串、符号化)、ObjC 层 CrossReferenceObjC(消息发送、类引用、ivar、ObjC 方法名)、Swift 层 CrossReferenceAnalysis(Swift 类型、对外的公开 API)。层与层之间经「识别器」扩展点相接,核心不认识任何一种语言;各层能 import 什么由源码扫描测试守住,只许 import 它们将来的落脚处也有的模块。真正搬到 MachOKitExtensions(核心)与 MachOObjCSection(ObjC 层)另写迁移提案,在本提案量完吞吐、跑稳之后做;
  4. +
  5. 把 SwiftThunkAnalysis 里已经写好的离线桩链与槽解析抽成独立的 CodeAddressResolution 模块,两边共用;
  6. +
  7. 补三类引用:经 ivar 偏移变量读写 ObjC ivar、C 字符串字面量、CFString 常量,并给每条引用标上它是怎么到达目标的(直接调用、本镜像桩、stub island、cache 共用桩、GOT 槽……);
  8. +
  9. 新增地址符号化:任意一个地址,说出它在哪个镜像的哪个函数加多少偏移,或者它是桩、最终跳到谁,或者它是槽、里面装着谁;
  10. +
  11. 新增 swift-section refs 与 swift-section symbolicate 两个子命令(文本与 JSON 输出),并在 RuntimeViewer 的 CLI 与 MCP 上接出 callers / callees / references / symbolicate。
  12. +
+ +

要定的事

+
没有留待拍板的事。九个落地步骤都已完成,用户验收后已落地为 0097,合进本库与 RuntimeViewer 的 next(见决策日志最后一行);没做完的列在「后续项」。下层模块迁出后对外的公开模型留给之后的迁移提案(见非目标)。
+ +

架构图

+
新增修改删除未着色的是不变的上下文。虚线框右上角是这一层将来的落脚处。
+ +
+
+
MachOSwiftSection
+
+
Sources/Executables/swift-section · Sources/Commands/SwiftSectionKit
+
swift-section refs, symbolicate
CrossReferences/ReferencesRequest, SymbolicateRequest, CrossReferenceInput
+
+
▼ depends on
+
+
Sources/Analysis/CrossReferenceAnalysis — Swift layer + public facade [stays]
+
CrossReferenceAnalyzer
facade: CodeImageSet + recognizers; implements the three recordings +
    +
  • + init(dyldCache:recordingStringReferences:)
  • +
  • + init(machOFiles:recordingStringReferences:)
  • +
  • + symbolication(of:) -> AddressSymbolication
  • +
+
+
SwiftCodeReferenceRecognizer
accessors, value metadata, mangled names, swift_* helpers
+
SwiftMetadataNames
split from ImageFallbackNames
+
CodeReferenceTarget, CodeReferenceTable, CodeReferenceIndex, CodeFunction
public model stays here;+ objectiveCInstanceVariable, + cString, + constantString;+ route
+
AddressSymbolication
public
+
RuntimeHelperNames → SwiftRuntimeHelperNames
Swift names only; the libobjc list moves to ObjCRuntimeHelperNames
+
+
▼ @_exported import
+
+
Sources/Analysis/CrossReferenceObjC — package, not a product [MachOObjCSection: ObjCCodeReferences]
+
ObjCCodeReferenceRecognizer · ObjCCodeReferenceRecording
sends, entry points, selector stubs, receivers, class / super refs, ivars, objc_* helpers
+
ObjectiveCClassIndex, MessageSendEntryPoints
moved
+
ObjCImageSections, ObjCMethodNames
split from ImageFunctionTable, ImageFallbackNames
+
└─▶ MachOObjCSection (package)
+
+
▼
+
+
Sources/Analysis/CrossReferenceCore — package, not a product [MachOKitExtensions: MachOCodeReferences]
+
CodeReferenceRecognitionSession, CodeReferenceRecording, ResolvedCallTarget
the extension point: five moments in the scan
+
CodeImageSet
images, mappings, function tables(split from CrossReferenceAnalyzer)
+
ReferenceScanner, RegisterFile, ImageFunctionTable
moved; language-free;register tags replace methodReceiver;+ route, + C string / CFString, + ldrsw sources
+
CrossReferenceMemory
package protocol
+
├─ 新增 InProcessCrossReferenceMemory — today's pointer reads, moved
+
└─ 新增 FileCrossReferenceMemory ──▶ CodeAddressResolution
+
CodeLocation, CodeReferenceRoute, CodeReferenceKind, IndirectCallEvidence
moved down, re-exported
+
+
▼
+
+
Sources/Analysis/CodeAddressResolution — package, not a product [MachOKitExtensions: MachOAddressResolution]
+
CodeAddressResolution
+
    +
  • ImageAddressSpace(原 ThunkAddressSpace)
  • +
  • CacheImageLocator(原 CacheImageResolver)
  • +
  • StubChainResolver:stubs, ld64 trampolines, stub islands, cache-shared stubs + register constants they set
  • +
  • SlotResolver:any pointer slot → rebase target or bound symbol
  • +
+
+
+
+
Sources/Analysis/SwiftThunkAnalysis
+
MachOThunkEnvironment
uses CodeAddressResolution
+
ThunkAddressSpace, CacheImageResolver
+
+
+
Sources/Support/ARM64InstructionDecoding
+
ARM64InstructionWord
+ 32-bit ldr, ldrsw
+
+
+ +
+
RuntimeViewer
+
RuntimeViewerCrossReferences
switch over new targets;+ symbolicate engine command
+
RuntimeViewerCommandLine
+ callers, callees, references, symbolicate(protocol 2 → 3)
+
RuntimeViewerMCPBridge
+ Callers, Callees, TypeReferences, Symbolicate
+

按层拆分不改 RuntimeViewer 用到的名字:下移的类型经 @_exported import 原名可见。

+
+
+ +

扫描一个函数时,核心层在哪里问识别器

+
+
enterFunction
ObjC session tags x0 as the method receiver
+
▼
+
bl / b out of the function → core resolves the target(own stubs, GOT, stub islands, other images) +
not recognized → sessions.resolveCallTarget(ObjC: __objc_stubs selector)
+
sessions.noteCall(ObjC: x1 selector, x0 receiver → recordMessageSend;Swift: accessor, mangled name → recordSwiftType)
+
no session claimed it → core records .function / .importedSymbol / .unrecognized;registers kept across the call = what the sessions return
+
+
▼
+
adrp+add / adr built an address +
core: C string, CFString(when requested);sessions.noteAddress(ObjC: class object;Swift: metadata, accessor, large string)
+
+
▼
+
ldr from a slot → sessions.noteSlotLoad
ObjC: classref, superref, ivar offset;Swift: GOT → type
+
▼
+
blr / braa → core records the indirect call
pointer-authentication constant, displacement
+
▼
+
CrossReferenceAnalyzer(facade)implements every recording → public CodeReference
+
+ +

一次 refs 查询的数据流

+
+
swift-section refs --selector makeKeyAndOrderFront: --dyld-shared-cache <cache>
ReferencesCommand.makeRequest()
+
▼
+
ReferencesRequest → CrossReferenceInput: FullDyldCache(url:) → CrossReferenceAnalyzer(dyldCache:)
CodeImageSet from cache header imageInfos; FileCrossReferenceMemory over mapped subcache files
+
▼
+
imageIndices(referencingSelector:among: all)
prefilter(ObjC layer)
+
▼
+
for each candidate image, concurrently: references(to: [.selector("makeKeyAndOrderFront:")], inImageAt:) +
ReferenceScanner over the image's __text bytes
+
bl X → StubChainResolver(X) → trampoline sets x1, ends at objc_msgSend → ObjC session: selector → .messageSend route .cacheSharedStub
+
adrp+ldr slot → SlotResolver(slot) → rebase target → ObjC session: class object route .pointerSlot
+
+
▼
+
functions(containing: sites) → names
symbols, export trie, ObjC method lists, Swift metadata
+
▼
+
StandardStreamOutput: text rows | one JSON document
+
+ +

改动地图

+

步骤号对应「落地步骤」。第 2 步把文件按层搬家;之后各行的路径写的是搬家后的位置(核心层 Sources/Analysis/CrossReferenceCore/,ObjC 层 Sources/Analysis/CrossReferenceObjC/,Swift 层仍是 Sources/Analysis/CrossReferenceAnalysis/)。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Sources/Analysis/CrossReferenceAnalysis/Memory/CrossReferenceMemory.swift · CrossReferenceMemory新增package 协议:区间字节、槽内容、C 字符串、指针掩码;第 2 步随核心层搬到 CrossReferenceCore/Memory/两种模式唯一的本质差别收在这里1、2
…/Memory/InProcessCrossReferenceMemory.swift · InProcessCrossReferenceMemory新增搬入现有的直接读指针与 slide 换算进程内行为不变1、2
现有 22 处 UnsafeRawPointer(bitPattern:)(ReferenceScanner、ObjectiveCClassIndex、SwiftTypeIndex、ImageFunctionTable、+SwiftTypes、+Prefiltering、ImageFallbackNames)、StoredPointer修改改走 CrossReferenceMemory;掩码由 memory 提供读取抽象;文件模式没有 InProcessContext1
Sources/Analysis/CrossReferenceCore/新增核心层模块:CodeLocation、CodeReferenceRoute、IndirectCallEvidence(由顶层下移),镜像表、函数表、扫描循环、寄存器跟踪、链接关系与导入名预筛、RenamedReexportIndex按层拆分2
…/CrossReferenceCore/Recognition/CodeReferenceRecognition.swift · CodeReferenceRecognitionSession、CodeReferenceRecording、ResolvedCallTarget、ScanSite新增package 协议:会话在五个时机(进入函数、解析只有它认得的调用目标、调用点、算出地址、读槽)被问;核心层产出的引用交给谁扩展点;核心不认识任何语言;引用不经核心转手2
…/CrossReferenceCore/Images/CodeImageSet.swift、CodeImageSet+Linkage.swift · CodeImageSet、RuntimeLibraryRules新增由 CrossReferenceAnalyzer 里与语言无关的部分拆出:镜像与映射、按镜像缓存的函数表、锁、releaseImageData 的核心部分顶层门面之下的核心状态2
…/CrossReferenceCore/Scanning/ReferenceScanner.swift修改(搬家)只留通用识别;ObjC 与 Swift 的分支改成在五个时机问识别器;findsTypeReferences 一类的跳过改成每个识别器按这次查询要的种类决定按层拆分2
…/CrossReferenceCore/Scanning/RegisterFile.swift修改(搬家)methodReceiver 状态换成识别器可用的寄存器标记位(随 mov 复制、写入即清除、调用后按识别器给的保留集合保留)去掉核心里唯一的 ObjC 状态2
…/CrossReferenceCore/Scanning/ImageFunctionTable.swift修改(搬家)ObjC 节的范围(__objc_stubs、selref、superref、classref)移出,只留函数起点、名字、data in code、本镜像桩、GOT、段范围按层拆分2
Sources/Analysis/CrossReferenceObjC/ · ObjCCodeReferenceRecognizer、ObjCCodeReferenceRecording新增ObjC 层模块:发送与 super 发送、libobjc 专用入口、__objc_stubs 与跳板常量里的 selector、接收者、classref / superref / 类对象、objc_* 运行时辅助函数、ReceiverClassHint(由顶层下移)按层拆分2
…/CrossReferenceObjC/ObjectiveCClassIndex.swift、MessageSendEntryPoints.swift修改(搬家)原样搬入属于 ObjC 层2
…/CrossReferenceObjC/ObjCImageSections.swift、ObjCMethodNames.swift新增由 ImageFunctionTable 拆出的 ObjC 节范围与方法标记;由 ImageFallbackNames 拆出的 ObjC 方法列表回退名按层拆分2
…/CrossReferenceObjC/ 预筛修改(搬家)imageIndices(referencingSelector:)、imageIndices(referencingObjectiveCClassAt:)、objectiveCClassLocations(named:) 的实现由 +Prefiltering 搬来,顶层门面转发按层拆分2
Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift · SwiftCodeReferenceRecognizer新增由扫描器拆出的 Swift 部分:元数据访问器、值类型元数据、mangled name 实例化辅助函数与运行时入口、swift_* 运行时辅助函数、swift_getInitializedObjCClass 的 x0 保留按层拆分2
…/CrossReferenceAnalysis/Scanning/SwiftMetadataNames.swift、…/CrossReferenceCore/Scanning/ExportedFunctionNames.swift新增由 ImageFallbackNames 拆出:Swift 元数据回退名(Swift 层)、导出 trie 的名字(核心层),都是函数表附件按层拆分2
…/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift · CrossReferenceAnalyzer修改变成门面:持有 CodeImageSet 与两个识别器,实现三个记录协议造出公开的 CodeReference;公开方法签名不变;@_exported import 两个下层模块;之后持有 CrossReferenceMemory、拆出「进程」与「文件」两条构造、images 标 deprecated公开 API 不变;支持文件模式2、4
…/CrossReferenceAnalysis/Scanning/RuntimeHelperNames.swift改名改名 SwiftRuntimeHelperNames,只留 Swift 的名单;libobjc 的名单移到 ObjC 层的 ObjCRuntimeHelperNames核心不许出现运行时名字2
…/CrossReferenceAnalysis/Scanning/ImageFallbackNames.swift删除三种来源拆成三层各自的函数表附件,起名顺序留在门面的 codeFunction(at:in:)按层拆分2
Sources/Analysis/CrossReferenceAnalysis/Exports.swift、CrossReferenceAnalyzer+Linkage.swift、+Prefiltering.swift新增 / 修改@_exported import 两个下层模块;公开预筛与链接方法转发到各层公开 API 不变2
Sources/Analysis/CodeAddressResolution/ImageAddressSpace.swift · ImageAddressSpace新增由 ThunkAddressSpace 搬来,连同地址约定的注释两个分析模块共用3
…/CodeAddressResolution/CacheImageLocator.swift · CacheImageLocator新增由 CacheImageResolver 搬来同上3
…/CodeAddressResolution/StubChainResolver.swift · StubChainResolver新增由 MachOThunkEnvironment 的桩链部分抽出,补 27 的 cache 共用桩,记录每一跳与跳板设定的寄存器常量同上;符号化要每一跳3
…/CodeAddressResolution/SlotResolver.swift · SlotResolver新增由 MachOThunkEnvironment 的槽解析抽出,泛化到任意指针槽同上3
Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift修改GOT 桩的载入之后必须紧跟经同一寄存器的跳转开头是 adrp; ldr 的普通函数被误认成桩3
Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift修改改用上面四个类型,行为不变去重3
…/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift · ThunkAddressSpace删除调用点改用 ImageAddressSpace已搬走3
…/CrossReferenceCore/Memory/FileCrossReferenceMemory.swift · FileCrossReferenceMemory新增值,unowned(unsafe) 引用镜像集持有的 Storage:MachOKit 映射的文件字节;cache 的槽按 mapping 预取的 slide info 解(v5 自己解,其余交给 MachOKit),独立文件的槽经 SlotResolver,bind 落到所覆盖文件的导出上文件模式4
…/CrossReferenceCore/Images/CodeImage.swift · CodeImage、ImageLinkEdit新增与读取器无关的镜像描述(slide、读取器 offset 与地址的换算只在构造处定一次);__LINKEDIT 的各表按地址经读取层读两种模式共用一套读法4
…/CrossReferenceCore/Images/CodeImageSet.swift修改images: [CodeImage];新增 dyldCache(_:…) 与 files(_:…) 两个构造器(独立文件按 dyld 的做法错开);持有文件读取层的存储文件模式4
…/CrossReferenceCore/Scanning/ImageFunctionTable.swift、ExportedFunctionNames、RenamedReexportIndex、CodeImageSet+Linkage修改符号、间接符号、桩、函数起点、data in code、导出树、依赖都改走 CodeImage / ImageLinkEdit文件模式4
…/CrossReferenceObjC/ObjectiveCClassIndex.swift、ObjCMethodNames.swift、ObjCImageSections.swift、+Prefiltering修改类名、方法表、objc 桩按读取器分两条路读(MachOObjCSection 的 API 各一套,文件里 imp 是读取器 offset);按名字导入的 _objc_msgSend 认成发送文件模式4
…/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift、SwiftMetadataNames.swift、CrossReferenceAnalyzer+SwiftTypes.swift修改经 MachOSwiftSectionRepresentableWithCache 泛型读描述符;文件里的 mangled name 经文件的读取上下文解文件模式4
…/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift、FileAnalysisError.swift修改 / 新增init(dyldCache:)、init(machOFiles:)、imageCount、FileAnalysisError公开入口4
…/CodeAddressResolution/SlotResolver.swift、ImageAddressSpace.swift修改独立文件的链式 fixup 目标按 __TEXT 加偏移换算(address(forHeaderOffset:))修 bug:可执行文件的槽解错 4 GiB4
Tests/CrossReferenceAnalysisTests/FileModeTests.swift、StandaloneFileReferenceDumpTests.swift新增文件模式的行为测试;独立文件引用导出(按环境变量启用,供与反汇编器对照)验证4
Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift修改load(_:) 之外新增 32 位 ldr 与 ldrsw 的解码ivar 偏移变量的读法5
…/CrossReferenceCore/Scanning/ReferenceScanner.swift、RegisterFile.swift修改记录 route;C 字符串与 CFString;跟踪 ldrsw / 32 位 ldr 读出的来源,交给识别器引用路线;新引用种类5
…/CrossReferenceObjC/ObjCCodeReferenceRecognizer.swift修改ivar 偏移变量 → ivar 引用;selector 优先于 C 字符串认领新引用种类5
…/CrossReferenceAnalysis/SwiftCodeReferenceRecognizer.swift修改Swift 大字符串字面量(adrp; add; sub #0x20)记成 C 字符串引用新引用种类5
…/CrossReferenceAnalysis/Models/CodeReference.swift · CodeReferenceTarget、CodeReference修改新增三个 target case;新增 route(类型是核心层的 CodeReferenceRoute,以 CodeReference.Route 暴露);旧初始化方法 deprecated新引用种类;引用路线5
…/Models/CodeReferenceTable.swift · CodeReferenceTable.Key修改新增 instanceVariable、cString、constantString 键按新目标查5
…/Models/CodeReferenceIndex.swift · CodeReferenceIndex修改编码新 target 与 route常驻索引也要带上5
…/CrossReferenceAnalyzer+Prefiltering.swift 及两层的预筛修改新增 ivar(ObjC 层)与字符串(核心层)的预筛新查询5
…/CrossReferenceAnalysis/Symbolication/AddressSymbolication.swift · AddressSymbolication新增公开的符号化结果模型(顶层,因为它带 CodeReferenceTarget)符号化6
…/CrossReferenceCore/Symbolication/、…/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift · symbolication(of:)新增核心按「函数 → 桩 → 槽 → 字符串 → 最近符号 → 未映射」判断结构,识别器补含义与名字,门面组装符号化6
Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift新增由文件、cache 或本机 cache 建分析器两个子命令共用7
…/SwiftSectionKit/CrossReferences/ReferencesRequest.swift · ReferencesRequest新增预筛 → 并发逐镜像查 → 起名 → 文本 / JSONrefs 的逻辑7
…/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift · SymbolicateRequest新增批量符号化 → 文本 / JSONsymbolicate 的逻辑7
…/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift新增文本与 JSON 的拼写(CrossReferenceJSONValue、目标起名)两个子命令共用,JSON 名字即契约7
Sources/Analysis/CrossReferenceCore/Images/CodeImageSet+SymbolLookup.swift;门面 locations(ofSymbolNamed:among:)新增按名字在导出表与符号表里找定义refs --symbol / --class7
Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift · ReferenceCollector修改键集合拷一份自己的并发共用键集合时的引用计数争抢7
Sources/Executables/swift-section/Commands/ReferencesCommand.swift、SymbolicateCommand.swift新增flag、validate()、makeRequest()CLI 入口7
Sources/Executables/swift-section/Models/CrossReferenceInputOptionGroup.swift新增多文件 / cache / 本机 cache、-a、--in-image现有选项组只产出单个 MachOFile7
Sources/Executables/swift-section/SwiftSectionCommand.swift修改登记两个子命令CLI 入口7
Sources/Executables/swift-section/Models/CommandLineSupport.swift修改--in-image / --function-image 的错误译成退出码 64用法错误按惯例7
Package.swift修改新增 CrossReferenceCore、CrossReferenceObjC、CodeAddressResolution 三个 target(不做 product);CrossReferenceAnalysis 依赖前两个,CrossReferenceCore 与 SwiftThunkAnalysis 依赖第三个;SwiftSectionKit 与 swift-section 依赖 CrossReferenceAnalysis模块图2、3、7
Tests/CrossReferenceAnalysisTests/CrossReferenceLayerBoundaryTests.swift新增源码扫描:每层只 import 允许的模块;核心层没有 objc_ / swift_ 字面量守住拆分的边界2
Tests/CrossReferenceAnalysisTests/…新增对照、按层拆分、文件模式、新种类、符号化测试(见落地步骤)验证1–6
Tests/CodeAddressResolutionTests/…新增桩链、槽解析测试验证3
Tests/SwiftThunkAnalysisTests/…修改抽取前后结果一致的守护测试去重不改行为3
Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift、Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift新增refs / symbolicate 的文本与 JSON 输出、flag 映射与拒绝的组合验证7
Documentations/Internal/Modules/CrossReferenceAnalysis.md修改三层的分工与识别器;文件模式、读取抽象、新种类、路线、符号化、拆分前后与离线吞吐实测模块参考2、4–6
Documentations/Internal/Modules/CrossReferenceCore.md、CrossReferenceObjC.md、CodeAddressResolution.md新增三个新模块的参考;各写明将来的落脚处与名字模块参考2、3
AGENTS.md(模块层级图与各模块说明)、Documentations/README.md修改登记三个新模块与它们的去向项目约定2、3
Documentations/Visions/ReverseEngineeringWithoutIDA.md修改「我们选的方向」第 6 条:语言无关的分析核心也归 MachOKitExtensions,ObjC 专属归 MachOObjCSection愿景与提案一致2
AgentPlugins/swift-section/skills/swift-section-cli/修改两个新子命令的用法与坑AGENTS.md 要求7
README.md(CLI 一节)修改列出两个新子命令面向用户7
Documentations/Internal/ProjectEvolutionLog.md、Documentations/Glossary.md修改追加本批次;登记「符号化」「引用路线」「识别器」「stub island」等术语文档约定9
RuntimeViewer RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift修改switch reference.target(:92)补三个新 case穷尽 switch 会编译失败5
RuntimeViewer …/RuntimeViewerCrossReferences/(新文件)· 符号化引擎命令新增引擎侧 crossReferenceSymbolicate 与 crossReferenceLocateSymbol 两个命令,RuntimeEngine.symbolicate(_:inImageAt:)、locations(ofSymbolNamed:),线上类型 RuntimeAddressSymbolication、RuntimeSymbolLocationCLI / MCP 的符号化与按名字找函数8
RuntimeViewer …/RuntimeViewerCrossReferences/RuntimeCrossReferenceTargetResolution.swift新增目标写法(方法、Swift 成员、符号、地址、selector)→ 查询主体,CLI 与 MCP 共用两个前端一套写法8
RuntimeViewer …/RuntimeViewerCrossReferences/Models/RuntimeCrossReferenceRow.swift、RuntimeAddressSymbolicationRow.swift新增CLI --json 与 MCP 每行字段的唯一来源,地址一律十六进制字符串字段名一致8
RuntimeViewer …/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift、Models/RuntimeCrossReferenceError.swift修改两处穷尽 switch 补三个新目标(不显示);符号化与按名定位的实现;错误加 addressNeedsImage、targetNotFound、ambiguousTarget源码兼容;新命令8
RuntimeViewer …/Model/CommandFailure.swift修改失败代码加 targetNotFound、crossReferencesUnavailableCLI8
RuntimeViewer Documentations/Guides/CommandLineInterface.md、AgentPlugins/runtime-viewer/(skill 与两个清单 1.3.0)、README.md修改四个子命令与目标写法RuntimeViewer 的 AGENTS.md 要求8
RuntimeViewer RuntimeViewerCommandLine/Sources/RuntimeViewerCommandLineInterface/Model/Command.swift、CommandResult.swift修改.callers / .callees / .references / .symbolicate 与结果CLI8
RuntimeViewer …/CommandLine/Subcommands.swift、Execution/CommandExecutor.swift、Rendering/TextRenderer.swift修改四个子命令的解析、执行与显示CLI8
RuntimeViewer …/Protocol/WireMessage.swift · CommandLineProtocol.version修改2 → 3新增命令8
RuntimeViewer RuntimeViewerMCP/Sources/RuntimeViewerMCPBridge/MCPBridgeServer.swift、MCPBridgeProtocol.swift修改Callers、Callees、TypeReferences、Symbolicate 四个工具,30 秒等待 references(within:_:),响应类型 MCPCrossReferencesResponse 等MCP9
RuntimeViewer Documentations/Evolutions/README.md、0056-cross-references.md修改cross-repository draft 一行;暂缓表第 4 步指向本提案提案索引9
RuntimeViewer AgentPlugins/runtime-viewer/、Documentations/Guides/CommandLineInterface.md、Documentations/Evolutions/README.md修改skill 与两个插件清单的 version;使用指南;cross-repository draft 一行文档同批8、9
+ +

动机

+

完整动机见愿景《不依赖 IDA 的逆向》的「现状与代价」。这一步特有的部分:

+
    +
  • 最常卡住的就是这一块。逆向 agent 的笔记里约 15 条用「扫 selref / GOT 字节 → 换算子 cache 偏移 → 反汇编 stub island → a2s 起名」这条手工链路回答「谁调用了它」,13 条涉及 selref,12 条涉及 GOT(~/.claude/agent-memory/reverse-explorer/cross-cache-caller-search.md、全局 reverse-engineering skill 的 references/ipsw-cache-recipes.md)。现成工具都会静默漏:ipsw dyld xref 不跟进 stub island,dyld_info -imports 漏掉大部分 bind。2026-10-29 有一次因此判错:UINSPasteboardWritingItemProvider 在 27.0 和 27.2 上都有两个调用者,它们经 __DATA_CONST.__got 读本镜像自己的类对象,ipsw dyld disass 只显示 ldr x0, [x23, #0x590],没有类名。
  • +
  • 分析器已经有了,只是够不着这些目标。CrossReferenceAnalyzer 在进程内 1.6–3.0 秒扫完 macOS 27.2 的整个 cache,认得 27 的 cache 共用 selector 桩与 GOT 桩、stub island 多跳(Internal/Modules/CrossReferenceAnalysis.md「吞吐」节)。但它的构造器用 DyldCacheLoaded.current 与 _dyld_get_image_header,只看得到正在运行的系统;卷上归档的 7 个 macOS 版本(15.5 到 27.2)和 /Volumes/RE 下的 app 都够不着。0072 把 MachOFile 与 swift-section 子命令明确留给了后续提案。
  • +
  • RuntimeViewer 只在界面里给出交叉引用。RuntimeViewer 0056 的第 4 步(CLI 与 MCP)在 2026-10-26 经用户批准拆成暂缓项,说明以后另起提案。全部对话记录里 RuntimeViewer 的 MCP 一次也没被调用过;agent 要查调用者,只能退回 IDA 或 ipsw。
  • +
  • 地址起名是同一个问题的另一面。dyld_info -disassemble 把 macOS 26.7 SwiftUICore 的 2,195 个 __auth_stubs 桩标成同一个错名,15.3 万条 bl 的目标因此标错(RuntimeViewer 记忆 dyld-info-mislabels-cache-stubs.md);ipsw dyld a2s 对 27 的 cache 共用 objc_msgSend$… 桩只回 ?,agent 只能先反汇编桩的前三条,自己算 adrp x1 的页加 add x1 的偏移,再去读字符串。分析器在扫描时本来就要把每个桩解析到底,把这一步单独开放出来就是符号化。
  • +
+ +

提议方案

+

1. 读取抽象:CrossReferenceMemory

+

分析器里所有「按地址读」都改走一个 package 级协议 CrossReferenceMemory,它只回答分析器真正问的几个问题:某个镜像某个区间的连续只读字节(扫描热循环用,循环本身不变,仍对一段缓冲区逐条解码);某个槽里装的是什么(目标地址,或导入符号名);某个地址处的 C 字符串;去掉指针认证位的掩码。

+

两种实现:

+
    +
  • InProcessCrossReferenceMemory:今天的行为原样搬进来——读 dyld 已绑定的值、按 vmaddrSlide 换算。
  • +
  • FileCrossReferenceMemory:基于 FullDyldCache 或一组 MachOFile。代码字节来自映射的文件;槽的内容由 fixup 解码得到——cache 镜像里 GOT 是 rebase(指向别的镜像或本镜像的类对象),独立文件里是 bind、self-bind 或 rebase。地址约定沿用 ThunkAddressSpace:未滑动地址 − sharedRegionStart。
  • +
+

协议选「分析器专用的小协议」而不是直接用 ReadingContext:ReadingContext 回答「按类型读一个元素」,分析器要的是「槽里装着谁」——在进程内是读已绑定的值,在文件里是解 fixup,这层差别正是两种模式唯一的本质区别。FileCrossReferenceMemory 内部仍用 ReadingContext 读元素。

+ +

2. 按层拆成三个模块

+

交叉引用拆成三个模块,依赖从上到下:

+ + + + + + + +
模块(本库里的名字)管什么将来的落脚处与名字
CrossReferenceCore镜像表与读取抽象(进程内、文件两种)、函数表(起点、符号与导出名、data in code)、本镜像桩与 GOT、stub island、指令扫描与寄存器跟踪、跳板设定的寄存器常量、间接调用的指针认证常量、C 字符串与 CFString、链接关系与导入名预筛、符号化的通用部分、识别器扩展点MachOKitExtensions,MachOCodeReferences
CrossReferenceObjCobjc_msgSend 系列与 libobjc 专用入口、__objc_stubs 与 cache 共用 selector 桩的含义、x1 的 selector 与 x0 的接收者、classref / superref / 类对象、ivar 偏移变量、ObjC 方法列表给出的回退名、selector 与类的预筛、objc_* 运行时辅助函数MachOObjCSection,ObjCCodeReferences
CrossReferenceAnalysis(原模块)Swift 元数据访问器、值类型元数据、mangled name 实例化、SymbolicDemangler 起名、Swift 类型预筛、swift_* 运行时辅助函数;把三层拼成对外的 CrossReferenceAnalyzer,持有全部公开模型留在本库
+

CodeAddressResolution(第 3 节)在核心层之下,将来随核心一起迁到 MachOKitExtensions,改名 MachOAddressResolution。

+

扩展点:识别器。每个语言层有一个识别器(每个分析器一个,建分析器时读一次自己要的运行时符号,按镜像记住自己的索引),它为每次扫描造一个会话;核心层定义会话协议 CodeReferenceRecognitionSession(单线程,持有这次扫描的记忆化与当前函数的状态)。核心的扫描循环只在「前期调研 · 按层拆分的依据」列出的五个时机问识别器:进入函数、解析不认识的调用目标、调用点、算出地址、读槽。识别器按顺序排成一列,核心逐个问,第一个认领的为准;新增一种语言的识别只是多一个识别器,核心不改。识别器产出的引用不经核心转手:各层定义自己的记录协议(CodeReferenceRecording、ObjCCodeReferenceRecording、SwiftCodeReferenceRecording),顶层实现全部三个,直接造出公开的 CodeReference。细节见「详细设计」。

+

公开模型第一步全部留在顶层。CodeReferenceTarget、CodeReferenceTable、CodeReferenceIndex、CodeFunction 都还在 CrossReferenceAnalysis;纯数据、不含语言的 CodeLocation 下移到核心层,ReceiverClassHint 下移到 ObjC 层,顶层 @_exported import 两个下层模块,RuntimeViewer 的 import CrossReferenceAnalysis 照旧看得到它们。两个下层模块这一步不做 library product,不对外承诺 API。下层模块对外该长什么样(例如没有 Swift 层时目标用什么类型表示),等迁移提案时有了具体的使用方再定。

+

边界由测试守住。源码扫描测试逐层检查 import:核心层只许 import 将来 MachOKitExtensions 里也有的模块(MachOKit、MachOKitExtensions、读取层与基础模块迁移提案搬过去的那些、CodeAddressResolution、ARM64InstructionDecoding、Foundation);ObjC 层在此之上多一个 MachOObjCSection;两层都不许出现 MachOSwiftSection、SwiftInspection、Demangling。核心层的源码里还不许出现 objc_ 与 swift_ 开头的符号名字面量——运行时的名单属于各自的层。

+

本库里的名字刻意不同于落脚处的名字。理由见「前期调研 · 按层拆分的依据」的「模块名与版本」:本库只要发布过一个与 MachOKitExtensions 2.x 新模块同名的模块,旧版本本库与新版本 MachOKitExtensions 就解析不到一起;而且基础模块迁移之后,本库带 MachO 前缀的模块只留 ABI 模型。搬的时候改名,只动本库内部的 import——两个下层模块不是 product,没有外部使用方。

+

为什么分两步。本提案还有四项「先实测」的未知(离线吞吐、__text 能否连续读、functionStarts 在 cache 镜像上的语义、27 的 cache 文件里 __objc_stubs 的大小);识别器的接口也要在扫描热路径上量过才算定下来。在一个仓库里改这些只要改一处;跨三个仓库时核心每改一次都要按 MachOKitExtensions → MachOObjCSection → 本库的顺序发版。拆分在本库里做完、量过、跑稳,迁移就只剩机械地搬文件。

+ +

3. 抽出 CodeAddressResolution

+

把 SwiftThunkAnalysis 里与 Swift thunk 无关的离线解析抽成新的 package 模块 Sources/Analysis/CodeAddressResolution,SwiftThunkAnalysis 与 CrossReferenceCore 共用:

+
    +
  • ImageAddressSpace:原 ThunkAddressSpace,地址约定与它的长注释一起搬。
  • +
  • CacheImageLocator:原 CacheImageResolver,「地址 → cache 镜像」与按路径懒打开。
  • +
  • StubChainResolver:桩、ld64 跳板、stub island 多跳、27 的 cache 共用 selector 桩与 GOT 桩 → 最终目标(函数地址或导入符号名),连同跳板一路设定的寄存器常量(cache 共用 selector 桩在 x1 里放的地址),并记下经过的每一跳。常量是什么意思(selector)由 ObjC 层解释,这个模块不认识 selector。
  • +
  • SlotResolver:任意指针槽 → 里面装着谁(rebase 的目标地址,或 bind 的符号名)。GOT、auth GOT 与 ObjC 的 selref / classref / superref / protoref、ivar 偏移变量共用它;哪个节算哪种槽由上层说。
  • +
+

这个模块只依赖 MachOKit、MachOKitExtensions 与读取层,不碰 Swift 与 ObjC 元数据,将来随核心层一起迁进 MachOKitExtensions(见第 2 节)。

+ +

4. 文件模式的分析器

+
let cache = try FullDyldCache(url: URL(filePath: "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e"))
+let analyzer = try CrossReferenceAnalyzer(dyldCache: cache)
+

镜像表来自 cache 头的 imageInfos;imagePaths、imageIndex(forPath:)、函数表、预筛、referenceTable 等全部照旧可用。location(ofRuntimeAddress:) 在 cache 文件模式下接受的就是未滑动地址;一组独立文件里各文件按 dyld 的做法错开(与已放下的重叠就滑到其后的下一个 MB 边界),那时它接受的是错开后的地址。images: [MachOImage] 在文件模式下为空,只在文档注释里写明,不标 deprecated(见决策日志);imageCount 在两种模式下都给镜像数。

+

实现(第 4 步):每个镜像由核心层的 CodeImage 描述——reader 是 MachOImage 或 MachOFile,两种读取器的差别(slide、读取器 API 给出的 offset 落在哪个地址)只在构造它的地方定一次;__LINKEDIT 里的表(符号表、间接符号、函数起点、data in code、导出树)一律按「__LINKEDIT 的地址 + 表的偏移 − 段的文件偏移」经读取层读(ImageLinkEdit),进程内与文件里是同一个算法。ObjC 层与 Swift 层用到 MachOObjCSection / MachOSwiftSection 各读取器一套的 API 时,经 asMachOImage / asMachOFile 或 MachOSwiftSectionRepresentableWithCache 打开。文件读取层 FileCrossReferenceMemory 是个值,以 unowned(unsafe) 引用由镜像集持有的存储:经 existential 的每次读都复制一次读取层,类或持有引用的值每次复制都要计数,整 cache 建表因此慢过 6 倍。cache 的槽按 mapping 预取的 slide info 解:v5(macOS 14 / iOS 17 起的 arm64e cache)在读取层里直接解,其余交给 MachOKit。

+ +

5. 新的引用种类与引用路线

+

各种引用落在哪一层写在每条末尾。

+
    +
  • ObjC ivar:adrp + ldrsw(或 32 位 ldr)读 __objc_ivar 里的偏移变量 → .objectiveCInstanceVariable(className:name:)。解码器补 ldrsw 与 32 位 ldr。名字取自偏移变量的符号 _OBJC_IVAR_$_<类>.<ivar>;没有符号时从类的 ivar 列表反查(ivar 记录里的 offset 字段指向这个槽)。ObjC 层,经「读槽」时机。
  • +
  • C 字符串字面量:adrp + add 落进 __cstring / __objc_methname / __oslogstring,且没被当作 selector 用掉 → .cString(String)。覆盖 objc_getClass("…")、sel_registerName、dlsym 一类调用。核心层;识别器按顺序问,ObjC 层先认领当作 selector 的那些。Swift 大字符串字面量的写法是 adrp; add; sub #0x20(对象里存的是「地址 − 0x20」),也要认成指向那段字符的引用——Binary Ninja 在实测里正是漏在这里。这个写法是 Swift 的约定,由 Swift 层的识别器认出,记成同一种 C 字符串引用。
  • +
  • CFString 常量:adrp + add 落进 __cfstring → 解出字符串指针 → .constantString(String)。覆盖 NSSelectorFromString(@"…")、NSUserDefaults 键一类用法。核心层:__cfstring 的结构是 CoreFoundation 的链接约定,不依赖 ObjC 运行时。
  • +
  • 两种字符串引用默认不记录:它们数量大,RuntimeViewer 常驻的索引不需要。构造分析器时用 recordingStringReferences: true 打开,swift-section refs --string 会自动打开。
  • +
  • 对其他镜像符号的数据引用(第 4 步核对时补进来):只分析一个 app 而不带它链接的库时,经 GOT 槽读别的镜像的类(adrp; ldr x0, [_OBJC_CLASS_$_CALayer@GOT])、ivar 或数据,槽里是 bind,读出的是导入名而不是地址,现在什么都不记——进程内槽里是地址,会记成类引用。改为记一条指向导入符号的 .reference,ObjC 层再把 _OBJC_CLASS_$_<类> 认成按名字的类引用。核心层(读槽时机拿到导入名)加 ObjC 层。
  • +
  • 引用路线:CodeReference 新增 route,说明引用是怎么到达目标的。照 Binary Ninja 的「引用按来源种类建模」,但只在代码引用上加一个字段,不引入数据引用(见非目标)。
  • +
+ +

6. 地址符号化

+
let symbolication = analyzer.symbolication(of: 0x1_9012_3450)
+// symbolication.meaning == .stub(hops: [0x1_9012_3450], target: .messageSend(selector: "setFrame:", receiver: .unknown))
+

回答「这个地址是什么」,按顺序判断:在某个函数体里(函数起点、名字、偏移;名字来自符号、ImageFallbackNames 的回退名);是桩或 stub island 的跳板(每一跳与最终目标);是一个槽(槽的种类与里面装的目标);是 C 字符串或 CFString(内容);以上都不是时给最近的前一个符号加偏移;不在任何映射里时如实说没有映射。判断顺序与函数、桩、槽、字符串的结构由核心层给出;桩的最终目标与槽里的东西是什么(selector、类、Swift 类型)、没有符号的函数叫什么,由 ObjC 层与 Swift 层经同一列识别器补上。

+ +

7. swift-section refs 与 swift-section symbolicate

+
swift-section refs --selector makeKeyAndOrderFront: --dyld-shared-cache /Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e
+swift-section refs --class UINSPasteboardWritingItemProvider --uses-system-dyld-shared-cache --json
+swift-section refs --function 0x1880a1000 --callees --uses-system-dyld-shared-cache
+swift-section refs --string NSWindowDidBecomeKeyNotification --in-image AppKit /path/to/Foo.app/Contents/MacOS/Foo
+swift-section symbolicate 0x19012345 0x1e1226590 --dyld-shared-cache /Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e
+
    +
  • 查询(恰好一个):--selector、--symbol(C 符号、Swift 修饰名、_OBJC_CLASS_$_…)、--class、--function <地址>(以它开头或包含它的函数的调用者;加 --callees 改列它引用了什么)、--ivar <类>.<ivar>、--string <文本>。
  • +
  • 输入:一个或多个独立 Mach-O 文件,或 --dyld-shared-cache <路径>,或 --uses-system-dyld-shared-cache;-a/--architecture。--in-image 可重复,限定扫描哪些镜像。
  • +
  • 输出:文本每条引用一行——镜像短名、所在函数名加偏移、调用点地址、引用种类与路线;--json 输出一个 JSON 文档,地址一律写成十六进制字符串(照 Binary Ninja MCP 的理由:避免客户端丢失 64 位精度)。
  • +
  • --limit <n> 截断时如实标出 isTruncated。
  • +
+ +

8. RuntimeViewer:CLI 与 MCP

+

按 0056 §8 原定的设计实现它暂缓的第 4 步,并加上符号化:

+
    +
  • CLI 子命令 callers、callees、references、symbolicate;目标写法照 0056:-[类 sel]、Swift 名、符号名,或 0x… 加 --image;选项 --selector、--scope image|indexed、--receiver、--include-runtime、--limit。CLI 协议版本 CommandLineProtocol.version 由 2 升到 3。
  • +
  • MCP 工具 Callers、Callees、TypeReferences、Symbolicate,@MCPTool(hints: [.readOnly]),照现有工具带 windowIdentifier;每次最多等 30 秒,isComplete == false 时返回部分结果。
  • +
  • 只覆盖活的引擎(本机、Catalyst、注入的进程);文件引擎见非目标。
  • +
+ +

非目标

+
    +
  • 把核心层与 ObjC 层真正迁出本库,以及迁出后两个下层模块对外的公开模型:另写迁移提案(见第 2 节)。那份提案要定的事先记在这里——下层的引用目标在没有 Swift 层时用什么类型表示;ARM64InstructionDecoding 是否一起迁、迁过去叫什么;IndirectCallEvidence.Table 里 vtable / PWT / VWT 这些 Swift 的叫法留在核心还是改由 Swift 层分类;进程内构造器在 MachOKitExtensions 承诺的 Linux 上怎么条件编译;MachOObjCSection 发 0.9.0 时怎样与本库的版本要求衔接。
  • +
  • 落盘索引:沿用 0072 与 RuntimeViewer 0056 的决定。第 4 步实测离线吞吐,结果写进模块文档,是否需要持久化由愿景的后续阶段决定。
  • +
  • 数据引用(方法表条目 → IMP、CFString → 字符串这类「数据 → 地址」)与其余数据解码(KeyPath、ObjC 字面量、Swift 字符串):愿景第 3 阶段。
  • +
  • 带注解的反汇编、函数清单命令:愿景第 2 阶段。
  • +
  • 跨基本块的常量追踪、调用点常量参数普查:愿景第 4 阶段。
  • +
  • 接收者类型推断、Swift 字段级引用。
  • +
  • x86_64。
  • +
  • 0072「后续」里列的其余项:协议见证与 override 的起名、objc_getClass("…") 解析成类引用(本提案只把它记成 C 字符串引用)、Swift 的 super 发送、协议类型引用。
  • +
  • RuntimeViewer:CLI 直接读文件引擎、文件引擎上的交叉引用(RuntimeViewer「暂缓的后续项」里的另一条)、MCP 无头化(RuntimeViewer 愿景《无头 RuntimeViewer》的「之后可以接」)。
  • +
  • idax 建库时写入桩名与 Swift 函数名:IDA 已降为后备。
  • +
+ +

详细设计

+
+公开 API(CrossReferenceAnalysis) +

按全局 apple-style-api-design skill 的顺序,先写调用点:

+
// Simplest: what is this address?
+let analyzer = try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: cacheURL))
+print(analyzer.symbolication(of: 0x1_9012_3450))
+
+// Most common: who sends a selector, across an archived cache.
+let selectorKey = CodeReferenceTable.Key.selector("makeKeyAndOrderFront:")
+for imageIndex in analyzer.imageIndices(referencingSelector: "makeKeyAndOrderFront:", among: analyzer.imagePaths.indices) {
+    for reference in analyzer.references(to: [selectorKey], inImageAt: imageIndex) {
+        print(analyzer.imagePaths[imageIndex], reference.instructionAddress, reference.route)
+    }
+}
+
+// Most complex: an app and its frameworks, string references included.
+let files = try appBundle.machOFileURLs.map { try MachOFile(url: $0) }
+let appAnalyzer = try CrossReferenceAnalyzer(machOFiles: files, recordingStringReferences: true)
+

声明:

+
extension CrossReferenceAnalyzer {
+    /// Analyzes every image of a dyld shared cache read from disk, such as an archived one.
+    /// `recordingStringReferences` arrives with step 5.
+    public convenience init(dyldCache: FullDyldCache, recordingStringReferences: Bool = false) throws
+
+    /// Analyzes standalone Mach-O files, such as an app's executable and its embedded frameworks.
+    public convenience init(machOFiles: [MachOFile], recordingStringReferences: Bool = false) throws
+
+    /// Why an analyzer could not be made from files: `Code.unsupportedArchitecture` for a cache or
+    /// a file holding no arm64 code. A struct with codes, since more may come.
+    public struct FileAnalysisError: Error, Hashable, Sendable { public let code: Code; public let path: String }
+
+    /// The number of images the analyzer covers, in either mode.
+    public var imageCount: Int { get }
+
+    /// What the address is: a place inside a function, a stub, a pointer slot, a string, or nothing mapped.
+    public func symbolication(of address: UInt64) -> AddressSymbolication
+}
+
+extension CrossReferenceAnalyzer {
+    /// The in-process analyzer's images; empty for one made from files. Not deprecated: in-process
+    /// hosts read what only a `MachOImage` tells (its slide, its header).
+    public let images: [MachOImage]
+}
+
+public enum CodeReferenceTarget: Hashable, Sendable {
+    // … the nine existing cases …
+    /// A load of an Objective-C instance variable's offset variable (`_OBJC_IVAR_$_Class.ivar`).
+    case objectiveCInstanceVariable(className: String, name: String)
+    /// A C string literal whose address the code materializes. Recorded only when string references are recorded.
+    case cString(String)
+    /// A constant `CFString` / `NSString` literal. Recorded only when string references are recorded.
+    case constantString(String)
+}
+
+// CrossReferenceCore — re-exported by CrossReferenceAnalysis.
+/// How the code reached what it references: the instructions and trampolines on the way, not what the target is.
+public enum CodeReferenceRoute: UInt8, Hashable, Sendable {
+    /// `bl` / `b` straight to the target.
+    case direct
+    /// A stub in the referencing image's own stub sections (`__stubs`, `__auth_stubs`, `__objc_stubs`).
+    case imageStub
+    /// A trampoline in a dyld shared cache stub island, possibly after several hops.
+    case stubIsland
+    /// A stub shared by the whole cache: macOS / iOS 27's `objc_msgSend$…` selector stubs and GOT stubs.
+    case cacheSharedStub
+    /// `adrp` + `ldr` through a pointer slot: a GOT or auth GOT slot, or a slot of an Objective-C reference section.
+    case pointerSlot
+    /// `adrp` + `add`, or `adr`, computing the target's address.
+    case addressMaterialization
+    /// `ldr` of a literal pool entry.
+    case literalLoad
+    /// A call or a jump through a register — `blr`, `br` and their authenticating forms; the
+    /// evidence says what is known. (Was `authenticatedIndirect`; see the decision log.)
+    case indirect
+}
+
+/// Whether the referencing instruction calls, leaves the function, or only takes an address.
+public enum CodeReferenceKind: Hashable, Sendable {
+    case call
+    case tailCall
+    case reference
+}
+
+// CrossReferenceAnalysis
+extension CodeReference {
+    public typealias Route = CodeReferenceRoute
+    /// Was a nested enum; the cases are unchanged.
+    public typealias Kind = CodeReferenceKind
+
+    public let route: Route
+
+    public init(function: CodeLocation, instructionAddress: UInt64, kind: Kind, target: CodeReferenceTarget, route: Route, isRuntimeHelperCall: Bool)
+
+    @available(*, deprecated, renamed: "init(function:instructionAddress:kind:target:route:isRuntimeHelperCall:)")
+    public init(function: CodeLocation, instructionAddress: UInt64, kind: Kind, target: CodeReferenceTarget, isRuntimeHelperCall: Bool)
+}
+
+extension CodeReferenceTable.Key {
+    // new cases
+    case instanceVariable(className: String, name: String)
+    case cString(String)
+    case constantString(String)
+}
+
+public struct AddressSymbolication: Hashable, Sendable {
+    public let address: UInt64
+    public let imagePath: String?
+    public let segmentName: String?
+    public let sectionName: String?
+    public let meaning: Meaning
+
+    public enum Meaning: Hashable, Sendable {
+        /// Inside a function's body.
+        case function(start: CodeLocation, name: String?, offset: UInt64)
+        /// A stub or stub-island trampoline; `hops` lists every trampoline passed through, starting with the address asked about.
+        case stub(hops: [UInt64], target: CodeReferenceTarget)
+        /// A pointer slot and what it holds.
+        case pointerSlot(PointerSlotKind, target: CodeReferenceTarget)
+        case cString(String)
+        case constantString(String)
+        /// None of the above: the nearest preceding symbol.
+        case symbol(name: String, offset: UInt64)
+        /// Mapped by an image, but none of the above and no symbol at or below it.
+        case data
+        /// Not inside any mapped image.
+        case unmapped
+    }
+
+    public enum PointerSlotKind: Hashable, Sendable {
+        case globalOffsetTable
+        case selectorReference
+        case classReference
+        case superclassReference
+        case protocolReference
+        case instanceVariableOffset
+    }
+}
+

(CodeReferenceTable.Key 的新 case 在实现里直接写进原 enum;上面用 extension 的写法只为标出新增部分。)

+

命名取舍:

+
    +
  • 用 symbolication / symbolicate 而不是 resolve:MachOKit 与 MachOKitExtensions 里 resolveBind / resolveRebase 的 resolve 指「解 fixup」,同一个词不能再指「说出地址是什么」;symbolication 是 Apple 自己的说法(atos、崩溃报告的 symbolication)。
  • +
  • 方法用名词短语 symbolication(of:):它没有副作用,按 API Design Guidelines 读成名词短语。
  • +
  • route 不给默认值:它影响结果是否可信,按「影响正确性的参数不给默认值」处理;旧初始化方法保留一个版本并标 renamed:。
  • +
  • 路线只描述「代码怎么到达」,不描述「槽在哪个节」:原先列的 selectorReference(selref)与 classReference(classref / superref)并进 pointerSlot。路线由核心层产出,核心不认识 ObjC 的节;槽是哪一种,看引用的目标(selector 还是类)或对槽地址做符号化(PointerSlotKind)即可得知。
  • +
  • Route 与 Kind 定义在核心层、以 CodeReference 的 typealias 暴露:核心层要产出这两个值,而 CodeReference 本身留在顶层。CodeReference.Kind.call 一类写法照旧可用。
  • +
+
+ +
+按层拆分与识别器(package) +

三层之间的接口全部是 package 级:两个下层模块这一步不做 product,接口还可以按实测改。下面是第 2 步实际做成的样子。

+

核心层的扩展点(CrossReferenceCore/Recognition/CodeReferenceRecognition.swift):

+
/// One scan of one image by one language layer, on one thread.
+package protocol CodeReferenceRecognitionSession: AnyObject {
+    /// Slots, unslid, holding references the session reads besides the core's GOT: `__objc_classrefs`.
+    var referenceSlotRanges: [Range<UInt64>] { get }
+    /// Slots a load from which the session watches on every load: `__objc_superrefs`.
+    var watchedSlotRanges: [Range<UInt64>] { get }
+    /// Whether the session looks at addresses built and slots loaded at all.
+    var looksForAddressReferences: Bool { get }
+
+    /// A function starts; may tag registers (an Objective-C method's receiver in `x0`).
+    func enterFunction(at functionIndex: Int, registers: RegisterFile)
+    /// A target only this session can read (`__objc_stubs`); asked before the core resolves it.
+    func claimCallTarget(at target: UInt64) -> CallTargetClaim?
+    /// The session's role for a target the core resolved; asked once per distinct target of a scan.
+    func role(of target: ResolvedCallTarget) -> CalleeRole?
+    /// Records what the call stands for in place of the plain call reference — a message send.
+    func recordCallStandIn(_ call: ScannedCall, registers: RegisterFile) -> Bool
+    /// After the call's reference: records what it references besides (a Swift type); returns
+    /// the caller-saved registers, by bit, that keep their contents across it.
+    func noteCallMade(_ call: ScannedCall, registers: RegisterFile) -> UInt32
+    /// An address an instruction built, at its runtime address; `isCode` when in the image's `__text`.
+    func recordAddressReference(toRuntimeAddress address: UInt, isCode: Bool, at site: ScanSite) -> Bool
+    /// A load from a reference slot that holds the runtime address `value`.
+    func recordSlotReference(holding value: UInt, at site: ScanSite) -> Bool
+    /// A load from one of `watchedSlotRanges`.
+    func noteWatchedSlotLoad(from slot: UInt64)
+}
+
+/// Where the references a scan finds go; each language layer refines it.
+package protocol CodeReferenceRecording: AnyObject {
+    func recordCall(to target: ResolvedCallTarget, targetAddress: UInt64, at site: ScanSite, isRuntimeHelperCall: Bool)
+    func recordIndirectCall(_ evidence: IndirectCallEvidence, at site: ScanSite)
+}
+
+/// What the core resolves a call target to, knowing no language.
+package enum ResolvedCallTarget: Hashable {
+    case function(CodeLocation)
+    case importedSymbol(UnsafePointer<CChar>)
+    /// macOS / iOS 27's cache-shared selector stub: `x1` = the selector string, then a branch.
+    case registerSettingTrampoline(register: Int, value: UInt64)
+    case unrecognized
+}
+

ObjC 层(CrossReferenceObjC)与 Swift 层各自细化记录协议:

+
package protocol ObjCCodeReferenceRecording: CodeReferenceRecording {
+    func recordMessageSend(selector: String, receiver: ReceiverClassHint, at site: ScanSite)
+    func recordSuperMessageSend(selector: String, className: String?, at site: ScanSite)
+    func recordClassReference(_ classObject: ObjectiveCClassObject, at site: ScanSite)
+}
+
+protocol SwiftCodeReferenceRecording: CodeReferenceRecording {
+    func recordSwiftType(descriptor: CodeLocation, at site: ScanSite)
+    func recordSwiftTypeName(_ name: SwiftTypeName, at site: ScanSite)
+}
+

规则:

+
    +
  • 识别器是各层的具体类型,没有共同协议:ObjCCodeReferenceRecognizer、SwiftCodeReferenceRecognizer 各自按镜像记住类索引与 Swift 类型索引,各有 makeSession(table:recording:…)。门面是组合根,本来就认识两个具体的层,再抽一个识别器协议说不出能带来什么。核心只认会话协议。
  • +
  • 会话排成一列,顺序就是优先级:门面按 ObjC、Swift 的顺序建会话;同一个时机第一个认领的为准。核心只在没有会话代替时记录普通调用。
  • +
  • 调用不拖慢扫描:每个不同的调用目标只问一次各会话的角色,结果连同核心的解析一起记在扫描器的调用计划里;没有角色的调用——绝大多数——不经过任何会话。地址与槽按地址记住是哪个会话认领的(或谁都没认领),下次只问那一个或直接跳过。
  • +
  • 门面是组合根:CrossReferenceAnalyzer 里的 ReferenceCollector 实现全部三个记录协议,直接造公开的 CodeReference 并按查询的键过滤(原 ReferenceScanner.keep)。下层不认识 CodeReferenceTarget,所以加一种目标不碰下层。
  • +
  • 查询只给一个开关:两层的会话收到同一个「找不找类与类型引用」的开关(原 findsTypeReferences),与拆分前一致;只查 selector 或函数时两层都跳过地址与槽,ObjC 层在发送处照旧认类字面量接收者。
  • +
  • 寄存器标记:RegisterFile 的「方法接收者」状态换成通用的标记(setTag(_:of:) / tag(of:)),随 mov 复制、写入即清除;ObjC 会话用标记 1。调用后保留哪些寄存器由会话按位返回(clobberCallerSavedRegisters(keepingMask:))。
  • +
  • 跳板常量:cache 共用 selector 桩由核心解析成 .registerSettingTrampoline(register: 1, value:),核心不解释;ObjC 会话把它读成发送。
  • +
  • 运行时库与辅助函数:核心不认识运行时库。门面把两层的规则(RuntimeLibraryRules:哪些路径是运行时库、哪些符号是辅助函数)交给 CodeImageSet;建镜像集时核心扫一遍运行时库的符号,记下辅助函数位置,并把每个符号交给门面,门面分发给两层各自记下 objc_msgSend、专用入口、swift_getTypeByMangledName… 这些位置。
  • +
  • 按镜像的缓存挂在函数表上:ImageFunctionTable.attachment(_:makingIt:),核心的 ExportedFunctionNames、ObjC 层的 ObjCImageSections 与 ObjCMethodNames、Swift 层的 SwiftMetadataNames。无名函数的起名不在扫描热路径上,由门面依次问这三个附件。
  • +
  • 预筛各归各层:导入名与链接关系在核心层(CodeImageSet+Linkage),selector 与类在 ObjC 层,Swift 类型在 Swift 层;门面上的公开预筛方法签名不变,只是转发。
  • +
  • 性能:会话只在事件上经 existential 调用。验收:在 Ultra 上 release 构建,拆分后整 cache 建表与 init、makeKeyAndOrderFront: 两条查询的耗时,相对拆分前的增幅都不超过 5%(ScanThroughputBenchmarkTests,按环境变量启用,两边各跑三轮取最好)。超出时先把会话列表改成具体类型的泛型参数、扫描入口标 @inline(always) 让门面特化,再量;数字写进模块文档。
  • +
+
+ +
+读取抽象(package) +
package protocol CrossReferenceMemory: Sendable {
+    /// The `length` bytes from `address` on — an address in the analyzer's own
+    /// address space — contiguous and read-only, or nil when they cannot be read.
+    func bytes(at address: UInt, length: Int) -> UnsafeRawBufferPointer?
+    /// What the pointer slot at `address` holds, its signature and tag bits stripped.
+    func slotContent(at address: UInt) -> SlotContent?
+    /// The bits of a stored pointer that are its address.
+    var addressMask: UInt { get }
+    /// Bulk forms for a pass over a whole section of slots (the selector prefilter):
+    /// one call rather than one call a slot. Default implementations go slot by slot.
+    func pointers(inSlotsAt address: UInt, count: Int) -> [UInt]
+    func readablePointers(at addresses: [UInt]) -> [UnsafeRawPointer?]
+}
+
+package enum SlotContent: Hashable, Sendable {
+    case address(UInt)
+    case importedSymbol(String)
+}
+
+// load(_:at:), pointer(at:), typedPointer(to:at:length:) are extension helpers.
+

并发:分析器今天是 @unchecked Sendable 加手写锁(裁决 A62)。FileCrossReferenceMemory 的读取是对只读映射的并发读,fixup 解码的记忆化沿用 MachOKitExtensions cached 视图里已有的锁。

+
+ +
+swift-section 的 JSON、地址约定、性能预算 +
{
+  "query": { "selector": "makeKeyAndOrderFront:" },
+  "input": { "dyldSharedCache": "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e", "imageCount": 4114 },
+  "scannedImageCount": 2759,
+  "isTruncated": false,
+  "references": [
+    {
+      "image": "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit",
+      "function": { "address": "0x18801a000", "name": "-[NSApplication _showWindow:]" },
+      "site": "0x18801a040",
+      "kind": "call",
+      "route": "cacheSharedStub",
+      "target": { "messageSend": { "selector": "makeKeyAndOrderFront:", "receiver": "unknown" } }
+    }
+  ]
+}
+

(示例中的函数名与地址是示意,不是实测值。)symbolicate --json 输出 {"symbolications": [ … ]},每项的字段对应 AddressSymbolication。字段名定下后即是契约,改名按 CLI 的破坏性变更处理。

+

地址的约定:CLI 与 API 进出的地址一律是未滑动的虚拟地址,也就是 IDA、ipsw、dyld_info 显示的那种。进程内模式在内部换算,调用方不需要知道 slide。

+

性能预算:拆分本身的验收见上文「按层拆分与识别器」。离线吞吐在第 4 步实测并写进模块文档:在 Ultra 上对 /Volumes/DyldSharedCaches/macOS/27.2 冷启动、热启动各跑 --selector makeKeyAndOrderFront: 与 --selector init。若冷启动的整 cache 查询超过 60 秒,在愿景里把「落盘」阶段提前。

+
+ +

前期调研

+
+现状代码怎么走的 +

以下路径相对于本仓库,读自 next(6e73eeaa)。

+

CrossReferenceAnalysis 的公开入口(Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift):

+
    +
  • public init?()(:85)只扫当前进程,非 arm64 时返回 nil;public let images: [MachOImage](:23)、imagePaths(:30)、imageIndex(forPath:)、location(ofRuntimeAddress:)(:250)。
  • +
  • 函数表:functions(inImageAt:)、function(containing:)、functions(containing:)、symbolName(at:)。
  • +
  • 引用:references(madeBy:)、referenceTable(ofImageAt:)、referenceIndex(ofImageAt:)、references(to:inImageAt:)(:449,键是 CodeReferenceTable.Key)。
  • +
  • 预筛(+Prefiltering.swift、+Linkage.swift、+SwiftTypes.swift):imageIndices(importing:among:)、imageIndices(referencingSelector:among:)、imageIndices(referencingObjectiveCClassAt:among:)、imageIndices(linkingImageAt:among:)、imageIndices(referencingSwiftType:among:) 等。
  • +
  • 宿主内存管理:prepareNames(inImageAt:)、preparePrefilters()、releaseImageData(exceptForImagesAt:)、approximateByteCount(ofImageDataAt:)。
  • +
+

模型(Models/):CodeLocation(镜像下标 + 未滑动地址);CodeReference(function、instructionAddress、kind: call | tailCall | reference、target、isRuntimeHelperCall,公开 memberwise 初始化方法在 CodeReference.swift:104);CodeReferenceTarget 有 function、importedSymbol、messageSend(selector:receiver:)、superMessageSend、swiftType、swiftTypeName、objectiveCClass、indirect、unrecognized 九种;CodeReferenceTable.Key 有 function、selector、importedSymbol、objectiveCClass、swiftTypeDescriptor 等。

+

分析器只能在进程内成立的依赖——本提案要拆掉的就是这些:

+
    +
  1. 构造器用 DyldCacheLoaded.current + cache.slide、_dyld_image_count、_dyld_get_image_header、dladdr(CrossReferenceAnalyzer.swift:89-120)。
  2. +
  3. 未滑动地址靠 image.vmaddrSlide 换成运行时地址。
  4. +
  5. 直接按地址读进程内存:UnsafeRawPointer(bitPattern:) 在 ReferenceScanner.swift 7 处、ObjectiveCClassIndex.swift 5 处、SwiftTypeIndex.swift 4 处、ImageFunctionTable.swift 2 处、+SwiftTypes.swift 2 处、+Prefiltering.swift 1 处、ImageFallbackNames.swift 1 处,共 22 处。
  6. +
  7. GOT 槽依赖 dyld 已经绑定好的值:模块文档写明「GOT 槽在进程内已经绑定,读出指针、去掉指针认证位就是目标」,懒绑定场景由 LazyBindingTests 守着。
  8. +
  9. 去掉指针认证位用 StoredPointer 里的 InProcessContext.addressMask。
  10. +
  11. 函数起点依赖 MachOImage.FunctionStarts 的偏移语义(模块文档说进程内给的已是绝对地址,与 MachOKit 的注释不符)。
  12. +
  13. 类名经 MachOObjCSection 读 class_rw_t(类已被运行时实现时)。
  14. +
+

已能认出的引用形态(Scanning/ReferenceScanner.swift、Scanning/RegisterFile.swift,解码器是 Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift):直接 bl / b 与尾调用、跳转表;镜像自带的 __objc_stubs 与 __stubs / __auth_stubs(读不出时由 ARM64Trampoline 补读 ld64 改写过的 nop; ldr x16, <slot>; br x16);27 的 cache 共用 selector 桩(adrp x1; add x1; b <objc_msgSend 副本>)与 GOT 桩(adrp x17; add x17; ldr x16, [x17]; braa);stub island 多跳;cache 内经典发送(x1 由 adrp / add 算出可打印的字符串地址);GOT / selref / classref / superref 的 adrp + ldr 与字面量 ldr;adrp + add / adr 算出类对象、元数据或访问器;Swift 类型访问器与 __swift_instantiateConcreteTypeFromMangledName*;按 autda / movk 鉴别常量区分 vtable、PWT、VWT 的间接调用。

+

解码器的覆盖:ARM64InstructionWord.load(_:)(:88)只认 64 位的 ldr / ldur / 前变址 ldr! / ldraa / ldrab;不认 ldrsw 与 32 位 ldr w,而 arm64 上读 ObjC ivar 偏移变量正是 adrp x8, _OBJC_IVAR_$_C.ivar@PAGE; ldrsw x8, [x8, …@PAGEOFF]。

+

性能(模块文档「吞吐」节,macOS 27.2,28 核):建分析器 0.06 秒(4,114 个镜像);每个镜像都建整表 3.0 秒、1.26 亿条引用;查 init 的调用者预筛出 2,759 个镜像,0.05 + 1.8 秒;查 makeKeyAndOrderFront: 0.06 + 0.33 秒;手写解码器单线程解码 AppKit 约 187 MiB/s,比 Capstone 快 25–50 倍。

+

本库已有的离线解析(Sources/Analysis/SwiftThunkAnalysis/Resolution/):

+
    +
  • MachOThunkEnvironment(package final class,551 行)已经在 MachOFile 上做了这几件事:callee(at:) 解析桩、ld64 跳板与 stub island(可多跳,hopping(from:to:islandHops:));callee(boundInSlotAt:) 解析 GOT 槽——独立文件经 resolveBind(fileOffset:) 得 bind 名,cache 里是 rebase 到别的镜像,再按地址找符号;pointer(at:)、slotSymbolName(at:);foreignCallee 与 dependencyCallee 跨镜像找导出。
  • +
  • CacheImageResolver(同文件 :466)用 imageInfos 按加载地址二分,回答「这个地址在 cache 的哪个镜像」,并按路径懒打开 MachOFile。
  • +
  • ThunkAddressSpace(ThunkAddressSpace.swift)定下 cache 镜像的偏移约定:未滑动地址 − sharedRegionStart,并实测记下三种看似可用、实际静默出错的换算(segment.fileOffset、MachOFile.fileOffset(of:)、FullDyldCache.address(of:),在 macOS 26 的 SwiftUI 上分别偏 0x88000、另一套记账、再偏 16384)。
  • +
+

读取层:Sources/MachO/MachOReading 已有 ReadingContext 协议(associatedtype Runtime、associatedtype Address、readElement(at:)、readElements(at:numberOfElements:)、readWrapperElement(at:))及 MachOContext / InProcessContext 两种实现。MachOKitExtensions 的草案 move-reading-and-resolving-modules(In Progress,四个仓库同名分支)正把它原名迁进 MachOKitExtensions 2.0.0,随本库 0.25.0 一起发。

+

swift-section CLI:根命令 Sources/Executables/swift-section/SwiftSectionCommand.swift;输入选项组 Models/MachOOptionGroup.swift(filePath、-p/--cache-image-path、-n/--cache-image-name、--dyld-shared-cache、--uses-system-dyld-shared-cache、-a/--architecture、--dependency-search-path),经 Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift 只产出单个 MachOFile。AGENTS.md 的 CLI 一节规定:子命令逻辑写进 SwiftSectionKit 的 Request 类型,可执行层只管 flag、validate()、makeRequest() 与错误翻译;输出一律经 StandardStreamOutput;CLI 改动要同批更新 AgentPlugins/swift-section/skills/swift-section-cli/。目前只有 evolution --json 与 snapshot 有 JSON,没有统一约定。swift-section target 现在不依赖 CrossReferenceAnalysis(Package.swift:920-941)。

+
+ +
+按层拆分的依据 +

今天的模块把三种语言层的逻辑混在一起。CrossReferenceAnalysis 有 21 个文件、4,511 行,依赖 MachOKit、MachOObjCSection、Demangling、ARM64InstructionDecoding、MachOFoundation、MachOSwiftSection、SwiftInspection(Package.swift:640-655)。按 import 看,ObjC 与 Swift 的部分集中在几个文件:ObjectiveCClassIndex.swift(@_spi(Core) import MachOObjCSection,读 ObjCClass64)、ImageFallbackNames.swift(ObjC 方法列表 + SymbolicDemangler)、SwiftTypeIndex.swift 与 CrossReferenceAnalyzer+SwiftTypes.swift(Swift 描述符、SymbolicDemangler、Demangling)。但扫描器本身不分层,ObjC 与 Swift 的识别在五个地方插进同一趟循环(Scanning/ReferenceScanner.swift):

+
    +
  1. 进入函数:ObjC 方法在 x0 上打「方法接收者」标记(:117-121),这是 RegisterFile 里唯一与语言有关的状态(RegisterFile.swift:17 的 methodReceiver)。
  2. +
  3. 解析调用目标(computeResolution,:690-715;functionTarget,:751-769):__objc_stubs 的 selector、libobjc 专用入口(objc_alloc_init 等)、objc_msgSend / objc_msgSendSuper2 的位置、Swift 元数据访问器与 mangled name 实例化辅助函数。这些位置表建在分析器上(CrossReferenceAnalyzer.swift:51-66)。
  4. +
  5. 调用点(reference(to:at:in:kind:isObjectiveCMethod:),:303-345):读 x1 的 selector(:585)、x0 的接收者(:363)、__objc_superrefs 给出的父类(:235、:564);调用之后 x0 是否保留由 objc_opt_self / objc_opt_class / swift_getInitializedObjCClass 决定(:143-152,名单在 CrossReferenceAnalyzer.swift:224-226)。
  6. +
  7. 算出地址与 5. 读槽(:401-473):认 ObjC 类对象、Swift 值类型元数据(kind 0x200–0x204)与元数据访问器。
  8. +
+

其余是通用的:指令解码、寄存器跟踪、分支间状态的传递、本镜像桩与 GOT、stub island、跨镜像函数、间接调用的指针认证常量。还有几处混用:RuntimeHelperNames 同时列 _swift_retain… 与 _objc_retain…;ImageFunctionTable(:35-46)同时存 __objc_stubs、__objc_selrefs、__objc_superrefs、classref 与 GOT 的范围;cache 共用 selector 桩由 ARM64Trampoline.selectorStub 认出(:728),形状是通用的(adrp x1; add x1; b <目标>),含义(selector)是 ObjC 的。IndirectCallEvidence.Table 列着 vtable / PWT / VWT,但扫描器只写过 .none(:355),没有别处赋值。

+

公开模型也把语言写死在封闭枚举里:CodeReferenceTarget 九个 case 里五个属于 ObjC 或 Swift;CodeReferenceTable.Key 有 selector、objectiveCClass、swiftTypeDescriptor;CodeFunction.Name 有 objectiveCMethod、swiftMetadata;另有 ReceiverClassHint、SwiftTypeName。

+

三层将来的落脚处。

+
    +
  • MachOKitExtensions:两份迁移提案都已 Accepted。落地后它有读取层、MachOPointers、MachOCaches、MachODependencies、MachOBase / MachOFoundation,以及语言无关的 MachOSymbols(带只收 C、C++、ObjC 名字的 SymbolIndexStore)——核心层要的依赖届时都在那里。它的 README 承诺支持 Linux,并因此去掉了 FrameworkToolbox;核心层的锁都是 NSLock,不用 FrameworkToolbox,但进程内构造器用的 _dyld_*、dladdr、DyldCacheLoaded.current(CrossReferenceAnalyzer.swift:90-117)只在 Darwin 上有。
  • +
  • MachOObjCSection:已依赖 MachOKitExtensions;模块按 ObjC 前缀命名(ObjCMetadataSource、ObjCIndexing、ObjCInterface 等)。ObjC 层现在经 @_spi(Core) 读的类结构,搬进去后就是包内访问。
  • +
  • 本库:Swift 层与 swift-section 的两个子命令。
  • +
+

模块名与版本。SwiftPM 不允许依赖图里出现同名模块,不论那个模块是不是 product、有没有被用到(MachOKitExtensions 迁移提案的调研)。本库对 MachOKitExtensions 的要求是 from: "1.3.2"(Package.swift:174,2.0.0 之后改成 from: "2.0.0",即 < 3.0.0),对 MachOObjCSection 是 "0.8.206" ..< "0.9.0"(Package.swift:217)。所以本库发布过的版本里只要有一个模块,和 MachOKitExtensions 2.x 之后新增的模块同名,旧版本本库与新版本 MachOKitExtensions 就解析不到一起。另外,基础模块迁移提案定下:迁完之后本库里带 MachO 前缀的只剩 ABI 模型。本提案原先把抽出的模块叫 MachOAddressResolution、放在 Sources/MachO/,两条都会撞上。

+

目前没有第二个使用方。在 REAgent、MachOKitUI、swift-decompiler 的源码里不分大小写搜 crossreference、xref,没有结果(REAgent 查调用者走 IDA);需要交叉引用而又不想带上 Swift 栈的使用方,现在还只是预期。

+
+ +
+上游或依赖是否已具备能力 +
    +
  • MachOKit(fork,本库要求 from: "0.55.102"):stubs(in:) / objcStubs(in:)(LoadCommand/Model/Section+Stubs.swift,Stub.Branch 为 .viaSlot / .direct / .unknown,带 indirectSymbolIndex);MachOFile.resolveBind(at:)(MachOFile.swift:927)、resolveRebase(at:)(:879)、DyldCache.resolveRebase(at:);MachOFile.functionStarts(:481);closestSymbol(at:…)(MachORepresentable.swift:396-745);DyldCache.symbolCache 读 .symbols 文件。没有 stub island 或 cache 共用桩的 API,没有「地址 → 所属镜像」的 API,没有共享 selector 哈希表的解析;selref / classref / protoref 没有专门的访问器。读文件经 p-x9 的 swift-fileio(内存映射)。
  • +
  • MachOKitExtensions(from: "1.3.2"):MachOFile.resolveBind(fileOffset:) 覆盖 chained fixup 与旧式 dyld info,但 isLoadedFromDyldCache 时直接返回 nil;resolveSelfBind(fileOffset:) 处理 BIND_SPECIAL_DYLIB_SELF;resolveRebase(fileOffset:) 对 cache 镜像走 cache;MachOFile.cached 的 fixupPointer(at:);DyldCacheSubCacheTable 子 cache 地址二分表。
  • +
+
+ +
+前人怎么做的(ipsw、dyld_info、IDA、Binary Ninja) +
    +
  • ipsw:dyld xref 不跟进 stub island;dyld a2s 对 27 的 cache 共用 objc_msgSend$ 桩只回 ?;没有 .a2s 符号缓存时 disass 会卡在解析符号上 12 分钟、占 23 GB 内存(逆向 agent 笔记)。
  • +
  • Apple dyld_info:只读本机正在运行的 cache;-disassemble 给 cache 桩标错名;-imports 漏 bind;-objc 对 cache 镜像静默无输出、退出码 0。
  • +
  • IDA:一个库只装得下几个镜像,跨镜像看不到;单镜像库的导入桩借用别的局部符号名;查调用者要两跳(槽 → j__<符号> 桩 → 调用者)。
  • +
  • Binary Ninja(开源部分取自 Vector35/binaryninja-api 的 dev 分支;用户装的是 6.0.10601 Personal): +
      +
    • 整个 cache 放进一个地址空间,跨镜像引用就是普通地址;全 cache 的符号单独存成 CacheSymbol,打开 cache 时读每个镜像的导出 trie 建「地址 → 符号」表,LC_SYMTAB 与 .symbols 本地符号等镜像被加载时才读(view/sharedcache/core/SharedCache.cpp:305、core/MachOProcessor.cpp:88-134)。
    • +
    • stub island 当作单独的区域;桩的判定看节名后缀(__stubs、__auth_stubs、__objc_stubs、_branch_islands);解析时在 MLIL 的 SSA 形式上沿跳转目标往回找 LOAD(CONST_PTR),命名为 j_<目标符号>(view/sharedcache/workflow/SharedCacheWorkflow.cpp)。
    • +
    • ObjC 调用点的 selector 取 x1 的 SSA 常量值;objc_msgSend$sel 桩不靠符号表,「不超过 32 字节、一个基本块、尾调用 msgSend」就当它是,并用同样的 x1 追踪取 selector(plugins/workflow_objc/src/activities/ 下的 objc_msg_send_calls.rs、name_stubs.rs)。
    • +
    • selector 到实现不改写调用,而是从 selector 字符串和 selref 槽各加一条数据引用指向 IMP,查询时两跳;改写成直接调用的选项默认关,源码 TODO 承认它总取第一个实现、需要接收者类型才做得好(objectivec/objc.cpp:1182-1184、rewrite_to_direct_call.rs)。
    • +
    • 引用分代码、数据、类型、变量四类,另有类型字段引用(get_code_refs_for_type_field);6.0 新增 get_derived_string_code_refs(派生字符串,例如 CFString 的代码引用)。数据流只在函数内做(docs/dev/concepts.md:160)。
    • +
    • 界面里引用列表有上限(ui.maxXrefItems = 1000),超出时计数后面带 +;可按方向、种类过滤。
    • +
    • 6.0 自带 MCP 服务器:GUI 内的 HTTP 版随所有 GUI 版本提供(含 Personal),能查交叉引用、调用者、反汇编、IL 与伪代码;无界面的 binaryninja_mcp 只随 Commercial / Ultimate。地址在输出里一律写成十六进制字符串,「so clients do not lose precision when handling 64-bit addresses」;列表结果带 count、total、nextOffset、truncated(应用内 docs/guide/mcp.html)。
    • +
    +
  • +
+
+ +
+验证过什么 +
    +
  • 已验证(引自现有文档与记忆):进程内分析器的吞吐数字;ThunkAddressSpace 的地址约定与三种错误换算(macOS 26 SwiftUI);UINSPasteboardWritingItemProvider 的两个经 GOT 的调用者(27.0、27.2);dyld_info 的 2,195 个错名桩(26.7 SwiftUICore)。
  • +
  • IDA 与 Binary Ninja 的交叉引用实测(2026-11-18,Finder 26.5.2 与 ControlCenter 26.7,详见愿景「我们选的方向」第 1 条):代码引用召回 IDA 一次查询 97.0%、两跳 99.4%,Binary Ninja 经 MCP 67.6%。三处双方的盲点直接变成本提案的测试用例:恰好页对齐的类对象(adrp; add #0,IDA 漏)、Swift 大字符串的 adrp; add; sub #0x20(Binary Ninja 漏)、retab 之后没建函数的异常清理代码(Binary Ninja 漏)。
  • +
  • 卷上有 cache 文件的版本:macOS 15.5、26.0(单文件);26.5.2、26.6.2、26.7(12 个子文件);27.0(79 个)、27.2(81 个)。本机运行 27.2。
  • +
  • 推测,第 1、4 步先实测: +
      +
    • 离线模式的吞吐。cache 在外置卷上、冷读几个 GB 的映射文件,预计比进程内慢,慢多少不知道。
    • +
    • 文件模式下能否拿到 __text 的连续只读字节(swift-fileio 的映射能否按区间给出指针),拿不到就按镜像把 __text 读进一块缓冲区。
    • +
    • MachOFile.functionStarts 在 cache 镜像上的偏移语义。
    • +
    • macOS 27 的 cache 文件里各镜像的 __objc_stubs 是否也是 0 大小(文档只说进程内为 0)。
    • +
    +
  • +
+
+ +

替代方案考量

+
+评估过但放弃的路径(15 条) +
    +
  • 另写一个离线分析器,不动现有的。否:扫描、寄存器跟踪、命名合计约 5,200 行,复制一份就会和进程内版本漂移;SwiftThunkAnalysis 里已经有一份重复的离线解析,正是本提案要合并的。
  • +
  • 把分析器改成对 MachO: MachORepresentable 泛型(本库其它模块的惯用写法)。否:两种模式的差别不在「哪种 Mach-O 类型」,而在「槽里的值怎么得到」——进程内读已绑定的值,文件里解 fixup。泛型会一路传染到 RuntimeViewer 持有分析器的会话类型,而一个小协议正好只隔离这一点。
  • +
  • 直接用 ReadingContext 当读取抽象。否,理由见「提议方案」第 1 节;FileCrossReferenceMemory 内部仍用它。
  • +
  • 后端用 ipsw 或 dyld_info。否:「前人怎么做的」里列的几类静默漏报、错名都会原样带进来。
  • +
  • 直接用 Binary Ninja。否:用户的 Personal 许可没有无界面 API,无界面的 binaryninja_mcp 也只随 Commercial / Ultimate;GUI 的 MCP 要求界面开着、当前视图跟随界面,多个 agent 会互相抢;整 cache 查询要把几千个镜像装进一个视图。2026-11-18 的实测里,它经 MCP 的代码引用召回只有 67.6%(IDA 两跳 99.4%),所以连核对也只作补充。
  • +
  • 现在就做落盘索引。否:0072 与 RuntimeViewer 0056 都定过不做;先量离线吞吐再说。
  • +
  • 地址符号化放进 MachOKit fork。否:fork 已落后上游 33 个提交,再加新能力只会更难合。
  • +
  • 一步到位:本提案直接把核心写进 MachOKitExtensions、ObjC 层写进 MachOObjCSection。否,改为分两步:本提案还有四项要先实测的未知,识别器接口也要在热路径上量过才定得下来;跨三个仓库时核心每改一次都要按序发版,而 MachOKitExtensions 此刻正在为 2.0.0 接收读取层与基础模块。用户在两种走法之间选了分两步。
  • +
  • 只抽桩链与槽解析,扫描器整体留在本库(本提案原先的方案)。否:ObjC 与 Swift 的识别仍和通用扫描混在一个依赖 Swift 栈的模块里,不带 Swift 的使用方(关掉 SwiftSection trait 的 MachOKitUI、MachOObjCSection 自己的 objc-section)永远拿不到交叉引用;越往上加功能,日后越难拆。
  • +
  • 核心层直接定义列着 ObjC 与 Swift case 的目标枚举,不开扩展点。否:这样也能做到核心不 import 上层,但每加一种语言层的目标都要改核心、在 MachOKitExtensions 发版,而且把 Swift 的词汇带进一个语言无关的包——违反开闭原则。识别器加记录协议让核心对新语言封闭、对扩展开放。
  • +
  • 核心层对目标类型泛型(CodeReference<Target>),各层用 SE-0280 的「enum case 当协议要求的实现」构造目标。否(这一步):泛型会扩散到 CodeReferenceTable、CodeReferenceIndex 和 RuntimeViewer 用到的每个名字;跨模块的泛型在 release 下不特化(package 函数不参与默认跨模块优化),扫描热路径上逐条引用的拷贝会走值见证调用。记录协议只在事件上做一次动态派发。下层将来要不要有自己的目标类型,留给迁移提案。
  • +
  • 本库里的模块直接用落脚处的名字(MachOCodeReferences、ObjCCodeReferences、MachOAddressResolution)。否:本库发布过的版本只要带着与 MachOKitExtensions 2.x 新模块同名的模块,两边就解析不到一起,迁移时就得让 MachOKitExtensions 再升一个大版本;基础模块迁移提案也定了迁完后本库带 MachO 前缀的只有 ABI 模型。两个下层模块不是 product,搬的时候改名只动本库内部的 import。
  • +
  • CLI 子命令叫 resolve。否:与 resolveBind / resolveRebase 撞义,见「详细设计」的命名取舍。
  • +
  • 照 Binary Ninja 建统一地址空间、换掉 CodeLocation。否:CodeLocation 是公开模型,RuntimeViewer 的查询层建在它上面;统一地址空间里最有用的「任何地址都说得出是什么」由符号化单独提供。
  • +
  • 照 Binary Ninja 加「selref / selector → IMP」的数据引用。本提案不做,归入愿景第 3 阶段的数据引用;现在按 selector 查发送者已经可以,从调用点到实现的两跳留给数据引用一起做。
  • +
+
+ +

影响

+

源码兼容性(source compatibility)

+

有破坏,逐条:

+
    +
  • CodeReferenceTarget 新增三个 case,CodeReferenceTable.Key 新增三个 case:对它们做穷尽 switch 的代码编译失败。已知下游只有 RuntimeViewer 的 CrossReferenceQuery.swift:92(switch reference.target),在第 5 步同一时间窗里补上: +
    // Before: nine cases.
    +// After: add
    +case .objectiveCInstanceVariable, .cString, .constantString:
    +    return nil   // not surfaced in the GUI yet
    + RuntimeViewer 本地按「本地路径优先」依赖本库(../../MachOSwiftSection),所以本库 next 一合进新 case,RuntimeViewer 的 next 就要跟着改,两边要同批合入。
  • +
  • CodeReference 的旧初始化方法标 deprecated(renamed: 到新签名),仍可用一个版本。
  • +
  • images 标 deprecated;进程内模式行为不变。
  • +
  • CodeReference.Route 去掉了原设计里的 selectorReference 与 classReference(并进 pointerSlot)。Route 是本提案新增的,没有已发布的使用方。
  • +
+

按层拆分不破坏源码:CodeLocation、IndirectCallEvidence、ReceiverClassHint 搬到下层模块,CodeReference.Kind 从嵌套 enum 改成指向核心层 CodeReferenceKind 的 typealias;顶层 @_exported import 两个下层模块,import CrossReferenceAnalysis 的代码照旧看得到同样的名字、同样的 case。类型的完整名字(模块前缀)变了,只影响按类型名做序列化的代码;RuntimeViewer 在第 2 步核对一次它跨进程传交叉引用结果时怎么编码。

+

其余全是新增。

+

ABI 兼容性

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+
    +
  • 本仓库内:SwiftThunkAnalysis 改用抽出的模块(行为不变,由守护测试保证);SwiftSectionKit 与 swift-section 新增对 CrossReferenceAnalysis 的依赖。
  • +
  • RuntimeViewer:见上;另有第 8、9 步的 CLI 与 MCP。它的常驻索引(CodeReferenceIndex)多出 route,第 5 步量出 approximateByteCount 的增量写进模块文档。
  • +
  • swift-decompiler:依赖本库的 SwiftThunkAnalysis 时只经它的公开接口,抽取不改公开接口;第 3 步核对一次。
  • +
  • MachOKitExtensions 的两次迁移(读取层、基础模块):都是原名迁入,import 不变;核心层与 ObjC 层只许 import 将来 MachOKitExtensions / MachOObjCSection 里也有的模块,正是以这两次迁移之后的样子为准。若迁移先合进 next,第 2、3 步照新的包依赖写 Package.swift。
  • +
  • 之后的迁移提案:本提案落地后,核心层、CodeAddressResolution 与 ObjC 层的文件应能原样搬走、只改 import 与模块名;做不到的地方(例如进程内构造器的 Darwin 条件编译)记进那份提案的调研。
  • +
+

文档与示例

+

README 的 CLI 一节、swift-section-cli skill、四个模块参考文档(CrossReferenceAnalysis 更新,CrossReferenceCore、CrossReferenceObjC、CodeAddressResolution 新增)、AGENTS.md 的模块层级图、愿景第 6 条、RuntimeViewer 的 CLI 使用指南与 runtime-viewer skill。

+

API 演进与废弃策略

+
    +
  • CodeReference.init(function:instructionAddress:kind:target:isRuntimeHelperCall:) 与 CrossReferenceAnalyzer.images:标 @available(*, deprecated, …) 保留一个次版本,下一个次版本删除。
  • +
  • ThunkAddressSpace、CacheImageResolver 是 package 级,直接搬走,不留旧名。
  • +
  • 搬到下层模块的公开类型不改名、不留转发:经 @_exported import 原名可见。
  • +
  • 三层之间的识别器与记录协议是 package 级,这一步不承诺稳定;迁移提案把它们变成公开 API 时再按 apple-style-api-design 定形。
  • +
  • 本库仍在 0.x,随下一个次版本发布,不需要大版本。
  • +
+ +

落地步骤

+
    +
  1. 读取抽象,行为不变(已完成) —— 改动地图里的 CrossReferenceMemory、InProcessCrossReferenceMemory、分析器与各扫描文件的读取改造、StoredPointer、Package.swift。 +
    • inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation(改造前后逐条比对整表)
    • +
    • crossReferenceAnalysisReadsMemoryOnlyThroughCrossReferenceMemory(源码扫描:分析模块里不再有 UnsafeRawPointer(bitPattern:))
  2. +
  3. 按层拆分,行为不变(已完成) —— 改动地图里步骤列为 2 的各行:建 CrossReferenceCore 与 CrossReferenceObjC,识别器、会话与三个记录协议,寄存器标记,CodeImageSet,函数表与回退名按层拆开,运行时名单分到两层,门面改为组合两个识别器,@_exported import,边界测试,三份模块文档、AGENTS.md、愿景第 6 条。先量拆分前的基准,拆完在同一台机器上再量。 +
    • inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation(沿用第 1 步的整表比对,AppKit、SwiftUICore、Foundation 逐条相同;比较前去掉类型搬家带来的拼写差异)
    • +
    • aFunctionStartingOutsideTextScansWhereItLies(第 1 步引入、吞吐基准发现的下溢陷入的复现)
    • +
    • crossReferenceLayersImportOnlyWhatTheirFutureHomesProvide(源码扫描:核心层、ObjC 层的 import 都在白名单里)
    • +
    • crossReferenceCoreSpellsNoRuntimeSymbolName(源码扫描:核心层没有 objc_ / swift_ 开头的字面量)
    • +
    • aRecognizerDefinedInTestsPlugsInWithoutChangingTheCore(测试里定义一个只认某个 C 函数的识别器,它的引用出现在结果里——扩展点确实开放)
    • +
    • selectorQueriesLookUpNoSwiftType(只查 selector 时 Swift 会话不建任何镜像的类型索引;ObjC 会话照旧为发送的类字面量接收者读类对象,与拆分前一致)
    • +
    • scanThroughputAfterTheLayerSplitIsRecordedInTheModuleDocument(不是断言:拆分前后整 cache 建表与两条查询的耗时写进模块文档,增幅超过 5% 时按「详细设计」的退路处理后再量)
    • +
    • publicNamesStillResolveThroughCrossReferenceAnalysis(只 import CrossReferenceAnalysis 的测试文件能用 CodeLocation、CodeReference.Kind.call、ReceiverClassHint.methodReceiver)
  4. +
  5. 抽出 CodeAddressResolution(已完成) —— 四个新类型、MachOThunkEnvironment 改用它们、删 ThunkAddressSpace、模块文档。 +
    • 线程读取的结果不变——由 SwiftThunkAnalysisTests 全套守着(归档 iOS 设备 cache 的 stub island、归档 macOS cache 的合并 accessor、模拟器运行时、独立文件),不另写测试
    • +
    • stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub(x1 的常量与最终的 objc_msgSend 副本;模块本身不认识 selector)
    • +
    • stubChainRecordsEveryStubIslandHop
    • +
    • slotResolverMatchesTheProcessForEveryGlobalOffsetTableSlotOfAppKit(含指向 AppKit 自己的类对象的槽)
    • +
    • slotResolverResolvesStandaloneBinds
    • +
    • cacheImageLocatorFindsTheImageAnAddressLiesIn
    • +
    • aFunctionLoadingAGlobalIsNoSlotStub(ARM64Trampoline 的修复,见决策日志)
  6. +
  7. 文件模式的分析器(已完成) —— CodeImage 与 ImageLinkEdit、FileCrossReferenceMemory、两个新构造器、各层按镜像读取的文件模式。 +
    • fileModeMatchesInProcessReferencesOnTheRunningSystemCache(同一个 cache 两种模式逐条比对,镜像取 AppKit、SwiftUICore、Foundation)
    • +
    • fileModeNamesFunctionsAsTheProcessDoes、fileModeReadsTheFallbackNameSourcesAsTheProcessDoes(函数名与 ObjC 方法表、Swift 元数据两种后备来源两种模式逐条一致)
    • +
    • fileModePrefiltersSelectorsAsTheProcessDoes
    • +
    • fileMemoryDecodesSlotsAsMachOKitDoes(v5 与没有 slide info 的模拟器 cache,逐槽与 MachOKit 一致)
    • +
    • archivedCacheFindsBothCallersOfPasteboardWritingItemProvider(27.0 与 27.2;卷不在时跳过)
    • +
    • archivedCacheFollowsStubIslandsForSelectorSends
    • +
    • standaloneAppResolvesImportedAndSelfBoundSymbols
    • +
    • standaloneExecutableResolvesRebasesAndObjectiveCStubs(SlotResolver 的修复,见决策日志)
    • +
    • fileModeScansExceptionCleanupCodeAfterReturn(retab 之后、没有函数起点的异常清理代码也要被扫到)
    • +
    • 吞吐:ScanThroughputBenchmarkTests 加 CROSS_REFERENCE_BENCHMARK_DYLD_CACHE,实测写进模块文档
    • +
    • 核对:卷上没有 Finder 26.5.2,也没有 2026-11-18 那次的标准答案与生成脚本;按原法重做要新写 otool -tV 加寄存器跟踪的脚本,留给用户看过之后再跑。改做抽样:ControlCenter 26.7 的文件模式结果(StandaloneFileReferenceDumpTests 导出)与 IDA 逐函数对照,见决策日志。
  8. +
  9. 新引用种类与路线(已完成) —— 解码器的 ldrsw / 32 位 ldr(含字面量形式)、核心层的字符串、路线与对导入符号的数据引用、ObjC 层的 ivar、三个 target、Route、表键、常驻索引编码。RuntimeViewer 的穷尽 switch 挪到第 8 步,与 RuntimeViewer 的其余改动一起做。 +
    • instanceVariableOffsetLoadsBecomeInstanceVariableReferences(带符号与剥了符号两种)
    • +
    • stringReferencesAreRecordedOnlyWhenRequested
    • +
    • constantStringReferencesCarryTheirCharacters(8 位与 UTF-16 两种)
    • +
    • everyReferenceCarriesTheRouteItTook、inProcessReferencesCarryTheirRoutes;iOS 设备 cache 经 stub island 的发送路线是 stubIsland(archivedCacheFollowsStubIslandsForSelectorSends)
    • +
    • referenceIndexRoundTripsNewTargetsAndRoutes
    • +
    • decoderDecodesThirtyTwoBitLoadAndLoadSignedWord
    • +
    • pageAlignedClassObjectMaterializationIsAReference(adrp; add #0,在运行中的 cache 里找)
    • +
    • swiftLargeStringLiteralPointsAtItsCharacters(adrp; add; sub #0x20)
    • +
    • 对导入符号的数据引用由 ControlCenter 的导出核对(_OBJC_CLASS_$_CALayer 一类)
  10. +
  11. 地址符号化(已完成) —— AddressSymbolication 与 symbolication(of:)、symbolication(of:inImageAt:);核心层的 AddressPlace 判断结构,门面补含义。 +
    • symbolicatesSwiftUICoreAuthStubsByTheirSlotsNotTheirIndirectSymbols(26.7 SwiftUICore 的全部 __auth_stubs 都解到函数或导入名;其中 5 个经 ipsw dyld macho --stubs 独立核对的桩,间接符号表给的是错名,正是 dyld_info 标错的那批)
    • +
    • symbolicatesCacheSharedMessageSendStubToItsSelector
    • +
    • symbolicatesGlobalOffsetTableSlotToItsBoundSymbol
    • +
    • symbolicatesAnAddressInsideAnUnnamedFunctionWithItsFallbackName
    • +
    • symbolicatesAnUnmappedAddressAsUnmapped
    • +
    • symbolicatesStringsAndObjectiveCSlots(C 字符串、CFString、__objc_ivar 的偏移变量)
  12. +
  13. swift-section refs 与 symbolicate(已完成) —— SwiftSectionKit 的三个类型、两个命令、选项组、登记、README、skill。 +
    • refsListsCallerRowsForASelectorInAnArchivedCache
    • +
    • refsJSONUsesHexadecimalStringAddresses
    • +
    • refsMarksTruncatedResultsWhenLimited
    • +
    • refsRequiresExactlyOneQuery
    • +
    • symbolicateAcceptsSeveralAddresses
    • +
    • refsListsTheCalleesOfAFunction、refsListsTheCallersOfASymbol、refsListsTheReferencesToAClass、refsReadsAStandaloneFatExecutable、symbolicateJSONUsesHexadecimalStringAddresses
    • +
    • crossReferenceCommandsWriteOnlyThroughStandardStreamOutput(沿用仓库已有的输出扫描测试)
  14. +
  15. RuntimeViewer CLI(已完成) —— 引擎侧符号化命令、四个子命令、协议版本、文本显示、使用指南、skill。 +
    • callersCommandJSONMatchesTheMCPResponseFields
    • +
    • commandLineProtocolVersionIsThree
    • +
    • symbolicateCommandWorksOnTheLocalSource
  16. +
  17. RuntimeViewer MCP 与收尾(已完成) —— 四个 MCP 工具;本库的 ProjectEvolutionLog.md、Glossary.md;RuntimeViewer 的 Evolutions/README.md 加 cross-repository draft 一行,0056 的暂缓表里把第 4 步那一行指向本提案。 +
    • callersToolReturnsAPartialResultAfterThirtySeconds
    • +
    • symbolicateToolRequiresAWindowIdentifier
  18. +
+

收尾时必须判断两件事(判断结果写进决策日志,不允许沉默跳过):

+
    +
  • 要不要配套专题文章 —— 预判要写一份 CLI 使用指南:「地址一律未滑动」「字符串引用要打开才记录」「截断标记」这几条契约在签名里看不出来。模块参考文档本身按约定更新。
  • +
  • 有没有引入新术语 —— 预计有「地址符号化(symbolication)」「引用路线(route)」「识别器(recognizer)」,以及 stub island、cache 共用桩若术语表里还没有。
  • +
+ +

后续项

+
    +
  • 全面核对没有重做:2026-11-18 那次用 otool -tV 加寄存器跟踪独立生成标准答案、再对照 IDA 的做法,生成脚本与 Finder 26.5.2 都已不在卷上。第 4 步改为 ControlCenter 26.7 三个函数的抽样核对。重做要新写生成标准答案的脚本,先给用户看过再跑。
  • +
  • Swift 类经 ObjC ivar 列表登记的偏移变量没有收:它们是 __data 里的 Swift 字段偏移全局量,不在 __objc_ivar(ControlCenter 的 BentoBackdrop.maskLayer 就是这样)。
  • +
  • ivar 名字的两个来源有 23 条之差(共约 182 万条 ivar 引用),没有逐条追。
  • +
  • RuntimeViewer:三种新目标(ivar、C 字符串、常量字符串)在界面里先不显示;App 工程本身没有构建过,只在沙盒里编过 Core、CLI 与 MCP 三个包;它跟的是本库的 next 分支,提交的 Package.resolved 已同日抬到本库的 a98cbc15。交叉引用测试模块整体并发跑时「分析器换新后要重新读名字」那组会超时,是基线就有的问题。
  • +
  • 核心层与 ObjC 层迁出本库:另写迁移提案,要定的事见「非目标」第一条。
  • +
+ +

决策日志

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-18Created as Draft调研了过去逆向卡住最久的地方,「跨镜像查谁用了它」与「地址起名」排在最前;用户选定先做这一块,并把它定为愿景《不依赖 IDA 的逆向》的第一步,伪代码不再是默认读物,IDA 退为后备
2026-11-18参照 Binary Ninja用户指出 IDA 的交叉引用弱、Binary Ninja 强。调研了它开源的 shared cache 视图与 ObjC 插件:采纳桩按节名判定与 j_ 式命名、引用按来源种类标注(本提案的 route)、地址写成十六进制字符串、结果带截断标记;selector → IMP 的数据引用留给愿景第 3 阶段
2026-11-18Binary Ninja 6 的 MCP用户升级到 Binary Ninja 6.0。它的 GUI 内 MCP 服务器 Personal 版也有,可作第 3 步的结果核对;无界面版仍要 Commercial / Ultimate,所以不作后端
2026-11-18实测后改用 IDA 核对在 Finder 与 ControlCenter 上实测:代码引用召回 IDA 两跳 99.4%、Binary Ninja 经 MCP 67.6%。第 3 步的核对改以独立生成的标准答案为准、IDA 对照、Binary Ninja 补充;双方的三处盲点(页对齐类对象、Swift 大字符串、retab 后的清理代码)加成测试
2026-11-18改为按层拆分、分两步迁移用户提出把核心放进 MachOKitExtensions、ObjC 与 Swift 各管自己的部分。核实了两份 MachOKitExtensions 迁移提案都已 Accepted,核心层要的依赖届时都在那里;难点在扫描器里 ObjC 与 Swift 的识别穿插在五个时机。用户在「一步到位写进三个仓库」与「先在本库拆层、量完再迁」之间选了后者。本提案因此新增第 2 步:拆成 CrossReferenceCore、CrossReferenceObjC、CrossReferenceAnalysis 三个模块,经识别器与记录协议相接,核心不认识任何语言,源码扫描守住 import 边界,公开模型与 API 留在顶层不变;MachOAddressResolution 改名 CodeAddressResolution,下层模块在本库里的名字刻意不同于落脚处,避开同名模块与 MachO 前缀两条约束;Route 去掉按节区分的两个 case。原第 2–8 步顺延为第 3–9 步(上面几行里的「第 3 步」指现在的第 4 步)。真正的搬迁另写迁移提案
2026-11-18Accepted用户批准,开始实现
2026-11-19第 1 步完成读取协议按分析器地址空间里的地址读(进程内就是运行时地址),而不是原设计的「未滑动地址 + 镜像下标」:现有代码处处用运行时地址,这样改动最小,文件模式给每个镜像定一个滑动量即可。进程内实现不检查映射,信任调用方——此前的直接读也不检查,可能读到未映射地址的地方本来就先问 isMapped。「整表不变」做成靠环境变量驱动的 A/B 测试(ReferenceTableDigestTests):基线用 git archive 导出、拷入同一个测试文件生成摘要,候选与之比对;两边都要带 USING_LOCAL_DEPENDENCIES=1,因为 next 已用到 swift-demangling 未发版的 API。2026-11-19 在 Ultra 上 AppKit、SwiftUICore、Foundation 三个镜像逐条一致
2026-11-19第 2 步完成按层拆分落地,与原设计的出入:识别器没有共同协议,两层各是具体类型,核心只认会话与记录协议(门面本来就认识两个具体的层);角色声明自己会不会代替调用、要不要事后记录,扫描器只调用需要的那个方法,调用计划里的角色用 SIMD4 存,一次扫描最多四个会话;运行时库的规则(RuntimeLibraryRules)由门面交给核心,建镜像集时只扫一遍运行时库的符号;各层按镜像的缓存挂在函数表上作附件,函数表在它那一遍里记下各节供 ObjC 层用;CodeReference.Kind 改成核心层 CodeReferenceKind 的 typealias。测试 selectorQueriesSkipClassAndTypeLookups 改为 selectorQueriesLookUpNoSwiftType:ObjC 会话为发送的类字面量接收者照旧读类对象,与拆分前一致。整表对照:String(describing:) 给枚举负载里的类型加模块前缀,Kind 的拼法也变了,摘要在比较前去掉这两处;归一化后 AppKit、SwiftUICore、Foundation 逐行一致,整 cache 4,116 个系统镜像的引用数逐个一致
2026-11-19修掉第 1 步引入的陷入吞吐基准扫整个 cache 时触发:第 1 步把读指令改成以 __text 起点为基的偏移,有些镜像的符号表把 __text 的函数起点放在节起点之下,减法下溢陷入。改回按地址经读取层读,instructionPointer(at:count:) 由调用方给条数。复现测试 FunctionStartOutsideTextTests 修复前陷入、修复后通过。同类排查:CodeReferenceIndex 的编码本就先比较再用 &-,没有别处
2026-11-19吞吐优化第一次量(Ultra,release,对 next)超了 5%:整 cache 建表 +8%、init 调用者 +8%、makeKeyAndOrderFront: +11%、建分析器 +24%。逐项采样后改了四处:读槽先做区间排除再查认领表(原来就是这个顺序);运行时库的符号只扫一遍;调用计划不再持有数组(复制计划时的引用计数)、只调用角色需要的方法;会话与收集器里热路径上的可变属性标 @exclusivity(unchecked)(它们只在一个线程上用);函数表记下各节,ObjC 层不再为每次扫描遍历一遍 load command。另给读取层加了两个批量读接口(pointers(inSlotsAt:count:)、readablePointers(at:)),selector 预筛按 256 个槽一块读,不再每个槽一次 existential 调用
2026-11-19吞吐验收同一台 Ultra、release、三方交替各三轮取最好:整 cache 建表 next 2.42 / 第 1 步 2.54 / 第 2 步 2.52 秒,init 调用者 1.70 / 1.71 / 1.74 秒,makeKeyAndOrderFront: 调用者 0.36 / 0.37 / 0.38 秒。第 2 步相对拆分前(第 1 步)在 −0.5% 到 +3% 之间,满足 5% 的验收线,不必退到泛型特化;整表多出的约 5% 来自第 1 步的读取层,记进模块文档。debug 下交叉引用全套 99 个测试通过
2026-11-19第 3 步完成CodeAddressResolution 按设计抽出,另有两处细节:它依赖 MachOReading(MachOFile.readElements,设计里说的读取层);CacheImageLocator 不自带 SharedCache,按镜像共用一个 locator 由线程读取器在 thunkResolution 组里做,本模块因此不依赖 MachOCaches,将来能原样搬走。SwiftThunkAnalysis 不再直接依赖 ARM64InstructionDecoding。行为清单对齐实际测试:抽取前后结果不变由 SwiftThunkAnalysisTests 全套守着;「本镜像类对象在 GOT 里」并进 AppKit 全部 GOT 槽与进程逐个比对的测试;独立文件的 self-bind 在 SlotResolver 里只是名字,换成地址是第 4 步文件模式的事,那条行为由第 4 步的 standaloneAppResolvesImportedAndSelfBoundSymbols 覆盖
2026-11-19修掉跳板把普通函数认成 GOT 桩写 stubChainRecordsEveryStubIslandHop 时发现:iOS 26.3.1 设备 cache 里 SwiftUI 经 stub island 调到 UIKitCore 的 UIHostingViewBase.viewGraph getter,它开头是 adrp x8; ldr x8, [x8, #0xb10]; ldr x0, [x20, x8](读一个字段偏移),ARM64Trampoline 读到 ldr 就认定是从槽里取目标的桩,链落到 sharedRegionStart + 0x38。这是 next 上就有的旧 bug。改成载入之后必须紧跟一条经同一寄存器的非调用跳转(三种 GOT 桩都是这个形状),复现测试 aFunctionLoadingAGlobalIsNoSlotStub 修复前四处断言全红、修复后通过。影响面:进程内扫描器只对不落在任何镜像里的地址认跳板,结果不变;线程读取器只在调用目标落在别的镜像、又不是 accessor 或运行时入口时才走到它,原来得出 unknown,现在也是。真正会受影响的是第 4 步的文件模式,它经同一个解析器一跳一跳地跟,所以在这一步修掉
2026-11-19第 4 步:镜像抽象每个镜像改由核心层的 CodeImage 描述,__LINKEDIT 的表经读取层按地址读(ImageLinkEdit),桩按 S_SYMBOL_STUBS 的 reserved1/2 与 ARM64Trampoline 自己读,不再经 MachOKit 各读取器一套的 symbols64、stubs(in:)、functionStarts。读取器专属的 API 只在 ObjC 层(MachOObjCSection)与 Swift 层(MachOSwiftSection)里经 asMachOImage / asMachOFile / MachOSwiftSectionRepresentableWithCache 打开。进程内结果不变:交叉引用全套 100 个测试与整表摘要照旧,吞吐与第 1 步相比 −3% 到 +3%
2026-11-19第 4 步:文件读取层的形状FileCrossReferenceMemory 是值,以 unowned(unsafe) 引用镜像集持有的存储,区间表放在手动分配的缓冲区。第一版是类,整 cache 建表 37 秒(进程内 2.5 秒):每次经 existential 读都复制读取层、计一次数,FullDyldCache.cacheAndFileOffset(for:) 每次还新建子 cache 对象、重读 slide info。按 mapping 预取 slide info、v5 在读取层里直接解之后 16.5 秒,改成值之后 2.6 秒,与进程内持平。v2、v3 的快速路径写过又删了:卷上没有能验证它们的 arm64 cache(模拟器 cache 没有 slide info),只留 v5,其余交给 MachOKit
2026-11-19第 4 步:API 与设计的出入两个构造器先不带 recordingStringReferences,第 5 步加字符串引用时一起加。失败时抛 FileAnalysisError(带 Code 的结构体,眼下只有 unsupportedArchitecture)。images 不标 deprecated:进程内的宿主与测试读的是只有 MachOImage 给得出的东西(slide、header),imagePaths / imageCount 替代不了,标了只会把它们推向无处可去;文件模式下它为空写在文档注释里。一组独立文件按 dyld 的做法错开地址。ObjC 层把按名字导入的 _objc_msgSend / _objc_msgSendSuper2 认成发送:不带 libobjc 分析一个 app 时它们就是这样到达的
2026-11-19修掉 SlotResolver 把 rebase 偏移当地址抽样核对 ControlCenter 时发现:几乎所有 objc 桩都没认出 selector。MachOKitExtensions 对独立文件的链式 fixup 给的是「相对首选加载地址的偏移」,SlotResolver(承自线程读取器的 rebaseTargetAddress,注释写着「独立文件给的是目标地址」)直接当地址用——dylib 的 __TEXT 在 0,两者相同,夹具都是 dylib,所以没被测到;可执行文件的 __TEXT 在 0x100000000,槽解出 0x798 而函数在 0x100000798。改为按 __TEXT 加偏移(ImageAddressSpace.address(forHeaderOffset:));没有链式 fixup、靠 opcode rebase 的旧文件,MachOKitExtensions 不解,文件读取层直接用槽里的值。复现测试 standaloneExecutableResolvesRebasesAndObjectiveCStubs 修复前四处断言全红、修复后通过。同类排查:别处(MachOPointers、线程读取器的描述符读取)都把这个结果当 MachOSwiftSection 自己口径的 offset 用,是一致的。修复后 ControlCenter 的发送从 967 条到 4,909 条,无法识别的调用从 3,933 条到 1 条
2026-11-19第 4 步完成吞吐(Ultra,release,归档 macOS 27.2 cache,三轮最好):建分析器 0.14 秒,整 cache 建表 2.58 秒(1.263 亿条),init 调用者预筛 0.04 + 扫描 1.74 秒,makeKeyAndOrderFront: 0.11 + 0.34 秒;进程里第一次查询 0.5 秒与 1.9 秒。读运行中的 cache 文件与外置卷上的归档一样快,远低于愿景里「冷启动整 cache 查询超过 60 秒就提前落盘」的线。核对改为抽样:ControlCenter 26.7 的三个函数(ObjC 发送与 super 发送、Swift 元数据访问器与类型引用、objc_allocWithZone 与 init),IDA 反汇编里的直接调用与发送本库逐一都有;差异两类——经 GOT 槽读别的镜像的类(槽里是 bind)不记,补进第 5 步;直接经 GOT 槽的 blraa 记成间接调用,进程内同样如此。按 2026-11-18 的做法重做全面核对,需要新写生成标准答案的脚本,留给用户
2026-11-19文件读取层不掩地址AddressMaskScanTests 不许库里出现自定义的地址掩码常量。文件读取层的 addressMask 改为不掩(解出的槽本来就是干净地址);slide info v5 的 34 位 runtimeOffset 是格式字段不是掩码,在扫描用例里加了一条只减不增、写明是哪个字段的白名单
2026-11-19第 5 步完成与设计的出入:路线的最后一种叫 indirect,不叫 authenticatedIndirect——不带认证的 blr / br 也得有路线,认证与否已在 IndirectCallEvidence 里。Swift 大字符串不需要 Swift 层专门认:add 算出的正是字符串起点,核心在那里记下;只是「减法算出的地址」从不当作字符串,否则 sub #0x20 之后的地址会落进前一个字符串中间。ivar 只认 __objc_ivar 里的偏移变量,即父类不在本镜像的 ObjC 类(父类是 NSObject 时 clang 用常量偏移、根本不载入);Swift 类经 ObjC ivar 列表登记的偏移变量是 __data 里的 Swift 字段偏移全局量,不在 __objc_ivar,没有收(ControlCenter 的 BentoBackdrop.maskLayer 就是这样),留作后续。对导入符号的数据引用记成 .importedSymbol(name:)、kind == .reference,不另外按名字认成 ObjC 类引用:类引用的 target 要带位置,导入的类没有;查一个类的全部引用时,调用方同时查 _OBJC_CLASS_$_<类>。查询里含字符串键时,那次扫描照样找字符串,不受分析器开关限制。32 位载入另认 ld64 改写出的字面量形式(ldrsw xt, label)。RuntimeViewer 的穷尽 switch 挪到第 8 步:它经远端版本依赖本库,本库发版之前不受影响
2026-11-19第 6 步完成与设计的出入:另有 symbolication(of:inImageAt:)——一组独立文件各留自己的地址,两个文件可能都有同一个未滑动地址(进程内,链接在 0 的测试 bundle 就占着 0x10),不指定镜像时取第一个有它的镜像,cache 优先。Meaning 多一个 .data:映射着、但不是函数、桩、槽、字符串,其下也没有符号,不能说成未映射。槽里的东西按节说:selector 引用给 .messageSend(selector:receiver: .unknown)(目标类型里没有单独的 selector),protocol 引用给协议名 .cString,GOT 给函数、类、Swift 类型或导入名,__objc_ivar 给 ivar。结构由核心层的 AddressPlace 判断(函数体、本镜像的桩、镜像之间的跳板链、槽、字符串、最近的符号),ObjC 层的 selector 桩、类与 ivar、Swift 类型与无符号函数的名字在门面补上。符号化用留存的函数表(第一版用不留存的,问 26.7 SwiftUICore 的全部桩花了 207 秒,改后 0.9 秒)。原计划的「对照 MachOKit 的 Stub.indirectSymbolIndex」不成立:那批桩上 MachOKit 读间接符号表与 dyld_info 一样标错,改为用 ipsw 独立核对的 5 个桩钉住、其余全部桩都要解出目标
2026-11-19ivar 名字改经读取层读第 5 步的 ivar 名字第二来源经 MachOObjCSection 遍历类,每个类都重走一遍加载命令,整 cache 建表因此慢了 30%(3.25 秒)。改为从 __objc_classlist 起经读取层读 class_ro_t 与 ivar 列表(已 realize 的类经 class_rw_t 的第二个字,指针剥签名),两种读取器一套代码;整表回到 2.57–2.66 秒,比第 4 步多约 4%,多出的正是 182 万条 ivar 引用。两条路给的名字有 23 条之差(共约 182 万条),没有逐条追
2026-11-19第 7 步完成与设计的出入:refs --function 多一个 --function-image——一组文件各有各的地址,两个链接在 0 的 dylib 会在同一地址都有函数,此时报错要求指名;symbolicate 的文件输入是可重复的 --file(位置参数是地址),--in-image 指地址属于哪个镜像。胖文件必须给 -a,沿用 README 自 0.10.0 起「不默默挑切片」的约定(实现时一度自动挑 arm64e,发现与约定相悖后改回)。--string 不需要打开 recordingStringReferences:按键查询本来就找字符串。--class 先找 _OBJC_CLASS_$_ 符号,找不到(cache 里多数私有类)再读各镜像的类表,并按类对象位置过滤同名类。--symbol 要求名字是函数的起点,变量报错;没有任何镜像定义时按导入名找(一组文件里调用外部库的情形)。为此门面加了 locations(ofSymbolNamed:among:)(导出表加符号表),CodeFunction.Name 加了 spelling。JSON 键排序、地址一律十六进制字符串,每条引用多一个 isRuntimeHelperCall。请求的 run(output:) 不收环境:不往产物里盖任何东西
2026-11-19修共用键集合的争抢写 refs 时发现:多个线程并发扫描、共用同一个键集合时,ReferenceCollector.keep 每检查一条引用都对该集合 retain/release 一次(tableKey.map(keptKeys.contains) 把集合捕获进闭包),28 个核争一个引用计数,整 cache 查 init 的调用者用了 152 秒、查 makeKeyAndOrderFront: 11.6 秒。next 上的 ReferenceScanner.keep 是同一写法,RuntimeViewer 并发查调用者时也共用一个键集合,是基线就有的问题;基准每个镜像现建一个集合,所以没暴露。改为收集器各留一份自己的拷贝、去掉闭包捕获:两条查询降到 2.2 秒与 1.05 秒(release CLI,含建分析器与起名)。基准的调用者查询改成共用一个键集合,与真实调用方一致,今后回归能在数字上看出;改后 init 的扫描 1.69 秒,与原来每镜像一个集合时相同
2026-11-19第 8 步完成与设计的出入:引擎侧加两个命令而不是一个——符号化之外还有「按名字定位符号」(crossReferenceLocateSymbol,用本库新加的 locations(ofSymbolNamed:among:)),因为查询主体没有「符号」这一种,符号名要先在引擎进程里换成函数地址。目标写法的解析放进 RuntimeViewerCrossReferences 的 RuntimeCrossReferenceTargetResolution,CLI 与 MCP 共用;按名字找类型由调用方传入,各前端沿用自己的查找规则。CLI 的 --json 与 MCP 的每行字段同出 Core 的 RuntimeCrossReferenceRow / RuntimeAddressSymbolicationRow(MCP 的响应类型要用 SwiftMCP 的 @Schema,Core 里不能用,所以 MCP 一侧逐字段照抄、测试钉住键名一致)。三种新目标(ivar、C 字符串、常量字符串)在 RuntimeViewer 里先不显示,照源码兼容性一节的约定返回空。失败代码新增 targetNotFound 与 crossReferencesUnavailable。RuntimeViewer 分支从远端 next 切出:本地 next 当时有十几个别的会话未推送的提交,从它切会在推送功能分支时把那些工作一并公开
2026-11-19第 9 步完成MCP 四个工具照现有工具带 windowIdentifier;30 秒的等待做成可单测的 MCPBridgeServer.references(within:_:):边查边收进度里的引用,到时取消查询、带着已有结果返回 isComplete: false 与说明(已扫完的镜像有缓存,再调一次接着扫)。RuntimeViewer 的提案索引加了 cross-repository draft 一行,暂缓表里第 4 步那一行指向本提案,0056 的决策日志记了一行
2026-11-19渲染 A/B 验证全部一致桩与槽的解析从 SwiftThunkAnalysis 抽成共用模块,动到了读取层,按 AGENTS.md 跑系统框架渲染 A/B:基线是开工时的 next(f8b25d2a),三条读取路径共 84 对 dump 与 interface 逐字节一致(归档 cache 15.5 与 26.6、iOS 15.5 至 26.5 模拟器、进程内)
2026-11-19RuntimeViewer 交叉引用模块的并发超时是基线就有的在沙盒里对本分支跑 RuntimeViewer 整个交叉引用测试模块(82 条并发),「分析器换新后要重新读名字」的两条等了 60 秒没等到;基线(RuntimeViewer 远端 next 加本库 next)整模块跑同样有其中一条在同一行失败,两边单跑这一组(18 条)都在 41 秒内全过。是会话队列在整模块并发时被前面的准备工作占满,与本次改动无关,没有修
2026-11-19实现完成,待用户看过后收尾九个落地步骤都已完成。本库全量测试(跳过 IntegrationTests)2,993 个零失败;渲染 A/B 84 对一致;RuntimeViewer 一侧在沙盒里对本分支编过 Core、CLI 与 MCP 三个包,新测试全过,App 工程本身没有构建。文档判断:配套使用指南不另写——CLI 的用法与契约写在 README、swift-section 插件的 references/cross-references.md 与 RuntimeViewer 的 Guides/CommandLineInterface.md,实现细节在三份模块文档;新术语「地址符号化」「识别器」「引用路线」「stub island」已登记进术语表。两个仓库的功能分支已在本地合进各自常驻的 next 检出,没有推送
2026-11-19Implemented,取号 0097,两个仓库合进各自的 next 并推送用户验收后批准收尾。验收在 JHs-Mac-Studio-Ultra 上用功能分支的 release 版 CLI 做(Xcode 27.2,本地兄弟依赖):运行中系统 cache 里 makeKeyAndOrderFront: 的 439 处发送,0.7 秒;归档 27.0 与 27.2 cache 里 UINSPasteboardWritingItemProvider 的两个调用者;cache 共用 objc_msgSend 桩解成 selector(ipsw dyld a2s 对同一地址只回 ?),GOT 槽、类对象与未映射地址的符号化;TextEdit 胖文件带 -a arm64e 找到 4 处发送,不带时按约定报错。落地前验证沿用「实现完成」一行的结果,之后只改了文档。文档判断不变:不另写使用指南,配套文档登记在头部,新术语已登记。正文去掉了段内硬换行,内容不变。没做完的列在「后续项」
+ +
+ + diff --git a/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md new file mode 100644 index 000000000..dd50b40f4 --- /dev/null +++ b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md @@ -0,0 +1,904 @@ +# 0097 - 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-18 +- **最后更新**: 2026-11-19 +- **所属愿景**: [不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)(第 1 阶段) +- **关联提案**: + - [0072 cross-reference-analysis](0072-cross-reference-analysis.md):进程内的交叉引用分析,本提案在它上面扩展。 + - [0076 objc-runtime-send-entry-points](0076-objc-runtime-send-entry-points.md):libobjc 的专用发送入口。 + - [0053](0053-shared-cache-infrastructure.md) `SharedCache`:本提案不新增 `SharedCache`,理由同 0072。 + - RuntimeViewer [0056 cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md):界面里的交叉引用;它暂缓的第 4 步「CLI 与 MCP」由本提案接手。 + - MachOKitExtensions [0002 move-reading-and-resolving-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) 与 [0003 move-macho-infrastructure-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md)(两份都已 Accepted):把本库的读取层、`MachOPointers` / `MachOCaches` / `MachODependencies` 与语言无关的 `MachOSymbols` 迁进 MachOKitExtensions 2.0.0。本提案拆出的核心层与 ObjC 层照同样的走法,**之后另写一份迁移提案**搬到 MachOKitExtensions 与 MachOObjCSection(见「提议方案」第 2 节)。 +- **实现分支 / PR**: 本库与 RuntimeViewer 都是 `feature/offline-cross-references-and-symbolication`(从各自的 `next` 切出),本地合进各自的 `next`,没开 PR +- **配套文档**: 用法与契约在 [README](../../README.md) 的 `refs` / `symbolicate` 两节、`swift-section` 插件的 [references/cross-references.md](../../AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md) 与 RuntimeViewer 的 `Documentations/Guides/CommandLineInterface.md`;实现说明在模块文档 [CrossReferenceAnalysis](../Internal/Modules/CrossReferenceAnalysis.md)、[CrossReferenceCore](../Internal/Modules/CrossReferenceCore.md)、[CrossReferenceObjC](../Internal/Modules/CrossReferenceObjC.md)、[CodeAddressResolution](../Internal/Modules/CodeAddressResolution.md) +- **网页版**: [0097-offline-cross-references-and-symbolication.html](0097-offline-cross-references-and-symbolication.html) + +## 摘要 + +`CrossReferenceAnalysis` 今天只能分析**当前进程**映射进来的镜像,读不了磁盘上的 app、也读不了 `/Volumes/DyldSharedCaches` 下归档的各版本 cache,而且没有命令行入口。本提案做六件事: + +1. 把分析器里「直接读进程内存」的地方收进一个读取抽象,新增从 `FullDyldCache` 和一组 `MachOFile` 构造分析器的入口,槽里的值改由 fixup 解码得到; +2. **把交叉引用按层拆成三个模块**:与语言无关的核心 `CrossReferenceCore`(指令扫描、函数表、桩与槽、字符串、符号化)、ObjC 层 `CrossReferenceObjC`(消息发送、类引用、ivar、ObjC 方法名)、Swift 层 `CrossReferenceAnalysis`(Swift 类型、对外的公开 API)。层与层之间经「识别器」扩展点相接,核心不认识任何一种语言;各层能 import 什么由源码扫描测试守住,只许 import 它们将来的落脚处也有的模块。真正搬到 MachOKitExtensions(核心)与 MachOObjCSection(ObjC 层)**另写迁移提案**,在本提案量完吞吐、跑稳之后做; +3. 把 `SwiftThunkAnalysis` 里已经写好的离线桩链与槽解析抽成独立的 `CodeAddressResolution` 模块,两边共用; +4. 补三类引用:经 ivar 偏移变量读写 ObjC ivar、C 字符串字面量、CFString 常量,并给每条引用标上它是怎么到达目标的(直接调用、本镜像桩、stub island、cache 共用桩、GOT 槽……); +5. 新增地址符号化:任意一个地址,说出它在哪个镜像的哪个函数加多少偏移,或者它是桩、最终跳到谁,或者它是槽、里面装着谁; +6. 新增 `swift-section refs` 与 `swift-section symbolicate` 两个子命令(文本与 JSON 输出),并在 RuntimeViewer 的 CLI 与 MCP 上接出 `callers` / `callees` / `references` / `symbolicate`。 + +## 动机 + +完整动机见愿景《[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)》的「现状与代价」。这一步特有的部分: + +- **最常卡住的就是这一块。** 逆向 agent 的笔记里约 15 条用「扫 selref / GOT 字节 → 换算子 cache 偏移 → 反汇编 stub island → `a2s` 起名」这条手工链路回答「谁调用了它」,13 条涉及 selref,12 条涉及 GOT(`~/.claude/agent-memory/reverse-explorer/cross-cache-caller-search.md`、全局 `reverse-engineering` skill 的 `references/ipsw-cache-recipes.md`)。现成工具都会静默漏:`ipsw dyld xref` 不跟进 stub island,`dyld_info -imports` 漏掉大部分 bind。2026-10-29 有一次因此判错:`UINSPasteboardWritingItemProvider` 在 27.0 和 27.2 上都有两个调用者,它们经 `__DATA_CONST.__got` 读**本镜像自己**的类对象,`ipsw dyld disass` 只显示 `ldr x0, [x23, #0x590]`,没有类名。 +- **分析器已经有了,只是够不着这些目标。** `CrossReferenceAnalyzer` 在进程内 1.6–3.0 秒扫完 macOS 27.2 的整个 cache,认得 27 的 cache 共用 selector 桩与 GOT 桩、stub island 多跳(`Internal/Modules/CrossReferenceAnalysis.md`「吞吐」节)。但它的构造器用 `DyldCacheLoaded.current` 与 `_dyld_get_image_header`,只看得到正在运行的系统;卷上归档的 7 个 macOS 版本(15.5 到 27.2)和 `/Volumes/RE` 下的 app 都够不着。0072 把 `MachOFile` 与 `swift-section` 子命令明确留给了后续提案。 +- **RuntimeViewer 只在界面里给出交叉引用。** RuntimeViewer 0056 的第 4 步(CLI 与 MCP)在 2026-10-26 经用户批准拆成暂缓项,说明以后另起提案。全部对话记录里 RuntimeViewer 的 MCP 一次也没被调用过;agent 要查调用者,只能退回 IDA 或 `ipsw`。 +- **地址起名是同一个问题的另一面。** `dyld_info -disassemble` 把 macOS 26.7 SwiftUICore 的 2,195 个 `__auth_stubs` 桩标成同一个错名,15.3 万条 `bl` 的目标因此标错(RuntimeViewer 记忆 `dyld-info-mislabels-cache-stubs.md`);`ipsw dyld a2s` 对 27 的 cache 共用 `objc_msgSend$…` 桩只回 `?`,agent 只能先反汇编桩的前三条,自己算 `adrp x1` 的页加 `add x1` 的偏移,再去读字符串。分析器在扫描时本来就要把每个桩解析到底,把这一步单独开放出来就是符号化。 + +## 前期调研 + +### 现状代码怎么走的 + +以下路径相对于本仓库,读自 `next`(`6e73eeaa`)。 + +**`CrossReferenceAnalysis` 的公开入口**(`Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift`): + +- `public init?()`(`:85`)只扫当前进程,非 arm64 时返回 `nil`;`public let images: [MachOImage]`(`:23`)、`imagePaths`(`:30`)、`imageIndex(forPath:)`、`location(ofRuntimeAddress:)`(`:250`)。 +- 函数表:`functions(inImageAt:)`、`function(containing:)`、`functions(containing:)`、`symbolName(at:)`。 +- 引用:`references(madeBy:)`、`referenceTable(ofImageAt:)`、`referenceIndex(ofImageAt:)`、`references(to:inImageAt:)`(`:449`,键是 `CodeReferenceTable.Key`)。 +- 预筛(`+Prefiltering.swift`、`+Linkage.swift`、`+SwiftTypes.swift`):`imageIndices(importing:among:)`、`imageIndices(referencingSelector:among:)`、`imageIndices(referencingObjectiveCClassAt:among:)`、`imageIndices(linkingImageAt:among:)`、`imageIndices(referencingSwiftType:among:)` 等。 +- 宿主内存管理:`prepareNames(inImageAt:)`、`preparePrefilters()`、`releaseImageData(exceptForImagesAt:)`、`approximateByteCount(ofImageDataAt:)`。 + +**模型**(`Models/`):`CodeLocation`(镜像下标 + 未滑动地址);`CodeReference`(`function`、`instructionAddress`、`kind: call | tailCall | reference`、`target`、`isRuntimeHelperCall`,公开 memberwise 初始化方法在 `CodeReference.swift:104`);`CodeReferenceTarget` 有 `function`、`importedSymbol`、`messageSend(selector:receiver:)`、`superMessageSend`、`swiftType`、`swiftTypeName`、`objectiveCClass`、`indirect`、`unrecognized` 九种;`CodeReferenceTable.Key` 有 `function`、`selector`、`importedSymbol`、`objectiveCClass`、`swiftTypeDescriptor` 等。 + +**分析器只能在进程内成立的依赖**——本提案要拆掉的就是这些: + +1. 构造器用 `DyldCacheLoaded.current` + `cache.slide`、`_dyld_image_count`、`_dyld_get_image_header`、`dladdr`(`CrossReferenceAnalyzer.swift:89-120`)。 +2. 未滑动地址靠 `image.vmaddrSlide` 换成运行时地址。 +3. 直接按地址读进程内存:`UnsafeRawPointer(bitPattern:)` 在 `ReferenceScanner.swift` 7 处、`ObjectiveCClassIndex.swift` 5 处、`SwiftTypeIndex.swift` 4 处、`ImageFunctionTable.swift` 2 处、`+SwiftTypes.swift` 2 处、`+Prefiltering.swift` 1 处、`ImageFallbackNames.swift` 1 处,共 22 处。 +4. **GOT 槽依赖 dyld 已经绑定好的值**:模块文档写明「GOT 槽在进程内已经绑定,读出指针、去掉指针认证位就是目标」,懒绑定场景由 `LazyBindingTests` 守着。 +5. 去掉指针认证位用 `StoredPointer` 里的 `InProcessContext.addressMask`。 +6. 函数起点依赖 `MachOImage.FunctionStarts` 的偏移语义(模块文档说进程内给的已是绝对地址,与 MachOKit 的注释不符)。 +7. 类名经 MachOObjCSection 读 `class_rw_t`(类已被运行时实现时)。 + +**已能认出的引用形态**(`Scanning/ReferenceScanner.swift`、`Scanning/RegisterFile.swift`,解码器是 `Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift`):直接 `bl` / `b` 与尾调用、跳转表;镜像自带的 `__objc_stubs` 与 `__stubs` / `__auth_stubs`(读不出时由 `ARM64Trampoline` 补读 ld64 改写过的 `nop; ldr x16, ; br x16`);27 的 cache 共用 selector 桩(`adrp x1; add x1; b `)与 GOT 桩(`adrp x17; add x17; ldr x16, [x17]; braa`);stub island 多跳;cache 内经典发送(`x1` 由 `adrp` / `add` 算出可打印的字符串地址);GOT / selref / classref / superref 的 `adrp` + `ldr` 与字面量 `ldr`;`adrp` + `add` / `adr` 算出类对象、元数据或访问器;Swift 类型访问器与 `__swift_instantiateConcreteTypeFromMangledName*`;按 `autda` / `movk` 鉴别常量区分 vtable、PWT、VWT 的间接调用。 + +**解码器的覆盖**:`ARM64InstructionWord.load(_:)`(`:88`)只认 64 位的 `ldr` / `ldur` / 前变址 `ldr!` / `ldraa` / `ldrab`;**不认 `ldrsw` 与 32 位 `ldr w`**,而 arm64 上读 ObjC ivar 偏移变量正是 `adrp x8, _OBJC_IVAR_$_C.ivar@PAGE; ldrsw x8, [x8, …@PAGEOFF]`。 + +**性能**(模块文档「吞吐」节,macOS 27.2,28 核):建分析器 0.06 秒(4,114 个镜像);每个镜像都建整表 3.0 秒、1.26 亿条引用;查 `init` 的调用者预筛出 2,759 个镜像,0.05 + 1.8 秒;查 `makeKeyAndOrderFront:` 0.06 + 0.33 秒;手写解码器单线程解码 AppKit 约 187 MiB/s,比 Capstone 快 25–50 倍。 + +**本库已有的离线解析**(`Sources/Analysis/SwiftThunkAnalysis/Resolution/`): + +- `MachOThunkEnvironment`(`package final class`,551 行)已经在 `MachOFile` 上做了这几件事:`callee(at:)` 解析桩、ld64 跳板与 stub island(可多跳,`hopping(from:to:islandHops:)`);`callee(boundInSlotAt:)` 解析 GOT 槽——独立文件经 `resolveBind(fileOffset:)` 得 bind 名,cache 里是 rebase 到别的镜像,再按地址找符号;`pointer(at:)`、`slotSymbolName(at:)`;`foreignCallee` 与 `dependencyCallee` 跨镜像找导出。 +- `CacheImageResolver`(同文件 `:466`)用 `imageInfos` 按加载地址二分,回答「这个地址在 cache 的哪个镜像」,并按路径懒打开 `MachOFile`。 +- `ThunkAddressSpace`(`ThunkAddressSpace.swift`)定下 cache 镜像的偏移约定:**未滑动地址 − `sharedRegionStart`**,并实测记下三种看似可用、实际静默出错的换算(`segment.fileOffset`、`MachOFile.fileOffset(of:)`、`FullDyldCache.address(of:)`,在 macOS 26 的 SwiftUI 上分别偏 0x88000、另一套记账、再偏 16384)。 + +**读取层**:`Sources/MachO/MachOReading` 已有 `ReadingContext` 协议(`associatedtype Runtime`、`associatedtype Address`、`readElement(at:)`、`readElements(at:numberOfElements:)`、`readWrapperElement(at:)`)及 `MachOContext` / `InProcessContext` 两种实现。MachOKitExtensions 的草案 `move-reading-and-resolving-modules`(In Progress,四个仓库同名分支)正把它原名迁进 MachOKitExtensions 2.0.0,随本库 0.25.0 一起发。 + +**`swift-section` CLI**:根命令 `Sources/Executables/swift-section/SwiftSectionCommand.swift`;输入选项组 `Models/MachOOptionGroup.swift`(`filePath`、`-p/--cache-image-path`、`-n/--cache-image-name`、`--dyld-shared-cache`、`--uses-system-dyld-shared-cache`、`-a/--architecture`、`--dependency-search-path`),经 `Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift` 只产出**单个** `MachOFile`。`AGENTS.md` 的 CLI 一节规定:子命令逻辑写进 `SwiftSectionKit` 的 Request 类型,可执行层只管 flag、`validate()`、`makeRequest()` 与错误翻译;输出一律经 `StandardStreamOutput`;CLI 改动要同批更新 `AgentPlugins/swift-section/skills/swift-section-cli/`。目前只有 `evolution --json` 与 snapshot 有 JSON,没有统一约定。`swift-section` target 现在不依赖 `CrossReferenceAnalysis`(`Package.swift:920-941`)。 + +### 按层拆分的依据 + +**今天的模块把三种语言层的逻辑混在一起。** `CrossReferenceAnalysis` 有 21 个文件、4,511 行,依赖 MachOKit、MachOObjCSection、Demangling、`ARM64InstructionDecoding`、`MachOFoundation`、`MachOSwiftSection`、`SwiftInspection`(`Package.swift:640-655`)。按 import 看,ObjC 与 Swift 的部分集中在几个文件:`ObjectiveCClassIndex.swift`(`@_spi(Core) import MachOObjCSection`,读 `ObjCClass64`)、`ImageFallbackNames.swift`(ObjC 方法列表 + `SymbolicDemangler`)、`SwiftTypeIndex.swift` 与 `CrossReferenceAnalyzer+SwiftTypes.swift`(Swift 描述符、`SymbolicDemangler`、Demangling)。但扫描器本身不分层,ObjC 与 Swift 的识别在五个地方插进同一趟循环(`Scanning/ReferenceScanner.swift`): + +1. **进入函数**:ObjC 方法在 `x0` 上打「方法接收者」标记(`:117-121`),这是 `RegisterFile` 里唯一与语言有关的状态(`RegisterFile.swift:17` 的 `methodReceiver`)。 +2. **解析调用目标**(`computeResolution`,`:690-715`;`functionTarget`,`:751-769`):`__objc_stubs` 的 selector、libobjc 专用入口(`objc_alloc_init` 等)、`objc_msgSend` / `objc_msgSendSuper2` 的位置、Swift 元数据访问器与 mangled name 实例化辅助函数。这些位置表建在分析器上(`CrossReferenceAnalyzer.swift:51-66`)。 +3. **调用点**(`reference(to:at:in:kind:isObjectiveCMethod:)`,`:303-345`):读 `x1` 的 selector(`:585`)、`x0` 的接收者(`:363`)、`__objc_superrefs` 给出的父类(`:235`、`:564`);调用之后 `x0` 是否保留由 `objc_opt_self` / `objc_opt_class` / `swift_getInitializedObjCClass` 决定(`:143-152`,名单在 `CrossReferenceAnalyzer.swift:224-226`)。 +4. **算出地址**与 5. **读槽**(`:401-473`):认 ObjC 类对象、Swift 值类型元数据(kind 0x200–0x204)与元数据访问器。 + +其余是通用的:指令解码、寄存器跟踪、分支间状态的传递、本镜像桩与 GOT、stub island、跨镜像函数、间接调用的指针认证常量。还有几处混用:`RuntimeHelperNames` 同时列 `_swift_retain…` 与 `_objc_retain…`;`ImageFunctionTable`(`:35-46`)同时存 `__objc_stubs`、`__objc_selrefs`、`__objc_superrefs`、classref 与 GOT 的范围;cache 共用 selector 桩由 `ARM64Trampoline.selectorStub` 认出(`:728`),形状是通用的(`adrp x1; add x1; b <目标>`),含义(selector)是 ObjC 的。`IndirectCallEvidence.Table` 列着 vtable / PWT / VWT,但扫描器只写过 `.none`(`:355`),没有别处赋值。 + +公开模型也把语言写死在封闭枚举里:`CodeReferenceTarget` 九个 case 里五个属于 ObjC 或 Swift;`CodeReferenceTable.Key` 有 `selector`、`objectiveCClass`、`swiftTypeDescriptor`;`CodeFunction.Name` 有 `objectiveCMethod`、`swiftMetadata`;另有 `ReceiverClassHint`、`SwiftTypeName`。 + +**三层将来的落脚处。** + +- **MachOKitExtensions**:两份迁移提案都已 Accepted。落地后它有读取层、`MachOPointers`、`MachOCaches`、`MachODependencies`、`MachOBase` / `MachOFoundation`,以及语言无关的 `MachOSymbols`(带只收 C、C++、ObjC 名字的 `SymbolIndexStore`)——核心层要的依赖届时都在那里。它的 README 承诺支持 Linux,并因此去掉了 FrameworkToolbox;核心层的锁都是 `NSLock`,不用 FrameworkToolbox,但进程内构造器用的 `_dyld_*`、`dladdr`、`DyldCacheLoaded.current`(`CrossReferenceAnalyzer.swift:90-117`)只在 Darwin 上有。 +- **MachOObjCSection**:已依赖 MachOKitExtensions;模块按 `ObjC` 前缀命名(`ObjCMetadataSource`、`ObjCIndexing`、`ObjCInterface` 等)。ObjC 层现在经 `@_spi(Core)` 读的类结构,搬进去后就是包内访问。 +- **本库**:Swift 层与 `swift-section` 的两个子命令。 + +**模块名与版本。** SwiftPM 不允许依赖图里出现同名模块,不论那个模块是不是 product、有没有被用到(MachOKitExtensions 迁移提案的调研)。本库对 MachOKitExtensions 的要求是 `from: "1.3.2"`(`Package.swift:174`,2.0.0 之后改成 `from: "2.0.0"`,即 `< 3.0.0`),对 MachOObjCSection 是 `"0.8.206" ..< "0.9.0"`(`Package.swift:217`)。所以本库发布过的版本里只要有一个模块,和 MachOKitExtensions 2.x 之后新增的模块同名,旧版本本库与新版本 MachOKitExtensions 就解析不到一起。另外,基础模块迁移提案定下:迁完之后本库里带 `MachO` 前缀的只剩 ABI 模型。本提案原先把抽出的模块叫 `MachOAddressResolution`、放在 `Sources/MachO/`,两条都会撞上。 + +**目前没有第二个使用方。** 在 REAgent、MachOKitUI、swift-decompiler 的源码里不分大小写搜 `crossreference`、`xref`,没有结果(REAgent 查调用者走 IDA);需要交叉引用而又不想带上 Swift 栈的使用方,现在还只是预期。 + +### 上游或依赖是否已具备能力 + +- **MachOKit**(fork,本库要求 `from: "0.55.102"`):`stubs(in:)` / `objcStubs(in:)`(`LoadCommand/Model/Section+Stubs.swift`,`Stub.Branch` 为 `.viaSlot` / `.direct` / `.unknown`,带 `indirectSymbolIndex`);`MachOFile.resolveBind(at:)`(`MachOFile.swift:927`)、`resolveRebase(at:)`(`:879`)、`DyldCache.resolveRebase(at:)`;`MachOFile.functionStarts`(`:481`);`closestSymbol(at:…)`(`MachORepresentable.swift:396-745`);`DyldCache.symbolCache` 读 `.symbols` 文件。**没有** stub island 或 cache 共用桩的 API,**没有**「地址 → 所属镜像」的 API,**没有**共享 selector 哈希表的解析;selref / classref / protoref 没有专门的访问器。读文件经 p-x9 的 `swift-fileio`(内存映射)。 +- **MachOKitExtensions**(`from: "1.3.2"`):`MachOFile.resolveBind(fileOffset:)` 覆盖 chained fixup 与旧式 dyld info,但 **`isLoadedFromDyldCache` 时直接返回 `nil`**;`resolveSelfBind(fileOffset:)` 处理 `BIND_SPECIAL_DYLIB_SELF`;`resolveRebase(fileOffset:)` 对 cache 镜像走 cache;`MachOFile.cached` 的 `fixupPointer(at:)`;`DyldCacheSubCacheTable` 子 cache 地址二分表。 + +### 前人怎么做的 + +- **ipsw**:`dyld xref` 不跟进 stub island;`dyld a2s` 对 27 的 cache 共用 `objc_msgSend$` 桩只回 `?`;没有 `.a2s` 符号缓存时 `disass` 会卡在解析符号上 12 分钟、占 23 GB 内存(逆向 agent 笔记)。 +- **Apple `dyld_info`**:只读本机正在运行的 cache;`-disassemble` 给 cache 桩标错名;`-imports` 漏 bind;`-objc` 对 cache 镜像静默无输出、退出码 0。 +- **IDA**:一个库只装得下几个镜像,跨镜像看不到;单镜像库的导入桩借用别的局部符号名;查调用者要两跳(槽 → `j__<符号>` 桩 → 调用者)。 +- **Binary Ninja**(开源部分取自 `Vector35/binaryninja-api` 的 `dev` 分支;用户装的是 6.0.10601 Personal): + - 整个 cache 放进一个地址空间,跨镜像引用就是普通地址;全 cache 的符号单独存成 `CacheSymbol`,打开 cache 时读每个镜像的导出 trie 建「地址 → 符号」表,LC_SYMTAB 与 `.symbols` 本地符号等镜像被加载时才读(`view/sharedcache/core/SharedCache.cpp:305`、`core/MachOProcessor.cpp:88-134`)。 + - stub island 当作单独的区域;桩的判定看节名后缀(`__stubs`、`__auth_stubs`、`__objc_stubs`、`_branch_islands`);解析时在 MLIL 的 SSA 形式上沿跳转目标往回找 `LOAD(CONST_PTR)`,命名为 `j_<目标符号>`(`view/sharedcache/workflow/SharedCacheWorkflow.cpp`)。 + - ObjC 调用点的 selector 取 `x1` 的 SSA 常量值;`objc_msgSend$sel` 桩不靠符号表,「不超过 32 字节、一个基本块、尾调用 msgSend」就当它是,并用同样的 `x1` 追踪取 selector(`plugins/workflow_objc/src/activities/` 下的 `objc_msg_send_calls.rs`、`name_stubs.rs`)。 + - selector 到实现不改写调用,而是从 selector 字符串和 selref 槽各加一条**数据引用**指向 IMP,查询时两跳;改写成直接调用的选项默认关,源码 TODO 承认它总取第一个实现、需要接收者类型才做得好(`objectivec/objc.cpp:1182-1184`、`rewrite_to_direct_call.rs`)。 + - 引用分代码、数据、类型、变量四类,另有类型字段引用(`get_code_refs_for_type_field`);6.0 新增 `get_derived_string_code_refs`(派生字符串,例如 CFString 的代码引用)。数据流只在函数内做(`docs/dev/concepts.md:160`)。 + - 界面里引用列表有上限(`ui.maxXrefItems = 1000`),超出时计数后面带 `+`;可按方向、种类过滤。 + - 6.0 自带 MCP 服务器:GUI 内的 HTTP 版随所有 GUI 版本提供(含 Personal),能查交叉引用、调用者、反汇编、IL 与伪代码;无界面的 `binaryninja_mcp` 只随 Commercial / Ultimate。地址在输出里一律写成十六进制字符串,「so clients do not lose precision when handling 64-bit addresses」;列表结果带 `count`、`total`、`nextOffset`、`truncated`(应用内 `docs/guide/mcp.html`)。 + +### 验证过什么 + +- 已验证(引自现有文档与记忆):进程内分析器的吞吐数字;`ThunkAddressSpace` 的地址约定与三种错误换算(macOS 26 SwiftUI);`UINSPasteboardWritingItemProvider` 的两个经 GOT 的调用者(27.0、27.2);`dyld_info` 的 2,195 个错名桩(26.7 SwiftUICore)。 +- IDA 与 Binary Ninja 的交叉引用实测(2026-11-18,Finder 26.5.2 与 ControlCenter 26.7,详见愿景「我们选的方向」第 1 条):代码引用召回 IDA 一次查询 97.0%、两跳 99.4%,Binary Ninja 经 MCP 67.6%。三处双方的盲点直接变成本提案的测试用例:恰好页对齐的类对象(`adrp; add #0`,IDA 漏)、Swift 大字符串的 `adrp; add; sub #0x20`(Binary Ninja 漏)、`retab` 之后没建函数的异常清理代码(Binary Ninja 漏)。 +- 卷上有 cache 文件的版本:macOS 15.5、26.0(单文件);26.5.2、26.6.2、26.7(12 个子文件);27.0(79 个)、27.2(81 个)。本机运行 27.2。 +- **推测,第 1、4 步先实测**: + - 离线模式的吞吐。cache 在外置卷上、冷读几个 GB 的映射文件,预计比进程内慢,慢多少不知道。 + - 文件模式下能否拿到 `__text` 的连续只读字节(`swift-fileio` 的映射能否按区间给出指针),拿不到就按镜像把 `__text` 读进一块缓冲区。 + - `MachOFile.functionStarts` 在 cache 镜像上的偏移语义。 + - macOS 27 的 cache **文件**里各镜像的 `__objc_stubs` 是否也是 0 大小(文档只说进程内为 0)。 + +## 提议方案 + +### 1. 读取抽象:`CrossReferenceMemory` + +分析器里所有「按地址读」都改走一个 package 级协议 `CrossReferenceMemory`,它只回答分析器真正问的几个问题: + +- 某个镜像某个区间的**连续只读字节**(扫描热循环用,循环本身不变,仍对一段缓冲区逐条解码); +- 某个**槽**里装的是什么(目标地址,或导入符号名); +- 某个地址处的 C 字符串; +- 去掉指针认证位的掩码。 + +两种实现: + +- `InProcessCrossReferenceMemory`:今天的行为原样搬进来——读 dyld 已绑定的值、按 `vmaddrSlide` 换算。 +- `FileCrossReferenceMemory`:基于 `FullDyldCache` 或一组 `MachOFile`。代码字节来自映射的文件;槽的内容由 fixup 解码得到——cache 镜像里 GOT 是 rebase(指向别的镜像或本镜像的类对象),独立文件里是 bind、self-bind 或 rebase。地址约定沿用 `ThunkAddressSpace`:未滑动地址 − `sharedRegionStart`。 + +协议选「分析器专用的小协议」而不是直接用 `ReadingContext`:`ReadingContext` 回答「按类型读一个元素」,分析器要的是「槽里装着谁」——在进程内是读已绑定的值,在文件里是解 fixup,这层差别正是两种模式唯一的本质区别。`FileCrossReferenceMemory` 内部仍用 `ReadingContext` 读元素。 + +### 2. 按层拆成三个模块 + +交叉引用拆成三个模块,依赖从上到下: + +| 模块(本库里的名字) | 管什么 | 将来的落脚处与名字 | +|---|---|---| +| `CrossReferenceCore` | 镜像表与读取抽象(进程内、文件两种)、函数表(起点、符号与导出名、data in code)、本镜像桩与 GOT、stub island、指令扫描与寄存器跟踪、跳板设定的寄存器常量、间接调用的指针认证常量、C 字符串与 CFString、链接关系与导入名预筛、符号化的通用部分、识别器扩展点 | MachOKitExtensions,`MachOCodeReferences` | +| `CrossReferenceObjC` | `objc_msgSend` 系列与 libobjc 专用入口、`__objc_stubs` 与 cache 共用 selector 桩的含义、`x1` 的 selector 与 `x0` 的接收者、classref / superref / 类对象、ivar 偏移变量、ObjC 方法列表给出的回退名、selector 与类的预筛、`objc_*` 运行时辅助函数 | MachOObjCSection,`ObjCCodeReferences` | +| `CrossReferenceAnalysis`(原模块) | Swift 元数据访问器、值类型元数据、mangled name 实例化、`SymbolicDemangler` 起名、Swift 类型预筛、`swift_*` 运行时辅助函数;把三层拼成对外的 `CrossReferenceAnalyzer`,持有全部公开模型 | 留在本库 | + +`CodeAddressResolution`(第 3 节)在核心层之下,将来随核心一起迁到 MachOKitExtensions,改名 `MachOAddressResolution`。 + +**扩展点:识别器。** 每个语言层有一个识别器(每个分析器一个,建分析器时读一次自己要的运行时符号,按镜像记住自己的索引),它为每次扫描造一个会话;核心层定义会话协议 `CodeReferenceRecognitionSession`(单线程,持有这次扫描的记忆化与当前函数的状态)。核心的扫描循环只在「前期调研 · 按层拆分的依据」列出的五个时机问识别器:进入函数、解析不认识的调用目标、调用点、算出地址、读槽。识别器按顺序排成一列,核心逐个问,第一个认领的为准;新增一种语言的识别只是多一个识别器,核心不改。识别器产出的引用不经核心转手:各层定义自己的记录协议(`CodeReferenceRecording`、`ObjCCodeReferenceRecording`、`SwiftCodeReferenceRecording`),顶层实现全部三个,直接造出公开的 `CodeReference`。细节见「详细设计」。 + +**公开模型第一步全部留在顶层。** `CodeReferenceTarget`、`CodeReferenceTable`、`CodeReferenceIndex`、`CodeFunction` 都还在 `CrossReferenceAnalysis`;纯数据、不含语言的 `CodeLocation` 下移到核心层,`ReceiverClassHint` 下移到 ObjC 层,顶层 `@_exported import` 两个下层模块,RuntimeViewer 的 `import CrossReferenceAnalysis` 照旧看得到它们。两个下层模块这一步不做 library product,不对外承诺 API。下层模块对外该长什么样(例如没有 Swift 层时目标用什么类型表示),等迁移提案时有了具体的使用方再定。 + +**边界由测试守住。** 源码扫描测试逐层检查 import:核心层只许 import 将来 MachOKitExtensions 里也有的模块(MachOKit、MachOKitExtensions、读取层与基础模块迁移提案搬过去的那些、`CodeAddressResolution`、`ARM64InstructionDecoding`、Foundation);ObjC 层在此之上多一个 MachOObjCSection;两层都不许出现 `MachOSwiftSection`、`SwiftInspection`、Demangling。核心层的源码里还不许出现 `objc_` 与 `swift_` 开头的符号名字面量——运行时的名单属于各自的层。 + +**本库里的名字刻意不同于落脚处的名字。** 理由见「前期调研 · 按层拆分的依据」的「模块名与版本」:本库只要发布过一个与 MachOKitExtensions 2.x 新模块同名的模块,旧版本本库与新版本 MachOKitExtensions 就解析不到一起;而且基础模块迁移之后,本库带 `MachO` 前缀的模块只留 ABI 模型。搬的时候改名,只动本库内部的 import——两个下层模块不是 product,没有外部使用方。 + +**为什么分两步。** 本提案还有四项「先实测」的未知(离线吞吐、`__text` 能否连续读、`functionStarts` 在 cache 镜像上的语义、27 的 cache 文件里 `__objc_stubs` 的大小);识别器的接口也要在扫描热路径上量过才算定下来。在一个仓库里改这些只要改一处;跨三个仓库时核心每改一次都要按 MachOKitExtensions → MachOObjCSection → 本库的顺序发版。拆分在本库里做完、量过、跑稳,迁移就只剩机械地搬文件。 + +### 3. 抽出 `CodeAddressResolution` + +把 `SwiftThunkAnalysis` 里与 Swift thunk 无关的离线解析抽成新的 package 模块 `Sources/Analysis/CodeAddressResolution`,`SwiftThunkAnalysis` 与 `CrossReferenceCore` 共用: + +- `ImageAddressSpace`:原 `ThunkAddressSpace`,地址约定与它的长注释一起搬。 +- `CacheImageLocator`:原 `CacheImageResolver`,「地址 → cache 镜像」与按路径懒打开。 +- `StubChainResolver`:桩、ld64 跳板、stub island 多跳、27 的 cache 共用 selector 桩与 GOT 桩 → 最终目标(函数地址或导入符号名),连同跳板一路设定的寄存器常量(cache 共用 selector 桩在 `x1` 里放的地址),并记下经过的每一跳。常量是什么意思(selector)由 ObjC 层解释,这个模块不认识 selector。 +- `SlotResolver`:任意指针槽 → 里面装着谁(rebase 的目标地址,或 bind 的符号名)。GOT、auth GOT 与 ObjC 的 selref / classref / superref / protoref、ivar 偏移变量共用它;哪个节算哪种槽由上层说。 + +这个模块只依赖 MachOKit、MachOKitExtensions 与读取层,不碰 Swift 与 ObjC 元数据,将来随核心层一起迁进 MachOKitExtensions(见第 2 节)。 + +### 4. 文件模式的分析器 + +```swift +let cache = try FullDyldCache(url: URL(filePath: "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e")) +let analyzer = try CrossReferenceAnalyzer(dyldCache: cache) +``` + +镜像表来自 cache 头的 `imageInfos`;`imagePaths`、`imageIndex(forPath:)`、函数表、预筛、`referenceTable` 等全部照旧可用。`location(ofRuntimeAddress:)` 在 cache 文件模式下接受的就是未滑动地址;一组独立文件里各文件按 dyld 的做法错开(与已放下的重叠就滑到其后的下一个 MB 边界),那时它接受的是错开后的地址。`images: [MachOImage]` 在文件模式下为空,只在文档注释里写明,不标 deprecated(见决策日志);`imageCount` 在两种模式下都给镜像数。 + +实现(第 4 步):每个镜像由核心层的 `CodeImage` 描述——`reader` 是 `MachOImage` 或 `MachOFile`,两种读取器的差别(slide、读取器 API 给出的 offset 落在哪个地址)只在构造它的地方定一次;`__LINKEDIT` 里的表(符号表、间接符号、函数起点、data in code、导出树)一律按「`__LINKEDIT` 的地址 + 表的偏移 − 段的文件偏移」经读取层读(`ImageLinkEdit`),进程内与文件里是同一个算法。ObjC 层与 Swift 层用到 MachOObjCSection / MachOSwiftSection 各读取器一套的 API 时,经 `asMachOImage` / `asMachOFile` 或 `MachOSwiftSectionRepresentableWithCache` 打开。文件读取层 `FileCrossReferenceMemory` 是个值,以 `unowned(unsafe)` 引用由镜像集持有的存储:经 existential 的每次读都复制一次读取层,类或持有引用的值每次复制都要计数,整 cache 建表因此慢过 6 倍。cache 的槽按 mapping 预取的 slide info 解:v5(macOS 14 / iOS 17 起的 arm64e cache)在读取层里直接解,其余交给 MachOKit。 + +### 5. 新的引用种类与引用路线 + +各种引用落在哪一层写在每条末尾。 + +- **ObjC ivar**:`adrp` + `ldrsw`(或 32 位 `ldr`)读 `__objc_ivar` 里的偏移变量 → `.objectiveCInstanceVariable(className:name:)`。解码器补 `ldrsw` 与 32 位 `ldr`。名字取自偏移变量的符号 `_OBJC_IVAR_$_<类>.`;没有符号时从类的 ivar 列表反查(ivar 记录里的 `offset` 字段指向这个槽)。ObjC 层,经「读槽」时机。 +- **C 字符串字面量**:`adrp` + `add` 落进 `__cstring` / `__objc_methname` / `__oslogstring`,且没被当作 selector 用掉 → `.cString(String)`。覆盖 `objc_getClass("…")`、`sel_registerName`、`dlsym` 一类调用。核心层;识别器按顺序问,ObjC 层先认领当作 selector 的那些。Swift 大字符串字面量的写法是 `adrp; add; sub #0x20`(对象里存的是「地址 − 0x20」),也要认成指向那段字符的引用——Binary Ninja 在实测里正是漏在这里。这个写法是 Swift 的约定,由 Swift 层的识别器认出,记成同一种 C 字符串引用。 +- **CFString 常量**:`adrp` + `add` 落进 `__cfstring` → 解出字符串指针 → `.constantString(String)`。覆盖 `NSSelectorFromString(@"…")`、`NSUserDefaults` 键一类用法。核心层:`__cfstring` 的结构是 CoreFoundation 的链接约定,不依赖 ObjC 运行时。 +- 两种字符串引用默认**不记录**:它们数量大,RuntimeViewer 常驻的索引不需要。构造分析器时用 `recordingStringReferences: true` 打开,`swift-section refs --string` 会自动打开。 +- **对其他镜像符号的数据引用**(第 4 步核对时补进来):只分析一个 app 而不带它链接的库时,经 GOT 槽读别的镜像的类(`adrp; ldr x0, [_OBJC_CLASS_$_CALayer@GOT]`)、ivar 或数据,槽里是 bind,读出的是导入名而不是地址,现在什么都不记——进程内槽里是地址,会记成类引用。改为记一条指向导入符号的 `.reference`,ObjC 层再把 `_OBJC_CLASS_$_<类>` 认成按名字的类引用。核心层(读槽时机拿到导入名)加 ObjC 层。 +- **引用路线**:`CodeReference` 新增 `route`,说明引用是怎么到达目标的。照 Binary Ninja 的「引用按来源种类建模」,但只在代码引用上加一个字段,不引入数据引用(见非目标)。 + +### 6. 地址符号化 + +```swift +let symbolication = analyzer.symbolication(of: 0x1_9012_3450) +// symbolication.meaning == .stub(hops: [0x1_9012_3450], target: .messageSend(selector: "setFrame:", receiver: .unknown)) +``` + +回答「这个地址是什么」,按顺序判断:在某个函数体里(函数起点、名字、偏移;名字来自符号、`ImageFallbackNames` 的回退名);是桩或 stub island 的跳板(每一跳与最终目标);是一个槽(槽的种类与里面装的目标);是 C 字符串或 CFString(内容);以上都不是时给最近的前一个符号加偏移;不在任何映射里时如实说没有映射。判断顺序与函数、桩、槽、字符串的结构由核心层给出;桩的最终目标与槽里的东西是什么(selector、类、Swift 类型)、没有符号的函数叫什么,由 ObjC 层与 Swift 层经同一列识别器补上。 + +### 7. `swift-section refs` 与 `swift-section symbolicate` + +```text +swift-section refs --selector makeKeyAndOrderFront: --dyld-shared-cache /Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e +swift-section refs --class UINSPasteboardWritingItemProvider --uses-system-dyld-shared-cache --json +swift-section refs --function 0x1880a1000 --callees --uses-system-dyld-shared-cache +swift-section refs --string NSWindowDidBecomeKeyNotification --in-image AppKit /path/to/Foo.app/Contents/MacOS/Foo +swift-section symbolicate 0x19012345 0x1e1226590 --dyld-shared-cache /Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e +``` + +- 查询(恰好一个):`--selector`、`--symbol`(C 符号、Swift 修饰名、`_OBJC_CLASS_$_…`)、`--class`、`--function <地址>`(以它开头或包含它的函数的调用者;加 `--callees` 改列它引用了什么)、`--ivar <类>.`、`--string <文本>`。 +- 输入:一个或多个独立 Mach-O 文件,或 `--dyld-shared-cache <路径>`,或 `--uses-system-dyld-shared-cache`;`-a/--architecture`。`--in-image` 可重复,限定扫描哪些镜像。 +- 输出:文本每条引用一行——镜像短名、所在函数名加偏移、调用点地址、引用种类与路线;`--json` 输出一个 JSON 文档,地址一律写成十六进制字符串(照 Binary Ninja MCP 的理由:避免客户端丢失 64 位精度)。 +- `--limit ` 截断时如实标出 `isTruncated`。 + +### 8. RuntimeViewer:CLI 与 MCP + +按 0056 §8 原定的设计实现它暂缓的第 4 步,并加上符号化: + +- CLI 子命令 `callers`、`callees`、`references`、`symbolicate`;目标写法照 0056:`-[类 sel]`、Swift 名、符号名,或 `0x…` 加 `--image`;选项 `--selector`、`--scope image|indexed`、`--receiver`、`--include-runtime`、`--limit`。CLI 协议版本 `CommandLineProtocol.version` 由 2 升到 3。 +- MCP 工具 `Callers`、`Callees`、`TypeReferences`、`Symbolicate`,`@MCPTool(hints: [.readOnly])`,照现有工具带 `windowIdentifier`;每次最多等 30 秒,`isComplete == false` 时返回部分结果。 +- 只覆盖活的引擎(本机、Catalyst、注入的进程);文件引擎见非目标。 + +### 非目标 + +- **把核心层与 ObjC 层真正迁出本库**,以及迁出后两个下层模块对外的公开模型:另写迁移提案(见第 2 节)。那份提案要定的事先记在这里——下层的引用目标在没有 Swift 层时用什么类型表示;`ARM64InstructionDecoding` 是否一起迁、迁过去叫什么;`IndirectCallEvidence.Table` 里 vtable / PWT / VWT 这些 Swift 的叫法留在核心还是改由 Swift 层分类;进程内构造器在 MachOKitExtensions 承诺的 Linux 上怎么条件编译;MachOObjCSection 发 0.9.0 时怎样与本库的版本要求衔接。 +- **落盘索引**:沿用 0072 与 RuntimeViewer 0056 的决定。第 4 步实测离线吞吐,结果写进模块文档,是否需要持久化由愿景的后续阶段决定。 +- **数据引用**(方法表条目 → IMP、CFString → 字符串这类「数据 → 地址」)与其余数据解码(KeyPath、ObjC 字面量、Swift 字符串):愿景第 3 阶段。 +- **带注解的反汇编、函数清单命令**:愿景第 2 阶段。 +- **跨基本块的常量追踪、调用点常量参数普查**:愿景第 4 阶段。 +- **接收者类型推断、Swift 字段级引用**。 +- **x86_64**。 +- 0072「后续」里列的其余项:协议见证与 override 的起名、`objc_getClass("…")` 解析成类引用(本提案只把它记成 C 字符串引用)、Swift 的 super 发送、协议类型引用。 +- **RuntimeViewer**:CLI 直接读文件引擎、文件引擎上的交叉引用(RuntimeViewer「暂缓的后续项」里的另一条)、MCP 无头化(RuntimeViewer 愿景《无头 RuntimeViewer》的「之后可以接」)。 +- **idax 建库时写入桩名与 Swift 函数名**:IDA 已降为后备。 + +## 改动地图 + +步骤号对应「落地步骤」。第 2 步把文件按层搬家;之后各行的路径写的是搬家后的位置(核心层 `Sources/Analysis/CrossReferenceCore/`,ObjC 层 `Sources/Analysis/CrossReferenceObjC/`,Swift 层仍是 `Sources/Analysis/CrossReferenceAnalysis/`)。 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Analysis/CrossReferenceAnalysis/Memory/CrossReferenceMemory.swift` · `CrossReferenceMemory` | 新增 | package 协议:区间字节、槽内容、C 字符串、指针掩码;第 2 步随核心层搬到 `CrossReferenceCore/Memory/` | 两种模式唯一的本质差别收在这里 | 1、2 | +| `…/Memory/InProcessCrossReferenceMemory.swift` · `InProcessCrossReferenceMemory` | 新增 | 搬入现有的直接读指针与 slide 换算 | 进程内行为不变 | 1、2 | +| 现有 22 处 `UnsafeRawPointer(bitPattern:)`(`ReferenceScanner`、`ObjectiveCClassIndex`、`SwiftTypeIndex`、`ImageFunctionTable`、`+SwiftTypes`、`+Prefiltering`、`ImageFallbackNames`)、`StoredPointer` | 修改 | 改走 `CrossReferenceMemory`;掩码由 memory 提供 | 读取抽象;文件模式没有 `InProcessContext` | 1 | +| `Sources/Analysis/CrossReferenceCore/` | 新增 | 核心层模块:`CodeLocation`、`CodeReferenceRoute`、`IndirectCallEvidence`(由顶层下移),镜像表、函数表、扫描循环、寄存器跟踪、链接关系与导入名预筛、`RenamedReexportIndex` | 按层拆分 | 2 | +| `…/CrossReferenceCore/Recognition/CodeReferenceRecognition.swift` · `CodeReferenceRecognitionSession`、`CodeReferenceRecording`、`ResolvedCallTarget`、`ScanSite` | 新增 | package 协议:会话在五个时机(进入函数、解析只有它认得的调用目标、调用点、算出地址、读槽)被问;核心层产出的引用交给谁 | 扩展点;核心不认识任何语言;引用不经核心转手 | 2 | +| `…/CrossReferenceCore/Images/CodeImageSet.swift`、`CodeImageSet+Linkage.swift` · `CodeImageSet`、`RuntimeLibraryRules` | 新增 | 由 `CrossReferenceAnalyzer` 里与语言无关的部分拆出:镜像与映射、按镜像缓存的函数表、锁、`releaseImageData` 的核心部分 | 顶层门面之下的核心状态 | 2 | +| `…/CrossReferenceCore/Scanning/ReferenceScanner.swift` | 修改(搬家) | 只留通用识别;ObjC 与 Swift 的分支改成在五个时机问识别器;`findsTypeReferences` 一类的跳过改成每个识别器按这次查询要的种类决定 | 按层拆分 | 2 | +| `…/CrossReferenceCore/Scanning/RegisterFile.swift` | 修改(搬家) | `methodReceiver` 状态换成识别器可用的寄存器标记位(随 `mov` 复制、写入即清除、调用后按识别器给的保留集合保留) | 去掉核心里唯一的 ObjC 状态 | 2 | +| `…/CrossReferenceCore/Scanning/ImageFunctionTable.swift` | 修改(搬家) | ObjC 节的范围(`__objc_stubs`、selref、superref、classref)移出,只留函数起点、名字、data in code、本镜像桩、GOT、段范围 | 按层拆分 | 2 | +| `Sources/Analysis/CrossReferenceObjC/` · `ObjCCodeReferenceRecognizer`、`ObjCCodeReferenceRecording` | 新增 | ObjC 层模块:发送与 super 发送、libobjc 专用入口、`__objc_stubs` 与跳板常量里的 selector、接收者、classref / superref / 类对象、`objc_*` 运行时辅助函数、`ReceiverClassHint`(由顶层下移) | 按层拆分 | 2 | +| `…/CrossReferenceObjC/ObjectiveCClassIndex.swift`、`MessageSendEntryPoints.swift` | 修改(搬家) | 原样搬入 | 属于 ObjC 层 | 2 | +| `…/CrossReferenceObjC/ObjCImageSections.swift`、`ObjCMethodNames.swift` | 新增 | 由 `ImageFunctionTable` 拆出的 ObjC 节范围与方法标记;由 `ImageFallbackNames` 拆出的 ObjC 方法列表回退名 | 按层拆分 | 2 | +| `…/CrossReferenceObjC/` 预筛 | 修改(搬家) | `imageIndices(referencingSelector:)`、`imageIndices(referencingObjectiveCClassAt:)`、`objectiveCClassLocations(named:)` 的实现由 `+Prefiltering` 搬来,顶层门面转发 | 按层拆分 | 2 | +| `Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift` · `SwiftCodeReferenceRecognizer` | 新增 | 由扫描器拆出的 Swift 部分:元数据访问器、值类型元数据、mangled name 实例化辅助函数与运行时入口、`swift_*` 运行时辅助函数、`swift_getInitializedObjCClass` 的 `x0` 保留 | 按层拆分 | 2 | +| `…/CrossReferenceAnalysis/Scanning/SwiftMetadataNames.swift`、`…/CrossReferenceCore/Scanning/ExportedFunctionNames.swift` | 新增 | 由 `ImageFallbackNames` 拆出:Swift 元数据回退名(Swift 层)、导出 trie 的名字(核心层),都是函数表附件 | 按层拆分 | 2 | +| `…/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift` · `CrossReferenceAnalyzer` | 修改 | 变成门面:持有 `CodeImageSet` 与两个识别器,实现三个记录协议造出公开的 `CodeReference`;公开方法签名不变;`@_exported import` 两个下层模块;之后持有 `CrossReferenceMemory`、拆出「进程」与「文件」两条构造、`images` 标 deprecated | 公开 API 不变;支持文件模式 | 2、4 | +| `…/CrossReferenceAnalysis/Scanning/RuntimeHelperNames.swift` | 改名 | 改名 `SwiftRuntimeHelperNames`,只留 Swift 的名单;libobjc 的名单移到 ObjC 层的 `ObjCRuntimeHelperNames` | 核心不许出现运行时名字 | 2 | +| `…/CrossReferenceAnalysis/Scanning/ImageFallbackNames.swift` | 删除 | 三种来源拆成三层各自的函数表附件,起名顺序留在门面的 `codeFunction(at:in:)` | 按层拆分 | 2 | +| `Sources/Analysis/CrossReferenceAnalysis/Exports.swift`、`CrossReferenceAnalyzer+Linkage.swift`、`+Prefiltering.swift` | 新增 / 修改 | `@_exported import` 两个下层模块;公开预筛与链接方法转发到各层 | 公开 API 不变 | 2 | +| `Sources/Analysis/CodeAddressResolution/ImageAddressSpace.swift` · `ImageAddressSpace` | 新增 | 由 `ThunkAddressSpace` 搬来,连同地址约定的注释 | 两个分析模块共用 | 3 | +| `…/CodeAddressResolution/CacheImageLocator.swift` · `CacheImageLocator` | 新增 | 由 `CacheImageResolver` 搬来 | 同上 | 3 | +| `…/CodeAddressResolution/StubChainResolver.swift` · `StubChainResolver` | 新增 | 由 `MachOThunkEnvironment` 的桩链部分抽出,补 27 的 cache 共用桩,记录每一跳与跳板设定的寄存器常量 | 同上;符号化要每一跳 | 3 | +| `…/CodeAddressResolution/SlotResolver.swift` · `SlotResolver` | 新增 | 由 `MachOThunkEnvironment` 的槽解析抽出,泛化到任意指针槽 | 同上 | 3 | +| `Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift` | 修改 | GOT 桩的载入之后必须紧跟经同一寄存器的跳转 | 开头是 `adrp; ldr` 的普通函数被误认成桩 | 3 | +| `Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift` | 修改 | 改用上面四个类型,行为不变 | 去重 | 3 | +| `…/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift` · `ThunkAddressSpace` | 删除 | 调用点改用 `ImageAddressSpace` | 已搬走 | 3 | +| `…/CrossReferenceCore/Memory/FileCrossReferenceMemory.swift` · `FileCrossReferenceMemory` | 新增 | 值,`unowned(unsafe)` 引用镜像集持有的 `Storage`:MachOKit 映射的文件字节;cache 的槽按 mapping 预取的 slide info 解(v5 自己解,其余交给 MachOKit),独立文件的槽经 `SlotResolver`,bind 落到所覆盖文件的导出上 | 文件模式 | 4 | +| `…/CrossReferenceCore/Images/CodeImage.swift` · `CodeImage`、`ImageLinkEdit` | 新增 | 与读取器无关的镜像描述(slide、读取器 offset 与地址的换算只在构造处定一次);`__LINKEDIT` 的各表按地址经读取层读 | 两种模式共用一套读法 | 4 | +| `…/CrossReferenceCore/Images/CodeImageSet.swift` | 修改 | `images: [CodeImage]`;新增 `dyldCache(_:…)` 与 `files(_:…)` 两个构造器(独立文件按 dyld 的做法错开);持有文件读取层的存储 | 文件模式 | 4 | +| `…/CrossReferenceCore/Scanning/ImageFunctionTable.swift`、`ExportedFunctionNames`、`RenamedReexportIndex`、`CodeImageSet+Linkage` | 修改 | 符号、间接符号、桩、函数起点、data in code、导出树、依赖都改走 `CodeImage` / `ImageLinkEdit` | 文件模式 | 4 | +| `…/CrossReferenceObjC/ObjectiveCClassIndex.swift`、`ObjCMethodNames.swift`、`ObjCImageSections.swift`、`+Prefiltering` | 修改 | 类名、方法表、objc 桩按读取器分两条路读(MachOObjCSection 的 API 各一套,文件里 `imp` 是读取器 offset);按名字导入的 `_objc_msgSend` 认成发送 | 文件模式 | 4 | +| `…/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift`、`SwiftMetadataNames.swift`、`CrossReferenceAnalyzer+SwiftTypes.swift` | 修改 | 经 `MachOSwiftSectionRepresentableWithCache` 泛型读描述符;文件里的 mangled name 经文件的读取上下文解 | 文件模式 | 4 | +| `…/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift`、`FileAnalysisError.swift` | 修改 / 新增 | `init(dyldCache:)`、`init(machOFiles:)`、`imageCount`、`FileAnalysisError` | 公开入口 | 4 | +| `…/CodeAddressResolution/SlotResolver.swift`、`ImageAddressSpace.swift` | 修改 | 独立文件的链式 fixup 目标按 `__TEXT` 加偏移换算(`address(forHeaderOffset:)`) | 修 bug:可执行文件的槽解错 4 GiB | 4 | +| `Tests/CrossReferenceAnalysisTests/FileModeTests.swift`、`StandaloneFileReferenceDumpTests.swift` | 新增 | 文件模式的行为测试;独立文件引用导出(按环境变量启用,供与反汇编器对照) | 验证 | 4 | +| `Sources/Support/ARM64InstructionDecoding/ARM64InstructionWord.swift` | 修改 | `load(_:)` 之外新增 32 位 `ldr` 与 `ldrsw` 的解码 | ivar 偏移变量的读法 | 5 | +| `…/CrossReferenceCore/Scanning/ReferenceScanner.swift`、`RegisterFile.swift` | 修改 | 记录 `route`;C 字符串与 CFString;跟踪 `ldrsw` / 32 位 `ldr` 读出的来源,交给识别器 | 引用路线;新引用种类 | 5 | +| `…/CrossReferenceObjC/ObjCCodeReferenceRecognizer.swift` | 修改 | ivar 偏移变量 → ivar 引用;selector 优先于 C 字符串认领 | 新引用种类 | 5 | +| `…/CrossReferenceAnalysis/SwiftCodeReferenceRecognizer.swift` | 修改 | Swift 大字符串字面量(`adrp; add; sub #0x20`)记成 C 字符串引用 | 新引用种类 | 5 | +| `…/CrossReferenceAnalysis/Models/CodeReference.swift` · `CodeReferenceTarget`、`CodeReference` | 修改 | 新增三个 target case;新增 `route`(类型是核心层的 `CodeReferenceRoute`,以 `CodeReference.Route` 暴露);旧初始化方法 deprecated | 新引用种类;引用路线 | 5 | +| `…/Models/CodeReferenceTable.swift` · `CodeReferenceTable.Key` | 修改 | 新增 `instanceVariable`、`cString`、`constantString` 键 | 按新目标查 | 5 | +| `…/Models/CodeReferenceIndex.swift` · `CodeReferenceIndex` | 修改 | 编码新 target 与 `route` | 常驻索引也要带上 | 5 | +| `…/CrossReferenceAnalyzer+Prefiltering.swift` 及两层的预筛 | 修改 | 新增 ivar(ObjC 层)与字符串(核心层)的预筛 | 新查询 | 5 | +| `…/CrossReferenceAnalysis/Symbolication/AddressSymbolication.swift` · `AddressSymbolication` | 新增 | 公开的符号化结果模型(顶层,因为它带 `CodeReferenceTarget`) | 符号化 | 6 | +| `…/CrossReferenceCore/Symbolication/`、`…/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift` · `symbolication(of:)` | 新增 | 核心按「函数 → 桩 → 槽 → 字符串 → 最近符号 → 未映射」判断结构,识别器补含义与名字,门面组装 | 符号化 | 6 | +| `Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift` | 新增 | 由文件、cache 或本机 cache 建分析器 | 两个子命令共用 | 7 | +| `…/SwiftSectionKit/CrossReferences/ReferencesRequest.swift` · `ReferencesRequest` | 新增 | 预筛 → 并发逐镜像查 → 起名 → 文本 / JSON | `refs` 的逻辑 | 7 | +| `…/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift` · `SymbolicateRequest` | 新增 | 批量符号化 → 文本 / JSON | `symbolicate` 的逻辑 | 7 | +| `…/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift` | 新增 | 文本与 JSON 的拼写(`CrossReferenceJSONValue`、目标起名) | 两个子命令共用,JSON 名字即契约 | 7 | +| `Sources/Analysis/CrossReferenceCore/Images/CodeImageSet+SymbolLookup.swift`;门面 `locations(ofSymbolNamed:among:)` | 新增 | 按名字在导出表与符号表里找定义 | `refs --symbol` / `--class` | 7 | +| `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift` · `ReferenceCollector` | 修改 | 键集合拷一份自己的 | 并发共用键集合时的引用计数争抢 | 7 | +| `Sources/Executables/swift-section/Commands/ReferencesCommand.swift`、`SymbolicateCommand.swift` | 新增 | flag、`validate()`、`makeRequest()` | CLI 入口 | 7 | +| `Sources/Executables/swift-section/Models/CrossReferenceInputOptionGroup.swift` | 新增 | 多文件 / cache / 本机 cache、`-a`、`--in-image` | 现有选项组只产出单个 `MachOFile` | 7 | +| `Sources/Executables/swift-section/SwiftSectionCommand.swift` | 修改 | 登记两个子命令 | CLI 入口 | 7 | +| `Sources/Executables/swift-section/Models/CommandLineSupport.swift` | 修改 | `--in-image` / `--function-image` 的错误译成退出码 64 | 用法错误按惯例 | 7 | +| `Package.swift` | 修改 | 新增 `CrossReferenceCore`、`CrossReferenceObjC`、`CodeAddressResolution` 三个 target(不做 product);`CrossReferenceAnalysis` 依赖前两个,`CrossReferenceCore` 与 `SwiftThunkAnalysis` 依赖第三个;`SwiftSectionKit` 与 `swift-section` 依赖 `CrossReferenceAnalysis` | 模块图 | 2、3、7 | +| `Tests/CrossReferenceAnalysisTests/CrossReferenceLayerBoundaryTests.swift` | 新增 | 源码扫描:每层只 import 允许的模块;核心层没有 `objc_` / `swift_` 字面量 | 守住拆分的边界 | 2 | +| `Tests/CrossReferenceAnalysisTests/…` | 新增 | 对照、按层拆分、文件模式、新种类、符号化测试(见落地步骤) | 验证 | 1–6 | +| `Tests/CodeAddressResolutionTests/…` | 新增 | 桩链、槽解析测试 | 验证 | 3 | +| `Tests/SwiftThunkAnalysisTests/…` | 修改 | 抽取前后结果一致的守护测试 | 去重不改行为 | 3 | +| `Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift`、`Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift` | 新增 | `refs` / `symbolicate` 的文本与 JSON 输出、flag 映射与拒绝的组合 | 验证 | 7 | +| `Documentations/Internal/Modules/CrossReferenceAnalysis.md` | 修改 | 三层的分工与识别器;文件模式、读取抽象、新种类、路线、符号化、拆分前后与离线吞吐实测 | 模块参考 | 2、4–6 | +| `Documentations/Internal/Modules/CrossReferenceCore.md`、`CrossReferenceObjC.md`、`CodeAddressResolution.md` | 新增 | 三个新模块的参考;各写明将来的落脚处与名字 | 模块参考 | 2、3 | +| `AGENTS.md`(模块层级图与各模块说明)、`Documentations/README.md` | 修改 | 登记三个新模块与它们的去向 | 项目约定 | 2、3 | +| `Documentations/Visions/ReverseEngineeringWithoutIDA.md` | 修改 | 「我们选的方向」第 6 条:语言无关的分析核心也归 MachOKitExtensions,ObjC 专属归 MachOObjCSection | 愿景与提案一致 | 2 | +| `AgentPlugins/swift-section/skills/swift-section-cli/` | 修改 | 两个新子命令的用法与坑 | `AGENTS.md` 要求 | 7 | +| `README.md`(CLI 一节) | 修改 | 列出两个新子命令 | 面向用户 | 7 | +| `Documentations/Internal/ProjectEvolutionLog.md`、`Documentations/Glossary.md` | 修改 | 追加本批次;登记「符号化」「引用路线」「识别器」「stub island」等术语 | 文档约定 | 9 | +| RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift` | 修改 | `switch reference.target`(`:92`)补三个新 case | 穷尽 switch 会编译失败 | 5 | +| RuntimeViewer `…/RuntimeViewerCrossReferences/`(新文件)· 符号化引擎命令 | 新增 | 引擎侧 `crossReferenceSymbolicate` 与 `crossReferenceLocateSymbol` 两个命令,`RuntimeEngine.symbolicate(_:inImageAt:)`、`locations(ofSymbolNamed:)`,线上类型 `RuntimeAddressSymbolication`、`RuntimeSymbolLocation` | CLI / MCP 的符号化与按名字找函数 | 8 | +| RuntimeViewer `…/RuntimeViewerCrossReferences/RuntimeCrossReferenceTargetResolution.swift` | 新增 | 目标写法(方法、Swift 成员、符号、地址、selector)→ 查询主体,CLI 与 MCP 共用 | 两个前端一套写法 | 8 | +| RuntimeViewer `…/RuntimeViewerCrossReferences/Models/RuntimeCrossReferenceRow.swift`、`RuntimeAddressSymbolicationRow.swift` | 新增 | CLI `--json` 与 MCP 每行字段的唯一来源,地址一律十六进制字符串 | 字段名一致 | 8 | +| RuntimeViewer `…/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift`、`Models/RuntimeCrossReferenceError.swift` | 修改 | 两处穷尽 switch 补三个新目标(不显示);符号化与按名定位的实现;错误加 `addressNeedsImage`、`targetNotFound`、`ambiguousTarget` | 源码兼容;新命令 | 8 | +| RuntimeViewer `…/Model/CommandFailure.swift` | 修改 | 失败代码加 `targetNotFound`、`crossReferencesUnavailable` | CLI | 8 | +| RuntimeViewer `Documentations/Guides/CommandLineInterface.md`、`AgentPlugins/runtime-viewer/`(skill 与两个清单 1.3.0)、`README.md` | 修改 | 四个子命令与目标写法 | RuntimeViewer 的 AGENTS.md 要求 | 8 | +| RuntimeViewer `RuntimeViewerCommandLine/Sources/RuntimeViewerCommandLineInterface/Model/Command.swift`、`CommandResult.swift` | 修改 | `.callers` / `.callees` / `.references` / `.symbolicate` 与结果 | CLI | 8 | +| RuntimeViewer `…/CommandLine/Subcommands.swift`、`Execution/CommandExecutor.swift`、`Rendering/TextRenderer.swift` | 修改 | 四个子命令的解析、执行与显示 | CLI | 8 | +| RuntimeViewer `…/Protocol/WireMessage.swift` · `CommandLineProtocol.version` | 修改 | 2 → 3 | 新增命令 | 8 | +| RuntimeViewer `RuntimeViewerMCP/Sources/RuntimeViewerMCPBridge/MCPBridgeServer.swift`、`MCPBridgeProtocol.swift` | 修改 | `Callers`、`Callees`、`TypeReferences`、`Symbolicate` 四个工具,30 秒等待 `references(within:_:)`,响应类型 `MCPCrossReferencesResponse` 等 | MCP | 9 | +| RuntimeViewer `Documentations/Evolutions/README.md`、`0056-cross-references.md` | 修改 | cross-repository draft 一行;暂缓表第 4 步指向本提案 | 提案索引 | 9 | +| RuntimeViewer `AgentPlugins/runtime-viewer/`、`Documentations/Guides/CommandLineInterface.md`、`Documentations/Evolutions/README.md` | 修改 | skill 与两个插件清单的 version;使用指南;`cross-repository draft` 一行 | 文档同批 | 8、9 | + +## 架构图 + +改了什么——模块与依赖(箭头指向被依赖的一方;方括号里是将来的落脚处): + +```text +MachOSwiftSection + Sources/Executables/swift-section ++ refs, symbolicate ───────────────────────────────┐ + Sources/Commands/SwiftSectionKit │ ++ CrossReferences/ReferencesRequest, SymbolicateRequest, CrossReferenceInput + v + Sources/Analysis +~ CrossReferenceAnalysis Swift layer + public facade [stays] +~ CrossReferenceAnalyzer facade: CodeImageSet + recognizers; implements the three recordings ++ SwiftCodeReferenceRecognizer accessors, value metadata, mangled names, swift_* helpers ++ SwiftMetadataNames (split from ImageFallbackNames) +~ CodeReferenceTarget, CodeReferenceTable, CodeReferenceIndex, CodeFunction public model stays here ++ AddressSymbolication + | @_exported import + v ++ CrossReferenceObjC package, not a product [MachOObjCSection: ObjCCodeReferences] ++ ObjCCodeReferenceRecognizer sends, entry points, selector stubs, receivers, class/super refs, ivars ++ ObjCCodeReferenceRecording +~ ObjectiveCClassIndex, MessageSendEntryPoints (moved) ++ ObjCImageSections, ObjCMethodNames (split from ImageFunctionTable, ImageFallbackNames) + | \ + v -> MachOObjCSection (package) ++ CrossReferenceCore package, not a product [MachOKitExtensions: MachOCodeReferences] ++ CodeReferenceRecognitionSession, CodeReferenceRecording, ResolvedCallTarget ++ CodeImageSet images, mappings, function tables (split from CrossReferenceAnalyzer) +~ ReferenceScanner, RegisterFile, ImageFunctionTable (moved; language-free) ++ CrossReferenceMemory: InProcessCrossReferenceMemory, FileCrossReferenceMemory +~ CodeLocation, CodeReferenceRoute, IndirectCallEvidence (moved down) + | + v ++ CodeAddressResolution package, not a product [MachOKitExtensions: MachOAddressResolution] ++ ImageAddressSpace, CacheImageLocator, StubChainResolver, SlotResolver + ^ +~ SwiftThunkAnalysis / MachOThunkEnvironment ─┘ +- ThunkAddressSpace, CacheImageResolver + + Sources/Support/ARM64InstructionDecoding +~ ARM64InstructionWord + 32-bit ldr, ldrsw + +RuntimeViewer +~ RuntimeViewerCrossReferences switch over new targets; + symbolicate engine command +~ RuntimeViewerCommandLine + callers, callees, references, symbolicate (protocol 2 -> 3) +~ RuntimeViewerMCPBridge + Callers, Callees, TypeReferences, Symbolicate +``` + +扫描一个函数时,核心层在哪里问识别器: + +```text +ReferenceScanner.scanFunction(at:) CrossReferenceCore + for session in sessions: session.enterFunction(...) ObjC: tag x0 as the method receiver + for each instruction: + bl / b out of the function + core: resolve target (own stubs, GOT, stub islands, other images via StubChainResolver) + not recognized? -> sessions: resolveCallTarget(...) ObjC: __objc_stubs selector + sessions: noteCall(callee, registers) ObjC: x1 selector, x0 receiver -> recordMessageSend + Swift: metadata accessor, mangled name -> recordSwiftType + no session claimed the call -> core: recordCall(.function / .importedSymbol / .unrecognized) + registers kept across the call = union of what the sessions return (objc_opt_self keeps x0) + adrp+add / adr built an address + core: C string, CFString (string references, when requested) + sessions: noteAddress(...) ObjC: class object; Swift: metadata, accessor, large string + ldr from a slot + sessions: noteSlotLoad(...) ObjC: classref, superref, ivar offset; Swift: GOT -> type + blr / braa + core: recordIndirectCall(pointer-authentication constant, displacement) + CrossReferenceAnalyzer (facade) implements every recording -> public CodeReference +``` + +一次 `refs` 查询的数据流: + +```text +swift-section refs --selector makeKeyAndOrderFront: --dyld-shared-cache + ReferencesCommand.makeRequest() + -> ReferencesRequest + -> CrossReferenceInput: FullDyldCache(url:) -> CrossReferenceAnalyzer(dyldCache:) + CodeImageSet from cache header imageInfos; FileCrossReferenceMemory over mapped subcache files + -> imageIndices(referencingSelector:among: all) prefilter (ObjC layer) + -> for each candidate image, concurrently: + references(to: [.selector("makeKeyAndOrderFront:")], inImageAt:) + ReferenceScanner over the image's __text bytes + bl X -> StubChainResolver(X) -> trampoline sets x1, ends at objc_msgSend + -> ObjC session: x1 constant is a selector -> .messageSend route .cacheSharedStub + adrp+ldr slot -> SlotResolver(slot) -> rebase target -> ObjC session: class object route .pointerSlot + -> functions(containing: sites) -> names (symbols, export trie, ObjC method lists, Swift metadata) + -> StandardStreamOutput: text rows | one JSON document +``` +## 详细设计 + +### 公开 API(`CrossReferenceAnalysis`) + +按全局 `apple-style-api-design` skill 的顺序,先写调用点: + +```swift +// Simplest: what is this address? +let analyzer = try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: cacheURL)) +print(analyzer.symbolication(of: 0x1_9012_3450)) + +// Most common: who sends a selector, across an archived cache. +let selectorKey = CodeReferenceTable.Key.selector("makeKeyAndOrderFront:") +for imageIndex in analyzer.imageIndices(referencingSelector: "makeKeyAndOrderFront:", among: analyzer.imagePaths.indices) { + for reference in analyzer.references(to: [selectorKey], inImageAt: imageIndex) { + print(analyzer.imagePaths[imageIndex], reference.instructionAddress, reference.route) + } +} + +// Most complex: an app and its frameworks, string references included. +let files = try appBundle.machOFileURLs.map { try MachOFile(url: $0) } +let appAnalyzer = try CrossReferenceAnalyzer(machOFiles: files, recordingStringReferences: true) +``` + +声明: + +```swift +extension CrossReferenceAnalyzer { + /// Analyzes every image of a dyld shared cache read from disk, such as an archived one. + /// `recordingStringReferences` arrives with step 5. + public convenience init(dyldCache: FullDyldCache, recordingStringReferences: Bool = false) throws + + /// Analyzes standalone Mach-O files, such as an app's executable and its embedded frameworks. + public convenience init(machOFiles: [MachOFile], recordingStringReferences: Bool = false) throws + + /// Why an analyzer could not be made from files: `Code.unsupportedArchitecture` for a cache or + /// a file holding no arm64 code. A struct with codes, since more may come. + public struct FileAnalysisError: Error, Hashable, Sendable { public let code: Code; public let path: String } + + /// The number of images the analyzer covers, in either mode. + public var imageCount: Int { get } + + /// What the address is: a place inside a function, a stub, a pointer slot, a string, or nothing mapped. + public func symbolication(of address: UInt64) -> AddressSymbolication +} + +extension CrossReferenceAnalyzer { + /// The in-process analyzer's images; empty for one made from files. Not deprecated: in-process + /// hosts read what only a `MachOImage` tells (its slide, its header). + public let images: [MachOImage] +} + +public enum CodeReferenceTarget: Hashable, Sendable { + // … the nine existing cases … + /// A load of an Objective-C instance variable's offset variable (`_OBJC_IVAR_$_Class.ivar`). + case objectiveCInstanceVariable(className: String, name: String) + /// A C string literal whose address the code materializes. Recorded only when string references are recorded. + case cString(String) + /// A constant `CFString` / `NSString` literal. Recorded only when string references are recorded. + case constantString(String) +} + +// CrossReferenceCore — re-exported by CrossReferenceAnalysis. +/// How the code reached what it references: the instructions and trampolines on the way, not what the target is. +public enum CodeReferenceRoute: UInt8, Hashable, Sendable { + /// `bl` / `b` straight to the target. + case direct + /// A stub in the referencing image's own stub sections (`__stubs`, `__auth_stubs`, `__objc_stubs`). + case imageStub + /// A trampoline in a dyld shared cache stub island, possibly after several hops. + case stubIsland + /// A stub shared by the whole cache: macOS / iOS 27's `objc_msgSend$…` selector stubs and GOT stubs. + case cacheSharedStub + /// `adrp` + `ldr` through a pointer slot: a GOT or auth GOT slot, or a slot of an Objective-C reference section. + case pointerSlot + /// `adrp` + `add`, or `adr`, computing the target's address. + case addressMaterialization + /// `ldr` of a literal pool entry. + case literalLoad + /// A call or a jump through a register — `blr`, `br` and their authenticating forms; the + /// evidence says what is known. (Was `authenticatedIndirect`; see the decision log.) + case indirect +} + +/// Whether the referencing instruction calls, leaves the function, or only takes an address. +public enum CodeReferenceKind: Hashable, Sendable { + case call + case tailCall + case reference +} + +// CrossReferenceAnalysis +extension CodeReference { + public typealias Route = CodeReferenceRoute + /// Was a nested enum; the cases are unchanged. + public typealias Kind = CodeReferenceKind + + public let route: Route + + public init(function: CodeLocation, instructionAddress: UInt64, kind: Kind, target: CodeReferenceTarget, route: Route, isRuntimeHelperCall: Bool) + + @available(*, deprecated, renamed: "init(function:instructionAddress:kind:target:route:isRuntimeHelperCall:)") + public init(function: CodeLocation, instructionAddress: UInt64, kind: Kind, target: CodeReferenceTarget, isRuntimeHelperCall: Bool) +} + +extension CodeReferenceTable.Key { + // new cases + case instanceVariable(className: String, name: String) + case cString(String) + case constantString(String) +} + +public struct AddressSymbolication: Hashable, Sendable { + public let address: UInt64 + public let imagePath: String? + public let segmentName: String? + public let sectionName: String? + public let meaning: Meaning + + public enum Meaning: Hashable, Sendable { + /// Inside a function's body. + case function(start: CodeLocation, name: String?, offset: UInt64) + /// A stub or stub-island trampoline; `hops` lists every trampoline passed through, starting with the address asked about. + case stub(hops: [UInt64], target: CodeReferenceTarget) + /// A pointer slot and what it holds. + case pointerSlot(PointerSlotKind, target: CodeReferenceTarget) + case cString(String) + case constantString(String) + /// None of the above: the nearest preceding symbol. + case symbol(name: String, offset: UInt64) + /// Mapped by an image, but none of the above and no symbol at or below it. + case data + /// Not inside any mapped image. + case unmapped + } + + public enum PointerSlotKind: Hashable, Sendable { + case globalOffsetTable + case selectorReference + case classReference + case superclassReference + case protocolReference + case instanceVariableOffset + } +} +``` + +(`CodeReferenceTable.Key` 的新 case 在实现里直接写进原 enum;上面用 extension 的写法只为标出新增部分。) + +命名取舍: + +- 用 **symbolication / symbolicate** 而不是 resolve:MachOKit 与 MachOKitExtensions 里 `resolveBind` / `resolveRebase` 的 resolve 指「解 fixup」,同一个词不能再指「说出地址是什么」;symbolication 是 Apple 自己的说法(`atos`、崩溃报告的 symbolication)。 +- 方法用名词短语 `symbolication(of:)`:它没有副作用,按 API Design Guidelines 读成名词短语。 +- `route` 不给默认值:它影响结果是否可信,按「影响正确性的参数不给默认值」处理;旧初始化方法保留一个版本并标 `renamed:`。 +- 路线只描述「代码怎么到达」,不描述「槽在哪个节」:原先列的 `selectorReference`(selref)与 `classReference`(classref / superref)并进 `pointerSlot`。路线由核心层产出,核心不认识 ObjC 的节;槽是哪一种,看引用的目标(selector 还是类)或对槽地址做符号化(`PointerSlotKind`)即可得知。 +- `Route` 与 `Kind` 定义在核心层、以 `CodeReference` 的 typealias 暴露:核心层要产出这两个值,而 `CodeReference` 本身留在顶层。`CodeReference.Kind.call` 一类写法照旧可用。 + +### 按层拆分与识别器(package) + +三层之间的接口全部是 `package` 级:两个下层模块这一步不做 product,接口还可以按实测改。下面是第 2 步实际做成的样子。 + +核心层的扩展点(`CrossReferenceCore/Recognition/CodeReferenceRecognition.swift`): + +```swift +/// One scan of one image by one language layer, on one thread. +package protocol CodeReferenceRecognitionSession: AnyObject { + /// Slots, unslid, holding references the session reads besides the core's GOT: `__objc_classrefs`. + var referenceSlotRanges: [Range] { get } + /// Slots a load from which the session watches on every load: `__objc_superrefs`. + var watchedSlotRanges: [Range] { get } + /// Whether the session looks at addresses built and slots loaded at all. + var looksForAddressReferences: Bool { get } + + /// A function starts; may tag registers (an Objective-C method's receiver in `x0`). + func enterFunction(at functionIndex: Int, registers: RegisterFile) + /// A target only this session can read (`__objc_stubs`); asked before the core resolves it. + func claimCallTarget(at target: UInt64) -> CallTargetClaim? + /// The session's role for a target the core resolved; asked once per distinct target of a scan. + func role(of target: ResolvedCallTarget) -> CalleeRole? + /// Records what the call stands for in place of the plain call reference — a message send. + func recordCallStandIn(_ call: ScannedCall, registers: RegisterFile) -> Bool + /// After the call's reference: records what it references besides (a Swift type); returns + /// the caller-saved registers, by bit, that keep their contents across it. + func noteCallMade(_ call: ScannedCall, registers: RegisterFile) -> UInt32 + /// An address an instruction built, at its runtime address; `isCode` when in the image's `__text`. + func recordAddressReference(toRuntimeAddress address: UInt, isCode: Bool, at site: ScanSite) -> Bool + /// A load from a reference slot that holds the runtime address `value`. + func recordSlotReference(holding value: UInt, at site: ScanSite) -> Bool + /// A load from one of `watchedSlotRanges`. + func noteWatchedSlotLoad(from slot: UInt64) +} + +/// Where the references a scan finds go; each language layer refines it. +package protocol CodeReferenceRecording: AnyObject { + func recordCall(to target: ResolvedCallTarget, targetAddress: UInt64, at site: ScanSite, isRuntimeHelperCall: Bool) + func recordIndirectCall(_ evidence: IndirectCallEvidence, at site: ScanSite) +} + +/// What the core resolves a call target to, knowing no language. +package enum ResolvedCallTarget: Hashable { + case function(CodeLocation) + case importedSymbol(UnsafePointer) + /// macOS / iOS 27's cache-shared selector stub: `x1` = the selector string, then a branch. + case registerSettingTrampoline(register: Int, value: UInt64) + case unrecognized +} +``` + +ObjC 层(`CrossReferenceObjC`)与 Swift 层各自细化记录协议: + +```swift +package protocol ObjCCodeReferenceRecording: CodeReferenceRecording { + func recordMessageSend(selector: String, receiver: ReceiverClassHint, at site: ScanSite) + func recordSuperMessageSend(selector: String, className: String?, at site: ScanSite) + func recordClassReference(_ classObject: ObjectiveCClassObject, at site: ScanSite) +} + +protocol SwiftCodeReferenceRecording: CodeReferenceRecording { + func recordSwiftType(descriptor: CodeLocation, at site: ScanSite) + func recordSwiftTypeName(_ name: SwiftTypeName, at site: ScanSite) +} +``` + +规则: + +- **识别器是各层的具体类型,没有共同协议**:`ObjCCodeReferenceRecognizer`、`SwiftCodeReferenceRecognizer` 各自按镜像记住类索引与 Swift 类型索引,各有 `makeSession(table:recording:…)`。门面是组合根,本来就认识两个具体的层,再抽一个识别器协议说不出能带来什么。核心只认会话协议。 +- **会话排成一列,顺序就是优先级**:门面按 ObjC、Swift 的顺序建会话;同一个时机第一个认领的为准。核心只在没有会话代替时记录普通调用。 +- **调用不拖慢扫描**:每个不同的调用目标只问一次各会话的角色,结果连同核心的解析一起记在扫描器的调用计划里;没有角色的调用——绝大多数——不经过任何会话。地址与槽按地址记住是哪个会话认领的(或谁都没认领),下次只问那一个或直接跳过。 +- **门面是组合根**:`CrossReferenceAnalyzer` 里的 `ReferenceCollector` 实现全部三个记录协议,直接造公开的 `CodeReference` 并按查询的键过滤(原 `ReferenceScanner.keep`)。下层不认识 `CodeReferenceTarget`,所以加一种目标不碰下层。 +- **查询只给一个开关**:两层的会话收到同一个「找不找类与类型引用」的开关(原 `findsTypeReferences`),与拆分前一致;只查 selector 或函数时两层都跳过地址与槽,ObjC 层在发送处照旧认类字面量接收者。 +- **寄存器标记**:`RegisterFile` 的「方法接收者」状态换成通用的标记(`setTag(_:of:)` / `tag(of:)`),随 `mov` 复制、写入即清除;ObjC 会话用标记 1。调用后保留哪些寄存器由会话按位返回(`clobberCallerSavedRegisters(keepingMask:)`)。 +- **跳板常量**:cache 共用 selector 桩由核心解析成 `.registerSettingTrampoline(register: 1, value:)`,核心不解释;ObjC 会话把它读成发送。 +- **运行时库与辅助函数**:核心不认识运行时库。门面把两层的规则(`RuntimeLibraryRules`:哪些路径是运行时库、哪些符号是辅助函数)交给 `CodeImageSet`;建镜像集时核心扫一遍运行时库的符号,记下辅助函数位置,并把每个符号交给门面,门面分发给两层各自记下 `objc_msgSend`、专用入口、`swift_getTypeByMangledName…` 这些位置。 +- **按镜像的缓存挂在函数表上**:`ImageFunctionTable.attachment(_:makingIt:)`,核心的 `ExportedFunctionNames`、ObjC 层的 `ObjCImageSections` 与 `ObjCMethodNames`、Swift 层的 `SwiftMetadataNames`。无名函数的起名不在扫描热路径上,由门面依次问这三个附件。 +- **预筛**各归各层:导入名与链接关系在核心层(`CodeImageSet+Linkage`),selector 与类在 ObjC 层,Swift 类型在 Swift 层;门面上的公开预筛方法签名不变,只是转发。 +- **性能**:会话只在事件上经 existential 调用。验收:在 Ultra 上 release 构建,拆分后整 cache 建表与 `init`、`makeKeyAndOrderFront:` 两条查询的耗时,相对拆分前的增幅都不超过 5%(`ScanThroughputBenchmarkTests`,按环境变量启用,两边各跑三轮取最好)。超出时先把会话列表改成具体类型的泛型参数、扫描入口标 `@inline(always)` 让门面特化,再量;数字写进模块文档。 + +### 读取抽象(package) + +```swift +package protocol CrossReferenceMemory: Sendable { + /// The `length` bytes from `address` on — an address in the analyzer's own + /// address space — contiguous and read-only, or nil when they cannot be read. + func bytes(at address: UInt, length: Int) -> UnsafeRawBufferPointer? + /// What the pointer slot at `address` holds, its signature and tag bits stripped. + func slotContent(at address: UInt) -> SlotContent? + /// The bits of a stored pointer that are its address. + var addressMask: UInt { get } + /// Bulk forms for a pass over a whole section of slots (the selector prefilter): + /// one call rather than one call a slot. Default implementations go slot by slot. + func pointers(inSlotsAt address: UInt, count: Int) -> [UInt] + func readablePointers(at addresses: [UInt]) -> [UnsafeRawPointer?] +} + +package enum SlotContent: Hashable, Sendable { + case address(UInt) + case importedSymbol(String) +} + +// load(_:at:), pointer(at:), typedPointer(to:at:length:) are extension helpers. +``` + +并发:分析器今天是 `@unchecked Sendable` 加手写锁(裁决 A62)。`FileCrossReferenceMemory` 的读取是对只读映射的并发读,fixup 解码的记忆化沿用 MachOKitExtensions `cached` 视图里已有的锁。 + +### `swift-section` 的 JSON + +```json +{ + "query": { "selector": "makeKeyAndOrderFront:" }, + "input": { "dyldSharedCache": "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e", "imageCount": 4114 }, + "scannedImageCount": 2759, + "isTruncated": false, + "references": [ + { + "image": "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit", + "function": { "address": "0x18801a000", "name": "-[NSApplication _showWindow:]" }, + "site": "0x18801a040", + "kind": "call", + "route": "cacheSharedStub", + "target": { "messageSend": { "selector": "makeKeyAndOrderFront:", "receiver": "unknown" } } + } + ] +} +``` + +(示例中的函数名与地址是示意,不是实测值。)`symbolicate --json` 输出 `{"symbolications": [ … ]}`,每项的字段对应 `AddressSymbolication`。字段名定下后即是契约,改名按 CLI 的破坏性变更处理。 + +### 地址的约定 + +CLI 与 API 进出的地址一律是**未滑动的虚拟地址**,也就是 IDA、`ipsw`、`dyld_info` 显示的那种。进程内模式在内部换算,调用方不需要知道 slide。 + +### 性能预算 + +拆分本身的验收见上文「按层拆分与识别器」。离线吞吐在第 4 步实测并写进模块文档:在 Ultra 上对 `/Volumes/DyldSharedCaches/macOS/27.2` 冷启动、热启动各跑 `--selector makeKeyAndOrderFront:` 与 `--selector init`。若冷启动的整 cache 查询超过 60 秒,在愿景里把「落盘」阶段提前。 + +## 替代方案考量 + +- **另写一个离线分析器,不动现有的。** 否:扫描、寄存器跟踪、命名合计约 5,200 行,复制一份就会和进程内版本漂移;`SwiftThunkAnalysis` 里已经有一份重复的离线解析,正是本提案要合并的。 +- **把分析器改成对 `MachO: MachORepresentable` 泛型**(本库其它模块的惯用写法)。否:两种模式的差别不在「哪种 Mach-O 类型」,而在「槽里的值怎么得到」——进程内读已绑定的值,文件里解 fixup。泛型会一路传染到 RuntimeViewer 持有分析器的会话类型,而一个小协议正好只隔离这一点。 +- **直接用 `ReadingContext` 当读取抽象。** 否,理由见「提议方案」第 1 节;`FileCrossReferenceMemory` 内部仍用它。 +- **后端用 `ipsw` 或 `dyld_info`。** 否:「前人怎么做的」里列的几类静默漏报、错名都会原样带进来。 +- **直接用 Binary Ninja。** 否:用户的 Personal 许可没有无界面 API,无界面的 `binaryninja_mcp` 也只随 Commercial / Ultimate;GUI 的 MCP 要求界面开着、当前视图跟随界面,多个 agent 会互相抢;整 cache 查询要把几千个镜像装进一个视图。2026-11-18 的实测里,它经 MCP 的代码引用召回只有 67.6%(IDA 两跳 99.4%),所以连核对也只作补充。 +- **现在就做落盘索引。** 否:0072 与 RuntimeViewer 0056 都定过不做;先量离线吞吐再说。 +- **地址符号化放进 MachOKit fork。** 否:fork 已落后上游 33 个提交,再加新能力只会更难合。 +- **一步到位:本提案直接把核心写进 MachOKitExtensions、ObjC 层写进 MachOObjCSection。** 否,改为分两步:本提案还有四项要先实测的未知,识别器接口也要在热路径上量过才定得下来;跨三个仓库时核心每改一次都要按序发版,而 MachOKitExtensions 此刻正在为 2.0.0 接收读取层与基础模块。用户在两种走法之间选了分两步。 +- **只抽桩链与槽解析,扫描器整体留在本库**(本提案原先的方案)。否:ObjC 与 Swift 的识别仍和通用扫描混在一个依赖 Swift 栈的模块里,不带 Swift 的使用方(关掉 SwiftSection trait 的 MachOKitUI、MachOObjCSection 自己的 `objc-section`)永远拿不到交叉引用;越往上加功能,日后越难拆。 +- **核心层直接定义列着 ObjC 与 Swift case 的目标枚举,不开扩展点。** 否:这样也能做到核心不 import 上层,但每加一种语言层的目标都要改核心、在 MachOKitExtensions 发版,而且把 Swift 的词汇带进一个语言无关的包——违反开闭原则。识别器加记录协议让核心对新语言封闭、对扩展开放。 +- **核心层对目标类型泛型(`CodeReference`),各层用 SE-0280 的「enum case 当协议要求的实现」构造目标。**否(这一步):泛型会扩散到 `CodeReferenceTable`、`CodeReferenceIndex` 和 RuntimeViewer 用到的每个名字;跨模块的泛型在 release 下不特化(`package` 函数不参与默认跨模块优化),扫描热路径上逐条引用的拷贝会走值见证调用。记录协议只在事件上做一次动态派发。下层将来要不要有自己的目标类型,留给迁移提案。 +- **本库里的模块直接用落脚处的名字(`MachOCodeReferences`、`ObjCCodeReferences`、`MachOAddressResolution`)。**否:本库发布过的版本只要带着与 MachOKitExtensions 2.x 新模块同名的模块,两边就解析不到一起,迁移时就得让 MachOKitExtensions 再升一个大版本;基础模块迁移提案也定了迁完后本库带 `MachO` 前缀的只有 ABI 模型。两个下层模块不是 product,搬的时候改名只动本库内部的 import。 +- **CLI 子命令叫 `resolve`。** 否:与 `resolveBind` / `resolveRebase` 撞义,见「详细设计」的命名取舍。 +- **照 Binary Ninja 建统一地址空间、换掉 `CodeLocation`。** 否:`CodeLocation` 是公开模型,RuntimeViewer 的查询层建在它上面;统一地址空间里最有用的「任何地址都说得出是什么」由符号化单独提供。 +- **照 Binary Ninja 加「selref / selector → IMP」的数据引用。** 本提案不做,归入愿景第 3 阶段的数据引用;现在按 selector 查发送者已经可以,从调用点到实现的两跳留给数据引用一起做。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏**,逐条: + +- `CodeReferenceTarget` 新增三个 case,`CodeReferenceTable.Key` 新增三个 case:对它们做穷尽 `switch` 的代码编译失败。已知下游只有 RuntimeViewer 的 `CrossReferenceQuery.swift:92`(`switch reference.target`),在第 5 步同一时间窗里补上: + + ```swift + // Before: nine cases. + // After: add + case .objectiveCInstanceVariable, .cString, .constantString: + return nil // not surfaced in the GUI yet + ``` + + RuntimeViewer 本地按「本地路径优先」依赖本库(`../../MachOSwiftSection`),所以本库 `next` 一合进新 case,RuntimeViewer 的 `next` 就要跟着改,两边要同批合入。 +- `CodeReference` 的旧初始化方法标 deprecated(`renamed:` 到新签名),仍可用一个版本。 +- `images` 标 deprecated;进程内模式行为不变。 +- `CodeReference.Route` 去掉了原设计里的 `selectorReference` 与 `classReference`(并进 `pointerSlot`)。`Route` 是本提案新增的,没有已发布的使用方。 + +**按层拆分不破坏源码**:`CodeLocation`、`IndirectCallEvidence`、`ReceiverClassHint` 搬到下层模块,`CodeReference.Kind` 从嵌套 enum 改成指向核心层 `CodeReferenceKind` 的 typealias;顶层 `@_exported import` 两个下层模块,`import CrossReferenceAnalysis` 的代码照旧看得到同样的名字、同样的 case。类型的完整名字(模块前缀)变了,只影响按类型名做序列化的代码;RuntimeViewer 在第 2 步核对一次它跨进程传交叉引用结果时怎么编码。 + +其余全是新增。 + +### ABI 兼容性 + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库内:`SwiftThunkAnalysis` 改用抽出的模块(行为不变,由守护测试保证);`SwiftSectionKit` 与 `swift-section` 新增对 `CrossReferenceAnalysis` 的依赖。 +- RuntimeViewer:见上;另有第 8、9 步的 CLI 与 MCP。它的常驻索引(`CodeReferenceIndex`)多出 `route`,第 5 步量出 `approximateByteCount` 的增量写进模块文档。 +- swift-decompiler:依赖本库的 `SwiftThunkAnalysis` 时只经它的公开接口,抽取不改公开接口;第 3 步核对一次。 +- MachOKitExtensions 的两次迁移(读取层、基础模块):都是原名迁入,import 不变;核心层与 ObjC 层只许 import 将来 MachOKitExtensions / MachOObjCSection 里也有的模块,正是以这两次迁移之后的样子为准。若迁移先合进 `next`,第 2、3 步照新的包依赖写 `Package.swift`。 +- 之后的迁移提案:本提案落地后,核心层、`CodeAddressResolution` 与 ObjC 层的文件应能原样搬走、只改 import 与模块名;做不到的地方(例如进程内构造器的 Darwin 条件编译)记进那份提案的调研。 + +### 文档与示例 + +README 的 CLI 一节、`swift-section-cli` skill、四个模块参考文档(`CrossReferenceAnalysis` 更新,`CrossReferenceCore`、`CrossReferenceObjC`、`CodeAddressResolution` 新增)、`AGENTS.md` 的模块层级图、愿景第 6 条、RuntimeViewer 的 CLI 使用指南与 `runtime-viewer` skill。 + +## API 演进与废弃策略 + +- `CodeReference.init(function:instructionAddress:kind:target:isRuntimeHelperCall:)` 与 `CrossReferenceAnalyzer.images`:标 `@available(*, deprecated, …)` 保留一个次版本,下一个次版本删除。 +- `ThunkAddressSpace`、`CacheImageResolver` 是 package 级,直接搬走,不留旧名。 +- 搬到下层模块的公开类型不改名、不留转发:经 `@_exported import` 原名可见。 +- 三层之间的识别器与记录协议是 package 级,这一步不承诺稳定;迁移提案把它们变成公开 API 时再按 `apple-style-api-design` 定形。 +- 本库仍在 0.x,随下一个次版本发布,不需要大版本。 + +## 落地步骤 + +1. **读取抽象,行为不变**(已完成) —— 改动地图里的 `CrossReferenceMemory`、`InProcessCrossReferenceMemory`、分析器与各扫描文件的读取改造、`StoredPointer`、`Package.swift`。 + - 行为:`inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation`(改造前后逐条比对整表) + - 行为:`crossReferenceAnalysisReadsMemoryOnlyThroughCrossReferenceMemory`(源码扫描:分析模块里不再有 `UnsafeRawPointer(bitPattern:)`) +2. **按层拆分,行为不变**(已完成) —— 改动地图里步骤列为 2 的各行:建 `CrossReferenceCore` 与 `CrossReferenceObjC`,识别器、会话与三个记录协议,寄存器标记,`CodeImageSet`,函数表与回退名按层拆开,运行时名单分到两层,门面改为组合两个识别器,`@_exported import`,边界测试,三份模块文档、`AGENTS.md`、愿景第 6 条。先量拆分前的基准,拆完在同一台机器上再量。 + - 行为:`inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation`(沿用第 1 步的整表比对,AppKit、SwiftUICore、Foundation 逐条相同;比较前去掉类型搬家带来的拼写差异) + - 行为:`aFunctionStartingOutsideTextScansWhereItLies`(第 1 步引入、吞吐基准发现的下溢陷入的复现) + - 行为:`crossReferenceLayersImportOnlyWhatTheirFutureHomesProvide`(源码扫描:核心层、ObjC 层的 import 都在白名单里) + - 行为:`crossReferenceCoreSpellsNoRuntimeSymbolName`(源码扫描:核心层没有 `objc_` / `swift_` 开头的字面量) + - 行为:`aRecognizerDefinedInTestsPlugsInWithoutChangingTheCore`(测试里定义一个只认某个 C 函数的识别器,它的引用出现在结果里——扩展点确实开放) + - 行为:`selectorQueriesLookUpNoSwiftType`(只查 selector 时 Swift 会话不建任何镜像的类型索引;ObjC 会话照旧为发送的类字面量接收者读类对象,与拆分前一致) + - 行为:`scanThroughputAfterTheLayerSplitIsRecordedInTheModuleDocument`(不是断言:拆分前后整 cache 建表与两条查询的耗时写进模块文档,增幅超过 5% 时按「详细设计」的退路处理后再量) + - 行为:`publicNamesStillResolveThroughCrossReferenceAnalysis`(只 `import CrossReferenceAnalysis` 的测试文件能用 `CodeLocation`、`CodeReference.Kind.call`、`ReceiverClassHint.methodReceiver`) +3. **抽出 `CodeAddressResolution`**(已完成) —— 四个新类型、`MachOThunkEnvironment` 改用它们、删 `ThunkAddressSpace`、模块文档。 + - 行为:线程读取的结果不变——由 `SwiftThunkAnalysisTests` 全套守着(归档 iOS 设备 cache 的 stub island、归档 macOS cache 的合并 accessor、模拟器运行时、独立文件),不另写测试 + - 行为:`stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub`(`x1` 的常量与最终的 `objc_msgSend` 副本;模块本身不认识 selector) + - 行为:`stubChainRecordsEveryStubIslandHop` + - 行为:`slotResolverMatchesTheProcessForEveryGlobalOffsetTableSlotOfAppKit`(含指向 AppKit 自己的类对象的槽) + - 行为:`slotResolverResolvesStandaloneBinds` + - 行为:`cacheImageLocatorFindsTheImageAnAddressLiesIn` + - 行为:`aFunctionLoadingAGlobalIsNoSlotStub`(`ARM64Trampoline` 的修复,见决策日志) +4. **文件模式的分析器**(已完成) —— `CodeImage` 与 `ImageLinkEdit`、`FileCrossReferenceMemory`、两个新构造器、各层按镜像读取的文件模式。 + - 行为:`fileModeMatchesInProcessReferencesOnTheRunningSystemCache`(同一个 cache 两种模式逐条比对,镜像取 AppKit、SwiftUICore、Foundation) + - 行为:`fileModeNamesFunctionsAsTheProcessDoes`、`fileModeReadsTheFallbackNameSourcesAsTheProcessDoes`(函数名与 ObjC 方法表、Swift 元数据两种后备来源两种模式逐条一致) + - 行为:`fileModePrefiltersSelectorsAsTheProcessDoes` + - 行为:`fileMemoryDecodesSlotsAsMachOKitDoes`(v5 与没有 slide info 的模拟器 cache,逐槽与 MachOKit 一致) + - 行为:`archivedCacheFindsBothCallersOfPasteboardWritingItemProvider`(27.0 与 27.2;卷不在时跳过) + - 行为:`archivedCacheFollowsStubIslandsForSelectorSends` + - 行为:`standaloneAppResolvesImportedAndSelfBoundSymbols` + - 行为:`standaloneExecutableResolvesRebasesAndObjectiveCStubs`(`SlotResolver` 的修复,见决策日志) + - 行为:`fileModeScansExceptionCleanupCodeAfterReturn`(`retab` 之后、没有函数起点的异常清理代码也要被扫到) + - 吞吐:`ScanThroughputBenchmarkTests` 加 `CROSS_REFERENCE_BENCHMARK_DYLD_CACHE`,实测写进模块文档 + - 核对:卷上没有 Finder 26.5.2,也没有 2026-11-18 那次的标准答案与生成脚本;按原法重做要新写 `otool -tV` 加寄存器跟踪的脚本,留给用户看过之后再跑。改做抽样:ControlCenter 26.7 的文件模式结果(`StandaloneFileReferenceDumpTests` 导出)与 IDA 逐函数对照,见决策日志。 +5. **新引用种类与路线**(已完成) —— 解码器的 `ldrsw` / 32 位 `ldr`(含字面量形式)、核心层的字符串、路线与对导入符号的数据引用、ObjC 层的 ivar、三个 target、`Route`、表键、常驻索引编码。RuntimeViewer 的穷尽 switch 挪到第 8 步,与 RuntimeViewer 的其余改动一起做。 + - 行为:`instanceVariableOffsetLoadsBecomeInstanceVariableReferences`(带符号与剥了符号两种) + - 行为:`stringReferencesAreRecordedOnlyWhenRequested` + - 行为:`constantStringReferencesCarryTheirCharacters`(8 位与 UTF-16 两种) + - 行为:`everyReferenceCarriesTheRouteItTook`、`inProcessReferencesCarryTheirRoutes`;iOS 设备 cache 经 stub island 的发送路线是 `stubIsland`(`archivedCacheFollowsStubIslandsForSelectorSends`) + - 行为:`referenceIndexRoundTripsNewTargetsAndRoutes` + - 行为:`decoderDecodesThirtyTwoBitLoadAndLoadSignedWord` + - 行为:`pageAlignedClassObjectMaterializationIsAReference`(`adrp; add #0`,在运行中的 cache 里找) + - 行为:`swiftLargeStringLiteralPointsAtItsCharacters`(`adrp; add; sub #0x20`) + - 对导入符号的数据引用由 ControlCenter 的导出核对(`_OBJC_CLASS_$_CALayer` 一类) +6. **地址符号化**(已完成) —— `AddressSymbolication` 与 `symbolication(of:)`、`symbolication(of:inImageAt:)`;核心层的 `AddressPlace` 判断结构,门面补含义。 + - 行为:`symbolicatesSwiftUICoreAuthStubsByTheirSlotsNotTheirIndirectSymbols`(26.7 SwiftUICore 的全部 `__auth_stubs` 都解到函数或导入名;其中 5 个经 `ipsw dyld macho --stubs` 独立核对的桩,间接符号表给的是错名,正是 `dyld_info` 标错的那批) + - 行为:`symbolicatesCacheSharedMessageSendStubToItsSelector` + - 行为:`symbolicatesGlobalOffsetTableSlotToItsBoundSymbol` + - 行为:`symbolicatesAnAddressInsideAnUnnamedFunctionWithItsFallbackName` + - 行为:`symbolicatesAnUnmappedAddressAsUnmapped` + - 行为:`symbolicatesStringsAndObjectiveCSlots`(C 字符串、`CFString`、`__objc_ivar` 的偏移变量) +7. **`swift-section refs` 与 `symbolicate`**(已完成) —— SwiftSectionKit 的三个类型、两个命令、选项组、登记、README、skill。 + - 行为:`refsListsCallerRowsForASelectorInAnArchivedCache` + - 行为:`refsJSONUsesHexadecimalStringAddresses` + - 行为:`refsMarksTruncatedResultsWhenLimited` + - 行为:`refsRequiresExactlyOneQuery` + - 行为:`symbolicateAcceptsSeveralAddresses` + - 行为:`refsListsTheCalleesOfAFunction`、`refsListsTheCallersOfASymbol`、`refsListsTheReferencesToAClass`、`refsReadsAStandaloneFatExecutable`、`symbolicateJSONUsesHexadecimalStringAddresses` + - 行为:`crossReferenceCommandsWriteOnlyThroughStandardStreamOutput`(沿用仓库已有的输出扫描测试) +8. **RuntimeViewer CLI**(已完成) —— 引擎侧符号化命令、四个子命令、协议版本、文本显示、使用指南、skill。 + - 行为:`callersCommandJSONMatchesTheMCPResponseFields` + - 行为:`commandLineProtocolVersionIsThree` + - 行为:`symbolicateCommandWorksOnTheLocalSource` +9. **RuntimeViewer MCP 与收尾**(已完成) —— 四个 MCP 工具;本库的 `ProjectEvolutionLog.md`、`Glossary.md`;RuntimeViewer 的 `Evolutions/README.md` 加 `cross-repository draft` 一行,0056 的暂缓表里把第 4 步那一行指向本提案。 + - 行为:`callersToolReturnsAPartialResultAfterThirtySeconds` + - 行为:`symbolicateToolRequiresAWindowIdentifier` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预判要写一份 CLI 使用指南:「地址一律未滑动」「字符串引用要打开才记录」「截断标记」这几条契约在签名里看不出来。模块参考文档本身按约定更新。 +- **有没有引入新术语** —— 预计有「地址符号化(symbolication)」「引用路线(route)」「识别器(recognizer)」,以及 stub island、cache 共用桩若术语表里还没有。 + +## 后续项 + +- **全面核对没有重做**:2026-11-18 那次用 `otool -tV` 加寄存器跟踪独立生成标准答案、再对照 IDA 的做法,生成脚本与 Finder 26.5.2 都已不在卷上。第 4 步改为 ControlCenter 26.7 三个函数的抽样核对。重做要新写生成标准答案的脚本,先给用户看过再跑。 +- **Swift 类经 ObjC ivar 列表登记的偏移变量没有收**:它们是 `__data` 里的 Swift 字段偏移全局量,不在 `__objc_ivar`(ControlCenter 的 `BentoBackdrop.maskLayer` 就是这样)。 +- **ivar 名字的两个来源有 23 条之差**(共约 182 万条 ivar 引用),没有逐条追。 +- **RuntimeViewer**:三种新目标(ivar、C 字符串、常量字符串)在界面里先不显示;App 工程本身没有构建过,只在沙盒里编过 Core、CLI 与 MCP 三个包;它跟的是本库的 `next` 分支,提交的 `Package.resolved` 已同日抬到本库的 `a98cbc15`。交叉引用测试模块整体并发跑时「分析器换新后要重新读名字」那组会超时,是基线就有的问题。 +- **核心层与 ObjC 层迁出本库**:另写迁移提案,要定的事见「非目标」第一条。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-18 | Created as Draft | 调研了过去逆向卡住最久的地方,「跨镜像查谁用了它」与「地址起名」排在最前;用户选定先做这一块,并把它定为愿景《不依赖 IDA 的逆向》的第一步,伪代码不再是默认读物,IDA 退为后备 | +| 2026-11-18 | 参照 Binary Ninja | 用户指出 IDA 的交叉引用弱、Binary Ninja 强。调研了它开源的 shared cache 视图与 ObjC 插件:采纳桩按节名判定与 `j_` 式命名、引用按来源种类标注(本提案的 `route`)、地址写成十六进制字符串、结果带截断标记;selector → IMP 的数据引用留给愿景第 3 阶段 | +| 2026-11-18 | Binary Ninja 6 的 MCP | 用户升级到 Binary Ninja 6.0。它的 GUI 内 MCP 服务器 Personal 版也有,可作第 3 步的结果核对;无界面版仍要 Commercial / Ultimate,所以不作后端 | +| 2026-11-18 | 实测后改用 IDA 核对 | 在 Finder 与 ControlCenter 上实测:代码引用召回 IDA 两跳 99.4%、Binary Ninja 经 MCP 67.6%。第 3 步的核对改以独立生成的标准答案为准、IDA 对照、Binary Ninja 补充;双方的三处盲点(页对齐类对象、Swift 大字符串、`retab` 后的清理代码)加成测试 | +| 2026-11-18 | 改为按层拆分、分两步迁移 | 用户提出把核心放进 MachOKitExtensions、ObjC 与 Swift 各管自己的部分。核实了两份 MachOKitExtensions 迁移提案都已 Accepted,核心层要的依赖届时都在那里;难点在扫描器里 ObjC 与 Swift 的识别穿插在五个时机。用户在「一步到位写进三个仓库」与「先在本库拆层、量完再迁」之间选了后者。本提案因此新增第 2 步:拆成 `CrossReferenceCore`、`CrossReferenceObjC`、`CrossReferenceAnalysis` 三个模块,经识别器与记录协议相接,核心不认识任何语言,源码扫描守住 import 边界,公开模型与 API 留在顶层不变;`MachOAddressResolution` 改名 `CodeAddressResolution`,下层模块在本库里的名字刻意不同于落脚处,避开同名模块与 `MachO` 前缀两条约束;`Route` 去掉按节区分的两个 case。原第 2–8 步顺延为第 3–9 步(上面几行里的「第 3 步」指现在的第 4 步)。真正的搬迁另写迁移提案 | +| 2026-11-18 | Accepted | 用户批准,开始实现 | +| 2026-11-19 | 第 1 步完成 | 读取协议按分析器地址空间里的地址读(进程内就是运行时地址),而不是原设计的「未滑动地址 + 镜像下标」:现有代码处处用运行时地址,这样改动最小,文件模式给每个镜像定一个滑动量即可。进程内实现不检查映射,信任调用方——此前的直接读也不检查,可能读到未映射地址的地方本来就先问 `isMapped`。「整表不变」做成靠环境变量驱动的 A/B 测试(`ReferenceTableDigestTests`):基线用 `git archive` 导出、拷入同一个测试文件生成摘要,候选与之比对;两边都要带 `USING_LOCAL_DEPENDENCIES=1`,因为 `next` 已用到 swift-demangling 未发版的 API。2026-11-19 在 Ultra 上 AppKit、SwiftUICore、Foundation 三个镜像逐条一致 | +| 2026-11-19 | 第 2 步完成 | 按层拆分落地,与原设计的出入:识别器没有共同协议,两层各是具体类型,核心只认会话与记录协议(门面本来就认识两个具体的层);角色声明自己会不会代替调用、要不要事后记录,扫描器只调用需要的那个方法,调用计划里的角色用 `SIMD4` 存,一次扫描最多四个会话;运行时库的规则(`RuntimeLibraryRules`)由门面交给核心,建镜像集时只扫一遍运行时库的符号;各层按镜像的缓存挂在函数表上作附件,函数表在它那一遍里记下各节供 ObjC 层用;`CodeReference.Kind` 改成核心层 `CodeReferenceKind` 的 typealias。测试 `selectorQueriesSkipClassAndTypeLookups` 改为 `selectorQueriesLookUpNoSwiftType`:ObjC 会话为发送的类字面量接收者照旧读类对象,与拆分前一致。整表对照:`String(describing:)` 给枚举负载里的类型加模块前缀,`Kind` 的拼法也变了,摘要在比较前去掉这两处;归一化后 AppKit、SwiftUICore、Foundation 逐行一致,整 cache 4,116 个系统镜像的引用数逐个一致 | +| 2026-11-19 | 修掉第 1 步引入的陷入 | 吞吐基准扫整个 cache 时触发:第 1 步把读指令改成以 `__text` 起点为基的偏移,有些镜像的符号表把 `__text` 的函数起点放在节起点之下,减法下溢陷入。改回按地址经读取层读,`instructionPointer(at:count:)` 由调用方给条数。复现测试 `FunctionStartOutsideTextTests` 修复前陷入、修复后通过。同类排查:`CodeReferenceIndex` 的编码本就先比较再用 `&-`,没有别处 | +| 2026-11-19 | 吞吐优化 | 第一次量(Ultra,release,对 `next`)超了 5%:整 cache 建表 +8%、`init` 调用者 +8%、`makeKeyAndOrderFront:` +11%、建分析器 +24%。逐项采样后改了四处:读槽先做区间排除再查认领表(原来就是这个顺序);运行时库的符号只扫一遍;调用计划不再持有数组(复制计划时的引用计数)、只调用角色需要的方法;会话与收集器里热路径上的可变属性标 `@exclusivity(unchecked)`(它们只在一个线程上用);函数表记下各节,ObjC 层不再为每次扫描遍历一遍 load command。另给读取层加了两个批量读接口(`pointers(inSlotsAt:count:)`、`readablePointers(at:)`),selector 预筛按 256 个槽一块读,不再每个槽一次 existential 调用 | +| 2026-11-19 | 吞吐验收 | 同一台 Ultra、release、三方交替各三轮取最好:整 cache 建表 `next` 2.42 / 第 1 步 2.54 / 第 2 步 2.52 秒,`init` 调用者 1.70 / 1.71 / 1.74 秒,`makeKeyAndOrderFront:` 调用者 0.36 / 0.37 / 0.38 秒。第 2 步相对拆分前(第 1 步)在 −0.5% 到 +3% 之间,满足 5% 的验收线,不必退到泛型特化;整表多出的约 5% 来自第 1 步的读取层,记进模块文档。debug 下交叉引用全套 99 个测试通过 | +| 2026-11-19 | 第 3 步完成 | `CodeAddressResolution` 按设计抽出,另有两处细节:它依赖 `MachOReading`(`MachOFile.readElements`,设计里说的读取层);`CacheImageLocator` 不自带 `SharedCache`,按镜像共用一个 locator 由线程读取器在 `thunkResolution` 组里做,本模块因此不依赖 `MachOCaches`,将来能原样搬走。`SwiftThunkAnalysis` 不再直接依赖 `ARM64InstructionDecoding`。行为清单对齐实际测试:抽取前后结果不变由 `SwiftThunkAnalysisTests` 全套守着;「本镜像类对象在 GOT 里」并进 AppKit 全部 GOT 槽与进程逐个比对的测试;独立文件的 self-bind 在 `SlotResolver` 里只是名字,换成地址是第 4 步文件模式的事,那条行为由第 4 步的 `standaloneAppResolvesImportedAndSelfBoundSymbols` 覆盖 | +| 2026-11-19 | 修掉跳板把普通函数认成 GOT 桩 | 写 `stubChainRecordsEveryStubIslandHop` 时发现:iOS 26.3.1 设备 cache 里 SwiftUI 经 stub island 调到 UIKitCore 的 `UIHostingViewBase.viewGraph` getter,它开头是 `adrp x8; ldr x8, [x8, #0xb10]; ldr x0, [x20, x8]`(读一个字段偏移),`ARM64Trampoline` 读到 `ldr` 就认定是从槽里取目标的桩,链落到 `sharedRegionStart + 0x38`。这是 `next` 上就有的旧 bug。改成载入之后必须紧跟一条经同一寄存器的非调用跳转(三种 GOT 桩都是这个形状),复现测试 `aFunctionLoadingAGlobalIsNoSlotStub` 修复前四处断言全红、修复后通过。影响面:进程内扫描器只对不落在任何镜像里的地址认跳板,结果不变;线程读取器只在调用目标落在别的镜像、又不是 accessor 或运行时入口时才走到它,原来得出 `unknown`,现在也是。真正会受影响的是第 4 步的文件模式,它经同一个解析器一跳一跳地跟,所以在这一步修掉 | +| 2026-11-19 | 第 4 步:镜像抽象 | 每个镜像改由核心层的 `CodeImage` 描述,`__LINKEDIT` 的表经读取层按地址读(`ImageLinkEdit`),桩按 `S_SYMBOL_STUBS` 的 `reserved1/2` 与 `ARM64Trampoline` 自己读,不再经 MachOKit 各读取器一套的 `symbols64`、`stubs(in:)`、`functionStarts`。读取器专属的 API 只在 ObjC 层(MachOObjCSection)与 Swift 层(MachOSwiftSection)里经 `asMachOImage` / `asMachOFile` / `MachOSwiftSectionRepresentableWithCache` 打开。进程内结果不变:交叉引用全套 100 个测试与整表摘要照旧,吞吐与第 1 步相比 −3% 到 +3% | +| 2026-11-19 | 第 4 步:文件读取层的形状 | `FileCrossReferenceMemory` 是值,以 `unowned(unsafe)` 引用镜像集持有的存储,区间表放在手动分配的缓冲区。第一版是类,整 cache 建表 37 秒(进程内 2.5 秒):每次经 existential 读都复制读取层、计一次数,`FullDyldCache.cacheAndFileOffset(for:)` 每次还新建子 cache 对象、重读 slide info。按 mapping 预取 slide info、v5 在读取层里直接解之后 16.5 秒,改成值之后 2.6 秒,与进程内持平。v2、v3 的快速路径写过又删了:卷上没有能验证它们的 arm64 cache(模拟器 cache 没有 slide info),只留 v5,其余交给 MachOKit | +| 2026-11-19 | 第 4 步:API 与设计的出入 | 两个构造器先不带 `recordingStringReferences`,第 5 步加字符串引用时一起加。失败时抛 `FileAnalysisError`(带 `Code` 的结构体,眼下只有 `unsupportedArchitecture`)。`images` 不标 deprecated:进程内的宿主与测试读的是只有 `MachOImage` 给得出的东西(slide、header),`imagePaths` / `imageCount` 替代不了,标了只会把它们推向无处可去;文件模式下它为空写在文档注释里。一组独立文件按 dyld 的做法错开地址。ObjC 层把按名字导入的 `_objc_msgSend` / `_objc_msgSendSuper2` 认成发送:不带 libobjc 分析一个 app 时它们就是这样到达的 | +| 2026-11-19 | 修掉 `SlotResolver` 把 rebase 偏移当地址 | 抽样核对 ControlCenter 时发现:几乎所有 objc 桩都没认出 selector。MachOKitExtensions 对独立文件的链式 fixup 给的是「相对首选加载地址的偏移」,`SlotResolver`(承自线程读取器的 `rebaseTargetAddress`,注释写着「独立文件给的是目标地址」)直接当地址用——dylib 的 `__TEXT` 在 0,两者相同,夹具都是 dylib,所以没被测到;可执行文件的 `__TEXT` 在 0x100000000,槽解出 0x798 而函数在 0x100000798。改为按 `__TEXT` 加偏移(`ImageAddressSpace.address(forHeaderOffset:)`);没有链式 fixup、靠 opcode rebase 的旧文件,MachOKitExtensions 不解,文件读取层直接用槽里的值。复现测试 `standaloneExecutableResolvesRebasesAndObjectiveCStubs` 修复前四处断言全红、修复后通过。同类排查:别处(`MachOPointers`、线程读取器的描述符读取)都把这个结果当 MachOSwiftSection 自己口径的 offset 用,是一致的。修复后 ControlCenter 的发送从 967 条到 4,909 条,无法识别的调用从 3,933 条到 1 条 | +| 2026-11-19 | 第 4 步完成 | 吞吐(Ultra,release,归档 macOS 27.2 cache,三轮最好):建分析器 0.14 秒,整 cache 建表 2.58 秒(1.263 亿条),`init` 调用者预筛 0.04 + 扫描 1.74 秒,`makeKeyAndOrderFront:` 0.11 + 0.34 秒;进程里第一次查询 0.5 秒与 1.9 秒。读运行中的 cache 文件与外置卷上的归档一样快,远低于愿景里「冷启动整 cache 查询超过 60 秒就提前落盘」的线。核对改为抽样:ControlCenter 26.7 的三个函数(ObjC 发送与 super 发送、Swift 元数据访问器与类型引用、`objc_allocWithZone` 与 `init`),IDA 反汇编里的直接调用与发送本库逐一都有;差异两类——经 GOT 槽读别的镜像的类(槽里是 bind)不记,补进第 5 步;直接经 GOT 槽的 `blraa` 记成间接调用,进程内同样如此。按 2026-11-18 的做法重做全面核对,需要新写生成标准答案的脚本,留给用户 | +| 2026-11-19 | 文件读取层不掩地址 | `AddressMaskScanTests` 不许库里出现自定义的地址掩码常量。文件读取层的 `addressMask` 改为不掩(解出的槽本来就是干净地址);slide info v5 的 34 位 `runtimeOffset` 是格式字段不是掩码,在扫描用例里加了一条只减不增、写明是哪个字段的白名单 | +| 2026-11-19 | 第 5 步完成 | 与设计的出入:路线的最后一种叫 `indirect`,不叫 `authenticatedIndirect`——不带认证的 `blr` / `br` 也得有路线,认证与否已在 `IndirectCallEvidence` 里。Swift 大字符串不需要 Swift 层专门认:`add` 算出的正是字符串起点,核心在那里记下;只是「减法算出的地址」从不当作字符串,否则 `sub #0x20` 之后的地址会落进前一个字符串中间。ivar 只认 `__objc_ivar` 里的偏移变量,即父类不在本镜像的 ObjC 类(父类是 `NSObject` 时 clang 用常量偏移、根本不载入);Swift 类经 ObjC ivar 列表登记的偏移变量是 `__data` 里的 Swift 字段偏移全局量,不在 `__objc_ivar`,没有收(ControlCenter 的 `BentoBackdrop.maskLayer` 就是这样),留作后续。对导入符号的数据引用记成 `.importedSymbol(name:)`、`kind == .reference`,不另外按名字认成 ObjC 类引用:类引用的 target 要带位置,导入的类没有;查一个类的全部引用时,调用方同时查 `_OBJC_CLASS_$_<类>`。查询里含字符串键时,那次扫描照样找字符串,不受分析器开关限制。32 位载入另认 ld64 改写出的字面量形式(`ldrsw xt, label`)。RuntimeViewer 的穷尽 switch 挪到第 8 步:它经远端版本依赖本库,本库发版之前不受影响 | +| 2026-11-19 | 第 6 步完成 | 与设计的出入:另有 `symbolication(of:inImageAt:)`——一组独立文件各留自己的地址,两个文件可能都有同一个未滑动地址(进程内,链接在 0 的测试 bundle 就占着 0x10),不指定镜像时取第一个有它的镜像,cache 优先。`Meaning` 多一个 `.data`:映射着、但不是函数、桩、槽、字符串,其下也没有符号,不能说成未映射。槽里的东西按节说:selector 引用给 `.messageSend(selector:receiver: .unknown)`(目标类型里没有单独的 selector),protocol 引用给协议名 `.cString`,GOT 给函数、类、Swift 类型或导入名,`__objc_ivar` 给 ivar。结构由核心层的 `AddressPlace` 判断(函数体、本镜像的桩、镜像之间的跳板链、槽、字符串、最近的符号),ObjC 层的 selector 桩、类与 ivar、Swift 类型与无符号函数的名字在门面补上。符号化用留存的函数表(第一版用不留存的,问 26.7 SwiftUICore 的全部桩花了 207 秒,改后 0.9 秒)。原计划的「对照 MachOKit 的 `Stub.indirectSymbolIndex`」不成立:那批桩上 MachOKit 读间接符号表与 `dyld_info` 一样标错,改为用 `ipsw` 独立核对的 5 个桩钉住、其余全部桩都要解出目标 | +| 2026-11-19 | ivar 名字改经读取层读 | 第 5 步的 ivar 名字第二来源经 MachOObjCSection 遍历类,每个类都重走一遍加载命令,整 cache 建表因此慢了 30%(3.25 秒)。改为从 `__objc_classlist` 起经读取层读 `class_ro_t` 与 ivar 列表(已 realize 的类经 `class_rw_t` 的第二个字,指针剥签名),两种读取器一套代码;整表回到 2.57–2.66 秒,比第 4 步多约 4%,多出的正是 182 万条 ivar 引用。两条路给的名字有 23 条之差(共约 182 万条),没有逐条追 | +| 2026-11-19 | 第 7 步完成 | 与设计的出入:`refs --function` 多一个 `--function-image`——一组文件各有各的地址,两个链接在 0 的 dylib 会在同一地址都有函数,此时报错要求指名;`symbolicate` 的文件输入是可重复的 `--file`(位置参数是地址),`--in-image` 指地址属于哪个镜像。胖文件必须给 `-a`,沿用 README 自 0.10.0 起「不默默挑切片」的约定(实现时一度自动挑 arm64e,发现与约定相悖后改回)。`--string` 不需要打开 `recordingStringReferences`:按键查询本来就找字符串。`--class` 先找 `_OBJC_CLASS_$_` 符号,找不到(cache 里多数私有类)再读各镜像的类表,并按类对象位置过滤同名类。`--symbol` 要求名字是函数的起点,变量报错;没有任何镜像定义时按导入名找(一组文件里调用外部库的情形)。为此门面加了 `locations(ofSymbolNamed:among:)`(导出表加符号表),`CodeFunction.Name` 加了 `spelling`。JSON 键排序、地址一律十六进制字符串,每条引用多一个 `isRuntimeHelperCall`。请求的 `run(output:)` 不收环境:不往产物里盖任何东西 | +| 2026-11-19 | 修共用键集合的争抢 | 写 `refs` 时发现:多个线程并发扫描、共用同一个键集合时,`ReferenceCollector.keep` 每检查一条引用都对该集合 retain/release 一次(`tableKey.map(keptKeys.contains)` 把集合捕获进闭包),28 个核争一个引用计数,整 cache 查 `init` 的调用者用了 152 秒、查 `makeKeyAndOrderFront:` 11.6 秒。`next` 上的 `ReferenceScanner.keep` 是同一写法,RuntimeViewer 并发查调用者时也共用一个键集合,是基线就有的问题;基准每个镜像现建一个集合,所以没暴露。改为收集器各留一份自己的拷贝、去掉闭包捕获:两条查询降到 2.2 秒与 1.05 秒(release CLI,含建分析器与起名)。基准的调用者查询改成共用一个键集合,与真实调用方一致,今后回归能在数字上看出;改后 `init` 的扫描 1.69 秒,与原来每镜像一个集合时相同 | +| 2026-11-19 | 第 8 步完成 | 与设计的出入:引擎侧加两个命令而不是一个——符号化之外还有「按名字定位符号」(`crossReferenceLocateSymbol`,用本库新加的 `locations(ofSymbolNamed:among:)`),因为查询主体没有「符号」这一种,符号名要先在引擎进程里换成函数地址。目标写法的解析放进 `RuntimeViewerCrossReferences` 的 `RuntimeCrossReferenceTargetResolution`,CLI 与 MCP 共用;按名字找类型由调用方传入,各前端沿用自己的查找规则。CLI 的 `--json` 与 MCP 的每行字段同出 Core 的 `RuntimeCrossReferenceRow` / `RuntimeAddressSymbolicationRow`(MCP 的响应类型要用 SwiftMCP 的 `@Schema`,Core 里不能用,所以 MCP 一侧逐字段照抄、测试钉住键名一致)。三种新目标(ivar、C 字符串、常量字符串)在 RuntimeViewer 里先不显示,照源码兼容性一节的约定返回空。失败代码新增 `targetNotFound` 与 `crossReferencesUnavailable`。RuntimeViewer 分支从远端 `next` 切出:本地 `next` 当时有十几个别的会话未推送的提交,从它切会在推送功能分支时把那些工作一并公开 | +| 2026-11-19 | 第 9 步完成 | MCP 四个工具照现有工具带 `windowIdentifier`;30 秒的等待做成可单测的 `MCPBridgeServer.references(within:_:)`:边查边收进度里的引用,到时取消查询、带着已有结果返回 `isComplete: false` 与说明(已扫完的镜像有缓存,再调一次接着扫)。RuntimeViewer 的提案索引加了 cross-repository draft 一行,暂缓表里第 4 步那一行指向本提案,0056 的决策日志记了一行 | +| 2026-11-19 | 渲染 A/B 验证全部一致 | 桩与槽的解析从 `SwiftThunkAnalysis` 抽成共用模块,动到了读取层,按 AGENTS.md 跑系统框架渲染 A/B:基线是开工时的 `next`(f8b25d2a),三条读取路径共 84 对 dump 与 interface 逐字节一致(归档 cache 15.5 与 26.6、iOS 15.5 至 26.5 模拟器、进程内) | +| 2026-11-19 | RuntimeViewer 交叉引用模块的并发超时是基线就有的 | 在沙盒里对本分支跑 RuntimeViewer 整个交叉引用测试模块(82 条并发),「分析器换新后要重新读名字」的两条等了 60 秒没等到;基线(RuntimeViewer 远端 `next` 加本库 `next`)整模块跑同样有其中一条在同一行失败,两边单跑这一组(18 条)都在 41 秒内全过。是会话队列在整模块并发时被前面的准备工作占满,与本次改动无关,没有修 | +| 2026-11-19 | 实现完成,待用户看过后收尾 | 九个落地步骤都已完成。本库全量测试(跳过 IntegrationTests)2,993 个零失败;渲染 A/B 84 对一致;RuntimeViewer 一侧在沙盒里对本分支编过 Core、CLI 与 MCP 三个包,新测试全过,App 工程本身没有构建。文档判断:配套使用指南不另写——CLI 的用法与契约写在 README、`swift-section` 插件的 `references/cross-references.md` 与 RuntimeViewer 的 `Guides/CommandLineInterface.md`,实现细节在三份模块文档;新术语「地址符号化」「识别器」「引用路线」「stub island」已登记进术语表。两个仓库的功能分支已在本地合进各自常驻的 `next` 检出,没有推送 | +| 2026-11-19 | Implemented,取号 0097,两个仓库合进各自的 `next` 并推送 | 用户验收后批准收尾。验收在 JHs-Mac-Studio-Ultra 上用功能分支的 release 版 CLI 做(Xcode 27.2,本地兄弟依赖):运行中系统 cache 里 `makeKeyAndOrderFront:` 的 439 处发送,0.7 秒;归档 27.0 与 27.2 cache 里 `UINSPasteboardWritingItemProvider` 的两个调用者;cache 共用 `objc_msgSend` 桩解成 selector(`ipsw dyld a2s` 对同一地址只回 `?`),GOT 槽、类对象与未映射地址的符号化;TextEdit 胖文件带 `-a arm64e` 找到 4 处发送,不带时按约定报错。落地前验证沿用「实现完成」一行的结果,之后只改了文档。文档判断不变:不另写使用指南,配套文档登记在头部,新术语已登记。正文去掉了段内硬换行,内容不变。没做完的列在「后续项」 | diff --git a/Documentations/Evolutions/0098-move-cross-reference-layers.html b/Documentations/Evolutions/0098-move-cross-reference-layers.html new file mode 100644 index 000000000..76d325399 --- /dev/null +++ b/Documentations/Evolutions/0098-move-cross-reference-layers.html @@ -0,0 +1,618 @@ + + + + + +0098 - 交叉引用的核心层与 ObjC 层迁出本库 + + + +
+ +

0098 - 交叉引用的核心层与 ObjC 层迁出本库

+
+ 状态:Implemented + 对应提案最后更新:2026-11-19 + 作者:JH + 创建:2026-11-19 + 所属愿景:不依赖 IDA 的逆向(第 6 条:分层归属) +
+

本页是 0098-move-cross-reference-layers.md 的网页版,两者对不上时以 Markdown 原文为准。实现分支:三个仓库都是 feature/move-cross-reference-layers(本库与 MachOKitExtensions 从 feature/move-macho-infrastructure-modules 切出,MachOObjCSection 从 next 切出)。本提案是 MachOKitExtensions、MachOObjCSection 与本库共用的唯一提案;另外两个仓库的提案索引各加一行 cross-repository 指向这里(落地步骤第 1 步)。

+

关联提案:0097 offline-cross-references-and-symbolication(在本库里把交叉引用拆成核心、ObjC、Swift 三层,并给下层定好了落脚处与名字;它的「非目标」第一条留给本提案的五个问题,在这里逐一定下);MachOKitExtensions 0002 move-reading-and-resolving-modules 与 0003 move-macho-infrastructure-modules(与本提案同日落地,都是 Implemented:把本库的读取层与 MachO 基础模块搬进 MachOKitExtensions 2.0.0。本提案的实现叠在它们的分支上,三份同日落地)。

+

配套文档:实现说明 MachOKitExtensions MachOCodeReferences.md、MachOAddressResolution.md、ARM64InstructionDecoding.md,MachOObjCSection ObjCCodeReferences.md;三层的总说明仍是本库的 Modules/CrossReferenceAnalysis.md。不另写使用指南:调用方契约没变。

+ + + +

摘要

+

0097 在本库里把交叉引用拆成了三层,并约定下层量完、跑稳之后再搬走。本提案就做这次搬家:与语言无关的三个模块搬进 MachOKitExtensions——CrossReferenceCore 改名 MachOCodeReferences,CodeAddressResolution 改名 MachOAddressResolution,ARM64InstructionDecoding 名字不变;ObjC 层 CrossReferenceObjC 搬进 MachOObjCSection,成为新 target ObjCCodeReferences。下层只给本库开 SPI(@_spi(Internals)),对外的分析器、公开模型和 Swift 层留在本库的 CrossReferenceAnalysis,RuntimeViewer 不用改代码。核心层的进程内部分用 #if canImport(Darwin) 包住,文件模式在 Linux 上也能编;顺带删掉从来只写 .none、没人读过的 IndirectCallEvidence.table。测试跟着代码走,但因为分析器留在本库,真正搬走的只有直接测下层的几组和源码扫描。实现叠在两份 MachOKitExtensions 搬迁提案的分支上,按 MachOKitExtensions 2.0.0、MachOObjCSection 0.8.207、本库 0.25.0 的顺序同日落地。

+ +

要定的事

+
没有留待拍板的设计问题:两轮澄清提问定下了节奏、API 范围、Linux、测试归属、ARM64 模块与 table 字段,其余按默认定的也经用户确认(见决策日志)。等用户批准(状态改 Accepted)后开工;开工第一步是把 next 合进本库的基础设施搬迁分支。
+ +

架构图

+
新增 / 搬入改动删除 / 搬走
+
+
+
MachOSwiftSection 0.25.0
+
CrossReferenceAnalysis
facade + Swift layer; imports the layers below via @_spi(Internals); @_exported for the five public value types
+
SwiftThunkAnalysis
-> MachOAddressResolution
+
SwiftDeclarationRendering
-> MachOAddressResolution
+
CrossReferenceCore
moved to MachOKitExtensions
+
CrossReferenceObjC
moved to MachOObjCSection
+
CodeAddressResolution
moved to MachOKitExtensions
+
ARM64InstructionDecoding
moved to MachOKitExtensions
+
+
+
MachOKitExtensions 2.0.0
+
MachOKitExtensions, MachOReading, …
from the two move proposals
+
ARM64InstructionDecoding
no dependencies
+
MachOAddressResolution
-> MachOReading, ARM64InstructionDecoding
+
MachOCodeReferences
-> MachOReading, MachOAddressResolution, ARM64InstructionDecoding; in-process parts behind #if canImport(Darwin)
+
+
+
MachOObjCSection 0.8.207
+
MachOObjCSection
upstream target, untouched
+
ObjCCodeReferences
-> MachOObjCSection, MachOCodeReferences
+
Package.swift
MachOKitExtensions 2.0.0..<3.0.0
+
+
+ +

一次扫描的调用链(搬家前后不变,只是模块换了包)

+
CrossReferenceAnalyzer.references(to:inImageAt:)                 [MachOSwiftSection / CrossReferenceAnalysis]
+  -> ReferenceScanner.scan(function:...)                         [MachOKitExtensions / MachOCodeReferences, @_spi(Internals)]
+       -> CodeReferenceRecognitionSession (one per layer)
+            ObjCCodeReferenceRecognizer.makeSession()            [MachOObjCSection / ObjCCodeReferences, @_spi(Internals)]
+            SwiftCodeReferenceRecognizer.makeSession()           [MachOSwiftSection / CrossReferenceAnalysis]
+       -> StubChainResolver / SlotResolver                       [MachOKitExtensions / MachOAddressResolution]
+       -> ARM64InstructionWord                                   [MachOKitExtensions / ARM64InstructionDecoding]
+  <- CodeReference (built by the facade's recorders)             [MachOSwiftSection]
+ +

落地顺序(发版依赖)

+
+
MachOKitExtensions 2.0.0three modules added
→ +
MachOObjCSection 0.8.207ObjCCodeReferences needs MachOCodeReferences
→ +
MachOSwiftSection 0.25.0requires both
→ +
RuntimeViewer pin bump
+
+ +

改动地图

+

MachOKitExtensions(从 feature/move-macho-infrastructure-modules 切出)

+ + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Package.swift修改加 product 与 target ARM64InstructionDecoding、MachOAddressResolution、MachOCodeReferences;加 test target MachOAddressResolutionTests、MachOCodeReferencesTests第 1 节2、3
Sources/ARM64InstructionDecoding/ARM64InstructionWord.swift、ARM64Trampoline.swift新增(搬入)原样搬;门面用到的 adding、branchTarget、callTarget、load 改 @_spi(Internals) public,其余保持 package核心与地址解析离不开它2
Sources/MachOAddressResolution/ 四个文件新增(搬入)原样搬;四个类型及本库用到的成员改 @_spi(Internals) publicSwiftThunkAnalysis、SwiftDeclarationRendering 跨包使用2
Sources/MachOCodeReferences/(19 个文件)新增(搬入)原样搬;本库与 MachOObjCSection 用到的约 27 个类型及其成员改 @_spi(Internals) public第 2 节3
Memory/InProcessCrossReferenceMemory.swift修改import MachOFoundation 改 import MachOReading;整个文件包进 #if canImport(Darwin)第 1、4 节3
Images/CodeImageSet.swift · inProcess(...)修改#if arch(arm64) 改 #if canImport(Darwin) && arch(arm64)第 4 节3
Models/IndirectCallEvidence.swift修改删 Table 与 table,构造器去掉 table:第 3 节3
Scanning/ReferenceScanner.swift修改写入 IndirectCallEvidence 处去掉 table: .none第 3 节3
Tests/MachOAddressResolutionTests/MachOAddressResolutionTests.swift新增(搬入并改写)本库 CodeAddressResolutionTests 的四条,镜像与 cache 从 MachOKit 直接拿第 5 节2
Tests/MachOCodeReferencesTests/MalformedExportTrieTests.swift新增(搬入)改 import第 5 节3
Tests/MachOCodeReferencesTests/CoreOnlyScanTests.swift新增theCoreScansWithOnlyARecognizerFromTests:只装测试里的识别器,驱动 ReferenceScanner证明核心在 MachOKitExtensions 里不靠语言层也能扫3
Tests/MachOCodeReferencesTests/SourceScanTests.swift新增(搬入并合并)不写 objc_ / swift_ 字面量、只有 InProcessCrossReferenceMemory 把地址变成指针、不写自定义地址掩码常量(含 slide info 白名单)第 5 节3
README.md修改模块列表加三个模块,写明 SPI 只给 MachOSwiftSection 用、Linux 上进程内部分不可用文档5
Documentations/Internal/MachOCodeReferences.md、MachOAddressResolution.md、ARM64InstructionDecoding.md新增(从本库搬入并改写)本库同名模块文档的内容,加 SPI 与 Linux 说明文档跟代码走5
Documentations/Internal/SharedCache.md修改thunkResolution 组那一行的 CacheImageResolver 改成 CacheImageLocator(类型在 MachOAddressResolution)0097 改了本库那份 MachOCaches.md,而它在基础设施搬迁里已搬来这里;第 0 步合并时本库那份保持删除2
Documentations/Evolutions/README.md修改加 cross-repository draft 一行指向本提案跨仓库提案的登记方式1
Documentations/Evolutions/0003-move-macho-infrastructure-modules.md(MachOKitExtensions)修改第 109 行与第 189 行的图改为 ARM64InstructionDecoding 也搬;决策日志加一行;落地清单的顺序改成第 6 节第 1、6 节1
Documentations/Evolutions/0002-move-reading-and-resolving-modules.md(MachOKitExtensions)修改决策日志加一行:落地顺序改成 MachOKitExtensions 2.0.0 先于 MachOObjCSection 的 tag第 6 节1
Documentations/README.md修改登记三份模块文档文档索引5
+ +

MachOObjCSection(从 next 切出)

+ + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Package.swift修改加 product 与 target ObjCCodeReferences(依赖 MachOKit、MachOObjCSection、MachOKitExtensions 的 MachOCodeReferences)与 test target ObjCCodeReferencesTests;MachOKitExtensions 要求改 "2.0.0"..<"3.0.0"第 1、6 节4
Sources/ObjCCodeReferences/(8 个文件)新增(搬入)原样搬;本库门面用到的十个类型改 @_spi(Internals) public;@_spi(Core) import MachOObjCSection 照旧fork 新增放单独 target4
Tests/ObjCCodeReferencesTests/SourceScanTests.swift新增只经 CrossReferenceMemory 读内存、不写 swift_ 字面量第 5 节4
Documentations/Internal/ObjCCodeReferences.md新增(从本库 CrossReferenceObjC.md 搬入并改写)加 SPI 说明文档跟代码走5
Documentations/README.md、Documentations/Evolutions/README.md修改登记模块文档;加 cross-repository draft 一行索引1、5
+ +

MachOSwiftSection(从合过 next 的 feature/move-macho-infrastructure-modules 切出)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
feature/move-macho-infrastructure-modules(分支)修改合入 origin/next(含 0097),解冲突,新 target 的 .target(.MachOFoundation) / .target(.MachOReading) 改成 .product(...),测试支持模块按那份提案改名本提案的基线0
Package.swift修改删 target CrossReferenceCore、CrossReferenceObjC、CodeAddressResolution、ARM64InstructionDecoding 与 test target CodeAddressResolutionTests;CrossReferenceAnalysis、SwiftThunkAnalysis、SwiftDeclarationRendering、CrossReferenceAnalysisTests、SwiftThunkAnalysisTests 改依赖 MachOKitExtensions 的三个 product 与 MachOObjCSection 的 ObjCCodeReferences;MachOObjCSection 要求改 "0.8.207"..<"0.9.0"第 1、6 节2、3、4、6
Sources/Support/ARM64InstructionDecoding/、Sources/Analysis/CodeAddressResolution/删除搬到 MachOKitExtensions第 1 节2
Sources/Analysis/CrossReferenceCore/删除搬到 MachOKitExtensions第 1 节3
Sources/Analysis/CrossReferenceObjC/删除搬到 MachOObjCSection第 1 节4
Sources/Analysis/SwiftThunkAnalysis/(AccessorThunkReader、DependencyImageResolver、MachOThunkEnvironment、ThunkTypeNodeBuilder、ObjCMethodThunkReferences)修改import CodeAddressResolution 改 @_spi(Internals) import MachOAddressResolution;用到解码器的改 @_spi(Internals) import ARM64InstructionDecoding第 2 节2
Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift修改同上第 2 节2
Sources/Analysis/CrossReferenceAnalysis/Exports.swift修改@_exported import MachOCodeReferences、@_exported import ObjCCodeReferences门面的公开类型照旧可见3、4
Sources/Analysis/CrossReferenceAnalysis/ 其余文件修改import 改名,用到内部接口的加 @_spi(Internals) import;构造 IndirectCallEvidence 处去掉 table:(若有)第 2、3 节3、4
Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift修改删 name(of:)、refs --json 的 table 键与文本输出里的「through …」第 3 节3
AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md修改间接调用照实际输出描述,不再说带哪张表CLI 输出变了,skill 同批改3
Tests/CrossReferenceAnalysisTests/MalformedExportTrieTests.swift删除搬到 MachOKitExtensions第 5 节3
Tests/CrossReferenceAnalysisTests/RecognizerExtensionPointTests.swift修改第一条搬走,selectorQueriesLookUpNoSwiftType 留下第 5 节3
Tests/CrossReferenceAnalysisTests/CrossReferenceLayerBoundaryTests.swift删除两条白名单不再需要,运行时名字扫描搬到 MachOKitExtensions第 5 节3
Tests/CrossReferenceAnalysisTests/MemoryAccessScanTests.swift修改只扫 CrossReferenceAnalysis下层的部分搬走3
ARM64InstructionDecodingTests.swift、RegisterFileTests.swift、InstructionEncoding.swift修改@_spi(Internals) import 搬走的模块Capstone 对照留在本库2、3
Tests/CrossReferenceAnalysisTests/StandaloneBindSlotTests.swift新增(从 CodeAddressResolutionTests 挪入)slotResolverResolvesStandaloneBinds要 SymbolTestsCore 夹具2
Tests/CodeAddressResolutionTests/删除四条搬走、一条挪入 CrossReferenceAnalysisTests第 5 节2
Tests/SwiftSymbolsTests/SymbolTableEquivalenceTests.swift修改前缀判断先算进局部变量,不放在 && 的自动闭包里基础设施搬迁带来的测试在 Xcode 26.6 的 release 下编不过5
Tests/CrossReferenceAnalysisTests/ 其余用到内部接口的文件、Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift修改@_spi(Internals) importpackage 不再跨包2、3、4
AGENTS.md修改模块依赖图;CrossReferenceAnalysis、ARM64InstructionDecoding、CodeAddressResolution 三条改写第 7 节5
Documentations/Internal/Modules/CrossReferenceCore.md、CrossReferenceObjC.md、CodeAddressResolution.md删除搬到另外两个仓库第 7 节5
Documentations/Internal/Modules/CrossReferenceAnalysis.md、SwiftThunkAnalysis.md、SwiftSectionKit.md修改改写分层一节与模块链接第 7 节5
Documentations/README.md、Glossary.md、Visions/ReverseEngineeringWithoutIDA.md修改模块文档索引与链接;愿景第 6 条与相关提案表第 7 节1、5
Documentations/Evolutions/README.md修改登记本提案索引1
Changelogs/0.25.0.md修改Breaking:IndirectCallEvidence.table 删除;下层模块移到 MachOKitExtensions / MachOObjCSection发版说明6
Documentations/Internal/ProjectEvolutionLog.md修改落地时加一节账本6
+ +

RuntimeViewer

+ + + + + + +
文件 / 类型动作改什么为什么步骤
五个提交进仓库的 Package.resolved修改落地后抬本库与 MachOObjCSection 的 next revision惯例6
RuntimeViewerCore/Package.swift修改MachODependencies 改从 MachOKitExtensions 取,并加它为直接依赖基础设施搬迁要求,落地那天与本库 next 同日改6
+ +

动机

+

完整动机见愿景《不依赖 IDA 的逆向》「我们选的方向」第 6 条:与语言无关的部分归 MachOKitExtensions,ObjC 专属的归 MachOObjCSection,Swift 专属的与命令入口留在本库;新代码先在本库写成独立模块、用源码扫描守住边界,量过、跑稳之后另写迁移提案整体搬过去。这一步特有的部分:

+
    +
  • 拆层的前提已经满足。0097 留下的四项「先实测」的未知都已量完:离线整 cache 建表 2.58 秒,与进程内持平;拆层前后吞吐差别在 −0.5% 到 +3% 之间;全量 2,993 个测试零失败,渲染 A/B 84 对逐字节一致。识别器接口在扫描热路径上量过,不再需要在一个仓库里反复改。
  • +
  • 下层现在借住在一个读 Swift 元数据的库里。MachOAddressResolution 要做的事与 Swift 无关,本库的 SwiftThunkAnalysis 与 SwiftDeclarationRendering 只是它的两个使用者;ObjC 层读类表要借 MachOObjCSection 的 SPI(@_spi(Core) import MachOObjCSection,为了 ObjCClass64(layout:offset:)),搬进 MachOObjCSection 之后这就是包内调用。愿景后面几个阶段都要建在核心层上,核心在 MachOKitExtensions,它们就不必依赖一个 Swift 元数据库。
  • +
  • 趁 2.0.0 一起搬最省。MachOKitExtensions 2.0.0 本来就是大版本,本库 0.25.0 本来就是破坏性版本。同日落地只走一轮三个仓库的发版;之后单独搬,就要再来一轮发版,本库还要再发一个破坏性版本。
  • +
  • 本库里的名字就是为这一步起的。0097 刻意让下层在本库里的名字不同于落脚处,避免本库已发布版本里的模块与 MachOKitExtensions 2.x 的新模块同名;下层两个模块也没有做成 product,没有外部使用方。搬的时候改名,只动本库内部的 import。
  • +
+ +

提议方案

+

1. 去向与名字

+ + + + + + + + + +
本库现在去向新名字product依赖
ARM64InstructionDecodingMachOKitExtensionsARM64InstructionDecoding(不变)是无
CodeAddressResolutionMachOKitExtensionsMachOAddressResolution是MachOKit、MachOKitExtensions、MachOReading、ARM64InstructionDecoding
CrossReferenceCoreMachOKitExtensionsMachOCodeReferences是MachOKit、MachOKitExtensions、MachOReading、MachOAddressResolution、ARM64InstructionDecoding
CrossReferenceObjCMachOObjCSectionObjCCodeReferences(新 target,不进上游的 MachOObjCSection target)是MachOKit、MachOObjCSection、MachOCodeReferences
CrossReferenceAnalysis留在本库不变是(已是)ARM64InstructionDecoding、MachOAddressResolution、MachOCodeReferences、ObjCCodeReferences,以及原有的 Swift 层依赖
+
    +
  • ARM64InstructionDecoding 不是 Mach-O 专有的,不加 MachO 前缀。本库 0.25.0 起不再有同名模块;本库 0.24.0 及更早的版本要求 MachOKitExtensions 1.x,永远不会与 2.0.0 同时解析,所以不会撞名。
  • +
  • 核心层改为直接依赖 MachOReading,不再依赖 MachOFoundation:只有这样,MachOCodeReferences 才不会带进 MachOSymbols、MachODependencies(以及本库那份 MachOBase 里的 Utilities)。ObjC 层去掉两个没用的依赖。
  • +
  • 文件原样搬,目录结构照旧(Images/、Memory/、Models/、Recognition/、Scanning/、Symbolication/),除了下面几节列出的改动,只改 import 与访问级别。
  • +
+ +

2. API:只给本库开 SPI

+
    +
  • 跨包用到的 package 声明改成 @_spi(Internals) public,同包里用到的保持 package。判据是「另一个 package 的模块要不要用它」:MachOAddressResolution → MachOCodeReferences、ARM64InstructionDecoding → 两者都在 MachOKitExtensions 一个包里,保持 package;MachOCodeReferences 被 ObjCCodeReferences 和 CrossReferenceAnalysis 用到的那些、MachOAddressResolution 被 SwiftThunkAnalysis 与 SwiftDeclarationRendering 用到的四个类型、ARM64InstructionWord 被门面用到的四个成员、ObjCCodeReferences 被门面用到的十个类型,改成 SPI。两个仓库都用 Internals 这个分组名:MachOKitExtensions 已有这个分组;MachOObjCSection 现有的是 Core 与 Support,新分组不与它们冲突。
  • +
  • 已经公开的值类型保持 public:CodeLocation、CodeReferenceKind、CodeReferenceRoute、IndirectCallEvidence(删掉 table 之后)、ReceiverClassHint。它们今天就是本库公开 API 的一部分(经 @_exported),RuntimeViewer 用着其中的 CodeLocation 与 ReceiverClassHint。
  • +
  • 对外的分析器、公开模型与 Swift 层留在本库。CrossReferenceAnalyzer、CodeReference、CodeReferenceTarget、CodeReferenceTable、CodeReferenceIndex、CodeFunction、AddressSymbolication 都不动。单用 MachOKitExtensions 做不了交叉引用;下层对外该长什么样,等真有不经本库的使用方时再定——0097 非目标里留下的问题 (a) 因此不在本提案里回答。
  • +
  • SPI 不承诺 semver。MachOKitExtensions 与 MachOObjCSection 的模块文档写明:@_spi(Internals) 的接口只给 MachOSwiftSection 用,随时可能变,不算破坏性变更。
  • +
  • 门面的导出照旧。Exports.swift 改成 @_exported import MachOCodeReferences 与 @_exported import ObjCCodeReferences,import CrossReferenceAnalysis 的使用方照旧看得到那几个公开值类型;门面里要用内部接口的文件另写 @_spi(Internals) import。
  • +
+ +

3. 删掉 IndirectCallEvidence.table

+

IndirectCallEvidence 只保留与语言无关的事实:tableOffset、pointerAuthenticationConstant、isAddressBlended。Table 枚举与 table 属性删掉,构造器去掉 table: 参数,扫描器的写入点跟着改。将来要区分 vtable、协议见证表、值见证表时,由 Swift 层在门面里另加,不回到核心层。这是本库公开 API 的破坏性改动,随 0.25.0 发布,写进 changelog 的 Breaking 一节;本库之外没有使用方,不留废弃期。refs --json 里永远是 "none" 的 table 键一起删掉:refs 是 0.25.0 才有的命令,还没发布。

+ +

4. Linux:文件模式能编,进程内部分用 #if 包住

+
    +
  • MachOCodeReferences 里,CodeImageSet.inProcess(...) 从 #if arch(arm64) 改成 #if canImport(Darwin) && arch(arm64);InProcessCrossReferenceMemory.swift 整个文件包进 #if canImport(Darwin)。文件模式不包。
  • +
  • ObjCCodeReferences 里按 asMachOImage 分支的几处先不包,编译报错再包。
  • +
  • 照两份搬迁提案的做法:不加 Linux CI,本机验证不了,模块文档写明「Linux 上未验证」。门面(本库)不变——本库不承诺 Linux。
  • +
+ +

5. 测试:跟着代码走

+

分析器留在本库,所以只有直接测下层、不经门面的测试能搬:

+ + + + + + + + + + + + + +
测试去向怎么改
MalformedExportTrieTests(RenamedReexportIndex)MachOKitExtensions MachOCodeReferencesTests改 import
RecognizerExtensionPointTests.aRecognizerDefinedInTestsPlugsInWithoutChangingTheCore同上,改名 theCoreScansWithOnlyARecognizerFromTests不借门面:从运行中的 cache 直接建 CodeImageSet,只装测试里定义的识别器,驱动 ReferenceScanner
CodeAddressResolutionTests 里不要夹具的三条与要归档 iOS cache 的 stubChainRecordsEveryStubIslandHopMachOKitExtensions MachOAddressResolutionTestsAppKit 镜像与 cache 改从 MachOKit(DyldCacheLoaded.current、FullDyldCache)直接拿,不借门面的 ProcessAnalyzer
源码扫描:核心不写 objc_ / swift_ 字面量、只有 InProcessCrossReferenceMemory 把地址变成指针、不写自定义地址掩码常量(连同 slide info 那条白名单)MachOKitExtensions MachOCodeReferencesTests扫描目录换成 Sources/MachOCodeReferences
源码扫描:ObjC 层只经 CrossReferenceMemory 读内存、不写 swift_ 字面量MachOObjCSection ObjCCodeReferencesTests(新)扫描目录换成 Sources/ObjCCodeReferences
CrossReferenceLayerBoundaryTests 的两条 import 白名单删除下层搬走之后 SwiftPM 本身就不允许它们 import 本库的模块
ARM64InstructionDecodingTests、RegisterFileTests(Capstone 对照)与辅助的 InstructionEncoding.swift留在本库改成 @_spi(Internals) import;MachOKitExtensions 不加 Capstone 依赖
slotResolverResolvesStandaloneBinds(SymbolTestsCore 夹具)留在本库,挪进 CrossReferenceAnalysisTestsCodeAddressResolutionTests target 删除
其余经门面的测试、ReferenceTableDigestTests、ScanThroughputBenchmarkTests、PublicNameTests、MemoryAccessScanTests 与 AddressMaskScanTests 对本库文件的部分留在本库用到下层内部接口的改成 @_spi(Internals) import
+
    +
  • MachOKitExtensions 没有 CI,那边的测试只在本地跑;MachOObjCSection 的 CI 在 PR 与推 main 时跑新 target 的测试。
  • +
  • 本库的缩写扫描(AbbreviatedIdentifierScanTests)不复制到另外两个仓库。
  • +
+ +

6. 版本与落地顺序

+
    +
  1. MachOKitExtensions 合入 main、发 2.0.0(两份搬迁加本提案的三个模块)。
  2. +
  3. MachOObjCSection 把 MachOKitExtensions 的下限抬到 2.0.0("2.0.0"..<"3.0.0"),推 main、等 CI、打 0.8.207。这意味着 0.8.207 起的 MachOObjCSection 不能再与本库 0.24.0 及更早的版本同时解析——它们要 MachOKitExtensions 1.x。
  4. +
  5. 本库把 MachOObjCSection 要求改成 "0.8.207"..<"0.9.0"、MachOKitExtensions 改成 from: "2.0.0",随 0.25.0 发布。
  6. +
  7. RuntimeViewer 抬钉(本库与 MachOObjCSection 的 next revision)。
  8. +
+

读取层搬迁提案落地清单里「MachOObjCSection 先打 tag」的顺序因此改成上面这样,那份提案的决策日志记一行。

+ +

7. 文档

+
    +
  • 模块文档跟着代码走:本库的 Internal/Modules/CrossReferenceCore.md、CodeAddressResolution.md 搬进 MachOKitExtensions 的 Documentations/Internal/(改名 MachOCodeReferences.md、MachOAddressResolution.md,加一份 ARM64InstructionDecoding.md),CrossReferenceObjC.md 搬进 MachOObjCSection 的 Documentations/Internal/ObjCCodeReferences.md;本库的 CrossReferenceAnalysis.md 改写「三个模块」一节,指向它们。
  • +
  • 本库 AGENTS.md:模块依赖图、CrossReferenceAnalysis 那一大段里「It is three modules」与 ARM64InstructionDecoding、CodeAddressResolution 两条改写成「下层在 MachOKitExtensions 与 MachOObjCSection,经 @_spi(Internals) 接入」。
  • +
  • 愿景第 6 条的「之后另写迁移提案」改成指向本提案;愿景的相关提案表加一行。
  • +
  • MachOKitExtensions 的 README 模块列表、两个仓库的提案索引与文档索引。
  • +
+ +

非目标

+
    +
  • 下层的独立公开 API:MachOKitExtensions 里不提供自己的分析器、不定义与语言无关的引用目标类型。等有不经本库的使用方时另写提案。
  • +
  • 在 Linux 上真编、加 Linux CI。
  • +
  • 给 MachOKitExtensions 加 CI(基础设施搬迁提案已把它留给单独的提案)。
  • +
  • 改扫描行为、加新的引用种类。除了删 IndirectCallEvidence.table,搬家前后每张引用表逐条一致。
  • +
  • 搬 Swift 层或门面,以及 SwiftThunkAnalysis、SwiftDeclarationRendering 本身。
  • +
  • MachOKitUI 的改动:它不用这几个模块;它因两份搬迁提案要做的 import MachOSymbols → import SwiftSymbols 由它自己的提案负责。
  • +
  • 把门面经 @_exported 带出的类型改名。
  • +
+ +

详细设计

+
+MachOKitExtensions 的 Package.swift +
// Products, added beside the nine from the two move proposals.
+.library(name: "ARM64InstructionDecoding", targets: ["ARM64InstructionDecoding"]),
+.library(name: "MachOAddressResolution", targets: ["MachOAddressResolution"]),
+.library(name: "MachOCodeReferences", targets: ["MachOCodeReferences"]),
+
+// Targets.
+.target(name: "ARM64InstructionDecoding"),
+.target(
+    name: "MachOAddressResolution",
+    dependencies: [
+        .product(name: "MachOKit", package: "MachOKit"),
+        "MachOKitExtensions",
+        "MachOReading",
+        "ARM64InstructionDecoding",
+    ]
+),
+.target(
+    name: "MachOCodeReferences",
+    dependencies: [
+        .product(name: "MachOKit", package: "MachOKit"),
+        "MachOKitExtensions",
+        "MachOReading",
+        "MachOAddressResolution",
+        "ARM64InstructionDecoding",
+    ]
+),
+.testTarget(name: "MachOAddressResolutionTests", dependencies: ["MachOAddressResolution"]),
+.testTarget(name: "MachOCodeReferencesTests", dependencies: ["MachOCodeReferences"]),
+
+
+MachOObjCSection 的 Package.swift +
.library(name: "ObjCCodeReferences", targets: ["ObjCCodeReferences"]),
+
+.target(
+    name: "ObjCCodeReferences",
+    dependencies: [
+        .product(name: "MachOKit", package: "MachOKit"),
+        "MachOObjCSection",
+        .product(name: "MachOCodeReferences", package: "MachOKitExtensions"),
+    ]
+),
+.testTarget(name: "ObjCCodeReferencesTests", dependencies: ["ObjCCodeReferences"]),
+

MachOKitExtensions 的要求从 "1.2.0"..<"3.0.0" 改成 "2.0.0"..<"3.0.0"(本地兄弟依赖的写法照该仓库现有的 USING_LOCAL_DEPENDENCIES 分支)。

+
+
+本库的 Package.swift +
// CrossReferenceAnalysis after the move.
+.target(
+    name: "CrossReferenceAnalysis",
+    dependencies: [
+        .product(name: "ARM64InstructionDecoding", package: "MachOKitExtensions"),
+        .product(name: "MachOAddressResolution", package: "MachOKitExtensions"),
+        .product(name: "MachOCodeReferences", package: "MachOKitExtensions"),
+        .product(name: "ObjCCodeReferences", package: "MachOObjCSection"),
+        // ...the Swift-layer dependencies it already has (SwiftInspection, MachOSwiftSection, ...)
+    ],
+    path: "Sources/Analysis/CrossReferenceAnalysis"
+),
+

SwiftThunkAnalysis 与 SwiftDeclarationRendering 的 .target(.CodeAddressResolution) 换成 .product(name: "MachOAddressResolution", package: "MachOKitExtensions")。

+
+
+SPI 的写法 +
// MachOKitExtensions/Sources/MachOAddressResolution/StubChainResolver.swift
+@_spi(Internals)
+public struct StubChainResolver {
+    @_spi(Internals)
+    public init(addressSpace: ImageAddressSpace, ...)
+    ...
+}
+
+// MachOSwiftSection/Sources/Analysis/SwiftThunkAnalysis/AccessorThunkReader.swift
+@_spi(Internals) import MachOAddressResolution
+

一个类型在同一个包里被别的模块用、又被另一个包的模块用时,只改成 SPI 一次;package 与 @_spi(Internals) public 不并存。

+
+
+IndirectCallEvidence 删掉 table 之后 +
/// Evidence for where an indirect call may go.
+public struct IndirectCallEvidence: Hashable, Sendable {
+    /// 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(tableOffset: Int64?, pointerAuthenticationConstant: UInt16?, isAddressBlended: Bool)
+}
+
+
+进程内部分的条件编译与门面的导出 +
// MachOCodeReferences/Images/CodeImageSet.swift
+#if canImport(Darwin) && arch(arm64)
+extension CodeImageSet {
+    @_spi(Internals)
+    public static func inProcess(...) -> CodeImageSet? { ... }
+}
+#endif
+
+// MachOCodeReferences/Memory/InProcessCrossReferenceMemory.swift
+#if canImport(Darwin)
+import MachOReading
+...
+#endif
+
+// MachOSwiftSection/Sources/Analysis/CrossReferenceAnalysis/Exports.swift
+@_exported import MachOCodeReferences
+@_exported import ObjCCodeReferences
+

@_exported 只带出 public 声明;SPI 声明要在用的文件里写 @_spi(Internals) import,不会经门面漏给 RuntimeViewer。

+
+

验收

+
    +
  • 整表一致:ReferenceTableDigestTests 的 A/B 以本提案开工时的 next 为基线,AppKit、SwiftUICore、Foundation 逐条一致;比较前去掉 IndirectCallEvidence 描述里的 table 与模块名前缀两处拼写差异。
  • +
  • 吞吐:Ultra、release、ScanThroughputBenchmarkTests 三方交替各三轮取最好,整 cache 建表与两条调用者查询相对基线不超过 +5%;超了先查跨包调用是否失去了包内的跨模块优化(package 函数本来也不吃默认的跨模块优化,预计不变)。
  • +
  • 渲染 A/B:SwiftThunkAnalysis 的读取路径换了模块,按 AGENTS.md 跑系统框架渲染 A/B,三条读取路径逐字节一致。
  • +
  • 三个仓库的全量测试:本库跳过 IntegrationTests;MachOKitExtensions 本地全量;MachOObjCSection 本地全量,并在 PR 上等 CI。
  • +
  • RuntimeViewer:在沙盒里用本地兄弟依赖编过 Core、CLI 与 MCP 三个包,交叉引用测试单跑通过。
  • +
+ +

前期调研

+
+现状代码怎么走的 +

四个要搬的模块(next 的 a98cbc15;package 与 public 的个数按声明关键字 grep,近似值):

+ + + + + + + + +
模块(本库)位置文件行数publicpackage实际 import
CrossReferenceCoreSources/Analysis/CrossReferenceCore193,29214(CodeLocation、CodeReferenceKind、CodeReferenceRoute、IndirectCallEvidence 及其成员)约 230Foundation、MachOKit(CodeImage.swift:2、FileCrossReferenceMemory.swift:2 带 @_spi(Support),为了 MemoryTrieTree)、MachOKitExtensions、ARM64InstructionDecoding、CodeAddressResolution、MachOFoundation(只在 Memory/InProcessCrossReferenceMemory.swift:1)
CrossReferenceObjCSources/Analysis/CrossReferenceObjC81,1521(ReceiverClassHint)约 78Foundation、MachOKit、MachOObjCSection(ObjCMethodNames.swift)、@_spi(Core) import MachOObjCSection(ObjectiveCClassIndex.swift:3)、CrossReferenceCore
CodeAddressResolutionSources/Analysis/CodeAddressResolution4434033Foundation、MachOKit、MachOKitExtensions、MachOReading(只为 readElements(offset:numberOfElements:),StubChainResolver.swift:52、ImageAddressSpace.swift:35)、ARM64InstructionDecoding
ARM64InstructionDecodingSources/Support/ARM64InstructionDecoding2311028(全部)无
+
    +
  • 核心层经 MachOFoundation 间接带进了 Utilities。InProcessCrossReferenceMemory.swift:40 只用到 InProcessContext.addressMask(在 MachOReading),但 import MachOFoundation 经 MachOBase/Exported.swift:10 的 @_exported import Utilities 把 FrameworkToolbox、AssociatedObject、MemberwiseInit、Dependencies、AsyncAlgorithms 都带了进来(Package.swift:356-368)。MemberImportVisibility 没有在任何 target 上打开,所以核心层别的文件可能悄悄用了这条链带进来的成员——这一点没有逐个核实,搬的时候编译会告诉我们。
  • +
  • 声明了但没用的依赖。CrossReferenceObjC 在 Package.swift:675-685 声明了 MachOFoundation 与 ARM64InstructionDecoding,没有一个源文件 import 它们。
  • +
  • 跨模块的 package 边(只数类型,不数成员): +
      +
    • 核心 → ObjC(16 个):ApproximateSize、CallTargetClaim、CalleeRole、CodeImage、CodeImageSet、CodeReferenceRecognitionSession、CodeReferenceRecording、CrossReferenceMemory、ImageFunctionTable、ImageFunctionTableAttachment、ImageLinkEdit、RegisterFile、ResolvedCallTarget、ScanSite、ScannedCall,以及 public 的 CodeLocation。
    • +
    • 核心 → CrossReferenceAnalysis(27 个):上面这些,加 CallTargetResolver、ExportedFunctionNames、Linkage、ReferenceScanner、RenamedReexportIndex、RuntimeLibraryRules、SlotContent、StringLiteralReference,以及 public 的 CodeReferenceKind、CodeReferenceRoute、IndirectCallEvidence。
    • +
    • ObjC → CrossReferenceAnalysis(10 个):ObjCCodeReferenceRecognizer、ObjCCodeReferenceRecording、ObjCImageSections、ObjCInstanceVariableNames、ObjCMethodNames、ObjCRuntimeFunctions、ObjCRuntimeHelperNames、ObjectiveCClassIndex、ObjectiveCClassObject,以及 public 的 ReceiverClassHint。
    • +
    • CodeAddressResolution → 核心:ImageAddressSpace、SlotResolver(搬家后同在 MachOKitExtensions,不跨包)。
    • +
    • CodeAddressResolution → SwiftThunkAnalysis:CacheImageLocator、ImageAddressSpace、SlotResolver、StubChainResolver,在 AccessorThunkReader、DependencyImageResolver、MachOThunkEnvironment、ThunkTypeNodeBuilder、ObjCMethodThunkReferences 里。
    • +
    • CodeAddressResolution → SwiftDeclarationRendering:ImageAddressSpace(Extensions/Node+OpaqueType.swift:4)。
    • +
    • ARM64InstructionDecoding → 核心与 CodeAddressResolution:ARM64InstructionWord 几乎全部、ARM64Trampoline(搬家后同包);→ CrossReferenceAnalysis:ARM64InstructionWord 的 adding、branchTarget、callTarget、load(跨包)。
    • +
    • MachOReading → 核心:InProcessContext.addressMask 在本库是 package(Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift:62);MachOKitExtensions 那份已是 public(读取层搬迁提案第 286 行就是为它改的),搬过去同包,不成问题。
    • +
    +
  • +
  • 只有在 Darwin 上才编得过的代码都在核心层的进程内部分。CodeImageSet.inProcess(...)(Images/CodeImageSet.swift:86-130)只有 #if arch(arm64),却用了 DyldCacheLoaded.current(:90,MachOKit 里在 #if canImport(Darwin) 内,DyldCacheLoaded+static.swift:9-20)、_dyld_image_count / _dyld_get_image_header(:112-113)、MachOImage(ptr:)(:114)、dladdr(:116-117)。InProcessCrossReferenceMemory 是唯一把地址变成指针的地方(UnsafeRawPointer(bitPattern:) 在 :14、:19、:25、:29),它的掩码来自 InProcessContext.addressMask,而 MachOKitExtensions 的 InProcessContext 整个在 #if canImport(Darwin) 里(Sources/MachOReading/ReadingContext/InProcessContext.swift:7)。ObjC 层在 ObjectiveCClassIndex.swift:146、ObjCMethodNames.swift:52-78、ObjCImageSections.swift:46 按 asMachOImage 分支,用的是类型而不是 dyld 调用;MachOKit 在 Linux 上也有 MachOImage,这几处大概能编,没有在 Linux 上验证过。锁都是 NSLock,没有 Mutex 或 FrameworkToolbox。
  • +
  • IndirectCallEvidence.table 从来只写 .none,也没人读。枚举在 Models/IndirectCallEvidence.swift:4-9,扫描器唯一的写入点给的是 .none(Scanning/ReferenceScanner.swift:355)。本库只有 SwiftSectionKit 的 CrossReferenceFormatting 读它:写进 refs --json(永远是 "none"),文本输出里的「through …」从来不会出现(调研时漏了这一处,见决策日志);RuntimeViewer 只读 tableOffset 与 pointerAuthenticationConstant(CrossReferenceQuery.swift:118、:977)。
  • +
  • 使用方。CrossReferenceAnalysis 是 library product(Package.swift:1523),经 Exports.swift 的 @_exported import 把两个下层的公开类型带出去。本库里 SwiftSectionKit 的 refs / symbolicate 用门面。RuntimeViewer 只有 RuntimeViewerCrossReferences 一个 target import CrossReferenceAnalysis(Analysis/ 下 9 个文件、3 个测试),用到下层的公开类型只有 CodeLocation(13 处)与 ReceiverClassHint。MachOKitUI 与 swift-decompiler 都不用这几个模块。四个要搬的模块都不是本库的 product。
  • +
+
+
+上游或依赖是否已具备能力 +
    +
  • MachOKitExtensions 在两份搬迁落地后(本机的本地 next,f67d290)有九个 product:MachOKitExtensions、MachOReading、MachOResolving、MachOPointers、MachOCaches、MachODependencies、MachOSymbols(与语言无关的那一半)、MachOBase、MachOFoundation;外部依赖只有 MachOKit ≥ 0.55.102、AssociatedObject、swift-fileio。核心层与地址解析要用的东西全在其中,没有一样留在本库。
  • +
  • MachOKitExtensions 没有 CI,README 承诺支持 Linux(理由是 MachOObjCSection 支持 Linux),Package.swift 只列 Apple 平台;Darwin 专属的代码用 #if canImport(Darwin)。两份搬迁提案都写明本机验证不了 Linux、也不加 Linux CI。SPI 分组已有 @_spi(Internals)(24 处)与 @_spi(Support)(4 处)。最新 tag 1.3.3;2.0.0 是大版本,保证本库的旧版本永远不会与它同时解析。
  • +
  • 基础设施搬迁提案写着 ARM64InstructionDecoding 留在本库(第 109 行,第 189 行的图也是)。核心层离不开它,本提案要改这一条,并在那份提案的决策日志里记一行。
  • +
  • 读取层搬迁提案的落地清单(决策日志第 298 行)的顺序是「MachOObjCSection 打 tag → MachOKitExtensions 合入 main 并发 2.0.0 → 本库抬 MachOObjCSection 下限、合入 next、随 0.25.0 发布」。ObjCCodeReferences 要依赖 MachOKitExtensions 2.0.0 的 MachOCodeReferences,所以 MachOObjCSection 的 tag 必须挪到 MachOKitExtensions 2.0.0 之后。
  • +
  • MachOObjCSection:七个 library product;要求 MachOKitExtensions "1.2.0"..<"3.0.0";SPI 分组是 @_spi(Core)(50 处)与 @_spi(Support)(46 处)。fork 新增的东西放单独的 target,上游的 MachOObjCSection target 目录不碰。版本号形状是 <上游 major>.<上游 minor>.<P>NN,fork 最新 tag 是 0.8.206;0.9.0 与 0.10.0 是上游 p-x9 的 tag,fork 不能发 0.9.0。CI 只有 ci.yml:推 main 与 PR 时跑,macos-26、Xcode 26.6,没有 Linux job。本库要求它 "0.8.200"..<"0.9.0"。
  • +
  • RuntimeViewer 跟的是本库与 MachOObjCSection 的 next 分支,五个提交进仓库的 Package.resolved 钉 revision;落地后照惯例抬钉。
  • +
  • 本库的搬迁分支落后 next。feature/move-macho-infrastructure-modules(已包含读取层那条分支)落后 origin/next 13 个提交,正好是 0097 的全部实现;它的 Package.swift 里还是拆层之前的 CrossReferenceAnalysis,SwiftThunkAnalysis 的几个文件改成了 import SwiftSymbols,MachOFixtureSupport 等测试支持模块要改名。合 next 进来预计在 Package.swift、MachOThunkEnvironment.swift、AGENTS.md、两份模块文档、MachOCaches.md 上冲突(没有实际试合)。
  • +
+
+
+前人怎么做的 +
    +
  • 读取层与基础设施两次搬迁就是本提案的模板:文件原样搬、package 改成 @_spi(Internals) public、模块名在 2.0.0 里一次定下、三个仓库按依赖顺序同日落地、功能分支只推送不合进常驻检出(MachOKitExtensions 的 main 一合,本库主检出与 MachOKitUI 就报模块重名,直到本库 0.25.0)。
  • +
  • SwiftPM 的两条硬约束:一个依赖图里模块名不能重复;package 访问级别只在一个 package 之内有效,跨包的「不对外承诺的公开」只能用 @_spi。Apple 自己的框架(SwiftUI 等)大量用 SPI 把内部接口开给自家的其他模块。
  • +
+
+
+验证过什么 +
    +
  • 测试几乎都经门面建分析器。逐个看了 Tests/CrossReferenceAnalysisTests 的 31 个文件与 Tests/CodeAddressResolutionTests:除了 Capstone 对照的两组、MalformedExportTrieTests 与几个源码扫描,其余都要 CrossReferenceAnalyzer,或者要 Swift 元数据、SymbolTestsCore 夹具。分析器留在本库,所以「测试跟代码走」实际搬走的很少。RecognizerExtensionPointTests 的第一条测的正是核心的扩展点,改成直接驱动 ReferenceScanner 就能在 MachOKitExtensions 里证明核心不靠任何语言层也能扫。CodeAddressResolutionTests 五条里有三条只借门面拿 AppKit 镜像和运行中的 cache,改成直接从 MachOKit 拿就能搬;slotResolverResolvesStandaloneBinds 要 SymbolTestsCore 夹具,留在本库。
  • +
  • 0097 没有改任何包依赖。RuntimeViewer 抬钉只是改 revision。
  • +
  • 没验证的:Linux 上能否编过;搬迁分支合 next 的确切冲突;MemberImportVisibility 关着时核心层还暗中依赖了哪些经 Utilities 带进来的成员。
  • +
+
+ +

替代方案考量

+
    +
  • 在 MachOKitExtensions 里做能单独用的公开 API:非 Swift 的工具也能用,但要走一轮完整的 API 设计、多问一两轮,工作量明显变大;今天没有任何不经本库的使用方。用户选了只开 SPI,等有使用方再做。
  • +
  • package 原样全部改成 public:约 300 个内部符号会变成要守 semver 的公开 API,以后每次改内部都可能是破坏性变更。否。
  • +
  • 核心层整个只在 Darwin 上有:省事,但文件模式本来与平台无关,MachOKitExtensions 又承诺 Linux。在 Linux 上真编一遍:要另找 Linux 环境,两份搬迁提案也都没做。都否。
  • +
  • 测试全部留在本库:改动最少,但搬走的仓库里没有自己的测试,下层改了只有本库能发现。用户选了测试跟代码走。
  • +
  • Capstone 对照测试搬去 MachOKitExtensions、加测试专用的 swift-capstone 依赖:要先核实 SwiftPM 会不会让使用方也去拉 Capstone,MachOKitExtensions 也不该为两组测试多一个大 C 库;改成写死的期望值:以后新增的解码就没有独立对照了。都否。
  • +
  • ARM64InstructionDecoding 改成 MachO 前缀:与其余模块命名一致,但它与 Mach-O 无关。并进 MachOAddressResolution:少一个 product,但门面要用解码器时得从地址解析模块导入,概念上不对。都否。
  • +
  • IndirectCallEvidence.table 原样搬过去:核心层里留几个 Swift 专有的名字,与「核心不认识任何语言」相悖;改成与语言无关的叫法:给一个从来只写 .none 的字段换名字没有意义。都否。
  • +
  • 不等 0.25.0、先单独落地:做不到——核心层依赖的 MachOReading 要靠两份搬迁提案先进 MachOKitExtensions。把 0.25.0 提前:要先给 swift-demangling 发版、处理 0057 读取接口旧转发的去留,用户选了不提前。
  • +
  • MachOObjCSection 发 0.9.0(0097 非目标里的设想):0.9.0 已是上游 p-x9 的 tag,fork 照自己的编号规则发 0.8.207。
  • +
+ +

影响

+

源码兼容性

+

有破坏,都随 0.25.0(本库本来就是破坏性版本):

+
    +
  • IndirectCallEvidence.table 与 IndirectCallEvidence.Table 删除,构造器去掉 table:。本库、RuntimeViewer、MachOKitUI、swift-decompiler 都没有调用点。 +
    // Before
    +IndirectCallEvidence(table: .none, tableOffset: offset, pointerAuthenticationConstant: constant, isAddressBlended: false)
    +// After
    +IndirectCallEvidence(tableOffset: offset, pointerAuthenticationConstant: constant, isAddressBlended: false)
  • +
  • CrossReferenceCore、CrossReferenceObjC、CodeAddressResolution、ARM64InstructionDecoding 四个模块从本库消失。它们不是 product,外部不能直接 import;经 CrossReferenceAnalysis 用到的公开类型照旧经 @_exported 可见,名字不变。
  • +
  • 写了 CrossReferenceCore.CodeLocation 这种带模块名的全称的代码要改成 MachOCodeReferences.CodeLocation;查过的使用方里没有这样写的。
  • +
+

不提供 @available(*, deprecated, renamed:) 过渡:被删的字段没有使用方,模块改名也没有外部 import。

+

ABI 兼容性

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+
    +
  • 本库:CrossReferenceAnalysis、SwiftThunkAnalysis、SwiftDeclarationRendering、SwiftSectionKit(经门面,不改代码)、CrossReferenceAnalysisTests、SwiftThunkAnalysisTests。
  • +
  • MachOKitExtensions:多三个 product,2.0.0 本来就是大版本。
  • +
  • MachOObjCSection:多一个 product;MachOKitExtensions 下限抬到 2.0.0,0.8.207 起不能与本库 0.24.0 及更早的版本同时解析(MachOKitUI 这类同时用两个库的使用方要和本库一起升到 0.25.0,而它本来就因两份搬迁提案要等 0.25.0)。
  • +
  • RuntimeViewer:不改代码,落地后抬钉;它的 Local workspace 的兄弟检出要包含三个仓库的新分支才能编(落地前在沙盒里验)。
  • +
  • MachOKitUI、swift-decompiler:不用这几个模块,不受影响。
  • +
+

文档与示例

+

见「提议方案」第 7 节。swift-section 插件的 skill 只讲命令行,不受影响;README 里 refs / symbolicate 的用法不变。

+

API 演进与废弃策略

+
    +
  • IndirectCallEvidence.table 直接删除,不留废弃期:从来只写 .none,没有读者。
  • +
  • 下层的 @_spi(Internals) 接口不承诺 semver,改它不算破坏性变更;公开的五个值类型照常守 semver。
  • +
  • 版本号:MachOKitExtensions 2.0.0(大版本,本来就是)、MachOObjCSection 0.8.207(fork 的补丁号)、本库 0.25.0(本来就是破坏性版本)。
  • +
+ +

落地步骤

+
    +
  1. 把基线备好(已完成) —— 把 origin/next 合进本库的 feature/move-macho-infrastructure-modules(merge,不 rebase、不强推),解冲突,按基础设施搬迁提案改名测试支持模块;先告诉在用这两条搬迁分支的会话。三个仓库从这里切出 feature/move-cross-reference-layers。 +
    • 行为:基础设施搬迁分支合入 next 后本库全量测试(跳过 IntegrationTests)通过,ReferenceTableDigestTests 与 next 逐条一致
  2. +
  3. 登记提案(已完成) —— 本提案状态改 Accepted;三个仓库的提案索引、两份搬迁提案的决策日志(ARM64 也搬、落地顺序)、愿景的相关提案表。 +
    • 行为:无代码改动
  4. +
  5. 解码与地址解析搬进 MachOKitExtensions(已完成,与第 3 步合并) +
      +
    • 行为:SwiftThunkAnalysisTests 全套照旧通过(线程读取经新模块,结果不变)
    • +
    • 行为:stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub、slotResolverMatchesTheProcessForEveryGlobalOffsetTableSlotOfAppKit、cacheImageLocatorFindsTheImageAnAddressLiesIn、stubChainRecordsEveryStubIslandHop 在 MachOKitExtensions 里通过,且不依赖本库
    • +
    • 行为:slotResolverResolvesStandaloneBinds 在本库的 CrossReferenceAnalysisTests 里通过
    • +
    • 行为:ARM64InstructionDecodingTests、RegisterFileTests 经 @_spi(Internals) import 照旧通过
    • +
  6. +
  7. 核心层搬进 MachOKitExtensions(已完成) +
      +
    • 行为:theCoreScansWithOnlyARecognizerFromTests(MachOKitExtensions 里,只装测试的识别器,扫出它认领的调用)
    • +
    • 行为:aTerminalSizePastTheTrieEndsTheNodeWithoutTrapping 在 MachOKitExtensions 里通过
    • +
    • 行为:coreSpellsNoRuntimeSymbolName、onlyInProcessMemoryTurnsAddressesIntoPointers、coreDefinesNoAddressMaskConstant(MachOKitExtensions 的源码扫描)
    • +
    • 行为:indirectCallEvidenceCarriesNoTable(IndirectCallEvidence 只有偏移、常量与是否混入地址三项)
    • +
    • 行为:inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation(整表 A/B,基线为开工时的 next)
    • +
    • 行为:publicNamesStillResolveThroughCrossReferenceAnalysis(只 import CrossReferenceAnalysis 的测试文件仍能用 CodeLocation、CodeReferenceKind.call、ReceiverClassHint.methodReceiver)
    • +
  8. +
  9. ObjC 层搬进 MachOObjCSection(已完成) +
      +
    • 行为:objectiveCLayerReadsMemoryOnlyThroughCrossReferenceMemory、objectiveCLayerSpellsNoSwiftRuntimeName(MachOObjCSection 的源码扫描)
    • +
    • 行为:整表 A/B 照旧逐条一致;selectorQueriesLookUpNoSwiftType 照旧通过
    • +
  10. +
  11. 文档与验收(已完成) —— 吞吐、渲染 A/B、三个仓库的全量测试、RuntimeViewer 沙盒构建。 +
      +
    • 行为:scanThroughputAfterTheMoveIsRecordedInTheModuleDocument(不是断言:整 cache 建表与两条查询的耗时写进 MachOCodeReferences.md,相对基线超过 +5% 先查原因再落地)
    • +
    • 行为:渲染 A/B 三条读取路径逐字节一致
    • +
  12. +
  13. 落地(随 0.25.0)(已完成) —— MachOKitExtensions 2.0.0 → MachOObjCSection 0.8.207 → 本库 0.25.0(要求改成 "0.8.207"..<"0.9.0")→ RuntimeViewer 抬钉,并照基础设施搬迁提案改 RuntimeViewerCore/Package.swift(MachODependencies 改从 MachOKitExtensions 取);本提案取号、改 Implemented,Changelogs/0.25.0.md 写 Breaking,账本加一节。 +
    • 行为:用远端依赖(不设 USING_LOCAL_DEPENDENCIES)、Xcode 26.6 编过本库并跑完 CI 名单里的套件
    • 行为:三个仓库除 debug 全量测试外,都再用 swift test -c release 跑一次(本库加 --skip IntegrationTests,与 CI 的 release 任务一致);之前三个仓库的测试都只在 debug 下跑过
  14. +
+

收尾时必须判断两件事(判断结果写进决策日志,不允许沉默跳过):

+
    +
  • 要不要配套专题文章 —— 预判不要:调用方契约没变(门面不变),SPI 的约定写进两份模块文档即可。
  • +
  • 有没有引入新术语 —— 预判没有:「识别器」等已在 0097 登记;术语表里指向旧模块文档的链接要改。
  • +
+ +

决策日志

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-19Created as Draft0097 落地当天,用户提出开始把交叉引用迁到 MachOKitExtensions。核心层依赖的 MachOReading 要靠两份 MachOKitExtensions 搬迁提案先搬过去,而那两份定了随本库 0.25.0 落地;用户在「现在写提案、随 0.25.0 落地」「把 0.25.0 提前」「先不动」三者中选了第一个。按完整档问了两轮,结论见下面几行
2026-11-19下层只开 SPI用户在「只给本库用的 SPI」「做成能单独用的公开 API」「原样全部改成 public」中选了第一个:今天没有不经本库的使用方,独立公开 API 要多一轮设计,全部改 public 则约 300 个内部符号要守 semver。0097 留下的问题 (a)「没有 Swift 层时引用目标用什么类型」因此不在本提案回答
2026-11-19Linux:文件模式能编用户选了用 #if canImport(Darwin) 包住进程内部分、文件模式在 Linux 上也能编、不加 Linux CI;否掉了「整个模块只在 Darwin 上有」与「另找 Linux 环境真编一遍」
2026-11-19测试跟代码走用户选了测试跟代码走,否掉了全部留在本库。之后核实:交叉引用的测试几乎都经门面建分析器,所以实际搬走的只有直接测下层的几组与源码扫描,另新写一条只装测试识别器的核心扫描测试,证明核心在 MachOKitExtensions 里不靠语言层也能扫
2026-11-19ARM64InstructionDecoding 也搬,名字不变核心层与地址解析都离不开它,而基础设施搬迁提案写着它留在本库,这一条要改。用户选了独立 product、名字不变;否掉了改成 MachO 前缀与并进 MachOAddressResolution
2026-11-19删掉 IndirectCallEvidence.table扫描器从来只写 .none,本库与 RuntimeViewer 都没读过。用户选了删掉;否掉了原样搬过去与改成与语言无关的叫法
2026-11-19Capstone 对照测试留在本库用户选了留在本库、经 SPI 测搬走的解码器,作为「测试跟代码走」的例外;否掉了给 MachOKitExtensions 加测试专用的 swift-capstone 依赖与改成写死的期望值
2026-11-19其余按默认定沿用 0097 定好的名字;ObjC 层在 MachOObjCSection 里另起 target;SPI 分组统一叫 Internals;MachOObjCSection 发 0.8.207(0.9.0 是上游的 tag);核心层改为直接依赖 MachOReading;落地顺序改为 MachOKitExtensions 2.0.0 先于 MachOObjCSection 的 tag;开工第一步把 next 合进基础设施搬迁分支;验收沿用 0097 的标准。用户确认了这些决定
2026-11-19Accepted用户看过简报后批准,开始实现
2026-11-19第 0 步:next 合进基础设施搬迁分支用 merge、不 rebase,合并提交 cf232949。冲突七处:Package.swift(SwiftThunkAnalysis 的依赖取两边之交:搬迁分支的 product 写法加 SwiftSymbols,next 去掉了对 ARM64InstructionDecoding 的直接依赖),MachOThunkEnvironment.swift(两边的 import 都留),AGENTS.md(符号索引改名与 ImageAddressSpace 两处都留),AccessorThunkResolutionExplained.md 与 SwiftSectionKit.md(next 新加的内容套用测试支持模块的改名),愿景第 6 条(两边的意思合成一条,并指向本提案),MachOCaches.md(修改/删除:它已搬去 MachOKitExtensions,本库保持删除,那一行改动补到 MachOKitExtensions 的 SharedCache.md)。next 带进来的代码里只有 CodeAddressResolutionTests 还 import 改名前的 MachOFixtureSupport。MachOKitExtensions 那边负责搬迁的会话确认两条分支都没有未推送的工作;基础设施搬迁提案记了一行「冲突已解、要重新验证」
2026-11-19第 2、3 步合成一步三个与语言无关的模块一次搬进 MachOKitExtensions、一起验证:分开搬时,第 2 步结束的中间状态里核心层还在本库、却要跨包用 ARM64InstructionDecoding 的几乎全部接口,第 3 步再把其中大半收回包内,白改一遍;远程构建一轮也要二三十分钟
2026-11-19搬走的 package 一律改成 @_spi(Internals) public更正第 2 节「同包内用到的保持 package」:一个 SPI 声明的签名里出现的类型也得是 public 或 SPI,按「跨包用到才改」逐个挑会一路连锁到几乎全部;SPI 本来不承诺稳定,两种做法对使用方没有区别。共 291 处
2026-11-19refs --json 去掉 table 键调研漏了一个读者:SwiftSectionKit 的 CrossReferenceFormatting 把 IndirectCallEvidence.table 写进 refs --json(永远是 "none"),文本输出里的「through …」从来不会出现。refs 是 0.25.0 才有的命令、还没发布,插件 skill 与 README 也没写这个键,所以随 table 一起删掉
2026-11-19地址解析测试换了对照stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub 原来对照门面在同一条指令上认出的发送,搬进 MachOKitExtensions 后没有门面,改成对照进程内存里同一地址(加上 cache 的 slide)上的 selector 字符串;GOT 槽那条直接读进程里的槽、掩码取 InProcessContext.addressMask;镜像定位那条从 MachOKit 的 cache 里取 libobjc
2026-11-19路径更正SwiftDeclarationRendering 在 Sources/Output/;MachOKitExtensions 的实现说明平放在 Documentations/Internal/,没有 Modules/ 子目录
2026-11-19第 0 步验证通过,基础设施搬迁分支已推送JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6,本地兄弟依赖;MachOKitExtensions 与 MachOObjCSection 经 agent 沙盒 LocalDependencies/MoveCrossReferenceLayers 的副本接入,Package.swift 那处本地改动不提交):合并后全量测试(跳过 IntegrationTests)2,910 个通过。随后把合并提交快进推到 feature/move-macho-infrastructure-modules;渲染 A/B 与本提案的候选一起跑
2026-11-19第 2–4 步验证通过同一台 Ultra、同样的工具链:MachOKitExtensions 全量 161 个测试通过(搬来的测试改了两处:本库测试支持里的 DyldCache(path: .current) 那边没有,改按 cache 文件路径打开;cache 里按名字找不到 libobjc.A.dylib,改按路径找);MachOObjCSection 照 CI 跳过 MachOObjCSectionTests 跑,343 个通过;本库全量 2,901 个通过(比第 0 步少 9 个、2 个套件,正是搬走与删掉的那几组)。整表 A/B:基线是 origin/next(9d5c0310),AppKit、SwiftUICore、Foundation 三个镜像的引用表摘要逐个一致
2026-11-19两侧共用的测试文件不 import SPIReferenceTableDigestTests 与 ScanThroughputBenchmarkTests 要原样拷到基线上跑,PublicNameTests 证明只 import 门面就够,三者都只用公开 API;批量给测试加 SPI import 时把它们排除。整表对照的归一化多去掉两样:新的模块名前缀,以及基线输出里永远是 .none 的 table 字段
2026-11-19插件 skill 同步references/cross-references.md 原来说间接调用显示 indirect through … 并带上哪张表,与实际输出不符(「through」从来不出现,表的信息已删),改成照实际输出描述
2026-11-19release 下的测试编译错误,修在本分支两侧预编 release 测试时,候选报 SymbolTableEquivalenceTests.swift 里「sending 'nameC' risks causing data races」:基础设施搬迁分支带来的测试里,&& 右侧的自动闭包捕获了非 Sendable 的指针,只有 Xcode 26.6 的 release 才报,debug 能过,0.25.0 合进 main 时 CI 的 release 任务也会卡在这里。先把前缀判断算进局部变量,行为不变;同样的写法全库只有这一处。用户决定修复只留在本分支,两份搬迁提案的落地清单都加一步「用 swift test -c release 跑一次」(决策日志在本提案的 MachOKitExtensions 分支上)
2026-11-19吞吐:不慢反快Ultra、Xcode 26.6、release,两侧交替各三轮取最好:进程内整 cache 建表 2.67 → 2.53 秒,init 调用者扫描 1.71 → 1.53 秒,makeKeyAndOrderFront: 0.317 → 0.293 秒;归档 macOS 27.2 cache 文件整表 2.75 → 2.51 秒(128,120,075 条引用,两侧相同)。各项快 1% 到 11%,满足「不超过 +5%」;候选同时包含两份搬迁提案,没有追是哪一处更快。进程内整表的引用数差 18,250 条,来自测试进程自己的镜像(两侧的测试二进制不同)。逐项数字在 MachOKitExtensions 的 MachOCodeReferences.md
2026-11-19渲染 A/B 全部一致基线 origin/next(9d5c0310),候选是本提案的分支(同时包含两份搬迁提案,所以这一轮也补上了基础设施搬迁欠的 A/B):归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 26.5 模拟器、进程内,共 84 对 dump 与 interface 逐字节一致,没有缺失与跳过
2026-11-19RuntimeViewer 验证沙盒里导出 RuntimeViewer 的 next(6cb25e09)与本提案的分支,MachOKitExtensions、MachOObjCSection 用本提案分支的副本:Core(含测试)、CLI、MCP 三个包都编过,RuntimeViewer 的源码一行没改;交叉引用测试 82 个通过(1 个预先标记的已知问题)。第一轮跑到一半退出码 1、没有汇总也没有崩溃报告,原样重跑一遍全过,原因没查明。另发现基础设施搬迁要求 RuntimeViewer 改清单:RuntimeViewerCore/Package.swift:269 从本库取 MachODependencies,搬迁后这个 product 只在 MachOKitExtensions,解析失败;沙盒里临时改成从 MachOKitExtensions 取才编得下去。用户决定落地那天再改 RuntimeViewer,记在基础设施搬迁提案(本提案的 MachOKitExtensions 分支上)与第 6 步
2026-11-19实现完成,待用户看过后收尾第 0 到 5 步都已完成,第 6 步(落地)随 0.25.0。功能分支没有合进任何常驻检出:两份搬迁提案定了它们的分支只推送、不合进常驻检出,本提案叠在它们上面,照同样的规矩(MachOKitExtensions 的 main 一合,本库主检出与 MachOKitUI 就报模块重名)。文档判断:不另写使用指南,调用方契约没变(门面不变);实现说明写在 MachOKitExtensions 的 MachOCodeReferences.md、MachOAddressResolution.md、ARM64InstructionDecoding.md 与 MachOObjCSection 的 ObjCCodeReferences.md,本库的 Modules/CrossReferenceAnalysis.md 仍是三层的总说明;没有新术语,术语表只改了链接。Ultra 上候选 worktree 的 Package.swift 有一处不提交的改动,把两个兄弟依赖指向 agent 沙盒 LocalDependencies/MoveCrossReferenceLayers,拉新代码前要先还原
2026-11-19落地前的 release 测试两侧都在 JHs-Mac-Studio-Ultra 上用 Xcode 26.6 跑 swift test -c release。MachOKitExtensions 161 个测试全过;两份搬迁提案记作后续项的 readersOfOneCacheFileShareOneMapping 已随第 7 步搬进 MachOKitExtensions,也通过。本库加 --skip IntegrationTests,2,901 个测试里红 6 条,都不是本提案带来的:SpecializedRuntimeTypeNameTests 的 5 条是已知的 release 必红(release 优化把测试里没用到的私有类型连描述符一起删了,CI 的套件名单不含它);LargeStackTaskExecutionTests.demanglerEntriesInsideTheBodyDoNotHop 在满载的全量里第 3.2 秒才轮到,executeAsync 被挤到了别的线程,单独连跑三次都通过。渲染 A/B 不重跑:落地前后代码没变,第 4 步的 84 对仍然覆盖
2026-11-19Implemented,编号 0098,随 0.25.0 落地按第 6 节的顺序同日落地:MachOKitExtensions 把本提案的分支(已含两份搬迁分支与 main 的全部提交)快进到 main,打 2.0.0,两份搬迁提案取号 0002、0003;MachOObjCSection 把分支 --no-ff 合进 next 并快进 main,CI 通过后打 0.8.207;本库把 MachOObjCSection 的要求改成 "0.8.207"..<"0.9.0",swift-demangling 改成 "0.7.4"..<"0.8.0"(0092 用到它 next 上的 useExistentialAny,0.7.4 同日发布),分支合进 next 后随 0.25.0 发布,账本第 138 节记两份搬迁、第 139 节记本提案。三个仓库的提案索引都改成编号链接,MachOObjCSection 索引里 0088、0096 两行过时的 cross-repository draft 一并改正。RuntimeViewer 照基础设施搬迁提案改清单、抬钉。没做的:MachOObjCSection 文档注释里的旧名 SymbolIndexStore(ObjCExportIndex.swift:129)留着,那是基础设施搬迁的遗留,不在本提案范围
+ +
+ + diff --git a/Documentations/Evolutions/0098-move-cross-reference-layers.md b/Documentations/Evolutions/0098-move-cross-reference-layers.md new file mode 100644 index 000000000..8662f5292 --- /dev/null +++ b/Documentations/Evolutions/0098-move-cross-reference-layers.md @@ -0,0 +1,545 @@ +# 0098 - 交叉引用的核心层与 ObjC 层迁出本库 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-19 +- **最后更新**: 2026-11-19 +- **所属愿景**: [不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)(「我们选的方向」第 6 条:分层归属) +- **关联提案**: + - [0097 offline-cross-references-and-symbolication](0097-offline-cross-references-and-symbolication.md):在本库里把交叉引用拆成核心、ObjC、Swift 三层,并给下层定好了落脚处与名字;它的「非目标」第一条留给本提案的五个问题,在这里逐一定下。 + - MachOKitExtensions [0002 move-reading-and-resolving-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) 与 [0003 move-macho-infrastructure-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md)(与本提案同日落地,都是 Implemented):把本库的读取层与 MachO 基础模块搬进 MachOKitExtensions 2.0.0。本提案的实现叠在它们的分支上,三份同日落地。 +- **跨仓库**: 本提案是 MachOKitExtensions、MachOObjCSection 与本库共用的唯一提案;另外两个仓库的提案索引各加一行 cross-repository 指向这里(落地步骤第 1 步)。 +- **实现分支 / PR**: 三个仓库都是 `feature/move-cross-reference-layers`。本库与 MachOKitExtensions 从各自的 `feature/move-macho-infrastructure-modules` 切出,MachOObjCSection 从 `next` 切出。 +- **配套文档**: 实现说明 MachOKitExtensions [MachOCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md)、[MachOAddressResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOAddressResolution.md)、[ARM64InstructionDecoding.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/ARM64InstructionDecoding.md),MachOObjCSection [ObjCCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/main/Documentations/Internal/ObjCCodeReferences.md);三层的总说明仍是本库的 [Modules/CrossReferenceAnalysis.md](../Internal/Modules/CrossReferenceAnalysis.md)。不另写使用指南:调用方契约没变 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +0097 在本库里把交叉引用拆成了三层,并约定下层量完、跑稳之后再搬走。本提案就做这次搬家:与语言无关的三个模块搬进 MachOKitExtensions——`CrossReferenceCore` 改名 `MachOCodeReferences`,`CodeAddressResolution` 改名 `MachOAddressResolution`,`ARM64InstructionDecoding` 名字不变;ObjC 层 `CrossReferenceObjC` 搬进 MachOObjCSection,成为新 target `ObjCCodeReferences`。下层只给本库开 SPI(`@_spi(Internals)`),对外的分析器、公开模型和 Swift 层留在本库的 `CrossReferenceAnalysis`,RuntimeViewer 不用改代码。核心层的进程内部分用 `#if canImport(Darwin)` 包住,文件模式在 Linux 上也能编;顺带删掉从来只写 `.none`、没人读过的 `IndirectCallEvidence.table`。测试跟着代码走,但因为分析器留在本库,真正搬走的只有直接测下层的几组和源码扫描。实现叠在两份 MachOKitExtensions 搬迁提案的分支上,按 MachOKitExtensions 2.0.0、MachOObjCSection 0.8.207、本库 0.25.0 的顺序同日落地。 + +## 动机 + +完整动机见愿景《[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)》「我们选的方向」第 6 条:与语言无关的部分归 MachOKitExtensions,ObjC 专属的归 MachOObjCSection,Swift 专属的与命令入口留在本库;新代码先在本库写成独立模块、用源码扫描守住边界,量过、跑稳之后另写迁移提案整体搬过去。这一步特有的部分: + +- **拆层的前提已经满足。** 0097 留下的四项「先实测」的未知都已量完:离线整 cache 建表 2.58 秒,与进程内持平;拆层前后吞吐差别在 −0.5% 到 +3% 之间;全量 2,993 个测试零失败,渲染 A/B 84 对逐字节一致(0097 决策日志「吞吐验收」「第 4 步完成」「实现完成」三行)。识别器接口在扫描热路径上量过,不再需要在一个仓库里反复改。 +- **下层现在借住在一个读 Swift 元数据的库里。** `MachOAddressResolution` 要做的事(桩链、槽、cache 镜像定位)与 Swift 无关,本库的 `SwiftThunkAnalysis` 与 `SwiftDeclarationRendering` 只是它的两个使用者;ObjC 层读类表要借 MachOObjCSection 的 SPI(`@_spi(Core) import MachOObjCSection`,`Sources/Analysis/CrossReferenceObjC/ObjectiveCClassIndex.swift:3`,为了 `ObjCClass64(layout:offset:)`),搬进 MachOObjCSection 之后这就是包内调用。愿景后面几个阶段(带注解的反汇编、数据解码、常量追踪)都要建在核心层上,核心在 MachOKitExtensions,它们就不必依赖一个 Swift 元数据库。 +- **趁 2.0.0 一起搬最省。** MachOKitExtensions 2.0.0 本来就是大版本(两份搬迁提案加模块),本库 0.25.0 本来就是破坏性版本(模块搬走、`MachOSymbols` 拆分)。同日落地只走一轮三个仓库的发版;之后单独搬,就要再来一轮 MachOKitExtensions → MachOObjCSection → 本库的发版,本库还要再发一个破坏性版本。 +- **本库里的名字就是为这一步起的。** 0097 刻意让下层在本库里的名字不同于落脚处(`CrossReferenceCore` 对 `MachOCodeReferences`),避免本库已发布版本里的模块与 MachOKitExtensions 2.x 的新模块同名;下层两个模块也没有做成 product,没有外部使用方。搬的时候改名,只动本库内部的 import。 + +## 前期调研 + +### 现状代码怎么走的 + +**四个要搬的模块**(`next` 的 `a98cbc15`;`package` 与 `public` 的个数按声明关键字 grep,近似值): + +| 模块(本库) | 位置 | 文件 | 行数 | `public` | `package` | 实际 import | +|---|---|---|---|---|---|---| +| `CrossReferenceCore` | `Sources/Analysis/CrossReferenceCore` | 19 | 3,292 | 14(`CodeLocation`、`CodeReferenceKind`、`CodeReferenceRoute`、`IndirectCallEvidence` 及其成员) | 约 230 | Foundation、MachOKit(`CodeImage.swift:2`、`FileCrossReferenceMemory.swift:2` 带 `@_spi(Support)`,为了 `MemoryTrieTree`)、MachOKitExtensions、ARM64InstructionDecoding、CodeAddressResolution、MachOFoundation(只在 `Memory/InProcessCrossReferenceMemory.swift:1`) | +| `CrossReferenceObjC` | `Sources/Analysis/CrossReferenceObjC` | 8 | 1,152 | 1(`ReceiverClassHint`) | 约 78 | Foundation、MachOKit、MachOObjCSection(`ObjCMethodNames.swift`)、`@_spi(Core) import MachOObjCSection`(`ObjectiveCClassIndex.swift:3`)、CrossReferenceCore | +| `CodeAddressResolution` | `Sources/Analysis/CodeAddressResolution` | 4 | 434 | 0 | 33 | Foundation、MachOKit、MachOKitExtensions、MachOReading(只为 `readElements(offset:numberOfElements:)`,`StubChainResolver.swift:52`、`ImageAddressSpace.swift:35`)、ARM64InstructionDecoding | +| `ARM64InstructionDecoding` | `Sources/Support/ARM64InstructionDecoding` | 2 | 311 | 0 | 28(全部) | 无 | + +- **核心层经 `MachOFoundation` 间接带进了 Utilities。** `InProcessCrossReferenceMemory.swift:40` 只用到 `InProcessContext.addressMask`(在 MachOReading),但 `import MachOFoundation` 经 `MachOBase/Exported.swift:10` 的 `@_exported import Utilities` 把 FrameworkToolbox、AssociatedObject、MemberwiseInit、Dependencies、AsyncAlgorithms 都带了进来(`Package.swift:356-368`)。`MemberImportVisibility` 没有在任何 target 上打开,所以核心层别的文件可能悄悄用了这条链带进来的成员——这一点没有逐个核实,搬的时候编译会告诉我们。 +- **声明了但没用的依赖。** `CrossReferenceObjC` 在 `Package.swift:675-685` 声明了 `MachOFoundation` 与 `ARM64InstructionDecoding`,没有一个源文件 import 它们。 +- **跨模块的 `package` 边**(只数类型,不数成员): + - 核心 → ObjC(16 个):`ApproximateSize`、`CallTargetClaim`、`CalleeRole`、`CodeImage`、`CodeImageSet`、`CodeReferenceRecognitionSession`、`CodeReferenceRecording`、`CrossReferenceMemory`、`ImageFunctionTable`、`ImageFunctionTableAttachment`、`ImageLinkEdit`、`RegisterFile`、`ResolvedCallTarget`、`ScanSite`、`ScannedCall`,以及 public 的 `CodeLocation`。 + - 核心 → `CrossReferenceAnalysis`(27 个):上面这些,加 `CallTargetResolver`、`ExportedFunctionNames`、`Linkage`、`ReferenceScanner`、`RenamedReexportIndex`、`RuntimeLibraryRules`、`SlotContent`、`StringLiteralReference`,以及 public 的 `CodeReferenceKind`、`CodeReferenceRoute`、`IndirectCallEvidence`。 + - ObjC → `CrossReferenceAnalysis`(10 个):`ObjCCodeReferenceRecognizer`、`ObjCCodeReferenceRecording`、`ObjCImageSections`、`ObjCInstanceVariableNames`、`ObjCMethodNames`、`ObjCRuntimeFunctions`、`ObjCRuntimeHelperNames`、`ObjectiveCClassIndex`、`ObjectiveCClassObject`,以及 public 的 `ReceiverClassHint`。 + - `CodeAddressResolution` → 核心:`ImageAddressSpace`、`SlotResolver`(搬家后同在 MachOKitExtensions,不跨包)。 + - `CodeAddressResolution` → `SwiftThunkAnalysis`:`CacheImageLocator`、`ImageAddressSpace`、`SlotResolver`、`StubChainResolver`,在 `AccessorThunkReader`、`DependencyImageResolver`、`MachOThunkEnvironment`、`ThunkTypeNodeBuilder`、`ObjCMethodThunkReferences` 里。 + - `CodeAddressResolution` → `SwiftDeclarationRendering`:`ImageAddressSpace`(`Extensions/Node+OpaqueType.swift:4`)。 + - `ARM64InstructionDecoding` → 核心与 `CodeAddressResolution`:`ARM64InstructionWord` 几乎全部、`ARM64Trampoline`(搬家后同包);→ `CrossReferenceAnalysis`:`ARM64InstructionWord` 的 `adding`、`branchTarget`、`callTarget`、`load`(跨包)。 + - MachOReading → 核心:`InProcessContext.addressMask` 在本库是 `package`(`Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift:62`);MachOKitExtensions 那份已是 public(读取层搬迁提案第 286 行就是为它改的),搬过去同包,不成问题。 +- **只有在 Darwin 上才编得过的代码都在核心层的进程内部分。** `CodeImageSet.inProcess(...)`(`Images/CodeImageSet.swift:86-130`)只有 `#if arch(arm64)`,却用了 `DyldCacheLoaded.current`(:90,MachOKit 里在 `#if canImport(Darwin)` 内,`DyldCacheLoaded+static.swift:9-20`)、`_dyld_image_count` / `_dyld_get_image_header`(:112-113)、`MachOImage(ptr:)`(:114)、`dladdr`(:116-117)。`InProcessCrossReferenceMemory` 是唯一把地址变成指针的地方(`UnsafeRawPointer(bitPattern:)` 在 :14、:19、:25、:29),它的掩码来自 `InProcessContext.addressMask`,而 MachOKitExtensions 的 `InProcessContext` 整个在 `#if canImport(Darwin)` 里(`Sources/MachOReading/ReadingContext/InProcessContext.swift:7`)。ObjC 层在 `ObjectiveCClassIndex.swift:146`、`ObjCMethodNames.swift:52-78`、`ObjCImageSections.swift:46` 按 `asMachOImage` 分支,用的是类型而不是 dyld 调用;MachOKit 在 Linux 上也有 `MachOImage`,这几处大概能编,没有在 Linux 上验证过。锁都是 `NSLock`,没有 `Mutex` 或 FrameworkToolbox。 +- **`IndirectCallEvidence.table` 从来只写 `.none`,也没人读。** 枚举在 `Models/IndirectCallEvidence.swift:4-9`(`classVirtualTable`、`protocolWitnessTable`、`valueWitnessTable`、`none`),扫描器唯一的写入点给的是 `.none`(`Scanning/ReferenceScanner.swift:355`)。本库只有 SwiftSectionKit 的 `CrossReferenceFormatting` 读它:写进 `refs --json`(永远是 `"none"`),文本输出里的「through …」从来不会出现(调研时漏了这一处,见决策日志);RuntimeViewer 只读 `tableOffset` 与 `pointerAuthenticationConstant`(`RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift:118`、`:977`)。 +- **使用方。** `CrossReferenceAnalysis` 是 library product(`Package.swift:1523`),经 `Sources/Analysis/CrossReferenceAnalysis/Exports.swift` 的 `@_exported import` 把两个下层的公开类型带出去。本库里 SwiftSectionKit 的 `refs` / `symbolicate`(`Sources/Commands/SwiftSectionKit/CrossReferences/` 的四个文件)用门面。RuntimeViewer 只有 `RuntimeViewerCore` 的 `RuntimeViewerCrossReferences` 一个 target import `CrossReferenceAnalysis`(`Analysis/` 下 9 个文件、3 个测试),用到下层的公开类型只有 `CodeLocation`(13 处)与 `ReceiverClassHint`(`CrossReferenceQuery.swift:764`、`ObjectiveCSendMatching.swift:28,41-65`)。MachOKitUI 与 swift-decompiler 都不用这几个模块。四个要搬的模块都不是本库的 product(product 列表 `Package.swift:1508-1536`)。 + +### 上游或依赖是否已具备能力 + +- **MachOKitExtensions 在两份搬迁落地后**(本机的本地 `next`,`f67d290`,已合入基础设施搬迁分支)有九个 product:`MachOKitExtensions`、`MachOReading`、`MachOResolving`、`MachOPointers`、`MachOCaches`、`MachODependencies`、`MachOSymbols`(与语言无关的那一半)、`MachOBase`、`MachOFoundation`(`Package.swift:66-112`);外部依赖只有 MachOKit ≥ 0.55.102、AssociatedObject、swift-fileio。核心层与地址解析要用的东西全在其中,没有一样留在本库。 +- **MachOKitExtensions 没有 CI**(基础设施搬迁提案第 82 行;`main` 与 `next` 都没有 `.github`),**README 承诺支持 Linux**(`README.md:127-136`,理由是 MachOObjCSection 支持 Linux),`Package.swift` 只列 Apple 平台;Darwin 专属的代码用 `#if canImport(Darwin)`(`InProcessContext.swift`、`DependencyLocating.swift`、`DyldCacheLoaded+Cached.swift`)。两份搬迁提案都写明本机验证不了 Linux、也不加 Linux CI。SPI 分组已有 `@_spi(Internals)`(24 处)与 `@_spi(Support)`(4 处)。最新 tag 1.3.3;2.0.0 是大版本,保证本库的旧版本永远不会与它同时解析。 +- **基础设施搬迁提案写着 `ARM64InstructionDecoding` 留在本库**(第 109 行「不迁 `Utilities`、`MachOMacros`、`ARM64InstructionDecoding` 及任何 Swift 层模块」,第 189 行的图也是)。核心层离不开它,本提案要改这一条,并在那份提案的决策日志里记一行。 +- **读取层搬迁提案的落地清单**(决策日志第 298 行)的顺序是「MachOObjCSection 打 tag → MachOKitExtensions 合入 `main` 并发 2.0.0 → 本库抬 MachOObjCSection 下限、合入 `next`、随 0.25.0 发布」。`ObjCCodeReferences` 要依赖 MachOKitExtensions 2.0.0 的 `MachOCodeReferences`,所以 MachOObjCSection 的 tag 必须挪到 MachOKitExtensions 2.0.0 之后。 +- **MachOObjCSection**(`.worktrees/MachOObjCSection`,`next`):library product 有 `MachOObjCSection`、`ObjCMetadataSource`、`ObjCDeclarationRendering`、`ObjCIndexing`、`ObjCInterface`、`ObjCOutputTransformer`、`ObjCDiffing`(`Package.swift:65-98`);要求 MachOKitExtensions `"1.2.0"..<"3.0.0"`(`:145-162`);SPI 分组是 `@_spi(Core)`(50 处)与 `@_spi(Support)`(46 处)。**fork 新增的东西放单独的 target**,上游的 `MachOObjCSection` target 目录不碰,合上游时才不冲突(`Documentations/Internal/ObjCMetadataSourceGenericization.md:37-55`)。版本号形状是 `<上游 major>.<上游 minor>.

NN`(`Documentations/Glossary.md:41-46`),fork 最新 tag 是 0.8.206;**`0.9.0` 与 `0.10.0` 是上游 p-x9 的 tag**,fork 不能发 0.9.0(0097 非目标里「MachOObjCSection 发 0.9.0」的说法不成立)。CI 只有 `ci.yml`:推 `main` 与 PR 时跑,macos-26、Xcode 26.6,`swift test --skip MachOObjCSectionTests`,没有 Linux job。本库要求它 `"0.8.200"..<"0.9.0"`(`Package.swift:185`)。 +- **RuntimeViewer 跟的是本库与 MachOObjCSection 的 `next` 分支**(`RuntimeViewerCore/Package.swift:119-137`),五个提交进仓库的 `Package.resolved` 钉 revision;落地后照 `chore: pin MachOSwiftSection …` 的惯例抬钉。 +- **本库的搬迁分支落后 `next`。** `feature/move-macho-infrastructure-modules`(已包含读取层那条分支)落后 `origin/next` 13 个提交,正好是 0097 的全部实现;它的 `Package.swift` 里还是拆层之前的 `CrossReferenceAnalysis`,`SwiftThunkAnalysis` 的几个文件改成了 import `SwiftSymbols`,`MachOFixtureSupport` 等测试支持模块要改名。合 `next` 进来预计在 `Package.swift`、`MachOThunkEnvironment.swift`、`AGENTS.md`、两份模块文档、`MachOCaches.md` 上冲突(MachOKitExtensions 那边的记录;没有实际试合)。 + +### 前人怎么做的 + +- **读取层与基础设施两次搬迁**(MachOKitExtensions 的两份提案)就是本提案的模板:文件原样搬、`package` 改成 `@_spi(Internals) public`、模块名在 2.0.0 里一次定下、三个仓库按依赖顺序同日落地、功能分支只推送不合进常驻检出(MachOKitExtensions 的 `main` 一合,本库主检出与 MachOKitUI 就报模块重名,直到本库 0.25.0)。 +- **SwiftPM 的两条硬约束**:一个依赖图里模块名不能重复;`package` 访问级别只在一个 package 之内有效,跨包的「不对外承诺的公开」只能用 `@_spi`。Apple 自己的框架(SwiftUI 等)大量用 SPI 把内部接口开给自家的其他模块。 + +### 验证过什么 + +- **测试几乎都经门面建分析器。** 逐个看了 `Tests/CrossReferenceAnalysisTests` 的 31 个文件与 `Tests/CodeAddressResolutionTests`:除了 Capstone 对照的两组(`ARM64InstructionDecodingTests`、`RegisterFileTests`)、`MalformedExportTrieTests` 与几个源码扫描,其余都要 `CrossReferenceAnalyzer`(`SharedAnalyzer` / `ProcessAnalyzer`),或者要 Swift 元数据、SymbolTestsCore 夹具。分析器留在本库,所以「测试跟代码走」实际搬走的很少(见「提议方案」第 5 节)。`RecognizerExtensionPointTests` 的第一条测的正是核心的扩展点,它借门面建分析器,改成直接驱动 `ReferenceScanner` 就能在 MachOKitExtensions 里证明核心不靠任何语言层也能扫。`CodeAddressResolutionTests` 五条里有三条只借门面拿 AppKit 镜像和运行中的 cache,改成直接从 MachOKit 拿就能搬;`slotResolverResolvesStandaloneBinds` 要 SymbolTestsCore 夹具,留在本库。 +- **0097 没有改任何包依赖。** `git diff 3181325d origin/next -- Package.swift` 里没有 `.package(` 一行的变化;RuntimeViewer 抬钉只是改 revision。 +- **没验证的**:Linux 上能否编过;搬迁分支合 `next` 的确切冲突;`MemberImportVisibility` 关着时核心层还暗中依赖了哪些经 Utilities 带进来的成员。 + +## 提议方案 + +### 1. 去向与名字 + +| 本库现在 | 去向 | 新名字 | product | 依赖 | +|---|---|---|---|---| +| `ARM64InstructionDecoding` | MachOKitExtensions | `ARM64InstructionDecoding`(不变) | 是 | 无 | +| `CodeAddressResolution` | MachOKitExtensions | `MachOAddressResolution` | 是 | MachOKit、MachOKitExtensions、MachOReading、ARM64InstructionDecoding | +| `CrossReferenceCore` | MachOKitExtensions | `MachOCodeReferences` | 是 | MachOKit、MachOKitExtensions、MachOReading、MachOAddressResolution、ARM64InstructionDecoding | +| `CrossReferenceObjC` | MachOObjCSection | `ObjCCodeReferences`(新 target,不进上游的 `MachOObjCSection` target) | 是 | MachOKit、MachOObjCSection、MachOCodeReferences | +| `CrossReferenceAnalysis` | 留在本库 | 不变 | 是(已是) | ARM64InstructionDecoding、MachOAddressResolution、MachOCodeReferences、ObjCCodeReferences,以及原有的 Swift 层依赖 | + +- `ARM64InstructionDecoding` 不是 Mach-O 专有的,不加 `MachO` 前缀。本库 0.25.0 起不再有同名模块;本库 0.24.0 及更早的版本要求 MachOKitExtensions 1.x,永远不会与 2.0.0 同时解析,所以不会撞名。 +- 核心层改为直接依赖 `MachOReading`,不再依赖 `MachOFoundation`:只有这样,`MachOCodeReferences` 才不会带进 `MachOSymbols`、`MachODependencies`(以及本库那份 `MachOBase` 里的 Utilities)。ObjC 层去掉两个没用的依赖。 +- 文件原样搬,目录结构照旧(`Images/`、`Memory/`、`Models/`、`Recognition/`、`Scanning/`、`Symbolication/`),除了下面几节列出的改动,只改 import 与访问级别。 + +### 2. API:只给本库开 SPI + +- **跨包用到的 `package` 声明改成 `@_spi(Internals) public`,同包里用到的保持 `package`。** 判据是「另一个 package 的模块要不要用它」:`MachOAddressResolution` → `MachOCodeReferences`、`ARM64InstructionDecoding` → 两者都在 MachOKitExtensions 一个包里,保持 `package`;`MachOCodeReferences` 被 `ObjCCodeReferences`(MachOObjCSection)和 `CrossReferenceAnalysis`(本库)用到的那些、`MachOAddressResolution` 被 `SwiftThunkAnalysis` 与 `SwiftDeclarationRendering` 用到的四个类型、`ARM64InstructionWord` 被门面用到的四个成员、`ObjCCodeReferences` 被门面用到的十个类型,改成 SPI。两个仓库都用 `Internals` 这个分组名:MachOKitExtensions 已有这个分组;MachOObjCSection 现有的是 `Core` 与 `Support`,新分组不与它们冲突。 +- **已经公开的值类型保持 public**:`CodeLocation`、`CodeReferenceKind`、`CodeReferenceRoute`、`IndirectCallEvidence`(删掉 `table` 之后)、`ReceiverClassHint`。它们今天就是本库公开 API 的一部分(经 `@_exported`),RuntimeViewer 用着其中的 `CodeLocation` 与 `ReceiverClassHint`。 +- **对外的分析器、公开模型与 Swift 层留在本库。** `CrossReferenceAnalyzer`、`CodeReference`、`CodeReferenceTarget`、`CodeReferenceTable`、`CodeReferenceIndex`、`CodeFunction`、`AddressSymbolication` 都不动。单用 MachOKitExtensions 做不了交叉引用;下层对外该长什么样(没有 Swift 层时引用目标用什么类型表示),等真有不经本库的使用方时再定——0097 非目标里留下的问题 (a) 因此不在本提案里回答。 +- **SPI 不承诺 semver。** MachOKitExtensions 与 MachOObjCSection 的模块文档写明:`@_spi(Internals)` 的接口只给 MachOSwiftSection 用,随时可能变,不算破坏性变更。 +- **门面的导出照旧。** `Exports.swift` 改成 `@_exported import MachOCodeReferences` 与 `@_exported import ObjCCodeReferences`,`import CrossReferenceAnalysis` 的使用方照旧看得到那几个公开值类型;门面里要用内部接口的文件另写 `@_spi(Internals) import`。 + +### 3. 删掉 `IndirectCallEvidence.table` + +`IndirectCallEvidence` 只保留与语言无关的事实:`tableOffset`、`pointerAuthenticationConstant`、`isAddressBlended`。`Table` 枚举与 `table` 属性删掉,构造器去掉 `table:` 参数,扫描器的写入点(`ReferenceScanner.swift:355`)跟着改。将来要区分 vtable、协议见证表、值见证表时,由 Swift 层在门面里另加,不回到核心层。这是本库公开 API 的破坏性改动,随 0.25.0 发布,写进 changelog 的 Breaking 一节;本库之外没有使用方(RuntimeViewer、MachOKitUI、swift-decompiler 都查过),不留废弃期。`refs --json` 里永远是 `"none"` 的 `table` 键一起删掉:`refs` 是 0.25.0 才有的命令,还没发布。 + +### 4. Linux:文件模式能编,进程内部分用 `#if` 包住 + +- `MachOCodeReferences` 里,`CodeImageSet.inProcess(...)` 从 `#if arch(arm64)` 改成 `#if canImport(Darwin) && arch(arm64)`;`InProcessCrossReferenceMemory.swift` 整个文件包进 `#if canImport(Darwin)`。文件模式(`FileCrossReferenceMemory`、从 `FullDyldCache` 或一组 `MachOFile` 建镜像集)不包。 +- `ObjCCodeReferences` 里按 `asMachOImage` 分支的几处先不包,编译报错再包。 +- 照两份搬迁提案的做法:不加 Linux CI,本机验证不了,模块文档写明「Linux 上未验证」。门面(本库)不变——本库不承诺 Linux。 + +### 5. 测试:跟着代码走 + +分析器留在本库,所以只有直接测下层、不经门面的测试能搬: + +| 测试 | 去向 | 怎么改 | +|---|---|---| +| `MalformedExportTrieTests`(`RenamedReexportIndex`) | MachOKitExtensions `MachOCodeReferencesTests` | 改 import | +| `RecognizerExtensionPointTests.aRecognizerDefinedInTestsPlugsInWithoutChangingTheCore` | 同上,改名 `theCoreScansWithOnlyARecognizerFromTests` | 不借门面:从运行中的 cache 直接建 `CodeImageSet`,只装测试里定义的识别器,驱动 `ReferenceScanner` | +| `CodeAddressResolutionTests` 里不要夹具的三条(`stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub`、`slotResolverMatchesTheProcessForEveryGlobalOffsetTableSlotOfAppKit`、`cacheImageLocatorFindsTheImageAnAddressLiesIn`)与要归档 iOS cache 的 `stubChainRecordsEveryStubIslandHop` | MachOKitExtensions `MachOAddressResolutionTests` | AppKit 镜像与 cache 改从 MachOKit(`DyldCacheLoaded.current`、`FullDyldCache`)直接拿,不借门面的 `ProcessAnalyzer` | +| 源码扫描:核心不写 `objc_` / `swift_` 字面量(`crossReferenceCoreSpellsNoRuntimeSymbolName`)、只有 `InProcessCrossReferenceMemory` 把地址变成指针(`MemoryAccessScanTests` 的核心部分)、不写自定义地址掩码常量(`AddressMaskScanTests`,连同 `FileCrossReferenceMemory` 那条 slide info 的白名单) | MachOKitExtensions `MachOCodeReferencesTests` | 扫描目录换成 `Sources/MachOCodeReferences` | +| 源码扫描:ObjC 层只经 `CrossReferenceMemory` 读内存、不写 `swift_` 字面量 | MachOObjCSection `ObjCCodeReferencesTests`(新) | 扫描目录换成 `Sources/ObjCCodeReferences` | +| `CrossReferenceLayerBoundaryTests` 的两条 import 白名单 | 删除 | 下层搬走之后 SwiftPM 本身就不允许它们 import 本库的模块 | +| `ARM64InstructionDecodingTests`、`RegisterFileTests`(Capstone 对照)与辅助的 `InstructionEncoding.swift` | 留在本库 | 改成 `@_spi(Internals) import`;MachOKitExtensions 不加 Capstone 依赖 | +| `slotResolverResolvesStandaloneBinds`(SymbolTestsCore 夹具) | 留在本库,挪进 `CrossReferenceAnalysisTests` | `CodeAddressResolutionTests` target 删除 | +| 其余经门面的测试、`ReferenceTableDigestTests`、`ScanThroughputBenchmarkTests`、`PublicNameTests`、`MemoryAccessScanTests` 与 `AddressMaskScanTests` 对本库文件的部分 | 留在本库 | 用到下层内部接口的改成 `@_spi(Internals) import` | + +- MachOKitExtensions 没有 CI,那边的测试只在本地跑;MachOObjCSection 的 CI 在 PR 与推 `main` 时跑新 target 的测试。 +- 本库的缩写扫描(`AbbreviatedIdentifierScanTests`)不复制到另外两个仓库。 + +### 6. 版本与落地顺序 + +叠在两份搬迁提案的分支上实现,三份同日落地,顺序: + +1. MachOKitExtensions 合入 `main`、发 **2.0.0**(两份搬迁加本提案的三个模块)。 +2. MachOObjCSection 把 MachOKitExtensions 的下限抬到 2.0.0(`"2.0.0"..<"3.0.0"`),推 `main`、等 CI、打 **0.8.207**。这意味着 0.8.207 起的 MachOObjCSection 不能再与本库 0.24.0 及更早的版本同时解析——它们要 MachOKitExtensions 1.x。 +3. 本库把 MachOObjCSection 要求改成 `"0.8.207"..<"0.9.0"`、MachOKitExtensions 改成 `from: "2.0.0"`,随 **0.25.0** 发布。 +4. RuntimeViewer 抬钉(本库与 MachOObjCSection 的 `next` revision)。 + +读取层搬迁提案落地清单里「MachOObjCSection 先打 tag」的顺序因此改成上面这样,那份提案的决策日志记一行。 + +### 7. 文档 + +- 模块文档跟着代码走:本库的 `Internal/Modules/CrossReferenceCore.md`、`CodeAddressResolution.md` 搬进 MachOKitExtensions 的 `Documentations/Internal/`(改名 `MachOCodeReferences.md`、`MachOAddressResolution.md`,加一份 `ARM64InstructionDecoding.md`),`CrossReferenceObjC.md` 搬进 MachOObjCSection 的 `Documentations/Internal/ObjCCodeReferences.md`;本库的 `CrossReferenceAnalysis.md` 改写「三个模块」一节,指向它们。 +- 本库 `AGENTS.md`:模块依赖图、`CrossReferenceAnalysis` 那一大段里「It is three modules」与 `ARM64InstructionDecoding`、`CodeAddressResolution` 两条改写成「下层在 MachOKitExtensions 与 MachOObjCSection,经 `@_spi(Internals)` 接入」。 +- 愿景第 6 条的「之后另写迁移提案」改成指向本提案;愿景的相关提案表加一行。 +- MachOKitExtensions 的 README 模块列表、两个仓库的提案索引与文档索引。 + +### 非目标 + +- **下层的独立公开 API**:MachOKitExtensions 里不提供自己的分析器、不定义与语言无关的引用目标类型。等有不经本库的使用方时另写提案。 +- **在 Linux 上真编、加 Linux CI。** +- **给 MachOKitExtensions 加 CI**(基础设施搬迁提案已把它留给单独的提案)。 +- **改扫描行为、加新的引用种类。** 除了删 `IndirectCallEvidence.table`,搬家前后每张引用表逐条一致。 +- **搬 Swift 层或门面**,以及 `SwiftThunkAnalysis`、`SwiftDeclarationRendering` 本身。 +- **MachOKitUI 的改动**:它不用这几个模块;它因两份搬迁提案要做的 `import MachOSymbols` → `import SwiftSymbols` 由它自己的提案负责。 +- **把门面经 `@_exported` 带出的类型改名。** + +## 改动地图 + +### MachOKitExtensions(`feature/move-cross-reference-layers`,从 `feature/move-macho-infrastructure-modules` 切出) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | 加 product 与 target `ARM64InstructionDecoding`、`MachOAddressResolution`、`MachOCodeReferences`;加 test target `MachOAddressResolutionTests`、`MachOCodeReferencesTests` | 第 1 节 | 2、3 | +| `Sources/ARM64InstructionDecoding/ARM64InstructionWord.swift`、`ARM64Trampoline.swift` | 新增(搬入) | 原样搬;门面用到的 `adding`、`branchTarget`、`callTarget`、`load` 改 `@_spi(Internals) public`,其余保持 `package` | 核心与地址解析离不开它 | 2 | +| `Sources/MachOAddressResolution/CacheImageLocator.swift`、`ImageAddressSpace.swift`、`SlotResolver.swift`、`StubChainResolver.swift` | 新增(搬入) | 原样搬;四个类型及本库用到的成员改 `@_spi(Internals) public` | `SwiftThunkAnalysis`、`SwiftDeclarationRendering` 跨包使用 | 2 | +| `Sources/MachOCodeReferences/`(`Images/`、`Memory/`、`Models/`、`Recognition/`、`Scanning/`、`Symbolication/` 共 19 个文件) | 新增(搬入) | 原样搬;本库与 MachOObjCSection 用到的约 27 个类型及其成员改 `@_spi(Internals) public` | 第 2 节 | 3 | +| `Sources/MachOCodeReferences/Memory/InProcessCrossReferenceMemory.swift` | 修改 | `import MachOFoundation` 改 `import MachOReading`;整个文件包进 `#if canImport(Darwin)` | 第 1、4 节 | 3 | +| `Sources/MachOCodeReferences/Images/CodeImageSet.swift` · `inProcess(...)` | 修改 | `#if arch(arm64)` 改 `#if canImport(Darwin) && arch(arm64)` | 第 4 节 | 3 | +| `Sources/MachOCodeReferences/Models/IndirectCallEvidence.swift` · `IndirectCallEvidence` | 修改 | 删 `Table` 与 `table`,构造器去掉 `table:` | 第 3 节 | 3 | +| `Sources/MachOCodeReferences/Scanning/ReferenceScanner.swift` | 修改 | 写入 `IndirectCallEvidence` 处去掉 `table: .none` | 第 3 节 | 3 | +| `Tests/MachOAddressResolutionTests/MachOAddressResolutionTests.swift` | 新增(搬入并改写) | 本库 `CodeAddressResolutionTests` 的四条,镜像与 cache 从 MachOKit 直接拿 | 第 5 节 | 2 | +| `Tests/MachOCodeReferencesTests/MalformedExportTrieTests.swift` | 新增(搬入) | 改 import | 第 5 节 | 3 | +| `Tests/MachOCodeReferencesTests/CoreOnlyScanTests.swift` | 新增 | `theCoreScansWithOnlyARecognizerFromTests`:只装测试里的识别器,驱动 `ReferenceScanner` | 证明核心在 MachOKitExtensions 里不靠语言层也能扫 | 3 | +| `Tests/MachOCodeReferencesTests/SourceScanTests.swift` | 新增(搬入并合并) | 不写 `objc_` / `swift_` 字面量、只有 `InProcessCrossReferenceMemory` 把地址变成指针、不写自定义地址掩码常量(含 slide info 白名单) | 第 5 节 | 3 | +| `README.md` | 修改 | 模块列表加三个模块,写明 SPI 只给 MachOSwiftSection 用、Linux 上进程内部分不可用 | 文档 | 5 | +| `Documentations/Internal/MachOCodeReferences.md`、`MachOAddressResolution.md`、`ARM64InstructionDecoding.md` | 新增(从本库搬入并改写) | 本库同名模块文档的内容,加 SPI 与 Linux 说明 | 文档跟代码走 | 5 | +| `Documentations/Internal/SharedCache.md` | 修改 | `thunkResolution` 组那一行的 `CacheImageResolver` 改成 `CacheImageLocator`(类型在 `MachOAddressResolution`) | 0097 改了本库那份 `MachOCaches.md`,而它在基础设施搬迁里已搬来这里;第 0 步合并时本库那份保持删除 | 2 | +| `Documentations/Evolutions/README.md` | 修改 | 加 cross-repository draft 一行指向本提案 | 跨仓库提案的登记方式 | 1 | +| `Documentations/Evolutions/0003-move-macho-infrastructure-modules.md(MachOKitExtensions)` | 修改 | 第 109 行与第 189 行的图改为 `ARM64InstructionDecoding` 也搬;决策日志加一行;落地清单的顺序改成第 6 节 | 第 1、6 节 | 1 | +| `Documentations/Evolutions/0002-move-reading-and-resolving-modules.md(MachOKitExtensions)` | 修改 | 决策日志加一行:落地顺序改成 MachOKitExtensions 2.0.0 先于 MachOObjCSection 的 tag | 第 6 节 | 1 | +| `Documentations/README.md` | 修改 | 登记三份模块文档 | 文档索引 | 5 | + +### MachOObjCSection(`feature/move-cross-reference-layers`,从 `next` 切出) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | 加 product 与 target `ObjCCodeReferences`(依赖 MachOKit、`MachOObjCSection`、MachOKitExtensions 的 `MachOCodeReferences`)与 test target `ObjCCodeReferencesTests`;MachOKitExtensions 要求改 `"2.0.0"..<"3.0.0"` | 第 1、6 节 | 4 | +| `Sources/ObjCCodeReferences/`(8 个文件) | 新增(搬入) | 原样搬;本库门面用到的十个类型改 `@_spi(Internals) public`;`@_spi(Core) import MachOObjCSection` 照旧 | fork 新增放单独 target | 4 | +| `Tests/ObjCCodeReferencesTests/SourceScanTests.swift` | 新增 | 只经 `CrossReferenceMemory` 读内存、不写 `swift_` 字面量 | 第 5 节 | 4 | +| `Documentations/Internal/ObjCCodeReferences.md` | 新增(从本库 `CrossReferenceObjC.md` 搬入并改写) | 加 SPI 说明 | 文档跟代码走 | 5 | +| `Documentations/README.md`、`Documentations/Evolutions/README.md` | 修改 | 登记模块文档;加 cross-repository draft 一行 | 索引 | 1、5 | + +### MachOSwiftSection(`feature/move-cross-reference-layers`,从合过 `next` 的 `feature/move-macho-infrastructure-modules` 切出) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `feature/move-macho-infrastructure-modules`(分支) | 修改 | 合入 `origin/next`(含 0097),解冲突,新 target 的 `.target(.MachOFoundation)` / `.target(.MachOReading)` 改成 `.product(...)`,测试支持模块按那份提案改名 | 本提案的基线 | 0 | +| `Package.swift` | 修改 | 删 target `CrossReferenceCore`、`CrossReferenceObjC`、`CodeAddressResolution`、`ARM64InstructionDecoding` 与 test target `CodeAddressResolutionTests`;`CrossReferenceAnalysis`、`SwiftThunkAnalysis`、`SwiftDeclarationRendering`、`CrossReferenceAnalysisTests`、`SwiftThunkAnalysisTests` 改依赖 MachOKitExtensions 的三个 product 与 MachOObjCSection 的 `ObjCCodeReferences`;MachOObjCSection 要求改 `"0.8.207"..<"0.9.0"` | 第 1、6 节 | 2、3、4、6 | +| `Sources/Support/ARM64InstructionDecoding/`、`Sources/Analysis/CodeAddressResolution/` | 删除 | 搬到 MachOKitExtensions | 第 1 节 | 2 | +| `Sources/Analysis/CrossReferenceCore/` | 删除 | 搬到 MachOKitExtensions | 第 1 节 | 3 | +| `Sources/Analysis/CrossReferenceObjC/` | 删除 | 搬到 MachOObjCSection | 第 1 节 | 4 | +| `Sources/Analysis/SwiftThunkAnalysis/`(`AccessorThunkReader`、`DependencyImageResolver`、`MachOThunkEnvironment`、`ThunkTypeNodeBuilder`、`ObjCMethodThunkReferences`) | 修改 | `import CodeAddressResolution` 改 `@_spi(Internals) import MachOAddressResolution`;用到解码器的改 `@_spi(Internals) import ARM64InstructionDecoding` | 第 2 节 | 2 | +| `Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift` | 修改 | 同上 | 第 2 节 | 2 | +| `Sources/Analysis/CrossReferenceAnalysis/Exports.swift` | 修改 | `@_exported import MachOCodeReferences`、`@_exported import ObjCCodeReferences` | 门面的公开类型照旧可见 | 3、4 | +| `Sources/Analysis/CrossReferenceAnalysis/` 其余文件 | 修改 | import 改名,用到内部接口的加 `@_spi(Internals) import`;构造 `IndirectCallEvidence` 处去掉 `table:`(若有) | 第 2、3 节 | 3、4 | +| `Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift` | 修改 | 删 `name(of:)`、`refs --json` 的 `table` 键与文本输出里的「through …」 | 第 3 节 | 3 | +| `AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md` | 修改 | 间接调用照实际输出描述,不再说带哪张表 | CLI 输出变了,skill 同批改 | 3 | +| `Tests/CrossReferenceAnalysisTests/MalformedExportTrieTests.swift` | 删除 | 搬到 MachOKitExtensions | 第 5 节 | 3 | +| `Tests/CrossReferenceAnalysisTests/RecognizerExtensionPointTests.swift` | 修改 | 第一条搬走,`selectorQueriesLookUpNoSwiftType` 留下 | 第 5 节 | 3 | +| `Tests/CrossReferenceAnalysisTests/CrossReferenceLayerBoundaryTests.swift` | 删除 | 两条白名单不再需要,运行时名字扫描搬到 MachOKitExtensions | 第 5 节 | 3 | +| `Tests/CrossReferenceAnalysisTests/MemoryAccessScanTests.swift` | 修改 | 只扫 `CrossReferenceAnalysis` | 下层的部分搬走 | 3 | +| `Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift`、`RegisterFileTests.swift`、`InstructionEncoding.swift` | 修改 | `@_spi(Internals) import` 搬走的模块 | Capstone 对照留在本库 | 2、3 | +| `Tests/CrossReferenceAnalysisTests/StandaloneBindSlotTests.swift` | 新增(从 `CodeAddressResolutionTests` 挪入) | `slotResolverResolvesStandaloneBinds` | 要 SymbolTestsCore 夹具 | 2 | +| `Tests/CodeAddressResolutionTests/` | 删除 | 四条搬走、一条挪入 `CrossReferenceAnalysisTests` | 第 5 节 | 2 | +| `Tests/SwiftSymbolsTests/SymbolTableEquivalenceTests.swift` | 修改 | 前缀判断先算进局部变量,不放在 `&&` 的自动闭包里 | 基础设施搬迁带来的测试在 Xcode 26.6 的 release 下编不过 | 5 | +| `Tests/CrossReferenceAnalysisTests/` 其余用到内部接口的文件、`Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift` | 修改 | `@_spi(Internals) import` | `package` 不再跨包 | 2、3、4 | +| `AGENTS.md` | 修改 | 模块依赖图;`CrossReferenceAnalysis`、`ARM64InstructionDecoding`、`CodeAddressResolution` 三条改写 | 第 7 节 | 5 | +| `Documentations/Internal/Modules/CrossReferenceCore.md`、`CrossReferenceObjC.md`、`CodeAddressResolution.md` | 删除 | 搬到另外两个仓库 | 第 7 节 | 5 | +| `Documentations/Internal/Modules/CrossReferenceAnalysis.md`、`SwiftThunkAnalysis.md`、`SwiftSectionKit.md` | 修改 | 改写分层一节与模块链接 | 第 7 节 | 5 | +| `Documentations/README.md`、`Documentations/Glossary.md`、`Documentations/Visions/ReverseEngineeringWithoutIDA.md` | 修改 | 模块文档索引与链接;愿景第 6 条与相关提案表 | 第 7 节 | 1、5 | +| `Documentations/Evolutions/README.md` | 修改 | 登记本提案 | 索引 | 1 | +| `Changelogs/0.25.0.md` | 修改 | Breaking:`IndirectCallEvidence.table` 删除;下层模块移到 MachOKitExtensions / MachOObjCSection | 发版说明 | 6 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时加一节 | 账本 | 6 | + +### RuntimeViewer + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| 五个提交进仓库的 `Package.resolved` | 修改 | 落地后抬本库与 MachOObjCSection 的 `next` revision | 惯例 | 6 | +| `RuntimeViewerCore/Package.swift` | 修改 | `MachODependencies` 改从 MachOKitExtensions 取,并加它为直接依赖 | 基础设施搬迁要求,落地那天与本库 `next` 同日改 | 6 | + +## 架构图 + +改了什么(模块与依赖,`+` 新增、`-` 删除、`~` 改动): + +```text +Before (MachOSwiftSection next, after 0097) After (all three land together) + +MachOSwiftSection MachOSwiftSection 0.25.0 + CrossReferenceAnalysis (facade, Swift layer) CrossReferenceAnalysis (facade, Swift layer) ~ imports below via @_spi(Internals) + |-- CrossReferenceObjC - |-- ObjCCodeReferences (MachOObjCSection) + | `-- MachOObjCSection (package) |-- MachOCodeReferences (MachOKitExtensions) + |-- CrossReferenceCore - |-- MachOAddressResolution (MachOKitExtensions) + | |-- CodeAddressResolution - `-- ARM64InstructionDecoding (MachOKitExtensions) + | |-- ARM64InstructionDecoding - SwiftThunkAnalysis ~ -> MachOAddressResolution + | `-- MachOFoundation (-> Utilities) SwiftDeclarationRendering ~ -> MachOAddressResolution + SwiftThunkAnalysis -> CodeAddressResolution + SwiftDeclarationRendering -> CodeAddressResolution + +MachOKitExtensions 1.3.x MachOKitExtensions 2.0.0 + MachOKitExtensions MachOKitExtensions, MachOReading, ... (two move proposals) + + ARM64InstructionDecoding + + MachOAddressResolution -> MachOReading, ARM64InstructionDecoding + + MachOCodeReferences -> MachOReading, MachOAddressResolution, ARM64InstructionDecoding + (in-process parts: #if canImport(Darwin)) + +MachOObjCSection 0.8.206 MachOObjCSection 0.8.207 + MachOObjCSection (upstream target) MachOObjCSection (upstream target, untouched) + + ObjCCodeReferences -> MachOObjCSection, MachOCodeReferences + ~ MachOKitExtensions requirement 2.0.0..<3.0.0 +``` + +一次扫描的调用链(搬家前后不变,只是模块换了包): + +```text +CrossReferenceAnalyzer.references(to:inImageAt:) [MachOSwiftSection / CrossReferenceAnalysis] + -> ReferenceScanner.scan(function:...) [MachOKitExtensions / MachOCodeReferences, @_spi(Internals)] + -> CodeReferenceRecognitionSession (one per layer) + ObjCCodeReferenceRecognizer.makeSession() [MachOObjCSection / ObjCCodeReferences, @_spi(Internals)] + SwiftCodeReferenceRecognizer.makeSession() [MachOSwiftSection / CrossReferenceAnalysis] + -> StubChainResolver / SlotResolver [MachOKitExtensions / MachOAddressResolution] + -> ARM64InstructionWord [MachOKitExtensions / ARM64InstructionDecoding] + <- CodeReference (built by the facade's recorders) [MachOSwiftSection] +``` + +落地顺序(发版依赖): + +```text +MachOKitExtensions 2.0.0 -> MachOObjCSection 0.8.207 -> MachOSwiftSection 0.25.0 -> RuntimeViewer pin bump +(three modules added) (ObjCCodeReferences needs (requires both) + MachOCodeReferences) +``` + +## 详细设计 + +### MachOKitExtensions 的 `Package.swift` + +```swift +// Products, added beside the nine from the two move proposals. +.library(name: "ARM64InstructionDecoding", targets: ["ARM64InstructionDecoding"]), +.library(name: "MachOAddressResolution", targets: ["MachOAddressResolution"]), +.library(name: "MachOCodeReferences", targets: ["MachOCodeReferences"]), + +// Targets. +.target(name: "ARM64InstructionDecoding"), +.target( + name: "MachOAddressResolution", + dependencies: [ + .product(name: "MachOKit", package: "MachOKit"), + "MachOKitExtensions", + "MachOReading", + "ARM64InstructionDecoding", + ] +), +.target( + name: "MachOCodeReferences", + dependencies: [ + .product(name: "MachOKit", package: "MachOKit"), + "MachOKitExtensions", + "MachOReading", + "MachOAddressResolution", + "ARM64InstructionDecoding", + ] +), +.testTarget(name: "MachOAddressResolutionTests", dependencies: ["MachOAddressResolution"]), +.testTarget(name: "MachOCodeReferencesTests", dependencies: ["MachOCodeReferences"]), +``` + +### MachOObjCSection 的 `Package.swift` + +```swift +.library(name: "ObjCCodeReferences", targets: ["ObjCCodeReferences"]), + +.target( + name: "ObjCCodeReferences", + dependencies: [ + .product(name: "MachOKit", package: "MachOKit"), + "MachOObjCSection", + .product(name: "MachOCodeReferences", package: "MachOKitExtensions"), + ] +), +.testTarget(name: "ObjCCodeReferencesTests", dependencies: ["ObjCCodeReferences"]), +``` + +MachOKitExtensions 的要求从 `"1.2.0"..<"3.0.0"` 改成 `"2.0.0"..<"3.0.0"`(本地兄弟依赖的写法照该仓库现有的 `USING_LOCAL_DEPENDENCIES` 分支)。 + +### 本库的 `Package.swift` + +```swift +// CrossReferenceAnalysis after the move. +.target( + name: "CrossReferenceAnalysis", + dependencies: [ + .product(name: "ARM64InstructionDecoding", package: "MachOKitExtensions"), + .product(name: "MachOAddressResolution", package: "MachOKitExtensions"), + .product(name: "MachOCodeReferences", package: "MachOKitExtensions"), + .product(name: "ObjCCodeReferences", package: "MachOObjCSection"), + // ...the Swift-layer dependencies it already has (SwiftInspection, MachOSwiftSection, ...) + ], + path: "Sources/Analysis/CrossReferenceAnalysis" +), +``` + +`SwiftThunkAnalysis` 与 `SwiftDeclarationRendering` 的 `.target(.CodeAddressResolution)` 换成 `.product(name: "MachOAddressResolution", package: "MachOKitExtensions")`。 + +### SPI 的写法 + +```swift +// MachOKitExtensions/Sources/MachOAddressResolution/StubChainResolver.swift +@_spi(Internals) +public struct StubChainResolver { + @_spi(Internals) + public init(addressSpace: ImageAddressSpace, ...) + ... +} + +// MachOSwiftSection/Sources/Analysis/SwiftThunkAnalysis/AccessorThunkReader.swift +@_spi(Internals) import MachOAddressResolution +``` + +一个类型在同一个包里被别的模块用、又被另一个包的模块用时,只改成 SPI 一次;`package` 与 `@_spi(Internals) public` 不并存。 + +### `IndirectCallEvidence` 删掉 `table` 之后 + +```swift +/// Evidence for where an indirect call may go. +public struct IndirectCallEvidence: Hashable, Sendable { + /// 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(tableOffset: Int64?, pointerAuthenticationConstant: UInt16?, isAddressBlended: Bool) +} +``` + +### 进程内部分的条件编译 + +```swift +// MachOCodeReferences/Images/CodeImageSet.swift +#if canImport(Darwin) && arch(arm64) +extension CodeImageSet { + @_spi(Internals) + public static func inProcess(...) -> CodeImageSet? { ... } +} +#endif + +// MachOCodeReferences/Memory/InProcessCrossReferenceMemory.swift +#if canImport(Darwin) +import MachOReading +... +#endif +``` + +### 门面的导出 + +```swift +// MachOSwiftSection/Sources/Analysis/CrossReferenceAnalysis/Exports.swift +@_exported import MachOCodeReferences +@_exported import ObjCCodeReferences +``` + +`@_exported` 只带出 public 声明;SPI 声明要在用的文件里写 `@_spi(Internals) import`,不会经门面漏给 RuntimeViewer。 + +### 验收 + +- **整表一致**:`ReferenceTableDigestTests` 的 A/B(0097 第 1 步做的那套)以本提案开工时的 `next` 为基线,AppKit、SwiftUICore、Foundation 逐条一致;比较前去掉 `IndirectCallEvidence` 描述里的 `table` 与模块名前缀两处拼写差异。 +- **吞吐**:Ultra、release、`ScanThroughputBenchmarkTests` 三方交替各三轮取最好,整 cache 建表与两条调用者查询相对基线不超过 +5%;超了先查跨包调用是否失去了包内的跨模块优化(`package` 函数本来也不吃默认的跨模块优化,预计不变)。 +- **渲染 A/B**:`SwiftThunkAnalysis` 的读取路径换了模块,按 `AGENTS.md` 跑系统框架渲染 A/B,三条读取路径逐字节一致。 +- **三个仓库的全量测试**:本库跳过 IntegrationTests;MachOKitExtensions 本地全量;MachOObjCSection 本地全量,并在 PR 上等 CI。 +- **RuntimeViewer**:在沙盒里用本地兄弟依赖编过 Core、CLI 与 MCP 三个包,交叉引用测试单跑通过。 + +## 替代方案考量 + +- **在 MachOKitExtensions 里做能单独用的公开 API**(自己的分析器、与语言无关的引用目标类型):非 Swift 的工具也能用,但要走一轮完整的 API 设计、多问一两轮,工作量明显变大;今天没有任何不经本库的使用方。用户选了只开 SPI,等有使用方再做。 +- **`package` 原样全部改成 `public`**:约 300 个内部符号会变成要守 semver 的公开 API,以后每次改内部都可能是破坏性变更。否。 +- **核心层整个只在 Darwin 上有**(模块包进 `#if canImport(Darwin)`):省事,但文件模式本来与平台无关,MachOKitExtensions 又承诺 Linux。**在 Linux 上真编一遍**:要另找 Linux 环境,两份搬迁提案也都没做。都否。 +- **测试全部留在本库**:改动最少,但搬走的仓库里没有自己的测试,下层改了只有本库能发现。用户选了测试跟代码走。 +- **Capstone 对照测试搬去 MachOKitExtensions、给它加测试专用的 swift-capstone 依赖**:要先核实 SwiftPM 会不会让使用方也去拉 Capstone,MachOKitExtensions 也不该为两组测试多一个大 C 库;**改成写死的期望值**:以后新增的解码就没有独立对照了。都否,这两组留在本库。 +- **`ARM64InstructionDecoding` 改成 `MachO` 前缀**(比如 `MachOARM64Decoding`):与 MachOKitExtensions 其余模块的命名一致,但它与 Mach-O 无关。**并进 `MachOAddressResolution`**:少一个 product,但门面要用解码器时得从地址解析模块导入,概念上不对。都否。 +- **`IndirectCallEvidence.table` 原样搬过去**:核心层里留几个 Swift 专有的名字,与「核心不认识任何语言」相悖;**改成与语言无关的叫法**:给一个从来只写 `.none` 的字段换名字没有意义。都否。 +- **不等 0.25.0、先单独落地**:做不到——核心层依赖的 `MachOReading` 要靠两份搬迁提案先进 MachOKitExtensions,而它们定了随 0.25.0 落地。**把 0.25.0 提前**:要先给 swift-demangling 发版、处理 0057 读取接口旧转发的去留(MachOKitUI 与 swift-decompiler 还没改用新接口),用户选了不提前。 +- **MachOObjCSection 发 0.9.0**(0097 非目标里的设想):`0.9.0` 已是上游 p-x9 的 tag,fork 照自己的编号规则发 0.8.207。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏**,都随 0.25.0(本库本来就是破坏性版本): + +- **`IndirectCallEvidence.table` 与 `IndirectCallEvidence.Table` 删除,构造器去掉 `table:`。** 本库、RuntimeViewer、MachOKitUI、swift-decompiler 都没有调用点。 + + ```swift + // Before + IndirectCallEvidence(table: .none, tableOffset: offset, pointerAuthenticationConstant: constant, isAddressBlended: false) + // After + IndirectCallEvidence(tableOffset: offset, pointerAuthenticationConstant: constant, isAddressBlended: false) + ``` + +- **`CrossReferenceCore`、`CrossReferenceObjC`、`CodeAddressResolution`、`ARM64InstructionDecoding` 四个模块从本库消失。** 它们不是 product,外部不能直接 import;经 `CrossReferenceAnalysis` 用到的公开类型(`CodeLocation`、`CodeReferenceKind`、`CodeReferenceRoute`、`IndirectCallEvidence`、`ReceiverClassHint`)照旧经 `@_exported` 可见,名字不变。 +- 写了 `CrossReferenceCore.CodeLocation` 这种带模块名的全称的代码要改成 `MachOCodeReferences.CodeLocation`;查过的使用方里没有这样写的。 + +不提供 `@available(*, deprecated, renamed:)` 过渡:被删的字段没有使用方,模块改名也没有外部 import。 + +### ABI 兼容性 + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本库**:`CrossReferenceAnalysis`、`SwiftThunkAnalysis`、`SwiftDeclarationRendering`、SwiftSectionKit(经门面,不改代码)、`CrossReferenceAnalysisTests`、`SwiftThunkAnalysisTests`。 +- **MachOKitExtensions**:多三个 product,2.0.0 本来就是大版本。 +- **MachOObjCSection**:多一个 product;MachOKitExtensions 下限抬到 2.0.0,0.8.207 起不能与本库 0.24.0 及更早的版本同时解析(MachOKitUI 这类同时用两个库的使用方要和本库一起升到 0.25.0,而它本来就因两份搬迁提案要等 0.25.0)。 +- **RuntimeViewer**:不改代码,落地后抬钉;它的 Local workspace 的兄弟检出要包含三个仓库的新分支才能编(落地前在沙盒里验)。 +- **MachOKitUI、swift-decompiler**:不用这几个模块,不受影响。 + +### 文档与示例 + +见「提议方案」第 7 节。`swift-section` 插件的 skill 只讲命令行,不受影响;README 里 `refs` / `symbolicate` 的用法不变。 + +## API 演进与废弃策略 + +- `IndirectCallEvidence.table` 直接删除,不留废弃期:从来只写 `.none`,没有读者。 +- 下层的 `@_spi(Internals)` 接口不承诺 semver,改它不算破坏性变更;公开的五个值类型照常守 semver。 +- 版本号:MachOKitExtensions 2.0.0(大版本,本来就是)、MachOObjCSection 0.8.207(fork 的补丁号)、本库 0.25.0(本来就是破坏性版本)。 + +## 落地步骤 + +0. **把基线备好**(已完成) —— 改动地图里本库的「`feature/move-macho-infrastructure-modules`(分支)」一行。把 `origin/next` 合进这条分支(merge,不 rebase、不强推),解冲突,按基础设施搬迁提案改名测试支持模块;先告诉在用这两条搬迁分支的会话。三个仓库从这里切出 `feature/move-cross-reference-layers`。 + - 行为:基础设施搬迁分支合入 `next` 后本库全量测试(跳过 IntegrationTests)通过,`ReferenceTableDigestTests` 与 `next` 逐条一致 +1. **登记提案**(已完成) —— 本提案状态改 Accepted;三个仓库的提案索引、两份搬迁提案的决策日志(ARM64 也搬、落地顺序)、愿景的相关提案表。 + - 行为:无代码改动 +2. **解码与地址解析搬进 MachOKitExtensions**(已完成,与第 3 步合并) —— 改动地图里步骤列为 2 的各行。 + - 行为:`SwiftThunkAnalysisTests` 全套照旧通过(线程读取经新模块,结果不变) + - 行为:`stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub`、`slotResolverMatchesTheProcessForEveryGlobalOffsetTableSlotOfAppKit`、`cacheImageLocatorFindsTheImageAnAddressLiesIn`、`stubChainRecordsEveryStubIslandHop` 在 MachOKitExtensions 里通过,且不依赖本库 + - 行为:`slotResolverResolvesStandaloneBinds` 在本库的 `CrossReferenceAnalysisTests` 里通过 + - 行为:`ARM64InstructionDecodingTests`、`RegisterFileTests` 经 `@_spi(Internals) import` 照旧通过 +3. **核心层搬进 MachOKitExtensions**(已完成) —— 步骤列为 3 的各行。 + - 行为:`theCoreScansWithOnlyARecognizerFromTests`(MachOKitExtensions 里,只装测试的识别器,扫出它认领的调用) + - 行为:`aTerminalSizePastTheTrieEndsTheNodeWithoutTrapping` 在 MachOKitExtensions 里通过 + - 行为:`coreSpellsNoRuntimeSymbolName`、`onlyInProcessMemoryTurnsAddressesIntoPointers`、`coreDefinesNoAddressMaskConstant`(MachOKitExtensions 的源码扫描) + - 行为:`indirectCallEvidenceCarriesNoTable`(`IndirectCallEvidence` 只有偏移、常量与是否混入地址三项) + - 行为:`inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation`(整表 A/B,基线为开工时的 `next`) + - 行为:`publicNamesStillResolveThroughCrossReferenceAnalysis`(只 `import CrossReferenceAnalysis` 的测试文件仍能用 `CodeLocation`、`CodeReferenceKind.call`、`ReceiverClassHint.methodReceiver`) +4. **ObjC 层搬进 MachOObjCSection**(已完成) —— 步骤列为 4 的各行。 + - 行为:`objectiveCLayerReadsMemoryOnlyThroughCrossReferenceMemory`、`objectiveCLayerSpellsNoSwiftRuntimeName`(MachOObjCSection 的源码扫描) + - 行为:整表 A/B 照旧逐条一致;`selectorQueriesLookUpNoSwiftType` 照旧通过 +5. **文档与验收**(已完成) —— 步骤列为 5 的各行;吞吐、渲染 A/B、三个仓库的全量测试、RuntimeViewer 沙盒构建。 + - 行为:`scanThroughputAfterTheMoveIsRecordedInTheModuleDocument`(不是断言:整 cache 建表与两条查询的耗时写进 `MachOCodeReferences.md`,相对基线超过 +5% 先查原因再落地) + - 行为:渲染 A/B 三条读取路径逐字节一致 +6. **落地(随 0.25.0)**(已完成) —— 第 6 节的顺序:MachOKitExtensions 2.0.0 → MachOObjCSection 0.8.207 → 本库 0.25.0(要求改成 `"0.8.207"..<"0.9.0"`)→ RuntimeViewer 抬钉,并照基础设施搬迁提案改 `RuntimeViewerCore/Package.swift`(`MachODependencies` 改从 MachOKitExtensions 取);本提案取号、改 Implemented,`Changelogs/0.25.0.md` 写 Breaking,账本加一节。 + - 行为:用远端依赖(不设 `USING_LOCAL_DEPENDENCIES`)、Xcode 26.6 编过本库并跑完 CI 名单里的套件 + - 行为:三个仓库除 debug 全量测试外,都再用 `swift test -c release` 跑一次(本库加 `--skip IntegrationTests`,与 CI 的 release 任务一致);之前三个仓库的测试都只在 debug 下跑过 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预判不要:调用方契约没变(门面不变),SPI 的约定写进两份模块文档即可。 +- **有没有引入新术语** —— 预判没有:「识别器」等已在 0097 登记;术语表里指向旧模块文档的链接要改。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-19 | Created as Draft | 0097 落地当天,用户提出开始把交叉引用迁到 MachOKitExtensions。核心层依赖的 `MachOReading` 要靠两份 MachOKitExtensions 搬迁提案先搬过去,而那两份定了随本库 0.25.0 落地;用户在「现在写提案、随 0.25.0 落地」「把 0.25.0 提前」「先不动」三者中选了第一个。按完整档问了两轮,结论见下面几行 | +| 2026-11-19 | 下层只开 SPI | 用户在「只给本库用的 SPI」「做成能单独用的公开 API」「原样全部改成 public」中选了第一个:今天没有不经本库的使用方,独立公开 API 要多一轮设计,全部改 public 则约 300 个内部符号要守 semver。0097 留下的问题 (a)「没有 Swift 层时引用目标用什么类型」因此不在本提案回答 | +| 2026-11-19 | Linux:文件模式能编 | 用户选了用 `#if canImport(Darwin)` 包住进程内部分、文件模式在 Linux 上也能编、不加 Linux CI;否掉了「整个模块只在 Darwin 上有」与「另找 Linux 环境真编一遍」 | +| 2026-11-19 | 测试跟代码走 | 用户选了测试跟代码走,否掉了全部留在本库。之后核实:交叉引用的测试几乎都经门面建分析器,所以实际搬走的只有直接测下层的几组与源码扫描,另新写一条只装测试识别器的核心扫描测试,证明核心在 MachOKitExtensions 里不靠语言层也能扫 | +| 2026-11-19 | `ARM64InstructionDecoding` 也搬,名字不变 | 核心层与地址解析都离不开它,而基础设施搬迁提案写着它留在本库,这一条要改。用户选了独立 product、名字不变;否掉了改成 `MachO` 前缀与并进 `MachOAddressResolution` | +| 2026-11-19 | 删掉 `IndirectCallEvidence.table` | 扫描器从来只写 `.none`,本库与 RuntimeViewer 都没读过。用户选了删掉;否掉了原样搬过去与改成与语言无关的叫法 | +| 2026-11-19 | Capstone 对照测试留在本库 | 用户选了留在本库、经 SPI 测搬走的解码器,作为「测试跟代码走」的例外;否掉了给 MachOKitExtensions 加测试专用的 swift-capstone 依赖与改成写死的期望值 | +| 2026-11-19 | 其余按默认定 | 沿用 0097 定好的名字;ObjC 层在 MachOObjCSection 里另起 target;SPI 分组统一叫 `Internals`;MachOObjCSection 发 0.8.207(`0.9.0` 是上游的 tag);核心层改为直接依赖 `MachOReading`;落地顺序改为 MachOKitExtensions 2.0.0 先于 MachOObjCSection 的 tag;开工第一步把 `next` 合进基础设施搬迁分支;验收沿用 0097 的标准。用户确认了这些决定 | +| 2026-11-19 | Accepted | 用户看过简报后批准,开始实现 | +| 2026-11-19 | 第 0 步:`next` 合进基础设施搬迁分支 | 用 merge、不 rebase,合并提交 `cf232949`。冲突七处:`Package.swift`(`SwiftThunkAnalysis` 的依赖取两边之交:搬迁分支的 product 写法加 `SwiftSymbols`,`next` 去掉了对 `ARM64InstructionDecoding` 的直接依赖),`MachOThunkEnvironment.swift`(两边的 import 都留),`AGENTS.md`(符号索引改名与 `ImageAddressSpace` 两处都留),`AccessorThunkResolutionExplained.md` 与 `SwiftSectionKit.md`(`next` 新加的内容套用测试支持模块的改名),愿景第 6 条(两边的意思合成一条,并指向本提案),`MachOCaches.md`(修改/删除:它已搬去 MachOKitExtensions,本库保持删除,那一行改动补到 MachOKitExtensions 的 `SharedCache.md`)。`next` 带进来的代码里只有 `CodeAddressResolutionTests` 还 import 改名前的 `MachOFixtureSupport`。MachOKitExtensions 那边负责搬迁的会话确认两条分支都没有未推送的工作;基础设施搬迁提案记了一行「冲突已解、要重新验证」 | +| 2026-11-19 | 第 2、3 步合成一步 | 三个与语言无关的模块一次搬进 MachOKitExtensions、一起验证:分开搬时,第 2 步结束的中间状态里核心层还在本库、却要跨包用 `ARM64InstructionDecoding` 的几乎全部接口,第 3 步再把其中大半收回包内,白改一遍;远程构建一轮也要二三十分钟 | +| 2026-11-19 | 搬走的 `package` 一律改成 `@_spi(Internals) public` | 更正第 2 节「同包内用到的保持 `package`」:一个 SPI 声明的签名里出现的类型也得是 public 或 SPI,按「跨包用到才改」逐个挑会一路连锁到几乎全部;SPI 本来不承诺稳定,两种做法对使用方没有区别。共 291 处 | +| 2026-11-19 | `refs --json` 去掉 `table` 键 | 调研漏了一个读者:SwiftSectionKit 的 `CrossReferenceFormatting` 把 `IndirectCallEvidence.table` 写进 `refs --json`(永远是 `"none"`),文本输出里的「through …」从来不会出现。`refs` 是 0.25.0 才有的命令、还没发布,插件 skill 与 README 也没写这个键,所以随 `table` 一起删掉 | +| 2026-11-19 | 地址解析测试换了对照 | `stubChainCarriesTheSelectorRegisterConstantOfACacheSharedSelectorStub` 原来对照门面在同一条指令上认出的发送,搬进 MachOKitExtensions 后没有门面,改成对照进程内存里同一地址(加上 cache 的 slide)上的 selector 字符串;GOT 槽那条直接读进程里的槽、掩码取 `InProcessContext.addressMask`;镜像定位那条从 MachOKit 的 cache 里取 libobjc | +| 2026-11-19 | 路径更正 | `SwiftDeclarationRendering` 在 `Sources/Output/`;MachOKitExtensions 的实现说明平放在 `Documentations/Internal/`,没有 `Modules/` 子目录 | +| 2026-11-19 | 第 0 步验证通过,基础设施搬迁分支已推送 | JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6,本地兄弟依赖;MachOKitExtensions 与 MachOObjCSection 经 agent 沙盒 `LocalDependencies/MoveCrossReferenceLayers` 的副本接入,`Package.swift` 那处本地改动不提交):合并后全量测试(跳过 IntegrationTests)2,910 个通过。随后把合并提交快进推到 `feature/move-macho-infrastructure-modules`;渲染 A/B 与本提案的候选一起跑 | +| 2026-11-19 | 第 2–4 步验证通过 | 同一台 Ultra、同样的工具链:MachOKitExtensions 全量 161 个测试通过(搬来的测试改了两处:本库测试支持里的 `DyldCache(path: .current)` 那边没有,改按 cache 文件路径打开;cache 里按名字找不到 `libobjc.A.dylib`,改按路径找);MachOObjCSection 照 CI 跳过 `MachOObjCSectionTests` 跑,343 个通过;本库全量 2,901 个通过(比第 0 步少 9 个、2 个套件,正是搬走与删掉的那几组)。整表 A/B:基线是 `origin/next`(`9d5c0310`),AppKit、SwiftUICore、Foundation 三个镜像的引用表摘要逐个一致 | +| 2026-11-19 | 两侧共用的测试文件不 import SPI | `ReferenceTableDigestTests` 与 `ScanThroughputBenchmarkTests` 要原样拷到基线上跑,`PublicNameTests` 证明只 import 门面就够,三者都只用公开 API;批量给测试加 SPI import 时把它们排除。整表对照的归一化多去掉两样:新的模块名前缀,以及基线输出里永远是 `.none` 的 `table` 字段 | +| 2026-11-19 | 插件 skill 同步 | `references/cross-references.md` 原来说间接调用显示 `indirect through …` 并带上哪张表,与实际输出不符(「through」从来不出现,表的信息已删),改成照实际输出描述 | +| 2026-11-19 | release 下的测试编译错误,修在本分支 | 两侧预编 release 测试时,候选报 `SymbolTableEquivalenceTests.swift` 里「sending 'nameC' risks causing data races」:基础设施搬迁分支带来的测试里,`&&` 右侧的自动闭包捕获了非 Sendable 的指针,只有 Xcode 26.6 的 release 才报,debug 能过,0.25.0 合进 `main` 时 CI 的 release 任务也会卡在这里。先把前缀判断算进局部变量,行为不变;同样的写法全库只有这一处。用户决定修复只留在本分支,两份搬迁提案的落地清单都加一步「用 `swift test -c release` 跑一次」(决策日志在本提案的 MachOKitExtensions 分支上) | +| 2026-11-19 | 吞吐:不慢反快 | Ultra、Xcode 26.6、release,两侧交替各三轮取最好:进程内整 cache 建表 2.67 → 2.53 秒,`init` 调用者扫描 1.71 → 1.53 秒,`makeKeyAndOrderFront:` 0.317 → 0.293 秒;归档 macOS 27.2 cache 文件整表 2.75 → 2.51 秒(128,120,075 条引用,两侧相同)。各项快 1% 到 11%,满足「不超过 +5%」;候选同时包含两份搬迁提案,没有追是哪一处更快。进程内整表的引用数差 18,250 条,来自测试进程自己的镜像(两侧的测试二进制不同)。逐项数字在 MachOKitExtensions 的 `MachOCodeReferences.md` | +| 2026-11-19 | 渲染 A/B 全部一致 | 基线 `origin/next`(`9d5c0310`),候选是本提案的分支(同时包含两份搬迁提案,所以这一轮也补上了基础设施搬迁欠的 A/B):归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 26.5 模拟器、进程内,共 84 对 dump 与 interface 逐字节一致,没有缺失与跳过 | +| 2026-11-19 | RuntimeViewer 验证 | 沙盒里导出 RuntimeViewer 的 `next`(`6cb25e09`)与本提案的分支,MachOKitExtensions、MachOObjCSection 用本提案分支的副本:Core(含测试)、CLI、MCP 三个包都编过,RuntimeViewer 的源码一行没改;交叉引用测试 82 个通过(1 个预先标记的已知问题)。第一轮跑到一半退出码 1、没有汇总也没有崩溃报告,原样重跑一遍全过,原因没查明。另发现基础设施搬迁要求 RuntimeViewer 改清单:`RuntimeViewerCore/Package.swift:269` 从本库取 `MachODependencies`,搬迁后这个 product 只在 MachOKitExtensions,解析失败;沙盒里临时改成从 MachOKitExtensions 取才编得下去。用户决定落地那天再改 RuntimeViewer,记在基础设施搬迁提案(本提案的 MachOKitExtensions 分支上)与第 6 步 | +| 2026-11-19 | 实现完成,待用户看过后收尾 | 第 0 到 5 步都已完成,第 6 步(落地)随 0.25.0。功能分支没有合进任何常驻检出:两份搬迁提案定了它们的分支只推送、不合进常驻检出,本提案叠在它们上面,照同样的规矩(MachOKitExtensions 的 `main` 一合,本库主检出与 MachOKitUI 就报模块重名)。文档判断:不另写使用指南,调用方契约没变(门面不变);实现说明写在 MachOKitExtensions 的 `MachOCodeReferences.md`、`MachOAddressResolution.md`、`ARM64InstructionDecoding.md` 与 MachOObjCSection 的 `ObjCCodeReferences.md`,本库的 `Modules/CrossReferenceAnalysis.md` 仍是三层的总说明;没有新术语,术语表只改了链接。Ultra 上候选 worktree 的 `Package.swift` 有一处不提交的改动,把两个兄弟依赖指向 agent 沙盒 `LocalDependencies/MoveCrossReferenceLayers`,拉新代码前要先还原 | +| 2026-11-19 | 落地前的 release 测试 | 两侧都在 JHs-Mac-Studio-Ultra 上用 Xcode 26.6 跑 `swift test -c release`。MachOKitExtensions 161 个测试全过;两份搬迁提案记作后续项的 `readersOfOneCacheFileShareOneMapping` 已随第 7 步搬进 MachOKitExtensions,也通过。本库加 `--skip IntegrationTests`,2,901 个测试里红 6 条,都不是本提案带来的:`SpecializedRuntimeTypeNameTests` 的 5 条是已知的 release 必红(release 优化把测试里没用到的私有类型连描述符一起删了,CI 的套件名单不含它);`LargeStackTaskExecutionTests.demanglerEntriesInsideTheBodyDoNotHop` 在满载的全量里第 3.2 秒才轮到,`executeAsync` 被挤到了别的线程,单独连跑三次都通过。渲染 A/B 不重跑:落地前后代码没变,第 4 步的 84 对仍然覆盖 | +| 2026-11-19 | Implemented,编号 0098,随 0.25.0 落地 | 按第 6 节的顺序同日落地:MachOKitExtensions 把本提案的分支(已含两份搬迁分支与 `main` 的全部提交)快进到 `main`,打 2.0.0,两份搬迁提案取号 0002、0003;MachOObjCSection 把分支 `--no-ff` 合进 `next` 并快进 `main`,CI 通过后打 0.8.207;本库把 MachOObjCSection 的要求改成 `"0.8.207"..<"0.9.0"`,swift-demangling 改成 `"0.7.4"..<"0.8.0"`(0092 用到它 `next` 上的 `useExistentialAny`,0.7.4 同日发布),分支合进 `next` 后随 0.25.0 发布,账本第 138 节记两份搬迁、第 139 节记本提案。三个仓库的提案索引都改成编号链接,MachOObjCSection 索引里 0088、0096 两行过时的 cross-repository draft 一并改正。RuntimeViewer 照基础设施搬迁提案改清单、抬钉。没做的:MachOObjCSection 文档注释里的旧名 `SymbolIndexStore`(`ObjCExportIndex.swift:129`)留着,那是基础设施搬迁的遗留,不在本提案范围 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 039abaa18..9a88a6430 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -83,6 +83,32 @@ | [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 | +| [0076](0076-objc-runtime-send-entry-points.md) | 交叉引用把 libobjc 的专用发送入口记成消息发送 | Implemented | +| [0077](0077-thunk-only-objc-members.md) | 只剩 `@objc` thunk 或 initializing entry point 的成员照样建出来 | Implemented | +| [0078](0078-objc-classes-without-class-objects.md) | 没有 class object 的 Swift 类:从 Swift 元数据读出它们的 ObjC 类数据 | Implemented | +| [0079](0079-swift-declared-objc-protocols.md) | Swift 源码定义的 `@objc` 协议,以及类对 ObjC 协议的遵循 | Implemented | +| [0080](0080-objc-evolution-interface.md) | `objc evolution --interface`:带演进标注的合并 ObjC 头文件 | Implemented | +| [0081](0081-evolution-unobservable-presence.md) | evolution 与 diff 区分「不存在」和「看不见」 | Implemented | +| [0082](0082-image-group-evolution.md) | 一个版本由一组 image 组成的演进 | Implemented | +| [0083](0083-exported-only-marking-mode.md) | 导出过滤进入标记模式,C 导入类型不再判成未导出 | Implemented | +| [0084](0084-comment-structure.md) | 注释结构标记:打印器给每条注释标出种类和各段角色 | Implemented | +| [0085](0085-abi-flag-words-bit-field.md) | ABI 层的 flag word 改用 `@BitField`,修掉三个读错位的访问器 | Implemented | +| [0086](0086-shared-dependency-openings.md) | 依赖定位器共享同一路径的打开,不再按根重开 cache 与显式文件 | Implemented | +| [0087](0087-resolvable-locatable-layout-wrapper-macro.md) | `@ResolvableLocatableLayoutWrapper`:样板宏改名并补上遵循 | Implemented | +| [0088](0088-machofile-performance.md) | 离线读取追平进程内:去掉 MachOFile 独有的开销,再压两边共用的部分 | Implemented | +| [0089](0089-swift-objc-interop-module.md) | 把 SwiftInspection 的 ObjC 部分拆成 SwiftObjCInterop 模块 | Implemented | +| [0090](0090-objc-imported-declarations.md) | ObjC 类、category 与协议按 ClangImporter 的规则建成 Swift 声明 | Implemented | +| [0091](0091-export-verdict-without-local-symbols.md) | 没有本地符号的镜像里,扩展中的类型与私有 `@objc` 协议也给出导出结论 | Implemented | +| [0092](0092-existential-any.md) | interface 与 dump 给 existential 写上 `any`,并修好 constrained existential 字段的类型 | Implemented | +| [0093](0093-observable-macro-folding.md) | 识别 `@Observable` 宏:interface 默认折叠它的展开 | Implemented | +| [0094](0094-init-accessor-recovery.md) | 还原 SE-0400 的 init accessor | Implemented | +| [0095](0095-observable-nested-expansion.md) | `@Observable` 的展开分两层:先出 `@ObservationTracked`,再展开它 | Implemented | +| [0096](0096-swift-first-imported-declarations.md) | Swift 实现的类,导入声明以 Swift 一侧为准 | Implemented | +| [0097](0097-offline-cross-references-and-symbolication.md) | 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | +| draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | +| draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | +| [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | +| [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | +| [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md deleted file mode 100644 index 249034ce1..000000000 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ /dev/null @@ -1,77 +0,0 @@ -# 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/Evolutions/draft-swift-declaration-model-indexing-layout.md b/Documentations/Evolutions/draft-swift-declaration-model-indexing-layout.md new file mode 100644 index 000000000..260e5e65a --- /dev/null +++ b/Documentations/Evolutions/draft-swift-declaration-model-indexing-layout.md @@ -0,0 +1,60 @@ +# Draft - SwiftDeclaration 的目录分成公开模型与索引代码两块 + +- **状态**: In Progress +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **关联提案**: [0042-swift-declaration-file-layout](0042-swift-declaration-file-layout.md)(上一次整理这个模块的文件;本提案沿用它「`Members/` 是模型、`Building/` 是索引期机器」的分界,把这条分界推到整个模块) +- **实现分支 / PR**: `refactor/swift-declaration-layout` + +## 摘要 + +0042 之后,这个模块新增的文件大多与 ObjC 相关(`ObjCProtocolDefinition`、`ObjCCategoryConformance`、`ResolvedObjCMemberFacts`、`TypeDefinition+ObjCMembers` / `+ObjCProtocols`、`ExtensionDefinition+ObjCMembers` / `+ThunkAttributes`、`DefinitionIndexing`),都放进了 `Components/Definitions/`,那里现在有 25 个文件:四个顶层声明的本体、五个成员定义、十三个 `+Indexing` 一类的索引扩展、两个 ObjC 事实类型,以及「每个定义只索引一次」的那把锁。`Components/` 这一层不区分任何东西,`Events/`、`Extensions/` 却放在它外面;同属成员的定义一半在 `Definitions/`、一半在 `Members/`;还有三个类型藏在别人的文件里。本批把模块分成 `Model/`(下游读的公开模型)和 `Indexing/`(填模型的代码,全是 `package` / `internal`)两棵树。只搬文件、原样剪切三个类型,不改任何代码。 + +## 方案 + +``` +Sources/Declaration/SwiftDeclaration/ +├─ Model/ +│ ├─ Definitions/ Definition(含 MutableDefinition)、TypeDefinition、ProtocolDefinition、 +│ │ ExtensionDefinition、ObjCProtocolDefinition(含 ObjCProtocolDefinitionError) +│ ├─ Members/ FunctionDefinition、VariableDefinition、SubscriptDefinition、FieldDefinition、 +│ │ WrappedPropertyDefinition、ObjCProtocolRequirementDefinition、Accessor、 +│ │ OrderedMember、MemberCategory、StrippedSymbolicRequirement、ResolvedObjCMemberFacts +│ ├─ Names/ 不变 +│ ├─ Kinds/ 不变 +│ └─ ExportStatus、SwiftAttribute、AssociatedTypeWitnessProjection、ObjCCategoryConformance +├─ Indexing/ +│ ├─ DefinitionIndexing.swift +│ ├─ TypeDefinition/ TypeDefinition+{Indexing, ClassDispatch, MemberIndexing, FinalRecovery, +│ │ ThunkAttributes, SynthesizedMembers, WrappedProperties, ObjCMembers, ObjCProtocols} +│ ├─ ExtensionDefinition/ ExtensionDefinition+{Indexing, ObjCMembers, ThunkAttributes} +│ ├─ ProtocolDefinition+Indexing.swift +│ ├─ ObjCProtocolDefinition+Indexing.swift +│ └─ Building/ 原 Components/Building/ 的九个文件,加上 ObjCProtocolNames +├─ Events/ 不变 +└─ Extensions/ 加上 DemanglingNode+StoredVariable +``` + +- **分界的判据是可见性**:`Model/` 里的类型是 `public` 的、索引结束后还留在模型里;`Indexing/` 里每个声明都是 `package` 或 `internal`,只在 `index(in:)` 与 `SwiftDeclarationIndexer.prepare()` 期间有人调用。逐一核对过:九个 `TypeDefinition+…`、三个 `ExtensionDefinition+…`、两个 `+Indexing` 与 `DefinitionIndexing` 里没有一个 `public` 声明。 +- **成员定义全部进 `Model/Members/`**:`FunctionDefinition` 这五个原在 `Definitions/`,和 `Accessor`、`OrderedMember` 本是同一类东西;`ResolvedObjCMemberFacts` 是三种成员定义上的公开投影,一并归入。 +- **三处原样剪切**,各自的 import 照抄原文件: + - `ObjCProtocolRequirementDefinition` 从 `ObjCProtocolDefinition.swift` 末尾抽成 `Model/Members/ObjCProtocolRequirementDefinition.swift`。 + - `ObjCProtocolNames` 从 `TypeDefinition+ObjCProtocols.swift` 抽成 `Indexing/Building/ObjCProtocolNames.swift`:`ObjCCategoryConformance.all(in:)` 也用它,不只属于 `TypeDefinition`。 + - `isStoredVariable` 从 `DefinitionBuilder.swift` 末尾抽成 `Extensions/DemanglingNode+StoredVariable.swift`,与 `DemanglingNode+AccessorKind` 并列。 +- **用 `git mv` 搬**,`git log --follow` 能接上每个文件的历史。没有测试、脚本或 `Package.swift` 按路径引用这些文件,源码扫描类测试按模块名取文件,不受目录层级影响。 +- **验证**:干净编译库与全部测试 target。不跑渲染 A/B:没有一行代码改变,输出不可能变。 +- **文档**:[Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md) 的「文件 → 子系统对照」重写,「TypeDefinition 的扩展」表补上漏掉的 `+ObjCMembers` 与 `+ObjCProtocols`(原文写「七个」、实有九个);术语表与现行实现说明里写着完整路径的行改成新路径;演进账本加一节。 +- **没问就定的假设**: + - `ProtocolDefinition` 与 `ObjCProtocolDefinition` 的索引扩展各只有一个文件,不单独建目录,照 0042「一个文件的目录是噪音」的判断。 + - `ObjCCategoryConformance` 放在 `Model/` 根下:它是公开的事实类型,挂在索引器上,不属于任何一种声明或成员。它的 `all(in:)` 是 `package` 的构建方法,与类型留在同一个文件,不拆。 + - 历史文档(已落地的提案、`TaskReports/`、`Reviews/`、`Roadmaps/`、演进账本旧章节、`ReviewAdjudications` 的发现记录、`SharedNodeStoreMigration` 与 `FieldMetadataRenderingMigration` 这类迁移记录)里的旧路径是当时的事实,保持原样。只写了 `Building/X.swift` 这种相对路径、且仍是新路径后缀的行也不改。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-06 | Created as Draft | 0042 之后新增的文件都堆进了 `Components/Definitions/`,用户要求把这个模块的文件层级重新整理 | +| 2026-11-06 | 采用「公开模型 / 索引代码」两分 | 用户在三个布局里选定。另两个:按声明分目录(每个声明一个目录装本体和全部扩展,但公开模型和索引代码又混在一起)、最小整理(只去掉 `Components/` 并归拢成员定义,`Definitions/` 仍剩约 20 个文件) | +| 2026-11-06 | 按轻量档写精简提案;状态 Draft → Accepted → In Progress | 用户批准方案;提案随功能分支落盘,不先单独提交进 `next`:`next` 的检出里有别处未提交的改动 | +| 2026-11-06 | 实现完成,待用户看过后收尾 | 52 个文件按方案搬完,三处剪切照方案;从空 scratch 编译库与全部测试 target,原始退出码 0。文档:模块参考的两张对照表重写,术语表与四份实现说明改路径,演进账本加一节;不另写实现说明或使用指南,布局与判据写在模块参考里;没有新术语 | +| 2026-11-06 | `AGENTS.md` 的 SwiftDeclaration 条目加一句归位规则 | 用户同意:0042 的布局就是被随手放进 `Definitions/` 的新文件冲乱的,agent 加新的索引步骤时默认会放在 `TypeDefinition.swift` 旁边 | diff --git a/Documentations/Evolutions/draft-swift-declaration-type-naming.md b/Documentations/Evolutions/draft-swift-declaration-type-naming.md new file mode 100644 index 000000000..433042377 --- /dev/null +++ b/Documentations/Evolutions/draft-swift-declaration-type-naming.md @@ -0,0 +1,48 @@ +# Draft - SwiftDeclaration 的类型名按角色统一后缀 + +- **状态**: In Progress +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **关联提案**: [draft-swift-declaration-model-indexing-layout](draft-swift-declaration-model-indexing-layout.md)(同一批整理的上一步:先把文件分成 `Model/` 与 `Indexing/`,本提案再理顺名字) +- **实现分支 / PR**: `refactor/swift-declaration-layout` + +## 摘要 + +这个模块的类型名有三处不成套。`Indexing/Building/` 下的六个命名空间用了四种起名法:「做事的人」`DefinitionBuilder`,「这一步」`MemberAttributeApplication` / `ObjCMemberApplication` / `WrappedPropertyRecovery`,「产物的复数」`StandInMemberSymbols` / `ObjCProtocolNames`;`OverrideSymbolMatcher.swift` 里却没有这个类型,只有两个包级自由函数。同一个意思用了两个词:`WrappedPropertyDefinition.Origin` 与 `ObjCProtocolRequirementDefinition.Source` 都表示「这条声明从哪来」。`AssociatedTypeWitnessProjection` 的「Projection」在模块里只此一处,存它的属性叫 `resolvedAssociatedTypeWitnesses`。本批按角色给命名空间统一后缀,并把三个公开名字改成与模块其余部分一致的词,公开的旧名留 deprecated 别名。 + +## 方案 + +**命名空间按角色取后缀**,后缀本身说明它干哪一类事: + +| 角色 | 后缀 | 成员 | +|---|---|---| +| 造出新的东西(成员定义、替身符号、协议名) | `…Builder` | `DefinitionBuilder` → `MemberDefinitionBuilder`,`StandInMemberSymbols` → `StandInMemberSymbolBuilder`,`ObjCProtocolNames` → `ObjCProtocolNameBuilder` | +| 拿二进制里另一处的证据对到已经建好的成员上 | `…Matcher` | `MemberAttributeApplication` → `ThunkAttributeMatcher`(thunk 符号 → `@objc` / `@nonobjc` / `distributed`),`ObjCMemberApplication` → `ObjCMemberMatcher`(ObjC 方法表 → `@objc`、`override`、显式 selector),`OverrideSymbolMatcher`(新建 `package enum`,收进原来的自由函数 `memberJoinKey` 与 `demangledOverrideSymbol`) | +| 补回二进制丢掉的事实 | `…Recovery` | `WrappedPropertyRecovery`(不变) | + +`MemberDefinitionBuilder` 多出的 `Member`:它只造成员定义(函数、变量、下标),不造 `TypeDefinition` 这类声明本体,`DefinitionBuilder` 读起来像后者。`ThunkAttributeMatcher` 里的 `Thunk` 与调用它的 `TypeDefinition+ThunkAttributes`、`ExtensionDefinition+ThunkAttributes` 对上。这几个都是 `package`,直接改名,模块外只有 SwiftIndexing、SwiftDiffing、SwiftDump 与一个测试在调用,一并改掉。 + +**三个公开名字**,旧名照仓库惯例在新类型旁边留 `@available(*, deprecated, renamed:)` 的别名: + +- `AssociatedTypeWitnessProjection` → `ResolvedAssociatedTypeWitness`,与存它的属性 `ExtensionDefinition.resolvedAssociatedTypeWitnesses` 同名。 +- `ConditionalWitnessCandidate` → `ResolvedAssociatedTypeWitness.ConditionalCandidate`:它只出现在见证的 `conditionalCandidates` 里,嵌进去之后名字不必再重复「Witness」。 +- `ObjCProtocolRequirementDefinition.Source` / `source` → `Origin` / `origin`,与 `WrappedPropertyDefinition.Origin` / `origin` 用同一个词。没选 `Source`:这个仓库里 `source` 还指源码与 `MachOSource`,`Origin` 不会被读歪。 + +**不改的**:`…Definition`(源码里有名字的一条声明)、`…Name`、`…Kind`、`…Facts`(与 SwiftInspection 的 `ObjCImplementationClassFacts` 同一个词)这几个后缀各自只表示一类东西;`ExportStatus`、`MemberCategory`、`OrderedMember`、`StrippedSymbolicRequirement`(没有名字,不是一条声明,所以不叫 `…Definition`)是互不相同的概念,名字不成套是对的。事件命名空间 `SwiftIndexEvents` 也有不一致(结果类型里夹着一个 `…Input`、计数字段三种拼法),另开一批:它的 payload case 改名留不了别名。 + +- **验证**:改名不改输出,干净编译库与全部测试 target;不跑渲染 A/B。`ResolvedAssociatedTypeWitness` 是 `Codable` 的,编码用的是属性名,类型改名与嵌套不改变 JSON。 +- **文档**:模块参考、术语表与现行实现说明里的名字改成新名;已落地的提案、任务报告、评审记录、演进账本旧章节、`ReviewAdjudications` 里的旧名保持原样。`Documentations/README.md` 的索引摘要这次不改:那几行概括的是历史文档,而且集成分支的检出里这份文件有别处未提交的改动。 +- **没问就定的假设**: + - deprecated 别名与 0057 的废弃转发一起在 0.25.0 删除。 + - 测试套件 `AssociatedTypeWitnessProjectionTests` 随类型改名为 `ResolvedAssociatedTypeWitnessTests`;CI 的套件筛选里没有它,不用跟着改。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-06 | Created as Draft | 目录整理之后,用户指出这个模块的类型名不成套 | +| 2026-11-06 | 范围定为包内命名空间加三个公开名字,事件命名空间另开一批 | 用户在三档范围里选定;事件 payload 的 case 改名留不了别名,改动量也大几倍 | +| 2026-11-06 | 命名空间按「造新东西 / 对证据 / 补事实」三类取后缀 | 用户选定,没选「一律叫做事的人」:`Applier`、`Recoverer` 读起来别扭 | +| 2026-11-06 | 第二类用 `…Matcher`,不用 `…Application` | 用户指出 `Application` 会被读成「应用程序」;`…Matcher` 与模块里已有的 `OverrideSymbolMatcher` 同类,用户选定。`…Applier` 读着别扭,`…Join` 不像名词,`…Annotator` 会和输出里的 annotation 撞词 | +| 2026-11-06 | 按轻量档写精简提案;状态 Draft → Accepted → In Progress | 用户批准方案;接着在目录整理的分支上做 | +| 2026-11-06 | 实现完成,待用户看过后收尾 | 按方案改完;`OverrideSymbolMatcher.swift` 原来两段文档注释叠在 `memberJoinKey` 上,收进 enum 时各归各位;SwiftIndexing 里私有的 `resolvedWitnessProjections` 一并改成 `resolvedAssociatedTypeWitnesses`。增量编译库与全部测试 target,原始退出码 0。文档:模块参考写上后缀规则,术语表与十份现行文档换成新名,演进账本加一节;不另写实现说明或使用指南;没有新术语 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 66f7b9470..b18aa182e 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -42,9 +42,18 @@ **这也是不要靠 bind 来判定墓碑的原因之一**:离线读一个 Resilient 策略的类,`MachOFile` 里只有 metadata pattern,根本没有 vtable word 可读——判据必须回到 descriptor 的 null 本身。 +**墓碑只说明槽指向的那个入口没有代码,不说明成员没有代码**:整模块优化的 app 里,一个 `@objc` 方法的槽可以是墓碑而它的 ObjC thunk 还在(Swift 函数体内联进了 thunk),一个 initializer 的 `__allocating_init` 槽可以是墓碑而它的 initializing entry point(`…fc`)还在。这两种成员由替身成员符号补建,槽号经节点联结照常挂上(见 thunk-only member)。 + - **主要出现在**:`ClassDumper` 的 vtable 循环、`DeclarationRenderConfiguration.deletedMethodSlotComment` - **延伸阅读**:[提案 vtable-slot-attribution](Evolutions/0020-vtable-slot-attribution-via-method-descriptor-symbols.md)、[PR #123 review findings 第 1 条](../Roadmaps/2026-09-06-pr123-review-findings.md) +### address symbolication(地址符号化) + +回答「这个未滑动地址是什么」:落在哪个镜像的哪个段与节,以及在那里的意思——某个函数体里、离起点多远(函数名的来源与列函数时相同,含 ObjC 方法表与 Swift 元数据给的后备名),一个桩或一串 stub island 以及最终通向哪里,一个指针槽(GOT、selector / class / superclass / protocol 引用、ivar 偏移变量)以及里面装的东西,一个 C 字符串或 `CFString`,或者最近的符号加偏移。结构由核心层的 `AddressPlace` 判断,语言层知道的(selector、类、ivar、Swift 类型)由门面补上。`dyld_info` 在 macOS 26 的 SwiftUICore 上给两千多个桩标错名,原因是它按间接符号表认桩,而符号化按桩实际加载的槽认。 + +- **主要出现在**:`CrossReferenceAnalyzer.symbolication(of:)`、`swift-section symbolicate`、RuntimeViewer 的 `symbolicate` 命令与 `Symbolicate` MCP 工具 +- **延伸阅读**:[0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md)、[Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md)「地址符号化」 + ### anchor 协议(anchor protocol) 一条 same-type 约束的 subject 里,关联类型所**限定的声明协议**——`τ_1_0.[Swift.Sequence]Element == [A]` 的 anchor 是 `Swift.Sequence`(mangling 层限定形式,demangle 后保留在 `dependentAssociatedTypeRef` 的第二个 child)。注意 anchor 是 canonicalization 后**继承链最上层的原始声明者**,不一定是源码 sugar 写在哪个协议上(`Collection<[A]>` 的约束 anchor 是 Sequence),也不一定在 opaque 组合成员之内。opaque 尖括号参数的归属裁决以它为第一信号。 @@ -56,35 +65,56 @@ 一个 dylib load name(`@rpath/Foo.framework/Versions/A/Foo`、`/usr/lib/libobjc.A.dylib`)归约成的镜像名:末段路径去**第一个**扩展名(`Foo`、`libobjc`)。这是与 MachOKit 的契约——`MachOImage(name:)` 对进程内每个镜像的路径做同一归约再比较,把未归约的 load name 喂给它永远匹配不到。它也是所有依赖集合的去重键:同一个库会被不同镜像以不同拼写链接,只有裸名跨拼写稳定。 -- **主要出现在**:`Sources/MachO/MachODependencies/DependencyLoadName.swift`、`DependencyClosure`、`FileDependencyLocator` -- **延伸阅读**:[Modules/MachODependencies.md](Internal/Modules/MachODependencies.md) §2 +- **主要出现在**:MachOKitExtensions `Sources/MachODependencies/DependencyLoadName.swift`、`DependencyClosure`、`FileDependencyLocator` +- **延伸阅读**:MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) §2 ### bucket(桶) 分类索引里「一个键对应的一组符号表行号」(如 `symbolRowsByOffset` 的值、`MemberSymbolRows` 的叶子)。旧形态是 `[UInt32]` 小数组——绝大多数桶只有一个元素,却各付一次堆分配;提案 0003 落地后值形态为 `SymbolRowBucket`(单元素内联于字典槽,第二个元素起才落堆数组),迭代序保持插入序。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`、`Sources/MachO/MachOSymbols/SymbolRowBucket.swift` +- **主要出现在**:`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift`、MachOKitExtensions `Sources/MachOSymbols/SymbolRowBucket.swift` - **延伸阅读**:[提案 0003](Evolutions/0003-symbol-row-bucket-flattening.md) ### cache scope(缓存范围,`ReadingContextCacheScope`) 一个 `ReadingContext` 声明的「按它读出来的东西,memo 缓存该存到哪一层」:`.image(identifier:)` 按镜像存(键就是 reader 的 `identifier`,与其它按镜像缓存同一个键,随镜像一起驱逐),`.process` 存进全进程共享的一层(地址是绝对地址,两个镜像不会撞),`.uncached` 不缓存。`MachOContext` 声明 `.image`,`InProcessContext` 声明 `.process`,其余实现默认 `.uncached`——以文件偏移为地址的第三方 context 如果落进全进程那层,两个镜像的偏移会互相串结果。反混淆 memo(`SymbolicDemanglerCache`)与节点驻留池(`InternedNodeReferenceCache`)按它选层。 -- **主要出现在**:`Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift`、`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`、`Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift` +- **主要出现在**:MachOKitExtensions `Sources/MachOReading/ReadingContext/ReadingContext.swift`、`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`、`Sources/Symbols/SwiftSymbols/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` +- **主要出现在**:MachOKitExtensions 的 `Sources/ARM64InstructionDecoding/ARM64Trampoline.swift`、MachOKitExtensions 的 `Sources/MachOCodeReferences/Scanning/ReferenceScanner.swift` - **延伸阅读**:[Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md)、[0072-cross-reference-analysis](Evolutions/0072-cross-reference-analysis.md) +### category conformance(category 遵循,`ObjCCategoryConformance`) + +本镜像 extension 别的模块的类(ObjC 类,或别的模块的 Swift 类)时采纳的 ObjC 协议,记在那个 extension 的 category 的协议表里,没有 Swift 的 conformance record。interface 把每个 category 打成一个 `extension X: P {}`。与类头部列出的 ObjC 协议的区别:同一模块里的 extension 会被编译器并进类自己的 `class_ro_t`,那些遵循打在类头部,不算 category 遵循。 + +- **主要出现在**:`Sources/Declaration/SwiftDeclaration/Model/ObjCCategoryConformance.swift`、`Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift` +- **延伸阅读**:[SwiftDeclaredObjCProtocols.md](Internal/SwiftDeclaredObjCProtocols.md)、[0079-swift-declared-objc-protocols](Evolutions/0079-swift-declared-objc-protocols.md) + +### category merging(category 并进类) + +同一镜像里给本镜像的类写的 category 不会以 category 的形式留下来:同模块 Swift extension 的成员由编译器直接并进类,其余的(ObjC 写的 category、Swift 给 ObjC 类写的 extension、`@objc(Name) @implementation extension`)由链接器并进类自己的表,`__objc_catlist` 里不再有它们,事后也分不出哪些成员来自 category。所以本库读到的 category 只有给别的镜像的类写的那些;`ObjCImplementationFixture` 整个没有 `__objc_catlist`。别与 dyld cache 的「预先附加」混淆:那是构建 cache 时把 category(含别的镜像的)挂到类上,类的表变成「多张表的表」,类自己的那张仍分得出来。 + +- **主要出现在**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift`、`ObjCImplementationClassIndex.swift` 的 `importedMethods(of:)` +- **延伸阅读**:[0090-objc-imported-declarations](Evolutions/0090-objc-imported-declarations.md) + +### class without a class object(没有 class object 的类,`SwiftClassWithoutClassObject`) + +`__objc_classlist` 里没有 class object 的 Swift 类:泛型类,父类在别的 resilience domain 的类,父类是本模块泛型类的类。它们的 `class_ro_t` 都静态存在,但只有经 Swift 元数据才找得到(generic metadata pattern、`ResilientClassMetadataPattern`、静态的 incomplete metadata)。后两种有 ObjC 祖先时还在 `__objc_stublist` 里登记一个 stub。交给 MachOObjCSection 时它们叫 supplied class(`ObjCSuppliedClass`),即宿主补进 ObjC 索引器的类。与 `@objc @implementation` 类的区别:那种类有 class object,没有的是 Swift 元数据。 + +- **主要出现在**:`Sources/Analysis/SwiftObjCInterop/SwiftClassWithoutClassObjectIndex.swift`、`Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift` +- **延伸阅读**:[ClassesWithoutClassObjects.md](Internal/ClassesWithoutClassObjects.md)、[0078-objc-classes-without-class-objects](Evolutions/0078-objc-classes-without-class-objects.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.25.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 是唯一实现;另外两种改成一行转发(`machO.context` / `.inProcess`),0.22.0 废弃,0.25.0 删除。 -- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、`Sources/MachO/MachOPointers/`、`Sources/MachO/MachOResolving/Resolvable.swift` +- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、MachOKitExtensions `Sources/MachOPointers/`、MachOKitExtensions `Sources/MachOResolving/Resolvable.swift` - **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) ### depth(泛型参数层号,`GenericParameterDepthLayout`) @@ -98,21 +128,21 @@ macOS 27 与 iOS 27 的 dyld shared cache 不再给每个镜像留自己的 `__o 一个 root 二进制经 `LC_LOAD_DYLIB` 家族 load command 解析出的依赖镜像集合(`MachODependencies.DependencyClosure`)。本项目里的「闭包」默认指**传递**闭包:BFS 递归、按裸镜像名去重、root 排除、解析顺序是契约的一部分(`SwiftLayout.ImageUniverse` 按此顺序惰性索引、命中即停)。同一类型也承载 `.direct` 遍历(只取 root 自己的一层),`SwiftInterfaceBuilderDependencies` 用的是这一种——名字里的「闭包」在那里只是复用同一个结果类型。定位不到的依赖记入 `unresolvedLoadNames`,不算失败。 -- **主要出现在**:`Sources/MachO/MachODependencies/DependencyClosure.swift`、`Sources/Analysis/SwiftLayout/ImageUniverse+DependencyClosure.swift` -- **延伸阅读**:[Modules/MachODependencies.md](Internal/Modules/MachODependencies.md)、[StaticLayoutDependencyClosure.md](Internal/StaticLayoutDependencyClosure.md) +- **主要出现在**:MachOKitExtensions `Sources/MachODependencies/DependencyClosure.swift`、`Sources/Analysis/SwiftLayout/ImageUniverse+DependencyClosure.swift` +- **延伸阅读**:MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)、[StaticLayoutDependencyClosure.md](Internal/StaticLayoutDependencyClosure.md) ### derived symbol forms(派生符号形态) 一个成员实现符号经追加后缀派生出的入口符号:`Tj`(dispatch thunk)、`Tq`(method descriptor)、`Tu`(async function pointer)、`TjTu`。library-evolution 构建的常态是**实现符号不导出、`Tj` 导出**(外部调用方经 thunk 派发),所以判断成员导出状态必须查全形态(`isExportedIncludingDerivedSymbols`)——裸查实现符号会把整个 resilient 库误判为未导出。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` +- **主要出现在**:`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift` - **延伸阅读**:[提案 0008](Evolutions/0008-interface-header-and-export-status-annotations.md)、[InterfaceHeaderAndExportStatusAnnotations.md](Internal/InterfaceHeaderAndExportStatusAnnotations.md) ### descriptor-only member(只剩 method descriptor 符号的成员) class 的 vtable 成员里,实现函数没有符号、只剩它自己 method descriptor 的 `Tq` 符号能说出它是谁的那一类。library-evolution 构建本来就只导出 `Tj` / `Tq`,实现符号保持 local(见上一条 derived symbol forms),所以镜像的 local 符号一旦被剥掉——系统 dyld shared cache 里的 AppKit、`strip -x` 过的二进制——public 的 class 方法和访问器就全都属于这一类:macOS 26.7 的 AppKit 因此在 interface 里少了 53 个成员。「实现符号没导出」不等于「没符号」:同一份 cache 里的 SwiftUI、SwiftUICore、Foundation 保留了 local 符号,不属于这一类。协议 requirement 也有 `Tq`,但它们从协议描述符打印,也不在此列。interface 过去只从实现符号建成员,这一类整个缺席;现在 `classDispatchLookups` 为每个有 `Tq`、实现指针非 null 的槽造一个成员符号(名字是 `Tq` 名去掉后缀,也就是实现函数本来的 mangled 名;偏移是 descriptor 记录的实现偏移,async 方法再跳一次到函数入口),`indexMembers` 在实现符号没有声明这个成员时用它补建。 -和 ABI 墓碑的区别:墓碑的实现指针是 null,镜像里根本没有这个成员的代码,所以不补建;descriptor-only member 的代码还在,只是没有名字。 +和 ABI 墓碑的区别:墓碑的实现指针是 null,槽指向的入口在镜像里没有代码,所以不从槽补建;descriptor-only member 的代码还在,只是没有名字。墓碑槽的成员若还剩 `@objc` thunk 或 initializing entry point,由那一边的替身补建(见 thunk-only member)。 - **主要出现在**:`TypeDefinition+ClassDispatch.swift`、`ClassDispatchLookups.vtableSlotMemberSymbols`、`TypeDefinition+MemberIndexing.swift` - **延伸阅读**:[提案 0054-interface-descriptor-only-vtable-members](Evolutions/0054-interface-descriptor-only-vtable-members.md) @@ -121,7 +151,7 @@ class 的 vtable 成员里,实现函数没有符号、只剩它自己 method d 把一个查询期 vend 出来的 `DemangledSymbol` 从共享 `SymbolTable` 上摘下来、换成自带单行表的独立值。共享表对「vend 十万个、随手丢弃」是正确的取舍,但**存进声明模型的长命值必须先 detach**——一个存活值会把整张表(几十万行 + 对镜像映射内存的引用)钉在内存里,让按镜像回收失效。六个存储点由 `SymbolTableRetentionTests` 钉住;查询路径**不要** detach。 -- **主要出现在**:`Sources/MachO/MachOSymbols/DemangledSymbol.swift`、AGENTS.md「Symbol indexing」段 +- **主要出现在**:`Sources/Symbols/SwiftSymbols/DemangledSymbol.swift`、AGENTS.md「Symbol indexing」段 - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### 等价类塌缩(equivalence-class collapse) @@ -133,11 +163,11 @@ Requirement Machine 最小化泛型签名时,把 pin 到同一具体类型的 ### eviction group(驱逐分组)、claim(认领)、live owner(活持有者) -按镜像缓存的三个所有权概念(`MachOCaches.SharedCacheRegistry`,2026-09-28 提案 `0053-shared-cache-composition-and-eviction-registry`)。**eviction group** 是一个 `SharedCache` 在创建时声明的家族(`SharedCacheEvictionGroup`,只有名字的结构体;`MachOCaches` 不定义任何家族,各模块在自己的扩展里声明 `symbolStore`、`internedNames`、`demangleMemo`、`objcHierarchy`……),一个镜像的缓存按家族而不是按 cache 驱逐;条目引用着别的家族存储的 cache 在创建时用 `follows:` 声明跟谁走(`symbolicMangling` / `objcImplementationClasses` / `objcHierarchy` / `objcAncestorResolver` 跟 `symbolStore`,`demangleMemo` 跟 `internedNames`),因为单独留下它们什么都释放不了;注册表据此反向建表、传递展开。**live owner** 是向注册表登记「我在用这个镜像的缓存」的对象,今天只有 `SwiftDeclarationIndexer`;**claim** 是它登记时在注册表锁内采样得到的「这个镜像还没有条目的家族」——那些是它即将建的,由它负责;镜像的最后一个 live owner 注销时驱逐它们认领的家族及其 dependents,提早注销的什么都不清。非持有者(渲染器、SwiftLayout)在登记之前填的条目永远不被认领。 +按镜像缓存的三个所有权概念(`MachOCaches.SharedCacheRegistry`,2026-09-28 提案 `0053-shared-cache-composition-and-eviction-registry`)。**eviction group** 是一个 `SharedCache` 在创建时声明的家族(`SharedCacheEvictionGroup`,只有名字的结构体;`MachOCaches` 不定义任何家族,各模块在自己的扩展里声明 `swiftSymbolStore`、`internedNames`、`demangleMemo`、`objcHierarchy`……),一个镜像的缓存按家族而不是按 cache 驱逐;条目引用着别的家族存储的 cache 在创建时用 `follows:` 声明跟谁走(`symbolicMangling` / `objcImplementationClasses` / `objcHierarchy` / `objcAncestorResolver` 跟 `swiftSymbolStore`,`demangleMemo` 跟 `internedNames`),因为单独留下它们什么都释放不了;注册表据此反向建表、传递展开。**live owner** 是向注册表登记「我在用这个镜像的缓存」的对象,今天只有 `SwiftDeclarationIndexer`;**claim** 是它登记时在注册表锁内采样得到的「这个镜像还没有条目的家族」——那些是它即将建的,由它负责;镜像的最后一个 live owner 注销时驱逐它们认领的家族及其 dependents,提早注销的什么都不清。非持有者(渲染器、SwiftLayout)在登记之前填的条目永远不被认领。 - **不要混淆**:`evict(groups:for:)` 是显式驱逐,只清点名的家族、不展开 followers;followers 只在最后一个持有者注销时展开。「内存压力驱逐」已不存在,宿主要清就调 `evictImagesWithoutLiveOwners()`。 -- **主要出现在**:`Sources/MachO/MachOCaches/SharedCacheRegistry.swift`、`Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift`、各模块的 `SharedCacheEvictionGroup+<模块>.swift`、`Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift`(`prepare()` 与 `deinit`) -- **延伸阅读**:[Modules/MachOCaches.md](Internal/Modules/MachOCaches.md) +- **主要出现在**:MachOKitExtensions `Sources/MachOCaches/SharedCacheRegistry.swift`、`Sources/MachOCaches/SharedCacheEvictionGroup.swift`、各模块的 `SharedCacheEvictionGroup+<模块>.swift`、`Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift`(`prepare()` 与 `deinit`) +- **延伸阅读**:MachOKitExtensions 的 [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md) ### export status(导出状态标注,`// not exported`) @@ -148,10 +178,10 @@ Requirement Machine 最小化泛型签名时,把 pin 到同一具体类型的 ### exported-only 过滤(`--exported-only`,`printExportedDeclarationsOnly`) -export status 的**过滤形态**:interface 只输出镜像导出的声明。类型 / 协议按描述符符号(`…Mn` / `…Mp`,优先取描述符 offset 处的符号,重整名只兜底)裁决,成员沿用 export status 的派生形态判定,扩展按「被扩展类型 / 遵循协议是否为本镜像内未导出声明」裁决(依据 **`ExportFilterScope`**——`printRoot` 从索引器表算出的本镜像内未导出 `TypeName` / `ProtocolName` 集合)。只在判定为 `false` 时删,`nil` 一律保留(绝不靠猜删);普通扩展被清空则整块删,conformance 扩展留 `{}`。与 export status 是同一个事实的两种呈现:删除条件即标注条件,两开关同开输出零标注。 +export status 的**过滤形态**:interface 只输出镜像导出的声明。类型 / 协议按描述符符号(`…Mn` / `…Mp`,优先取描述符 offset 处的符号,重整名只兜底;都判不了时私有或局部声明算未导出)裁决,Swift 声明的 `@objc` 协议没有描述符、私有的算未导出,成员沿用 export status 的派生形态判定,扩展按「被扩展类型 / 遵循协议是否为本镜像内未导出声明」裁决(依据 **`ExportFilterScope`**——`printRoot` 从索引器表算出的本镜像内未导出 `TypeName` / `ProtocolName` 集合)。只在判定为 `false` 时删,`nil` 一律保留(绝不靠猜删);普通扩展被清空则整块删,conformance 扩展留 `{}`。与 export status 是同一个事实的两种呈现:删除条件即标注条件,两开关同开输出零标注。C 导入类型(`__C` 模块)不裁决:它的描述符是本镜像自己的副本。标记模式下被删的内容照常打出,条件是 `swift.printExportedDeclarationsOnly` 关着。 - **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift`、`SwiftInterfaceBuilder.printRoot()` -- **延伸阅读**:[提案 0016](Evolutions/0016-exported-only-interface.md)、[ExportedOnlyInterfaceFiltering.md](Internal/ExportedOnlyInterfaceFiltering.md) +- **延伸阅读**:[提案 0016](Evolutions/0016-exported-only-interface.md)、[提案 0083](Evolutions/0083-exported-only-marking-mode.md)、[ExportedOnlyInterfaceFiltering.md](Internal/ExportedOnlyInterfaceFiltering.md) ### emission strategy(发射策略) @@ -167,6 +197,20 @@ linker 把字节相同的函数体合并到同一地址的优化。后果是「 - **主要出现在**:`Descriptor+MethodDescriptorSymbols.swift`、`ClassDumper`、`TypeDefinition.index`、`FinalKeywordICFRegressionTests`、`VTableSlotAttributionTests` - **延伸阅读**:[提案 vtable-slot-attribution](Evolutions/0020-vtable-slot-attribution-via-method-descriptor-symbols.md)、[提案 0006](Evolutions/0006-final-keyword-and-lazy-accessor-type-recovery.md) +### image group(image 组)与 move(搬家) + +evolution 里组成一个版本的一组 image,主 image 在前:Apple 拆过的框架以组为单位比较,例如 SwiftUI 与 SwiftUICore(macOS 15 起)、AppKit 与 UIFoundation、CollectionViewCore、CoreAutoLayout。组里的声明合成一个 API 面,一个声明从一个 image 挪到另一个 image(SwiftUI 的类型带 `@_originallyDefinedIn` 挪进 SwiftUICore,mangled name 不变)不再读成删除加新增,而是记一条 **move**:两侧都观测到它在场、所在的 image 不同,报告写 `> moved in 15.0: SwiftUI → SwiftUICore`。只跟着容器一起挪的成员不另记;move 不进兼容性判定。组里定义了的类型,另一个 image 给它加的普通 extension 并回类型本体比较。 + +- **主要出现在**:`Sources/Output/SwiftDiffing/ImageGroups.swift`(`ABIImageSnapshot`、`ImageMove`、`MergedImageGroup`)、`ABIEvolutionBuilder.evolution(ofImageGroups:versions:)`、`Sources/Output/SwiftInterface/InterfaceVersionRendering.swift`(`InterfaceVersionGroupUnit`);ObjC 一侧在 MachOObjCSection 的 `ObjCDiffing`(`ObjCAPIImageSnapshot`、`ObjCImageMove`) +- **延伸阅读**:[提案 0082](Evolutions/0082-image-group-evolution.md)、[ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) 第七批 + +### implied ObjC protocol(隐含的 ObjC 协议) + +类遵循一个继承了 ObjC 协议的 Swift 协议时(`protocol CopyingRefinement: NSCopying`),编译器也把那个 ObjC 协议记进类(或 category)的协议表(`getObjCProtocols` 的递归),尽管源码没写。interface 不打它,Swift 遵循已经说明了;dump 在类的 `// ObjC protocols:` 一行里标注 `(implied by a Swift conformance)`。只认得出本镜像的 Swift 协议隐含的。 + +- **主要出现在**:`ObjCProtocolAdoption.impliedProtocolRuntimeNames`(`Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift`) +- **延伸阅读**:[SwiftDeclaredObjCProtocols.md](Internal/SwiftDeclaredObjCProtocols.md) + ### instantiated type name(实例化类型名) 一个泛型类型某个实例化的名字,实参挂在声明对应参数的那一层:`Outer.Inner`、`Outer.Middle`。这是运行时 `_buildDemanglingForContext` 给实例化起名的形状;`SymbolicDemangler.instantiatedTypeNode(for:binding:in:)` 移植它,离线特化的结果与在线特化的 `TypeDefinition.typeName` 都用它。不要与把全部实参放进最内层的旧形状(`Outer.Inner`)混淆。 @@ -176,36 +220,43 @@ linker 把字节相同的函数体合并到同一地址的优化。后果是「 ### large-stack executor(大栈执行器,`LargeStackTaskExecution`) -swift-demangling 0.6.3 起提供的 `TaskExecutor`(`StackSafeExecutor.taskExecutor`,线程栈 16 MB,`@_spi(Internals)`)。demangler 每次 demangle / print / remangle 都按**调用线程的剩余栈**决定要不要跳到它的 8 MB 线程池——协作线程只有 512 KB,探针永远不过,async 打印循环因此每打印一个符号付一次线程往返;task 跑在大栈执行器的线程上时探针每个入口都通过,全程原地执行、零跳转。本库通过 `MachOSymbols.LargeStackTaskExecution.run` 在库入口(索引器 prepare、interface builder、printer 逐定义入口、diff / evolution、dump)自装偏好,宿主零改动;macOS 15 / iOS 18 以下静默回退为原样执行。与「跳转池」(demangler 自己的 8 MB `LargeStackThreadPool`,同步 `withLargeStack` 批次用)是两个池:执行器的 job 是整段 task,会占线程上百秒,不能挤占同步跳转的额度。 +swift-demangling 0.6.3 起提供的 `TaskExecutor`(`StackSafeExecutor.taskExecutor`,线程栈 16 MB,`@_spi(Internals)`)。demangler 每次 demangle / print / remangle 都按**调用线程的剩余栈**决定要不要跳到它的 8 MB 线程池——协作线程只有 512 KB,探针永远不过,async 打印循环因此每打印一个符号付一次线程往返;task 跑在大栈执行器的线程上时探针每个入口都通过,全程原地执行、零跳转。本库通过 `SwiftSymbols.LargeStackTaskExecution.run` 在库入口(索引器 prepare、interface builder、printer 逐定义入口、diff / evolution、dump)自装偏好,宿主零改动;macOS 15 / iOS 18 以下静默回退为原样执行。与「跳转池」(demangler 自己的 8 MB `LargeStackThreadPool`,同步 `withLargeStack` 批次用)是两个池:执行器的 job 是整段 task,会占线程上百秒,不能挤占同步跳转的额度。 -- **主要出现在**:`Sources/MachO/MachOSymbols/LargeStackTaskExecution.swift`、各 async 入口的 `LargeStackTaskExecution.run { … }` +- **主要出现在**:`Sources/Symbols/SwiftSymbols/LargeStackTaskExecution.swift`、各 async 入口的 `LargeStackTaskExecution.run { … }` - **延伸阅读**:[LargeStackTaskExecutorAdoption.md](Internal/LargeStackTaskExecutorAdoption.md)、提案 [0019-large-stack-executor-and-cross-version-parallelism](Evolutions/0019-large-stack-executor-and-cross-version-parallelism.md)、上游 swift-demangling `Documentations/StackSafety.md` 第八节 ### late-name 路径(`lateDemangledNode(forName:)`) sweep 覆盖范围之外的名字走的旁路:demangle 后 intern 进 `Storage` 自持的一个可追加 side store,名字 → 裁决字典保证一个名字只 demangle 一次(拒绝也缓存为 `nil` 裁决、不再重试)。与主表冻结不可变的性质相对。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` +- **主要出现在**:`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift` ### leg(腿,reader-split) 同一逻辑按 reader 类型分出的并行实现路径,口语记作「镜像腿 / 文件腿」:`MachOImage`(进程内映射,符号名可直指 LINKEDIT 字符串表、零拷贝)与 `MachOFile`(离线文件,名字须读进私有缓冲)。0001 的 sweep 收集与名字来源都是按腿分叉的。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`)、`Sources/MachO/MachOSymbols/SymbolTable.swift` +- **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolSweep.swift`、`Sources/MachOSymbols/SymbolTable.swift` ### lifecycle annotation(生命周期注解) -演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。打开 `--emit-available` 时,生命周期能完整写成一条 `@available` 的声明上方还会多一行真属性,它由同一份事实派生,是补充不是替代,注解照旧都在。 +演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。打开 `--emit-available` 时,生命周期能完整写成一条 `@available` 的声明上方还会多一行真属性,它由同一份事实派生,是补充不是替代,注解照旧都在。有版本看不到这条声明时(见 unobservable),位图另用 `◍` / `◌`,短语多出 `inferred present in …`、`not observable in …` 与 `… between A and B`。 - **主要出现在**:`Sources/Output/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md)、[提案 0060](Evolutions/0060-evolution-interface-available-annotations.md)(`@available` 属性) +### macro folding(宏展开的折叠,folded form / expanded form) + +interface 把一个 attached macro 生成的东西收回成源码里的写法:`@Observable` 展开的类印成 `@Observation.Observable` 加普通的 `var x: T`,这是**折叠形态**;`expandsMacros` 打开时照二进制原样印出 registrar、存储 `_x`、computed `x`、生成的方法与 conformance,这是**展开形态**。二进制不记宏本身,只记它生成的东西,所以「这个类用了宏」是从生成物推断出来的(`TypeDefinition.attachedMacros`)。折叠只发生在单版本 interface;模型、dump、diff、evolution 始终是展开形态,dump 另在类头上写出宏的名字。 + +- **主要出现在**:`SwiftDeclarationPrinter+ObservableMacro.swift`、`TypeDefinition+ObservableMacro.swift`、`ObservableMacroRecognition` +- **延伸阅读**:[0093-observable-macro-folding](Evolutions/0093-observable-macro-folding.md) + ### marking mode(标记模式,`marksOptionalContent`) -`SwiftDeclarationPrintConfiguration.marksOptionalContent` 为 `true` 时的打印:受显示选项控制的输出(偏移 / 地址 / 布局注释、stripped symbolic item、opaque 类型的约束、按 selector 名推断的 `@objc override`)不再由选项决定打不打,而是全部打出,包进 swift-semantic-string 的 `VisibilityRegion`,条件是对应的 `SwiftVisibilityOption`。条件记在原子的 `identifier` 上,所以文字与全部打开时逐字节相同。冻结后拆出区域表,按某组配置的 `isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)` 投影,与按那组配置直接打印(「普通打印」,即该开关为 `false`)完全相同。「可见性区域」「投影」是 swift-semantic-string 的术语,定义见其 `docs/VisibilityRegions.md`;MachOObjCSection 的对应物叫 marked rendering(其提案 0011)。 +`SwiftDeclarationPrintConfiguration.marksOptionalContent` 为 `true` 时的打印:受显示选项控制的输出(偏移 / 地址 / 布局注释、stripped symbolic item、opaque 类型的约束、按 selector 名推断的 `@objc override`、exported-only 过滤删掉的声明)不再由选项决定打不打,而是全部打出,包进 swift-semantic-string 的 `VisibilityRegion`,条件是对应的 `SwiftVisibilityOption`。条件记在原子的 `identifier` 上,所以文字就是每段受控内容都打出来的全量文字(exported-only 过滤关着)。冻结后拆出区域表,按某组配置的 `isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)` 投影,与按那组配置直接打印(「普通打印」,即该开关为 `false`)完全相同。「可见性区域」「投影」是 swift-semantic-string 的术语,定义见其 `docs/VisibilityRegions.md`;MachOObjCSection 的对应物叫 marked rendering(其提案 0011)。 - **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+VisibilityRegions.swift`、`SwiftDeclarationPrintConfiguration.swift`、`Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift`、`SwiftVisibilityOption.swift` -- **延伸阅读**:[提案 0056](Evolutions/0056-visibility-regions.md) +- **延伸阅读**:[提案 0056](Evolutions/0056-visibility-regions.md);导出过滤进入标记模式:[0083-exported-only-marking-mode](Evolutions/0083-exported-only-marking-mode.md) ### materialize(物化) @@ -224,15 +275,22 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 `SymbolTable` 里一行的名字字节从哪里读:**mapped 字符串表**(`MachOImage` 行直指镜像 mmap 的 LINKEDIT 字符串表,clean 页、零拷贝,代价是要求镜像保持加载)或**私有缓冲**(`MachOFile` 行与 export-trie 解码名,字节存进表自有的连续缓冲)。`PackedNameReference` 用 1 个 bit 区分两者。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift` +- **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolTable.swift` - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### nested-definition region(定义区域,`marksNestedDefinitions`) -`SwiftDeclarationPrintConfiguration.marksNestedDefinitions` 为 `true` 时,父定义打印结果里每个内联打印的嵌套类型或协议被包进 swift-semantic-string 的 `DefinitionRegion`,身份是名字节点的 mangled name,与 RuntimeViewer 的对象名相同。冻结后用 `separatingDefinitionRegions()` 拆出区域表;对深度为 d 的区域,`content(ofDefinitionRegion:)` 再加 `removingIndentation(levels: d + 1)` 得到的值,与该定义单独打印的结果逐项相同(文本、span、identifier,以及两种分离得到的表)。宿主因此只需打印父定义,不必再单独打印每个嵌套定义。与标记模式同时打开时,定义区域的编码放在可见性标记的内层,两者互不影响。 +`SwiftDeclarationPrintConfiguration.marksNestedDefinitions` 为 `true` 时,父定义打印结果里每个内联打印的嵌套类型或协议被包进 swift-semantic-string 的 `DefinitionRegion`,身份是名字节点的 mangled name,与 RuntimeViewer 的对象名相同。冻结后用 `separatingDefinitionRegions()` 拆出区域表;对深度为 d 的区域,`content(ofDefinitionRegion:)` 再加 `removingIndentation(levels: d + 1)` 得到的值,与该定义单独打印的结果逐项相同(文本、span、identifier,以及两种分离得到的表)。宿主因此只需打印父定义,不必再单独打印每个嵌套定义。与标记模式同时打开时,定义区域的编码放在可见性标记的内层,两者互不影响。唯一的例外:exported-only 过滤保留、外层却被它过滤掉的嵌套定义,在父定义的标记打印里随外层只在过滤关着时可见,与它单独打印不同,宿主要单独打印它(提案 0083-exported-only-marking-mode)。 - **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift`、`SwiftDeclarationPrintConfiguration.swift` -- **延伸阅读**:[提案 0068-nested-definition-regions](Evolutions/0068-nested-definition-regions.md);swift-semantic-string 的 `docs/DefinitionRegions.md` +- **延伸阅读**:[提案 0068-nested-definition-regions](Evolutions/0068-nested-definition-regions.md);swift-semantic-string 的 `docs/DefinitionRegions.md`;例外见 [0083-exported-only-marking-mode](Evolutions/0083-exported-only-marking-mode.md) + +### comment structure(注释结构,`marksCommentStructure`) + +`SwiftDeclarationPrintConfiguration.marksCommentStructure` 为 `true` 时,打印器给输出的每一条注释标出它是什么:注释包进 swift-semantic-string 的 `AnnotationRegion`,种类(kind)是 `AnnotationRegion.Kind` 的常量(本库扩展的 `memberAddress`、`fieldOffset`……,以及它自带的 `note`);注释的每一段包进 `AnnotationSegment`,角色(role)是 marker、label、qualifier、separator、key、value、name、type、treePrefix、text 之一。字段偏移树、枚举 case 块、元组 Type Layout、条件 witness 用区域的嵌套表达层级。冻结后 `separatingAnnotationRegions()` 得到与关着时逐个相同的冻结串,外加一张区域与段的表。宿主据此把注释画成标签,不必解析注释文本。 + +- **主要出现在**:`Sources/Output/SwiftDeclarationRendering/StructuredComment.swift`(每条注释的文字与段)、`AnnotationRegionKind+SwiftComments.swift`(种类清单)、`SwiftDeclarationPrintConfiguration.swift` +- **延伸阅读**:[提案 0084-comment-structure](Evolutions/0084-comment-structure.md);swift-semantic-string 的 `docs/AnnotationRegions.md` ### NodeStore / NodeReference @@ -248,25 +306,53 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:提案 0046-objc-implementation-class-recognition 的判据与证据分级 - **延伸阅读**:[提案 0046-objc-implementation-class-recognition](Evolutions/0046-objc-implementation-class-recognition.md) +### ObjC imported declaration(ObjC 导入声明,`ObjCImportedClassDefinition` 等) + +镜像里的 ObjC 类、category 或协议,按 Swift 导入它们的样子建成的声明,即 Xcode 的 Generated Interface 显示的那种。名字由本库移植的 ClangImporter 命名规则从 selector 与属性名推出,类型取自方法编码、采纳的协议里的扩展编码与属性特性串;Swift 实现的部分(桥接出去的 Swift 类、`@objc @implementation` 类、Swift extension 的成员)照抄 Swift 的声明,Swift 实现的类整个以 Swift 一侧为准(提案 [0096](Evolutions/0096-swift-first-imported-declarations.md))。与「Swift 声明的 `@objc` 协议」的区别:那是 Swift 源码声明、只有 ObjC 记录的协议,导入声明面向镜像里任意的 ObjC 声明。 + +- **主要出现在**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift`、`ObjCImportedMemberBuilder.swift`,`Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImported*Definition.swift`,`swift-section objc interface --swift` +- **延伸阅读**:[0090-objc-imported-declarations](Evolutions/0090-objc-imported-declarations.md) + +### recognizer(识别器,`CodeReferenceRecognitionSession`) + +交叉引用扫描里认某一种语言的那一层。核心层只认与语言无关的东西(调用、桩、槽、寄存器跟踪、字符串),在五个时机问各语言层的识别会话:进入函数、遇到只有它认得的调用目标、调用点、算出一个地址、读一个槽。ObjC 层认发送、类与 ivar,Swift 层认类型元数据与 mangled name。核心不 import 任何语言层,新语言加识别器即可,不改核心。 + +- **主要出现在**:MachOKitExtensions 的 `Sources/MachOCodeReferences/Recognition/`、MachOObjCSection 的 `ObjCCodeReferences`、`CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift` +- **延伸阅读**:[0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md)、MachOKitExtensions 的 [MachOCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md) + +### reference route(引用路线,`CodeReferenceRoute`) + +一条交叉引用是怎么到达目标的,与目标是什么无关:直接 `bl` / `b`(`direct`)、本镜像的桩(`imageStub`)、cache 镜像之间的 stub island(`stubIsland`)、全缓存共用桩(`cacheSharedStub`)、经指针槽(`pointerSlot`)、算出地址(`addressMaterialization`)、近距离的字面量 `ldr`(`literalLoad`)、经寄存器(`indirect`)。经桩的调用和直接调用一样真;路线是读者在采信之前核对、或亲自去看时顺着走的那条路。 + +- **主要出现在**:`CodeReference.route`、`swift-section refs` 每行的第五列与 JSON 的 `route` +- **延伸阅读**:[0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md)、[Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md)「引用种类与路线」 + +### refined member(改名成员,`NS_REFINED_FOR_SWIFT`) + +头文件标了 `NS_REFINED_FOR_SWIFT` 的 ObjC 成员:Swift 导入它时名字前加 `__`(属性名、方法基名、初始化器的第一个标签),原名留给一个包装它的纯 Swift 声明。二进制不记这个宏,本库从 Swift 一侧认:有凭据的是配上了 `__` 开头的 Swift 成员(`layerFilter` ↔ `__layerFilter`);推断的是没有 Swift 成员回答的 ObjC 属性,而同名的 Swift 属性类型明显不可能是它(`settings` 对上本模块的 struct)——Swift 不允许一个类型里有两个同名属性。方法只认前者:方法能按参数类型重载,同名说明不了改过名。导入声明把推断出的这种属性打成 `// NS_REFINED_FOR_SWIFT: var __name: …` 注释,挂在占了它原名的 Swift 属性正上方;`SwiftDeclarationPrinter.objcMembersRefinedForSwift(in:)` 交给宿主,由它在 ObjC 头文件里打回这个宏。 + +- **主要出现在**:`Sources/Output/SwiftPrinting/ObjCImplementingSwiftMembers.swift`、`ObjCRefinedForSwiftMember.swift`,`Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift` +- **延伸阅读**:[0096-swift-first-imported-declarations](Evolutions/0096-swift-first-imported-declarations.md) + ### ObjC ancestor override(ObjC 祖先覆写) 一个 Swift 成员覆写了从 ObjC 继承来的成员——NSView 的 `layout()`、NSObject 的 `description`——这件事在 Swift 元数据里没有记录:编译器给这种覆写发的是一条**新的**普通 vtable 项而不是 override 表项(`NeedsNewVTableEntryRequest` 对「被覆写者来自 clang」答「需要新项」),`@objc @implementation` 类更是没有 vtable。本仓库从 ObjC 侧判:类自己的 ObjC 方法表里某条方法的 selector 在祖先链(NSView → NSResponder → NSObject,跨镜像)上有人实现,它就是覆写;再把那条方法联结到 Swift 成员——IMP 处的 `To` 符号、或反汇编 IMP 找它引用的成员实现、或(默认关)只按 selector 名字唯一匹配。三档证据记在 `ObjCMember.evidence` 里,dump 打出来,interface 只打 `override`。自提案 `objc-member-selector-recovery` 起它是「ObjC member table」的一个投影(`overriddenAncestorClassName` 非空的成员)。 -- **主要出现在**:`SwiftInspection/ObjCMember.swift`、`SwiftThunkAnalysis/ObjCMembers/` +- **主要出现在**:`SwiftObjCInterop/ObjCMember.swift`、`SwiftThunkAnalysis/ObjCMembers/` - **延伸阅读**:[提案 0047-objc-ancestor-override-recovery](Evolutions/0047-objc-ancestor-override-recovery.md)、[ObjCMemberRecovery.md](Internal/ObjCMemberRecovery.md) ### ObjC member table(ObjC 成员表) 一个类的 ObjC 方法表——实例方法表、元类方法表、本镜像 `__objc_catlist` 里指向它的 category——的每一条联结到实现它的 Swift 成员之后得到的 per-class 表(`ObjCMemberTable`,按 Swift 符号名索引 `ObjCMember`)。方法表就是类的 `@objc` 成员清单,运行时靠它派发、strip 不会碰,所以它是三个 Swift 元数据不记的事实的来源:成员是 `@objc`(OS 框架 strip 掉 `To` thunk 符号后这是唯一证据)、它覆写了哪个祖先的成员(selector 在祖先链上有人实现)、它的 selector 是不是源码里 `@objc(name)` 写出来的(与编译器从 Swift 名正向推出的默认值不同,且不是从被覆写者或协议要求继承的——祖先链或协议没读完就不下这个判定)。联结证据分三档:IMP 处的 `To` 符号;反汇编无名 thunk 收它引用的成员实现,配「所属类」与「importer 拼法」两道守卫;只按名字(只对覆写)。三档**都在索引期跑完**并记进 `ObjCMember.evidence`,用不用是消费者的事:dump 每条都标证据,第三档写成 `(selector name, no symbol evidence)` 照常渲染;interface 只有 `override` 一个关键字、没处说明证据来源,默认不打,`--infer-objc-overrides` 才打。`@objc @implementation` 体不是例外:编译器同样从 Swift 名推导 selector 并要求头文件里有它,`draw(in:)` 要对上 `drawInRect:` 就得写 `@objc(drawInRect:)`。 -- **主要出现在**:`SwiftInspection/ObjCMember.swift`、`SwiftInspection/ObjCMemberShape.swift`、`SwiftThunkAnalysis/ObjCMembers/`、`SwiftDeclaration/Components/Building/ObjCMemberApplication.swift`、`SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift` +- **主要出现在**:`SwiftObjCInterop/ObjCMember.swift`、`SwiftObjCInterop/ObjCMemberShape.swift`、`SwiftThunkAnalysis/ObjCMembers/`、`SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift`、`SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift` - **延伸阅读**:[提案 0048-objc-member-selector-recovery](Evolutions/0048-objc-member-selector-recovery.md)、[ObjCMemberRecovery.md](Internal/ObjCMemberRecovery.md) ### ObjC ancestor resolver(ObjC 祖先解析器) 独立 Mach-O 文件的父类指针是 bind,ObjC 读取器跟不过去;祖先解析器(`ObjCAncestorResolver`)拿 bind 符号里的类名(`_OBJC_CLASS_$_UIView` 去前缀,Swift 父类是 `_TtC…` 运行时名)在文件的传递依赖闭包里找定义它的镜像——先问每个镜像的 export trie(bind 只能落到导出符号),有才建那个镜像的名字表,第一个命中即返回——祖先链从那个镜像继续走。祖先链的每一跳还把根镜像与闭包里每个独立文件对该祖先的 category 折进它的 selector 集合(cache 里的类由 dyld 预挂,文件世界里离线看不到)。按镜像登记在 `ObjCAncestorResolverStore`:indexer 与 `dump` 用各自的搜索路径注册,无人注册的文件默认走系统 cache,进程内镜像没有解析器。hierarchy 的 memo 键带解析器身份,宿主 provider 交出的断链也用它续。配套的平台守卫在 MachODependencies:cache 里另一个平台的同名镜像(macOS cache 的 Catalyst UIKit)永远不是候选。 -- **主要出现在**:`SwiftInspection/ObjCAncestorResolver.swift`、`SwiftInspection/ObjCClassMethodIndex.swift`、`MachODependencies/DependencyPlatforms.swift` +- **主要出现在**:`SwiftObjCInterop/ObjCAncestorResolver.swift`、`SwiftObjCInterop/ObjCClassMethodIndex.swift`、MachOKitExtensions `Sources/MachODependencies/DependencyPlatforms.swift` - **延伸阅读**:[提案 0049-objc-ancestor-dependency-closure](Evolutions/0049-objc-ancestor-dependency-closure.md)、[ObjCMemberRecovery.md](Internal/ObjCMemberRecovery.md) ### offline specialization(离线特化) @@ -280,7 +366,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 不给数据本体排序,而是另存一条「按某序排列的下标数组」(permutation),查询时在这条下标序列上二分。`SymbolTable.rowsSortedByName` 即名字序 permutation:行本体保持插入序不动,名字查找二分这条 `[UInt32]`。替代了被退役的名字键字典 `tableRowByName`。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift`(`row(forName:)`) +- **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolTable.swift`(`row(forName:)`) - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### position-based name(按位置起的名字) @@ -301,27 +387,41 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 宿主自己的读取器类型:手里拿着一个 `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` +- **主要出现在**:MachOKitExtensions `MachOReaderWrapper.swift` 与 `Sources/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)`。 -- **主要出现在**:`SwiftInspection/SwiftClassObjectIndex.swift`、`SwiftInspection/CustomObjCClassName.swift` +- **主要出现在**:`SwiftObjCInterop/SwiftClassObjectIndex.swift`、`SwiftObjCInterop/CustomObjCClassName.swift` - **延伸阅读**:[提案 0052-objc-custom-class-name](Evolutions/0052-objc-custom-class-name.md)、[CustomObjCClassNames.md](Internal/CustomObjCClassNames.md) ### row / `SymbolRow`(行) `SymbolTable` 的最小单位:每个唯一符号名一行,16 字节(canonical offset + `PackedNameReference`),行号(`UInt32`)是全部分类索引引用符号的方式。「一名一行」意味着按名字查询的语义是纯函数——同名必同行。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift` +- **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolTable.swift` + +### stand-in member symbol(替身成员符号) + +为镜像里没有实现符号的成员造的成员符号,照它顶替的那个实现符号的样子造:mangled 名与成员树都与实现符号相同,偏移是镜像里留下的那个入口。下游按名字推导的东西(导出判定、ObjC 方法表联结、`@objc` 标记)和按树推导的东西(vtable 联结、ABI 身份)因此都把它当成实现符号来读,不用分支。来源有三种:vtable 槽的 `Tq`(descriptor-only member)、`@objc` thunk(thunk-only member)、只剩 initializing entry point 的 initializer(`…fc` 改写成 allocator 的形状)。只补真实符号没有声明的成员,按成员实体节点结构相等判断。 + +- **主要出现在**:`StandInMemberSymbolBuilder`、`ClassDispatchLookups.vtableSlotMemberSymbols` +- **延伸阅读**:[DescriptorOnlyVTableMembers.md](Internal/DescriptorOnlyVTableMembers.md)、[ThunkOnlyObjCMembers.md](Internal/ThunkOnlyObjCMembers.md) ### store-identity vs 结构相等(structural equality) `NodeReference` 的两种相等语义,混用会静默出错:intrinsic `Hashable` 按**store 身份**(同一 store 里的同一下标才相等),跨 store 的结构相同树不相等;**结构相等**(`structurallyEquals` / `StructuralNodeReferenceKey`)逐节点比对,跨 store 成立。规则:键和查询可能来自**不同 store** 的任何 `Dictionary` / `Set` 必须用 `StructuralNodeReferenceKey`,裸 `NodeReference` 键只在单一 hash-consed store 内部安全。踩过的坑:override/vtable 注释丢失、subscript getter/setter 分桶、merged thunk 重复输出。 -- **主要出现在**:`Sources/MachO/MachOSymbols/StructuralNodeReferenceKey.swift`;键位清单见 AGENTS.md「Symbol indexing」段 +- **主要出现在**:`Sources/Symbols/SwiftSymbols/StructuralNodeReferenceKey.swift`;键位清单见 AGENTS.md「Symbol indexing」段 + +### stub island(桩岛) + +dyld shared cache 在子缓存之间放的跳板:`bl` 只能跳 ±128 MB,跨子缓存的调用先落到 island,由 island 用 `adrp` / `add` / `br` 算出目标再跳过去。island 不属于任何镜像,也不读槽位——这是它与 [cache-shared stub](#cache-shared-stub全缓存共用桩) 的区别。一串调用可能连过几个 island,交叉引用把整串记作一跳路线 `stubIsland`,符号化列出经过的每一个。 + +- **主要出现在**:`ARM64Trampoline`、`StubChainResolver`、`CodeReferenceRoute.stubIsland` +- **延伸阅读**:[0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md) ### supplementary APINotes(补充映射) @@ -332,11 +432,18 @@ TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备* ### sweep(构建扫描) -对一个镜像的**全量符号一遍扫过**的批处理构建过程:`SymbolIndexStore` 首次索引某镜像时,`buildStorageSweep` 遍历整张符号表 + export trie,收集行、对每个 Swift 符号 demangle 一次、把结果分类进各查询索引——与之相对的是查询期的按需单点操作。RuntimeViewer 语境里「按需索引 sweep」指用户打开某镜像才触发这一遍构建;sweep 期的临时缓冲是瞬态内存峰值的来源(完即释放)。 +对一个镜像的**全量符号一遍扫过**的批处理构建过程:`SwiftSymbolIndexStore` 首次索引某镜像时,先由 MachOKitExtensions 的 `SymbolSweep`(按 `SwiftSymbolTableRouting` 分表)遍历整张符号表 + export trie 收集行,再对每个 Swift 符号 demangle 一次、把结果分类进各查询索引——与之相对的是查询期的按需单点操作。RuntimeViewer 语境里「按需索引 sweep」指用户打开某镜像才触发这一遍构建;sweep 期的临时缓冲是瞬态内存峰值的来源(完即释放)。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`) +- **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolSweep.swift`(采集)、`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift`(`buildSymbolTableStage` 与第二段的 demangle 分类) - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md)、[SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) +### Swift-declared `@objc` protocol(Swift 声明的 `@objc` 协议,`ObjCProtocolDefinition`) + +Swift 源码里声明的 `@objc protocol`。它没有 protocol descriptor(不在 `__swift5_protos` 里),要求也没有任何 Swift 符号;镜像里只有一条 kind 为 `ObjCProtocol` 的 field descriptor 与一条 ObjC 协议记录(`protocol_t`)。本库据 field descriptor 认定本镜像声明了它,要求从记录读出:有本镜像的类实现时照抄那个成员(**取自实现者**),没有时按 ClangImporter 的规则从 selector 推出 Swift 名并用 `@objc(selector)` 钉住(**按 selector 命名**)。与 `@objc @implementation` 类无关:那是 ObjC 声明、Swift 实现的类。 + +- **主要出现在**:`Sources/Analysis/SwiftObjCInterop/SwiftDeclaredObjCProtocolIndex.swift`、`Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCProtocolDefinition.swift` +- **延伸阅读**:[SwiftDeclaredObjCProtocols.md](Internal/SwiftDeclaredObjCProtocols.md)、[0079-swift-declared-objc-protocols](Evolutions/0079-swift-declared-objc-protocols.md) + ### symbolic-mangling symbol(`_symbolic` 符号)与被引用者(referent) 编译器给每条带 symbolic reference 的 mangled name 生成的链接器去重符号:`_symbolic ` / `_default assoc type ` 前缀, @@ -345,7 +452,7 @@ TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备* 名字的地方,dyld shared cache 也保留着。被引用者不能单独 demangle:同一个 mangler 依次写出它们,后面的会借用前面的 substitution,必须连在一个 `$s` 后面一起 demangle。 -- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolicManglingSymbols.swift`(收集)、`Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift`(配对与解码) +- **主要出现在**:`Sources/Symbols/SwiftSymbols/SymbolicManglingSymbols.swift`(收集)、`Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift`(配对与解码) - **延伸阅读**:[SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md)、[提案 0050-symbolic-mangling-symbol-index](Evolutions/0050-symbolic-mangling-symbol-index.md) ### SymbolicDemangler(旧名 MetadataReader) @@ -355,6 +462,13 @@ substitution,必须连在一个 `$s` 后面一起 demangle。 - **主要出现在**:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift` - **延伸阅读**:[提案 0022](Evolutions/0022-rename-metadata-reader-to-symbolic-demangler.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) +### thunk-only member(只剩 `@objc` thunk 的成员) + +`@objc` 成员里,Swift 函数体被优化器内联进它的 Objective-C thunk(`$s…To`)、Swift entry point 随后被删掉的那一类:thunk 是它唯一的代码,也是唯一的符号。只有整模块优化下的 internal 成员会这样,因为每一处使用都可见、都内联完了才能删,所以这是 app 和 app 内嵌组件的形状,例如 Xcode 27.2 的 `Xcode Service` 里有 22 个。它和 OS 框架 strip 掉 `To` 符号正好相反:那里实现符号还在,thunk 没了名字。成员模型过去只从实现符号建成员,这一类在 dump 和 interface 里整个缺席;现在从 thunk 造替身成员符号补上。class 的 initializer 有同类的情形:allocating entry point 被内联掉后只剩 initializing entry point(`…fc`),Swift 6.4 连它也换成函数签名特化副本(`…fcTf…`),替身就从副本造。 + +- **主要出现在**:`SwiftSymbolIndexStore.objcThunkMemberSymbols`、`StandInMemberSymbolBuilder.memberStandIn(forObjCThunkSymbol:in:)`、`ClassDumper` 的 `[ObjC Thunk]` 一节 +- **延伸阅读**:[ThunkOnlyObjCMembers.md](Internal/ThunkOnlyObjCMembers.md) + ### TypeImportInfo(C 导入类型身份) C 导入类型的 type context descriptor 在名字字符串后面追加的一串以空字符分隔的身份分量,由 `TypeContextDescriptorFlags.hasImportInfo` 宣告:`N` 前缀是 ABI 名(`NSRange` 的 tag 叫 `_NSRange`,`CGColor` 是 `CGColorRef` typedef,`Decimal` 是 `NSDecimal`),`S` 前缀是符号命名空间(唯一取值 `t`,表示被提升为独立类型的 C typedef,mangling 里拼成 `typeAlias`),`R` 前缀是 importer 合成的关联实体名(`NS_ERROR_ENUM` 合成的错误 struct 是 `e`,mangling 里包一层 `relatedEntityDeclName`)。运行时 `_swift_buildDemanglingForContext` 据此改写 demangling 树,本项目的 `SymbolicDemangler` 照同一套规则改写;另有一条不依赖 import info 的规则:`__C` 下的 tag 枚举一律 mangle 成 `structure`。 @@ -373,7 +487,7 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 - **定义**:`DependencySearchPath.systemRoot(path:)`,一棵目录树,把依赖的绝对 install name 直接拼在它下面找文件:`/System/Library/Frameworks/Foo.framework/Foo`。iOS 26 及更早的模拟器运行时的 `RuntimeRoot` 就是这个形状;iOS 27 起模拟器改带自己的 `dyld_sim_shared_cache`,对应 `.dyldSharedCache(path:)`。 - **为什么要有**:不在 cache 里的二进制(第三方 app、老模拟器框架)调别的镜像里的 metadata accessor 时只有一个 bind 名,得先找到那个镜像才能查它的 accessor 索引。`DependencySearchPath.inferred(forRoot:)` 从根文件的磁盘位置推断出 cache 或 system root。 - **不要混淆**:`.machOFile(path:)` 是显式指定一个文件;system root 是按 install name 在目录树里现找。 -- **延伸阅读**:[MachODependencies 模块文档](Internal/Modules/MachODependencies.md)、[提案 standalone-file-thunk-resolution](Evolutions/0030-standalone-file-thunk-resolution.md) +- **延伸阅读**:MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)、[提案 standalone-file-thunk-resolution](Evolutions/0030-standalone-file-thunk-resolution.md) ### type-construction evaluation(类型构造求值) @@ -382,12 +496,28 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 - **主要出现在**:`Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift`、`AccessorThunkAnalyzer.swift` - **延伸阅读**:[专题导读](Internal/AccessorThunkResolutionExplained.md)、[提案 0029](Evolutions/0029-thunk-type-construction-evaluation.md)、[提案 0028](Evolutions/0028-offline-opaque-accessor-thunk-resolution.md) +### unclaimed record(没认领的记录) + +本镜像 `__objc_protolist` 里 Swift 生成、却没有本镜像的声明认领的 ObjC 协议记录。名字是 `_TtP…` 的已经按名字归了别的模块,剩下的都是改过名的协议:别的模块用 `@objc(Name)` 改过名、被本镜像引用的(Swift 会给引用到的协议生成一份副本),以及本镜像里改成与 Swift 名不同的名字、配不上 field descriptor 的。前一种才到依赖闭包里找它的 Swift 名;dump 在 `protocols` 段末尾一行列出它们。 + +- **主要出现在**:`SwiftDeclaredObjCProtocolIndex.unclaimedSwiftEmittedRecords(in:)`、`ObjCRuntimeNames.swiftProtocolNode(forRuntimeName:in:)` +- **延伸阅读**:[SwiftDeclaredObjCProtocols.md](Internal/SwiftDeclaredObjCProtocols.md) + ### union interface(并集接口) `evolution --interface` 的输出形态:N 个版本所有声明的**并集**只渲染一次的 Swift 接口——每条声明由「最后一个拥有它的版本」的模型与 printer 渲染文本,变化写进生命周期注解,同一成员改签名不裂成多行。与「逐 transition 串联 diff」(同一声明重复出现 N−1 次)和「只渲染最新版 + since 注解」(丢中间版本细节)相对。排序规则:最新版本声明序为脊柱,不在最新版的声明按其最后存在版本的顺序追加。 -- **主要出现在**:`Sources/Output/SwiftInterface/SwiftEvolutionInterfaceRenderer.swift`(`matchAcrossVersions`) -- **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md) +ObjC 一侧的同一种视图是 `objc evolution --interface` 输出的合并头文件,由 MachOObjCSection 的 `ObjCEvolutionInterfaceBuilder` 渲染:每条声明按 `objc dump` 的方式渲染,标注与 `objc evolution` 报告里的 lineage 一一对应。容器内以最新版本的顺序为准,删掉的成员插在它在最后那一版里的前一个成员之后。 + +- **主要出现在**:`Sources/Output/SwiftInterface/SwiftEvolutionInterfaceRenderer.swift`(`matchAcrossVersions`);ObjC 一侧在 MachOObjCSection 的 `ObjCInterface` 模块,本库经 `ObjCAPIEvolutionRequest` 的 `annotatedInterface` 调用 +- **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md);ObjC 一侧见 [提案 0080](Evolutions/0080-objc-evolution-interface.md) + +### unobservable(看不见,`LineagePresenceState`) + +evolution 与 diff 里「这个版本看不到这条声明」的状态,与「不在」相对。镜像没有 local Swift 符号的版本(macOS 13.0–14.8 dyld shared cache 里的 SwiftUI)里,只靠非导出符号才出现的成员没有名字,它缺席并不说明它不存在;类型、conformance、存储属性、导出的成员不受影响。一段看不见的版本,两侧观测到的版本都有这条声明时记为 **inferred present**(推断存在,位图 `◍`),否则记为 unobservable(位图 `◌`);两侧不同时,变化写成 `removed between 12.7 and 15.0` 这样的跨段事件。diff 里一侧看不见的成员进 `unobservableDeclarations`,不算删除或新增。 + +- **主要出现在**:`Sources/Output/SwiftDiffing/UnobservablePresence.swift`、`ABIEvolutionBuilder.swift`、`Sources/Output/SwiftInterface/EvolutionMarking.swift` +- **延伸阅读**:[提案 0081](Evolutions/0081-evolution-unobservable-presence.md)、[ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) 第六批 ### wrapper vs descriptor(高层包装 vs 描述符) diff --git a/Documentations/Internal/ABIDiffDesignAndLimitations.md b/Documentations/Internal/ABIDiffDesignAndLimitations.md index ceaeb7087..04a4ee123 100644 --- a/Documentations/Internal/ABIDiffDesignAndLimitations.md +++ b/Documentations/Internal/ABIDiffDesignAndLimitations.md @@ -182,6 +182,8 @@ ABI 事实。同一协议一侧带符号、一侧被 strip 时,diff 会报"解 pwtslot added"的假差异——无名可匹配,无廉价对策;比较双方应处于相近的 strip 状态。 +同一不对称的另一半——**非导出成员**——现已处理(演进提案 `evolution-unobservable-presence`,规则见 [`ABIEvolutionDesign.md`](ABIEvolutionDesign.md) 第六批):快照记下镜像有没有 local Swift 符号、每个成员是否导出;一侧没有 local Swift 符号时,另一侧只靠非导出符号出现的成员(以及只由这种成员组成的 extension)不报 removed / added,而是进 `ABIDiff.unobservableDeclarations`,文本报告单列一节,不算 breaking。仍未处理的有两处:上面的 `pwtslot:` 互换照旧;`diff --interface` 按两侧结构直接比对、不读 `ABIDiff`,这类成员在那里仍显示为 `-` / `+`。 + ## 局限 → 代码位置对照 | 局限 | 状态 / 位置 | @@ -191,4 +193,4 @@ pwtslot added"的假差异——无名可匹配,无廉价对策;比较双方 | 3. keyed 碰撞 | **已解决**(拆分消解 + 诊断兜底)。`Keying.swift` + `ABIDiagnostics.swift` | | 4. 字段顺序 / flags | enum case `indirect` **已修**;resilient/frozen 感知的字段顺序敏感性仍开放。`MemberRecord.swift` | | 5. per-conformance 归属 | **已解决**。`ABIDiffer.swift` `extensionContainerSnapshots` + [`PerConformanceAttribution.md`](PerConformanceAttribution.md) | -| 6. stripped requirement 投影 | **已解决**(`pwtslot:` 命名空间)。`MemberRecord.makeProtocolRequirement` + `memberRecords(of: ProtocolDefinition)` + [`ProtocolRequirementProjection.md`](ProtocolRequirementProjection.md);符号化状态不对称为新的文档化局限 | +| 6. stripped requirement 投影 | **已解决**(`pwtslot:` 命名空间)。`MemberRecord.makeProtocolRequirement` + `memberRecords(of: ProtocolDefinition)` + [`ProtocolRequirementProjection.md`](ProtocolRequirementProjection.md);符号化状态不对称为新的文档化局限,其中非导出成员一半已解决(`UnobservablePresence.swift` + `ABIDiff.unobservableDeclarations`),`pwtslot:` 互换与 `diff --interface` 仍开放 | diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index 8f3e5b654..c76216642 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -250,6 +250,33 @@ diff 的 verdict 交叉核对行。 - ~~注释接口的时间线版(每行标注 introduced-in)~~ —— 已由第五批落地 (`SwiftEvolutionInterfaceBuilder` 的并集注解接口,见下)。 +## 首轮落地后的增量(第七批)—— 一个版本由一组 image 组成 + +提案:[0082-image-group-evolution](../Evolutions/0082-image-group-evolution.md)。Apple 拆框架时声明在 image 之间搬家:AppKit 的类挪进 UIFoundation、CollectionViewCore,macOS 15 起 SwiftUI 的大批类型挪进 SwiftUICore(带 `@_originallyDefinedIn(module: "SwiftUI")`,mangled name 不变)。一个版本只读一个 image 时,搬走的报成 removed、搬来的报成 added。维护时会踩的决策: + +- **入口与输入**:`ABIEvolutionBuilder.evolution(ofImageGroups:versions:)`,每个版本一个有序的 `ABIImageSnapshot` 列表,主 image 在前。单 image 快照与文档格式不变,image 名由调用方给出——CLI 写进 provenance 的 `binaryPath` 是 ` (AppKit)`,推不出 image 名。空组就是这个版本什么都没有。 +- **合并**(`MergedImageGroup`):types、protocols、globals 直接拼接,同 key 的只比较组里第一个 image 的,其余走 key collision,`ABIKeyCollision.droppedImageNames` 写出被丢的那份来自哪个 image,`droppedRecordDescriptions` 把它拼成 `Shared (UIFoundation)`(两者数量对不上时只列签名),报告与联合接口末尾的警告都用这一处;四个 extension 桶里同 key 的容器合成一个,成员按组顺序拼接。 +- **并回类型本体**:组里定义了的类型,它的普通 extension 容器(没有协议、没有 `where`、不是 retroactive)并进类型容器。单 image 里这些成员本来就算在类型本体(mangling 不带 extension 上下文),跨 image 才分出去;不并回,类型搬家那一版就报成「类型里删掉、extension 里新增」。并回只影响成员列在哪个容器下,不影响身份,所以带 extension 上下文的跨模块 extension 也照此并回。 +- **看不见的版本**(第六批):组里任一 image 没有 local Swift 符号,这个版本就按没有处理,宁可多标看不见,不误报删除。 +- **搬家**(`ImageMove`):一个声明两次观测在场、中间只隔着看不见的版本,两侧的 image 集合不同就记一条(按集合比,调用方换个顺序列同一组 image 不算搬家;报出来的仍按各版本的组顺序列);隔着看不见的版本时用 `earliestVersionIndex` 标出起点,措辞与区间事件一致。中间有一次观测到的缺席就不比,那是删掉再加回来。成员只在旧集合 ≠ 新集合、并且 (旧, 新) 与所属容器的不同时才记:整个类型搬走时不给每个成员再记一遍,同名 extension 跨 image 合并后,没挪的成员也不会记成「A → A」。只有搬家的 lineage 也收录,成员的签名放在 `latestSignature`。搬家不进兼容性判定:旧 image 有没有 re-export 新 image,快照里没有这个事实。 +- **报告与 JSON**:`ABIVersionDescriptor.imageNames` 和两种 lineage 的 `imageMoves` 都是可选的,为空不编码,单 image 的 `evolution --json` 逐字节不变。报告头部那行下面紧跟 `Image group:` 和每个 image 的在场位图(按在轴上首次出现的顺序);搬家行写成 `> moved in 15.0: SwiftUI → SwiftUICore`,同一版本里排在事件之后;跳变摘要多一项 `N moved`。 +- **联合接口**:`AnySwiftEvolutionInterfaceBuilder(…, imageGroups:labels:…)`。一个版本是一个 `InterfaceVersionGroupUnit`,里面每个 image 一个 `InterfaceVersionUnit`;walker 渲染一个定义前先用 `renderingUnit(for:)` 取它所在 image 的单元——打印器从建它的那个 image 读事实,用错 image 会丢属性、地址与 opaque 解析——成员跟着所属定义走,全局声明按 image 逐个列。并回的 extension 由 `foldedExtensionDefinitions(of:)` 交给类型体渲染,判据与 evolution 的并回逐条一致;两边不一致,注解就查不到。图例在位图位置那行之后列出 image 组。 +- **单 image 索引的配套修复**:SwiftUI 给 SwiftUICore 类型加的、mangling 不带 extension 上下文的成员,原来只有类型所在 image 的定义会收,于是两边都不收。`indexExtensions()` 现在把这类成员当作所在类型的 extension 成员收进 `extension <类型>`,三条判据同时成立才收:上下文是「模块 → struct、class、enum 一路下来」;那个模块是本 image 自己的类型或协议所在的 Swift 模块(`__C` 除外);名字不在本 image 的类型与协议定义里。前两条都是踩出来的:只按类型名排除时,误收了嵌在带约束 extension 里的类型的访问器和协议自己的符号(上下文与定义对不上名字),SymbolTestsCore 的 interface 快照抓到;不看模块时,image 里带着的别的模块的成员——标准库内联进来的代码、ClangImporter 给 C 枚举合成的 `init?(rawValue:)`——被印成 `extension Swift.Array`、`extension __C.UIButtonType`,渲染 A/B 抓到。同一模块里没有类型描述符的内部命名空间、定义按名字收不到的成员,在单 image 里与拆分出去的类型的成员分不开,也一并收进来;它们是本模块真实的成员,原先同样被丢掉。dump 不经这条路径,不变。快照格式随之升到 10。 +- **局限**:搬家只在组内看得见,搬到组外 image 的仍是 removed;两版本的 `ABIDiffer.diff` 没有组入口;命令行不接;`@available` 的规则不看搬家。 + +## 首轮落地后的增量(第六批)—— 看不见的版本 + +提案:[0081-evolution-unobservable-presence](../Evolutions/0081-evolution-unobservable-presence.md)。镜像没有 local Swift 符号的版本——macOS 13.0–14.8 dyld shared cache 里的 SwiftUI——看不到只靠非导出符号才出现的成员。原来的 `presence: [Bool]` 分不出「不在」和「看不见」,macOS 27.0 SwiftUI 的 51 版 evolution 因此有 5,189 条两端都在、中间缺席的假缺口。维护时会踩的决策: + +- **事实从快照来,格式版本 9**:`ABISnapshot.hasLocalSwiftSymbols`(`SwiftSymbolIndexStore.hasLocalSwiftSymbols(in:)`,读符号表条目的 `N_EXT` 位——本库的 `isExternal` 只指未定义的导入,不能拿来判断)与 `MemberRecord.isExported`(`isExportedIncludingDerivedSymbols(names:in:)`,与 interface 的 `// not exported` 注释同一条规则)。两者都只是判定用的元数据,不进 key。冻结时由 `SwiftDiffableInterfaceBuilder` 经 `ABIModule` 交进来,`ABIDiffer` 仍不碰 Mach-O。 +- **谁会看不见**(`UnobservablePresence.swift`,evolution 与 diff 共用):`MemberRecord.needsLocalSymbolsToBeSeen` 是「只靠符号出现(函数、计算属性和下标、初始化器、`deinit`、全局)且没有判定说它导出」;`ContainerSnapshot.needsLocalSymbolsToBeSeen` 是「不是 conformance 的 extension,成员全是上面这种」。类型、协议、conformance 靠元数据,永远看得见。某个没有 local Swift 符号的版本里缺席时,取它前后最近一次出现的记录,**任一侧**需要 local 符号才看得见,这次缺席就记为 hidden——一侧的 hidden 不说假话,错判成 absent 才会。 +- **推断**(`PresenceResolution`):一段连续 hidden 两侧观测相同——都在记 `inferredPresent`,都不在记 `unobservable`、什么都不断言;两侧不同记一个跨段事件,`versionIndex` 是段后第一个观测到新状态的版本,`earliestVersionIndex` 是段首。挨着轴端的段保持 `unobservable`。容器看不见的地方成员跟着看不见;成员的跨段事件只在段两侧容器都观测在场时产生,沿用「容器缺席的转换不枚举成员」。推断的依据:都带符号的年份里,两端都在、中间某版真缺的声明只占 0.15%–0.6%(上限,见提案)。 +- **收录规则改了**:lineage 有事件,**或者**有版本没观测到它,就收录;后一种没有事件可带签名,另带 `latestSignature`。成员只在**它自己**看不见、而容器在那个版本观测在场,并且那段看不见的区段有话可说(推断存在,或让边界变得不确定)时才因此收录:只因容器看不见而看不见的成员归容器的 lineage 交代,与增删容器的成员一样不单独收录;两侧都不在的区段没什么可说,位图之外不会多一个字(两条都是实数据核对时发现的,否则 SwiftUI 那条轴上会平白多出数千条成员注解,其中 169 条只有位图、没有一个短语)。接口侧「查不到 = 全程在场、从未变化」的裁决因此仍然成立。`presence` 的含义扩成「观测到或推断为存在」。 +- **兼容性**:跨段事件计入 `versionIndex` 那一步;报告的 Transitions 段在那一步下面注明其中几条只知道发生在哪两个版本之间。 +- **N == 2 一致性保住了**:diff 用同一套规则,一侧看不见的成员和容器(看不见的容器只列容器本身,成员不展开)进 `ABIDiff.unobservableDeclarations`,不进变更、不算 breaking。`ABIUnobservablePresenceTests` 钉住「diff 的看不见清单 = 两版本 evolution 里带 `unobservable` 状态的 lineage」。 +- **JSON**:新字段全部可选,为空时不编码,所以轴上没有被剥版本时 `evolution --json` 与 `diff --json` 逐字节不变(测试钉住)。 +- **局限**:`diff --interface` 按两侧结构渲染,不走这套规则;被剥前后身份变了的声明——协议要求在被剥的版本里变成 `pwtslot:` 记录、私有类型丢了 discriminator——仍是一删一增;「有没有 local Swift 符号」是整个镜像一个布尔值,只剥了一部分 local 符号的镜像会被当成完整的,它的缺席照常算观测。 + ## 首轮落地后的增量(第五批)—— 并集注解接口(`evolution --interface`) 提案:`Evolutions/0013-swift-evolution-interface-builder.md`。把 N 版本演进渲染成 diff --git a/Documentations/Internal/AccessorFunctionReferenceRendering.md b/Documentations/Internal/AccessorFunctionReferenceRendering.md index 75b2e1e28..238426323 100644 --- a/Documentations/Internal/AccessorFunctionReferenceRendering.md +++ b/Documentations/Internal/AccessorFunctionReferenceRendering.md @@ -69,7 +69,7 @@ thunk 里先调 `__isPlatformVersionAtLeast`,再按结果在两个类型之间 `accessor function at N` 兜底——读取器读不了的引用变成「类型里嵌一个未读引用」(首次落地时读取器只认两种 形态,剩下的 5 条即如此)。文案沿用而不换,是因为它出自上游 `NodePrinter`、两条打印路径有 parity 测试钉着、快照归一化 也认这个前缀。 -- **另一支进了模型**。`AssociatedTypeWitnessProjection.conditionalCandidates`:每支一条,带版本条件、 +- **另一支进了模型**。`ResolvedAssociatedTypeWitness.conditionalCandidates`:每支一条,带版本条件、 thunk 那一支的类型、以及整条 witness 按该分支替换后的全文(宿主不必知道 thunk 嵌在树的哪一层)。 `Node.resolveOpaqueTypeCollectingConditionalCandidates(in:)` 用同一个 rewriter 跑一遍记下候选,再对 每个非默认分支按选择重跑一遍——每条 witness 一个双向 thunk(实测全部如此)就多一趟,没有笛卡尔积。 diff --git a/Documentations/Internal/AccessorThunkResolutionExplained.md b/Documentations/Internal/AccessorThunkResolutionExplained.md index 8280690b0..e0c4fd094 100644 --- a/Documentations/Internal/AccessorThunkResolutionExplained.md +++ b/Documentations/Internal/AccessorThunkResolutionExplained.md @@ -121,7 +121,7 @@ thunk 里每个 `bl` / `b` 都要知道「调的是谁」,否则无从推演 - **认不出、但在本镜像 `__TEXT` 里的函数**:不放弃,把它的指令也解码出来交给第三步跟进去算(见「被调函数没名字怎么办」)。 - 其余认不出的:不猜,让那一支降级。 -这里有一个反复踩过的坑值得单独记住:共享缓存里,`MachOSwiftSection` 用的「偏移」是 `虚拟地址 − 共享区域起始地址`,不是文件偏移。`segment.fileOffset`、`MachOFile.fileOffset(of:)`、`FullDyldCache.address(of:)` 是三套互不相同的账,混用不会报错,只会算出一个像模像样但错了几十字节的地址,最后指向隔壁 framework 的数据。同一个减法还有另一面:它对整个 cache 里的任何地址都算得出偏移,所以「这个地址在不在本镜像」不能靠它答,要按段范围判断(`ThunkAddressSpace.containsAddress`)——合并 accessor 那批第一版在 cache 上没解出来,就是把 rebase 出来的 libswiftSynchronization 地址当成了本镜像地址。 +这里有一个反复踩过的坑值得单独记住:共享缓存里,`MachOSwiftSection` 用的「偏移」是 `虚拟地址 − 共享区域起始地址`,不是文件偏移。`segment.fileOffset`、`MachOFile.fileOffset(of:)`、`FullDyldCache.address(of:)` 是三套互不相同的账,混用不会报错,只会算出一个像模像样但错了几十字节的地址,最后指向隔壁 framework 的数据。同一个减法还有另一面:它对整个 cache 里的任何地址都算得出偏移,所以「这个地址在不在本镜像」不能靠它答,要按段范围判断(`ImageAddressSpace.containsAddress`,原名 `ThunkAddressSpace`,现在在 MachOKitExtensions 的 `MachOAddressResolution` 模块)——合并 accessor 那批第一版在 cache 上没解出来,就是把 rebase 出来的 libswiftSynchronization 地址当成了本镜像地址。 ### 第三步:符号求值——寄存器里装的不是数,是「类型表达式」 @@ -193,7 +193,7 @@ thunk 之外还有一种「引用」不是指针:独立文件里的 witness ## 读出来的答案怎么进输出 - **原位替换**。kind-9 引用可以嵌在类型树的任何位置(`FeedbackGenerator.Body` 的引用在 `ModifiedContent, _AppearanceActionModifier>` 的中间),所以渲染侧是一个 `Node` 的 rewriter(`AccessorFunctionReferenceRewriter`),在树里找到引用、换成答案,外面的 `ModifiedContent<…>` 链和泛型实参照常保留。关联类型 witness 和 field record 走同一个 rewriter。 -- **两支都保留**。rewriter 用当前平台那支(版本满足支)替换,同时把每个 thunk 的全部候选记进一个账本;要另一支时用「选第 n 支」再跑一遍 rewriter,得到整条 witness 按那一支替换后的全文。这就是模型里 `AssociatedTypeWitnessProjection.conditionalCandidates` 的来源(每支带平台版本条件、thunk 那一支的类型、整条 witness 全文),也是 `interface` / `dump` 里 `typealias` 上方那几行注释的来源(`ConditionalWitnessComment`)。 +- **两支都保留**。rewriter 用当前平台那支(版本满足支)替换,同时把每个 thunk 的全部候选记进一个账本;要另一支时用「选第 n 支」再跑一遍 rewriter,得到整条 witness 按那一支替换后的全文。这就是模型里 `ResolvedAssociatedTypeWitness.conditionalCandidates` 的来源(每支带平台版本条件、thunk 那一支的类型、整条 witness 全文),也是 `interface` / `dump` 里 `typealias` 上方那几行注释的来源(`ConditionalWitnessComment`)。 - **diff 不看它**。哪个系统上读的二进制不是 ABI 事实,所以候选不进 ABI diff 的 key。 - **失败时**:树保留,引用位置打 `accessor function at N`(这句来自上游 `NodePrinter`,快照归一化认识它)。之前的做法是整棵树放弃、只打一个裸的描述符地址,把实参全丢了。 @@ -216,11 +216,16 @@ Sources/Analysis/SwiftThunkAnalysis/ ├── MachOThunkEnvironment.swift # 第二步:给调用目标起名(accessor 索引、本地符号、stub、槽位、跨镜像、bind 槽 → 函数引用);解码被跟进的函数 ├── DependencyImageResolver.swift # 独立文件:bind 名 → 按搜索路径找到的依赖镜像 → 它导出表里的位置(按根镜像共享) ├── MetadataAccessorIndex.swift # accessor 地址 → 类型描述符(按镜像缓存) - ├── ThunkAddressSpace.swift # 共享缓存偏移与地址的换算(三套账的坑就在这里收口;导出表偏移是第四套:相对 mach header) ├── ThunkTypeNodeBuilder.swift # 第四步:表达式 → 类型名节点 └── AccessorThunkOwnerLayout.swift # thunk 主人的泛型参数布局(argument(k) 对应哪个参数) -Sources/MachO/MachODependencies/ +MachOKitExtensions: Sources/MachOAddressResolution/(0.25.0 起在 MachOKitExtensions 包里;从 SwiftThunkAnalysis 抽出,交叉引用的文件模式共用) +├── ImageAddressSpace.swift # 共享缓存偏移与地址的换算(三套账的坑就在这里收口;导出表偏移是第四套:相对 mach header) +├── StubChainResolver.swift # 桩、stub island、cache 共用 selector 桩:一跳一跳读 +├── SlotResolver.swift # 指针槽里装着谁:bind 名或 rebase 目标 +└── CacheImageLocator.swift # cache 里按地址找镜像、读它导出的名字 + +MachOKitExtensions: Sources/MachODependencies/(0.25.0 起在 MachOKitExtensions 包里) ├── DependencySearchPath.swift # 搜索路径的四种(含 system root)、从文件位置推断、按形状归类 └── FileDependencyLocator.swift # 按 load name 找依赖文件:显式文件 → system root → cache diff --git a/Documentations/Internal/ClassesWithoutClassObjects.md b/Documentations/Internal/ClassesWithoutClassObjects.md new file mode 100644 index 000000000..acf2dd382 --- /dev/null +++ b/Documentations/Internal/ClassesWithoutClassObjects.md @@ -0,0 +1,61 @@ +# 没有 class object 的 Swift 类 + +提案 [`objc-classes-without-class-objects`](../Evolutions/0078-objc-classes-without-class-objects.md) 的实现说明。 + +## 一句话 + +泛型类、父类在别的 resilience domain 的类、父类是本模块泛型类的类,这三种 Swift 类在 `__objc_classlist` 里没有 class object,但它们的 `class_ro_t` 都静态存在于 Swift 元数据里。`SwiftClassWithoutClassObjectIndex`(SwiftObjCInterop)按镜像把它们找出来,本库的 ObjC 方法表据此给出 `override` 与显式 selector 的证据,`swift-section objc` 经 MachOObjCSection 0.8.201 的 `ObjCSuppliedClass` 把它们列出来。 + +## 三种类与编译器的元数据策略 + +编译器按 `IRGenModule::getClassMetadataStrategy`(`GenClass.cpp`)给每个类选一种元数据策略,只有 Fixed、Update、FixedOrUpdate 三种会把元数据静态生成完整并登记进 `__objc_classlist`(`GenMeta.cpp` 的 `emitClassMetadata`)。另外三种情况没有 class object: + +| 类 | 策略 | `class_ro_t` 在哪 | 元类的 `class_ro_t` | stub | +|---|---|---|---|---| +| 泛型类 | generic metadata pattern | generic metadata pattern 的 extra-data pattern 里第 (`ClassRODataOffset` − `OffsetInWords`) 个字 | 同一块里第 (`MetaclassRODataOffset` − `OffsetInWords`) 个字 | 没有 | +| 父类在别的 resilience domain | Resilient | `ResilientClassMetadataPattern.data` | `ResilientClassMetadataPattern.metaclass` 指向的元类的 `data` 字段 | 描述符的 `ObjCResilientClassStubInfo` | +| 父类是本模块的泛型类 | Singleton | 静态的 incomplete metadata(一个 class object 形状的结构)的 `data` 字段 | 它的 `isa` 字段指向的元类的 `data` 字段 | 只有私有符号 `…CMt` 能找到 | + +几点细节: + +- 泛型类那一行照的是运行时 `initializeClassMetadataFromPattern`(`Metadata.cpp`):它把 extra-data pattern 拷到实例化元数据 extra data 的 `OffsetInWords` 处,再让 data 指向 extra data 的第 `ClassRODataOffset` 个字。所以在 pattern 自己的数据里,模板在第 (`ClassRODataOffset` − `OffsetInWords`) 个字。模板里的 `class_ro_t.name` 是空指针,由运行时给每个实例化各取一个名字。没有 extra-data pattern 的泛型类是不开 ObjC interop 的构建,跳过。 +- Resilient 与 Singleton 的描述符都有 singleton metadata initialization,`incompleteMetadata` 字段在 Resilient 下改指向 `ResilientClassMetadataPattern`(两者是同一个 union),靠描述符的 `hasResilientSuperclass` 区分。 +- Update 与 FixedOrUpdate 策略的类同样有 singleton metadata initialization,它们的 incomplete metadata 就是 class list 里的 class object,所以按偏移排除:偏移落在 class list 里的不算。 +- Singleton 的 stub 描述符不记录(`addObjCResilientClassStubInfo` 只在 Resilient 策略下写),只能按符号找。编译器给它的是非公开 stub(`emitObjCResilientClassStub(_:isPublic: false)`):完整 stub 有一个私有符号 `…CMt`,它的第一个字是保留字,第二个字才是 isa;指向 isa 的别名 `…CMs` 只给公开 stub 定义,这里没有。所以把描述符符号 `…CMn` 换成 `…CMt` 去符号表里找(`SymbolIndexStore.offset(ofSymbolNamed:in:)`),再加一个字。`…CMt` 是 local 符号,剥掉 local 符号的镜像里找不到,`classStubOffset` 就留空。这种类的 category 不指向 stub(见下一条),MachOObjCSection 的索引器也只拿 `classStubOffset` 归挂在 stub 上的 category,所以缺了不影响什么。公开的 stub(Resilient 那一行)两个符号都有,`…CMs` 正是描述符记录的那个地址。 +- **category 指向哪里**:Swift `extension` 里的 `@objc` 成员编成 category,三种类各不相同。父类在别的 resilience domain 的类(`AncestryFlags::ResilientOther`),category 指向它的 stub,放在 `__objc_catlist2` 里(`GenClass.cpp` 的 `getClassMetadataRef()`、`GenDecl.cpp` 的 `emitExtension`)。父类是本模块泛型类的类,category 指向类自己的 incomplete metadata,放在 `__objc_catlist` 里,从那里读得出 `class_ro_t` 里的运行时名。泛型类的 `extension` 不许有 `@objc` 成员(`TypeCheckDeclObjC.cpp` 报 `objc_in_generic_extension`),没有 category。 +- 绝对指针(Singleton 的 `data` 与 `isa` 字段、Resilient 的元类的 `data` 字段)一律构造成 `ObjCClass64` 交给 MachOObjCSection 的读取器解:它处理 rebase、chained fixup、dyld cache 的偏移、进程内已 realize 的类(`data` 指向 `class_rw_t`)这些情况。相对指针(pattern 里的字段、`data`、`metaclass`、stub)用 `resolvedDirectOffset` 自己解。读出来的元类 `class_ro_t` 必须带 `RO_META` 标志,不带就当没读到。 + +## 名字与父类 + +- **名字**:泛型类用 Swift 限定名加上各层泛型参数(`Xcode_Service.MenuBarPanelWindow`,按 depth 与 index 命名,嵌套在泛型里的写成 `Outer.Inner`),因为模板里没有名字。另外两种用 `class_ro_t` 里的运行时名(`_TtC13Xcode_Service23MenuBarLabelHostingView`)。本库的 ObjC 方法表按 Swift 限定名查类,限定名到这些名字的映射由索引维护(`names(forSwiftClassQualifiedName:in:)`)。 +- **父类**:从描述符的 superclass mangled name 读,按能不能续链分四种(`SwiftClassWithoutClassObject.Superclass`): + - ObjC 类给运行时名(`__C.NSPanel` 给 `NSPanel`),没有声明父类的 Swift 根类给 `_TtCs12_SwiftObject`(运行时给它的父类)。祖先解析器按这个名字到依赖镜像里找:文件在它的依赖闭包里找,进程内镜像在已加载的镜像里找,两边都先查 export trie。进程内原本不需要按名字找(class object 的父类都是真指针),没有 class object 的类只有父类的名字,这一步是为它们加的,`ObjCAncestorResolver.classObject(named:)` 因此也接受进程内的根。 + - 同一镜像里有 class object 的 Swift 类,给 class list 里它的运行时名(`ObjCClassMethodIndex` 的名字表,以及改过名的类的 `SwiftClassObjectIndex`)。 + - 同一镜像里同样没有 class object 的类,给它在本索引里的名字,祖先链经新的 `ObjCSuperclassLocation.withoutClassObject` 接着走。 + - 别的镜像里的 Swift 类,给 Swift 写法(`SwiftUI.NSHostingView`),只作显示,链在这里断,`unresolvedAncestorName` 留空,不拿这个写法去查。 +- **有没有 ObjC 祖先**:看类标志位的 `UsesSwiftRefcounting`,ObjC 对象模型下它是 0;继承 `NSObject` 的 actor 保留 Swift 引用计数,按「是 actor 且有父类」另判(与 `SwiftClassObjectIndex` 判 `@objc(Name)` 合不合法用的是同一条规则)。 + +## 交给谁 + +- **本库的 ObjC 方法表**(`ObjCClassMethodIndex`):`runtimeNames(forSwiftClassQualifiedName:in:)` 把本索引的名字并进来,`hierarchy(forRuntimeName:in:)` 在找不到 class object 时从本索引读方法表、续链。这一侧不按 ObjC 祖先过滤,纯 Swift 类本来就没有 ObjC 方法,不出表。 +- **MachOObjCSection 的索引器**:`ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`(SwiftIndexing,公开)交出全部泛型类,以及有 ObjC 祖先的另外两种——编译器只给这些类往 `__objc_stublist` 登记 stub,MachOObjCSection 给它们写的注释也是 `registered through __objc_stublist`。`ObjCInterfaceSession` 与 `ObjCAPIRequests` 构造索引器时传入;`ObjCInterfaceIndexerClassHierarchyProvider` 在 `classGroup(forName:)` 落空时查 `suppliedClassGroup(forName:)`。 + +## 已知限制 + +- 父类是另一个镜像里的 Swift 类时链就断,`override` 不判。非泛型的那种(SwiftUI 的类继承 SwiftUICore 的类)可以按限定名到依赖镜像的 class list 里找;泛型的那种(`NSHostingView<…>`)在那个镜像里同样没有 class object,要跨镜像读它的 pattern。都留作后续。 +- 本库自己的读取器看不到父类在别的 resilience domain 的类的 category(Swift `extension` 里的 `@objc` 成员):读取器只读 `__objc_catlist`,这些 category 在 `__objc_catlist2` 里,它们指向的 stub 也读不出类名。MachOObjCSection 的索引器按 `classStubOffset` 归类,宿主经 provider 时拿得到。父类是本模块泛型类的类不受影响:category 指向类自己的 metadata,`targetClassName(of:)` 读出它的运行时名,照常并进方法表。fixture 里还没有带 `@objc` 成员的 `extension`,这两种情况都没有测试钉住。 +- 运行时名要用旧式 mangling 拼,本库没有旧式 remangler,所以别的镜像里的 Swift 父类只能给 Swift 写法,不能给它在运行时的名字。 + +## 验证 + +- `ClassesWithoutClassObjectsFixture`(SwiftSectionTestingSupport)测试时现编两个镜像:开 library evolution 的 kit(`ResilientBase: NSObject`),加上使用它的客户端,`.full` 与 `strip -x` 两种。客户端里有三种类各一个、纯 Swift 的泛型类、没有 ObjC 祖先的 Singleton 类,以及有 class object 的对照组。 +- `SwiftClassWithoutClassObjectIndexTests`(SwiftObjCInteropTests):文件、剥过的文件、进程内三条路径读出的种类、名字、父类、stub、方法表;方法表经泛型父类续到 `NSObject`,文件与进程内都是。 +- `ClassesWithoutClassObjectsInterfaceTests`(SwiftInterfaceTests)与 `ClassesWithoutClassObjectsRequestTests`(SwiftSectionKitTests):interface 里的 `@objc override`,`objc dump` 列出这些类。这两组与改过的 `ThunkOnlyObjCMemberTests` / `ThunkOnlyObjCMemberDumpTests` 在不含本改动的代码上都失败。 +- `PerImageCacheEvictionTests`:索引随 indexer 一起驱逐。 +- SymbolTestsCore 的快照随之变化:三个继承 `NSObject` 的泛型类,编译器合成的 `init()` 在 interface 里成了 `@objc override init()`,dump 里多了祖先链与覆写注释,与非泛型类一直以来的输出一致。 +- `Xcode Service`(Xcode 27.2):`objc dump` 列出 `Xcode_Service.MenuBarPanelWindow : NSPanel`(9 个方法,与 MachOObjCSection 那边的测试一致)与 `_TtC13Xcode_Service23MenuBarLabelHostingView : SwiftUI.NSHostingView`;interface 里 `MenuBarPanelWindow` 的 8 个 ObjC 成员(`canBecomeKey`、`setFrame(_:display:)`、`init(contentRect:styleMask:backing:defer:)` 等)都是 `@objc override`。 +- 渲染 A/B(2026-10-27,JHs-Mac-Studio-Ultra,基线 `next` d68e6c10):96 对里 66 对一致、30 对不同,都在 SwiftUI 与 SwiftUICore,各条腿都有。逐行归类: + - interface 只多出关键字:1576 处 `override`;14 处 `static` 改成 `override class`(`layerClass`、`cellClass`、`requiresConstraintBasedLayout` 这类 UIKit / AppKit 类成员的覆写);iOS 16.4 / 17.5 模拟器腿上剥过符号的 4 + 4 处 `@objc`;12 处新的显式 selector。没有删掉的声明,也没有类型变化。 + - 显式 selector 逐个核过。`_didUpdateFocusInContext:` 与 `_shouldUpdateFocusInContext:`:基线给有 class object 的兄弟类(`UIKitFocusableFillerItem`、`UIKitFocusableViewResponderItem`)的判定相同,这次是泛型的 `UIKitContainerFocusResponderItem`。`_nsAttributedSubstringFromRange:`:基线在 iOS 18.5 模拟器腿上就是这样判的。`springLoadingHighlightExited:`:`NSHostingView` 的方法表里只有这个 selector,没有 `springLoadingExited:`,类也不遵循 `NSSpringLoadingDestination`,所以 Swift 方法 `springLoadingExited(_:)` 确实以别的 selector 导出(看起来是 SwiftUI 的笔误,AppKit 不会调到它)。 + - dump 只多出注释:方法表的行尾注释、`// ObjC ancestor chain:` 一行及其后的空行、成员行前的 `@objc`;`ListCollectionViewCell` 原本是一行的空类体,多了祖先链注释后展开成多行。 + - 两侧渲染耗时相同(macOS 26.6 cache 的 SwiftUI interface 都是 19 秒)。 diff --git a/Documentations/Internal/CustomObjCClassNames.md b/Documentations/Internal/CustomObjCClassNames.md index a9782ed7c..431b589da 100644 --- a/Documentations/Internal/CustomObjCClassNames.md +++ b/Documentations/Internal/CustomObjCClassNames.md @@ -10,9 +10,9 @@ | 层 | 文件 | 做什么 | |---|---|---| -| SwiftInspection | `CustomObjCClassName.swift` | 公开值类型:名字 + 写法(`.objc` / `.objcRuntimeName`)。 | -| SwiftInspection | `SwiftClassObjectIndex.swift` | 按镜像的 `SharedCache`,只记改过名的类:描述符 offset → 名字与写法、类对象自己的 `instanceStart`;另有「Swift 限定名 → 运行时名」,给按名字查找的 ObjC 侧索引合并用。随 `ObjCClassHierarchies.removeCache(for:)` 驱逐。 | -| SwiftInspection | `ObjCClassMethodIndex.runtimeNames(forSwiftClassQualifiedName:in:)` | 查询时把上面那张限定名表的结果并进自己的表的结果。四个调用点(类本体、类的 extension、dump 的祖先链注释与成员注释)都不用改。 | +| SwiftObjCInterop | `CustomObjCClassName.swift` | 公开值类型:名字 + 写法(`.objc` / `.objcRuntimeName`)。 | +| SwiftObjCInterop | `SwiftClassObjectIndex.swift` | 按镜像的 `SharedCache`,只记改过名的类:描述符 offset → 名字与写法、类对象自己的 `instanceStart`;另有「Swift 限定名 → 运行时名」,给按名字查找的 ObjC 侧索引合并用。随 `ObjCClassHierarchies.removeCache(for:)` 驱逐。 | +| SwiftObjCInterop | `ObjCClassMethodIndex.runtimeNames(forSwiftClassQualifiedName:in:)` | 查询时把上面那张限定名表的结果并进自己的表的结果。四个调用点(类本体、类的 extension、dump 的祖先链注释与成员注释)都不用改。 | | SwiftLayout | `StaticTypeLayoutResolver.classFieldStartOffset` | classlist 的 `instanceStart` 表按限定名查不到时,按描述符问改名类的 `instanceStart`。 | | SwiftDeclaration | `TypeDefinition.customObjCClassName`、`attributeArgument(for:)`;`SwiftAttribute.objcRuntimeName` | `index(in:)` 里填;新 case 放在枚举末尾,已有 case 的 raw value 不变。 | | SwiftAttributeInference | `TypeAttributeInferrer.inferObjCType` | 原来是个空函数,现在按写法产出 `.objcType` / `.objcRuntimeName`。 | diff --git a/Documentations/Internal/DescriptorOnlyVTableMembers.md b/Documentations/Internal/DescriptorOnlyVTableMembers.md index a8d65740d..c14777d51 100644 --- a/Documentations/Internal/DescriptorOnlyVTableMembers.md +++ b/Documentations/Internal/DescriptorOnlyVTableMembers.md @@ -32,7 +32,7 @@ interface 的成员一直是从「实现函数的符号」建出来的。用 lib ## 替身符号为什么长这样 -**名字用实现函数的 mangled 名,不用 `Tq` 符号的名字。** 下游有三处按「成员的实现符号名」推导别的东西:导出判定往名字后面拼 `Tj` / `Tq` / `Tu` 去查 export trie(`isExportedIncludingDerivedSymbols`);ObjC 方法表按实现符号名 join(`ObjCMemberApplication`);ABI diff 的成员身份是重整后的声明节点。用实现函数的名字,这三处把替身当成它顶替的那个符号来读,一行不用改;用 `Tq` 的名字,导出判定会去查 `…TqTj` 这种不存在的符号。去掉后缀就能得到实现名,是因为 mangling 规则是把 `Tq` 原样追加在实体名后面。 +**名字用实现函数的 mangled 名,不用 `Tq` 符号的名字。** 下游有三处按「成员的实现符号名」推导别的东西:导出判定往名字后面拼 `Tj` / `Tq` / `Tu` 去查 export trie(`isExportedIncludingDerivedSymbols`);ObjC 方法表按实现符号名 join(`ObjCMemberMatcher`);ABI diff 的成员身份是重整后的声明节点。用实现函数的名字,这三处把替身当成它顶替的那个符号来读,一行不用改;用 `Tq` 的名字,导出判定会去查 `…TqTj` 这种不存在的符号。去掉后缀就能得到实现名,是因为 mangling 规则是把 `Tq` 原样追加在实体名后面。 **偏移用 descriptor 记录的实现偏移,async 方法再跳一次。** 地址注释读的是成员符号的偏移,替身的偏移必须和「有实现符号时」的那个一样,fixture 的完整版与剥离版逐字比对才能对上。async 方法的 vtable 槽里放的不是代码地址,而是 async function pointer(`Tu` 常量,调用方从它读 async context 的大小),实现符号在它指向的函数入口,所以要经 `AsyncFunctionPointer` 读一次 `function` 字段。读这个记录时要显式标注非可选类型:`resolve(from:in:)` 有一个返回可选值的重载,推断到那个重载会按另一种内存形状去读。 @@ -46,7 +46,7 @@ interface 的成员一直是从「实现函数的符号」建出来的。用 lib ## 什么时候不补 -- **ABI 墓碑**:实现指针是 null,镜像里没有这个成员的代码,只剩槽位。dump 带着墓碑注释列出它;interface 不补,和改动前一致。 +- **ABI 墓碑**:实现指针是 null,槽位指向的那个入口在镜像里没有代码。dump 带着墓碑注释列出它;interface 不从墓碑槽补,和改动前一致。不过成员本身未必没有代码了:整模块优化的 app 里,`@objc` 方法常常只剩它的 ObjC thunk,class 的 initializer 的 allocating entry point 被删、initializing entry point 还在。这两种由 [ThunkOnlyObjCMembers.md](ThunkOnlyObjCMembers.md) 的替身补上,槽号经节点联结照常挂到替身上。 - **modify / read 协程**:符号索引从不把这两种访问器当成员,有实现符号的 class 在 interface 里也看不到它们,补了会让剥离前后的输出形态不同。属性的 `{ get set }` 已经由 getter / setter 表达。 - **真实符号已经声明了这个成员**:按成员实体节点结构相等判断,merged function thunk 先跳过它开头的标记节点,因为 builder 会把 thunk 归到它代表的成员上。所以 fixture 这种没剥离的二进制,模型一个成员都不会多,也一个都不会变。 - **叫不出名字的槽**:internal 成员的 `Tq` 和实现符号一样是 local 的,剥离后这个槽谁也叫不出名字。按用户的指示跳过,不打占位符;dump 里它显示为 `sub_…` 或 ``。 diff --git a/Documentations/Internal/EventBasedDegradationReporting.md b/Documentations/Internal/EventBasedDegradationReporting.md index 2598c5bb1..3fe892da9 100644 --- a/Documentations/Internal/EventBasedDegradationReporting.md +++ b/Documentations/Internal/EventBasedDegradationReporting.md @@ -50,7 +50,7 @@ 宏的声明文件在 `Sources/OSToolbox/Macros/LoggableMacro.swift`,所以第一反应是给 target 加 `OSToolbox` product 依赖 —— SPM 报 `product 'OSToolbox' … not found`,据此很容易误判成「这里用不了 `@Loggable`」。 -**实际上项目里所有用法都是经 `FoundationToolbox` 拿到宏的**(`RuntimeFieldLayoutBackend`、`SymbolIndexStore` 都只 import 它)。加 `.product(name: "FoundationToolbox", package: "FrameworkToolbox")` 即可。 +**实际上项目里所有用法都是经 `FoundationToolbox` 拿到宏的**(`RuntimeFieldLayoutBackend`、`SwiftSymbolIndexStore` 都只 import 它)。加 `.product(name: "FoundationToolbox", package: "FrameworkToolbox")` 即可。 这也顺带解决了部署下限问题:本包部署到 **macOS 10.15 / iOS 13**,低于 `os.Logger` 的 macOS 11 / iOS 14,而 `@Loggable` 展开时自带 `#available` 回退到 `os_log`。所以**不要**为了绕开下限而手写 `os.Logger` 或裸 `os_log`。 @@ -102,7 +102,7 @@ private final class OpaqueTypeRewriter: Node.Rewriter, OpaqueTypeRew 而且只要有别的 suite 往 stdout 写一个字节,捕获断言就假失败。 -改为**源码扫描**:遍历 `Sources/` 下所有非宿主模块(`swift-section` / `MachOTestingSupport` 除外 —— CLI 是宿主,stderr/stdout 都是它的合法通道),匹配 `FileHandle.standardError` / `FileHandle.standardOutput` / 裸 `fputs(` / 裸 `print(`。 +改为**源码扫描**:遍历 `Sources/` 下所有非宿主模块(`swift-section` / `SwiftSectionTestingSupport` 除外 —— CLI 是宿主,stderr/stdout 都是它的合法通道),匹配 `FileHandle.standardError` / `FileHandle.standardOutput` / 裸 `fputs(` / 裸 `print(`。 **扫描必须能识别「裸调用」**:`node.print(using:)` 是本库的渲染 API,`printer.printRoot(...)` 也是 —— 简单 `contains("print(")` 会大面积误伤。`containsBareCall(to:in:)` 检查 `print(` 前一个字符不是字母/数字/`.`/`_`。配套的 `theStreamWriteScannerDiscriminates` 同时钉正例和反例,因为**一个只会返回「没找到」的扫描器等于没有扫描器**。 diff --git a/Documentations/Internal/ExportedOnlyInterfaceFiltering.md b/Documentations/Internal/ExportedOnlyInterfaceFiltering.md index 51393fa38..f5ed26863 100644 --- a/Documentations/Internal/ExportedOnlyInterfaceFiltering.md +++ b/Documentations/Internal/ExportedOnlyInterfaceFiltering.md @@ -16,7 +16,7 @@ interface 只输出镜像导出的声明。「导出」始终是 **export trie **过滤在打印期,不在索引期。** 用户选定。索引出的模型保持完整,RuntimeViewer 浏览、ABI diff / snapshot / evolution 全部不受影响;代价是打印器多了一组判定入口。(注意区分**动作**与**事实**:删不删仍然只发生在打印期, 但「类型 / 协议导出与否」这个事实本身自提案 `exported-declaration-flag` 起在索引期算好、存在模型上——见下文「这两腿住在声明模型上」。)索引期过滤本可顺带给 diff 一个「只比对导出面」的能力,但要在 -`DefinitionBuilder` 和四个 extension 桶上做更深的手术,且提案 0008 的标注本来就是打印期的事实——两者同层最自然。 +`MemberDefinitionBuilder` 和四个 extension 桶上做更深的手术,且提案 0008 的标注本来就是打印期的事实——两者同层最自然。 **绝不靠猜删东西。** 每个判定都是三态:`false` 才删,`true` 与 `nil` 都保留。`nil` 覆盖「镜像没有导出信息」「成员没有 join 上任何符号」 「重整名不可信」「宿主没装 `ExportFilterScope`」全部情形。这和标注的「绝不靠猜打标」是同一条原则的两面, @@ -26,16 +26,27 @@ interface 只输出镜像导出的声明。「导出」始终是 **export trie 查 trie。第一版这么做,fixture 当场暴露一个真实误删:`extension GenericRequirementTest where T: RawRepresentable { public struct RawRepresentableNestedStruct {} }` ——编译器给嵌套在**带约束扩展**里的类型 mangle 的上下文只含扩展自己的 requirement(`…VAASYRzrlE28RawRepresentableNestedStructVMn`), 而模型的名字节点带着类型的完整签名(interface 头部印出 `where A: RawRepresentable, A: ProtocolTest` 两条),重整结果与真实符号不等, -trie 查不到就成了假阴性,一个导出类型被删掉。因此裁决分两腿: +trie 查不到就成了假阴性,一个导出类型被删掉。因此裁决分三腿: 1. `symbolIndexStore.symbols(for: descriptor.offset)` 取**描述符所在位置**的符号(按 `Mn` / `Mp` 后缀挑),拿编译器自己的拼法查导出位图。 - 导出描述符必有 trie 行、未 strip 的镜像对未导出描述符也有本地 symtab 行,所以这一腿几乎总能答。 + 导出描述符必有 trie 行、未 strip 的镜像对未导出描述符也有本地 symtab 行,所以留着本地符号的镜像里这一腿总能答。 2. 只有描述符处没有任何符号(strip 过的镜像里的未导出类型)才用重整名查 trie——trie 在 symtab 被 strip 后依然完整, - 一次 miss 就是真阴性。但**含 `.extension` 上下文的名字拒绝兜底**(返回 `nil` → 保留):那正是第 1 腿存在的理由。 - -**这两腿住在声明模型上,不在打印器里**(提案 `exported-declaration-flag`)。`TypeDefinition.exportStatus` / -`ProtocolDefinition.exportStatus`(`SwiftDeclaration` 的 `ExportStatus` 四态枚举:`exported` / `notExported` / -`imageHasNoExportInformation` / `descriptorSymbolNameUnresolvable`)在定义构造时一次算好,`prepare()` 返回时整张表就都有值—— + 一次 miss 就是真阴性。但**含带约束扩展上下文的名字拒绝兜底**:那正是第 1 腿存在的理由。不带约束的扩展节点只有扩展所在的模块与被扩展的类型两个子节点, + 重整结果与编译器的拼法逐字相同(`ExtensionContextExportStatusTests` 在未 strip 的夹具上逐个比对),照常重整。 + Swift 写在 ObjC 类里的类型全都经过这种扩展上下文(`(extension in AppKit):__C.NSView`)。 +3. 第 2 腿拒绝时,私有或局部声明判 `notExported`——编译器不给它们 public 链接;`-enable-private-imports` 编出的模块会导出私有描述符, + 但那时第 1 腿已经在描述符上找到导出符号。认法有两种,任一成立即可:名字的上下文链(自己、外层类型、扩展所扩展的类型)里有私有声明或局部类型; + 或者描述符外层有匿名上下文(编译器给私有声明与局部声明套的那一层)。后一种在什么符号都没留的镜像里也读得到——那里匿名上下文没有名字, + 私有类型的名字里就没有鉴别器,光看名字认不出。其余保留为 `descriptorSymbolNameUnresolvable`。 + 泛型实参、扩展的要求与函数签名不在链上:特化出的 `Box` 与 `Box` 一样是导出的。 + +2026-11-10 之前第 2 腿拒绝一切扩展上下文、也没有第 3 腿(提案 `export-verdict-without-local-symbols`)。macOS 27.2 dyld shared cache 里的 +AppKit 只留导出、导入与 `_symbolic` 符号,未导出描述符上没有符号,写在 ObjC 类扩展里的约 45 个未导出类型(33 个是私有的)因此全部没有结论, +`--exported-only` 照样印出它们,RuntimeViewer 排除未导出之后也照样列出。 + +**这几腿住在声明模型上,不在打印器里**(提案 `exported-declaration-flag`)。`TypeDefinition.exportStatus` / +`ProtocolDefinition.exportStatus`(`SwiftDeclaration` 的 `ExportStatus` 枚举:`exported` / `notExported` / +`imageHasNoExportInformation` / `descriptorSymbolNameUnresolvable`,后来又加了 `declarationHasNoSymbol` 与 `declarationIsCImported`)在定义构造时一次算好,`prepare()` 返回时整张表就都有值—— 裁决只要描述符 offset 与名字节点,不碰 `index(in:)` 的产物。宿主(RuntimeViewer 的类型列表)因此能逐行标注而不必持有 machO, 打印器的 `exportVerdict(forTypeDefinition:/forProtocolDefinition:)` 退化为 `exportStatus.isExported` 的转发(签名不变,仍是 `Bool?`), `installExportFilterScope` 只筛 `isDefinitelyNotExported`——`printRoot()` 原先那趟全镜像重算随之消失。 @@ -43,6 +54,17 @@ trie 查不到就成了假阴性,一个导出类型被删掉。因此裁决分 `descriptorSymbolNameUnresolvable` 是**声明级**的(trie 正常,只是这一条的名字重整不可信)。 实测四个真实镜像(dyld shared cache 与 iOS 18.5 模拟器的 SwiftUICore、进程内 libswiftCore、`SymbolTestsCore`)共 8171 条类型 / 协议声明 **全部走第 1 腿**、无一落到这两个 case,裁决总耗时占 `prepare()` 的 0.15% 以内——所以它是无条件填充,没有配置开关。 +这四个镜像都留着本地符号;没留本地符号的镜像(上文的 AppKit)里,未导出声明全靠第 2、3 腿。 + +**C 导入类型不裁决**(提案 [0083-exported-only-marking-mode](../Evolutions/0083-exported-only-marking-mode.md))。`__C.CGSize` 一类类型在本镜像里的描述符 +是本镜像自己生成的一份副本:编译器给 Clang 声明的是非唯一链接(`swift/lib/SIL/IR/SIL.cpp` 的 `getDeclLinkage` 对 Clang 声明返回 +`PublicNonUnique`),每个用到它的模块各自生成一份、谁都不导出——fixture 里 `_$sSo11CMTimeFlagsVMn` 就是 private external。 +把它读成「未导出」,开了 `--show-c-imported-types` 的 `--exported-only` 会删掉 C 类型本身,而且因为它进了 `ExportFilterScope`, +本镜像给它写的公开扩展与 conformance(SwiftUI 的 `extension CGSize: VectorArithmetic`)也跟着被删。所以裁决在源头改为 +`declarationIsCImported`:`ExportStatus.resolve` 先看描述符的模块是不是 `__C` / `__C_Synthesized`(`isCImportedContextDescriptor`), +是就不查 trie。它不给结论,于是 C 类型本身保留、不进 scope,扩展照常按成员裁决;宿主读 `exportStatus` 的其他地方(RuntimeViewer 侧栏的 +「Not Exported」)一起正确。`ExportedOnlyLibraryEvolutionFixtureTests.cImportedTypeIsNotRuledOnAndItsPublicExtensionsAreKept` +(即时编译的模块扩展 `CGPoint`)与 `ExportStatusTests.cImportedTypeIsNotRuledOn`(`CMTimeFlags`)钉住它;修复前前者的四条断言全红。 **扩展的判据要靠索引器的表,符号推不出「本镜像内」。** 扩展没有自己的描述符符号,能判的只有「被扩展类型 / 遵循协议是不是本镜像内未导出声明」。 「本镜像内」不能从符号存储推断——strip 过的镜像里一个未导出的类型**一个符号都没有**,用 `typeInfo` / `containsSymbol` 判会把被删私有类型的 @@ -63,35 +85,70 @@ conformance 扩展全部漏下来。所以 `SwiftInterfaceBuilder.printRoot()` 所以它发一对 start / completed 包住空结果。 **字段循环先筛后印,保留原始下标。** `renderModelFields` 的字段记录与布局注释都按原始位置取(`fieldRecords[safe:]`、 -`storedFieldComments(forFieldAtIndex:)`),而尾部换行跟着「最后一个实际渲染的字段」走。所以先把 `fields.enumerated()` 过滤成 -`renderedFields`,再用 `offsetEnumerated()` 遍历——`fieldIndex` 取原始下标,`offset.isEnd` 取渲染序列的末尾。枚举 case 没有符号,永远不筛。 +`storedFieldComments(forFieldAtIndex:)`),而尾部换行跟着「最后一个实际渲染的字段」走。所以先把 `fields.enumerated()` 筛成 +`renderedFields`(每项带原始下标与可见条件),再逐项打印——`fieldIndex` 取原始下标,尾部换行放在循环之后、条件是「任一字段可见」。枚举 case 没有符号,永远不筛。 + +## 标记模式 + +提案 [0083-exported-only-marking-mode](../Evolutions/0083-exported-only-marking-mode.md)。标记模式(`marksOptionalContent`,提案 0056) +把受选项控制的内容全部打出、标上可见条件,宿主按选项投影;RuntimeViewer 的 Find 语料就是这样打印的。导出过滤原本不在其中, +开着这个选项 Find 照样搜得到被删的成员。现在 `SwiftVisibilityOption.printExportedDeclarationsOnly`(`swift.printExportedDeclarationsOnly`) +也是一个可见性选项,`isVisibilityOptionEnabled` 认它: + +- **判定照旧,动作改为标记。** `isExcludedByExportFilter` 一族在开关打开**或**标记模式下都会裁决(`evaluatesExportFilter`),标记模式不看开关本身的取值。 + 每个原本「不输出」的地方改问 `exportFilterVisibility(excluded:)`:保留的内容 `.always`;过滤掉的内容普通打印时 `nil`(略过), + 标记模式下是 `.disabled("swift.printExportedDeclarationsOnly")`——只在开关关着时可见。覆盖三个打印入口、被清空的普通扩展、 + 成员循环、存储属性、`printRoot` 的两个全局块与 ObjC category conformance 块。已经打好的 `SemanticString` 用 `visible(under:)` + (`markAtoms(from:visibleUnder:)` 的包装)补标,不改文本与元素边界;要保留元素结构的一组内容(全局块一项的注释行与声明)包 `VisibilityRegion`。 +- **scope 照旧要装。** `printRoot()` 在标记模式下也装 `ExportFilterScope`;逐个定义打印的宿主(RuntimeViewer)给语料打印器也要装。 +- **分隔符交给容器,闭合换行除外。** `MemberList`、`BlockList`、`NestedDeclaration` 会把成员的条件带到自己打的换行与分隔符上, + conformance 扩展被清空后照样投影成 `{}`。管不到的是 `DeclarationBlock` 闭合 `}` 前的换行:它按**全量打印**的 body 最后一个字节决定补不补 + (swift-semantic-string 的设计记录把这列为已知例外)。body 留着嵌套类型、之后的声明全被过滤时(`public enum Namespace { public struct Member {}; static func internalHelper() }`), + 全量打印以成员列表的换行结尾、块不补换行,投影到开关打开就只剩嵌套类型的 `}`,印成 `}}`。所以标记模式下,类型与扩展 body 里嵌套定义之后的部分 + (`bodyAfterNestedDefinitions(of:content:)`)在「其中每个声明都被过滤」(`excludesEveryDeclarationAfterNestedDefinitions(of:)`: + 存储属性与成员全被过滤,且没有枚举 case、`deinit`、关联类型记录、ObjC ivar)时去掉最后那个换行,让块自己补一个条件为「body 任一部分可见」的换行。 + 开关关着时它顶替被去掉的那个;开着时嵌套定义在就补、body 全空就不补(`{}`)。协议 body 没有嵌套定义,不需要。 +- **事件**:标记模式下被过滤的定义也打印了,所以照常派发 start / completed。 +- **嵌套定义区域契约的例外**(`marksNestedDefinitions`):被过滤的定义里嵌着一个**没被过滤**的定义时,父定义的标记打印把整段、连同这个子定义, + 都标成「开关关着才可见」,取出的子定义区域于是比它单独打印多了这个条件:开关关着时两者相同,开着时区域消失、单独打印还在。 + 这在现有编码下修不掉——父定义投影到开关打开时必须整段不可见,子定义单独打印时又必须可见,同一段原子带不了两种条件; + 要在「取出区域」时去掉祖先加上的条件,得改 swift-semantic-string 的区域编码。所以写进契约作为例外:宿主遇到「自己的 `exportStatus` 不是 + `isDefinitelyNotExported`、外层某个定义是」的嵌套定义,单独打印它。RuntimeViewer 接入时在 Foundation 碰到一例 + (`LocalePreferences` 没导出、`LocalePreferences.ICUSymbolsAndStrings` 导出了,源码里两者都是 `package`,导出与否看苹果的导出清单), + 它的 Find 语料已按此单独打印。`ExportedOnlyFixture` 用链接器的 `-unexported_symbol` 把 `UnexportedParent` 的类型符号移出导出表造出同样的形态, + `NestedDefinitionRegionContractTests.exportedOnlyFixtureNestedDefinitionsTakeOutAsTheirOwnPrints` 把这个区域按上述例外严格检查、其余区域照旧按契约检查。 ## 模块结构 ``` Sources/Output/SwiftPrinting/ -├── SwiftDeclarationPrintConfiguration.swift # printExportedDeclarationsOnly -├── SwiftDeclarationPrinter+ExportFilter.swift # ExportFilterScope、installExportFilterScope、类型 / 协议 verdict 的转发、全部 isExcludedByExportFilter 判定 -├── SwiftDeclarationPrinter.swift # 三个入口的过滤壳 + printIncluded… 体;成员循环 where 过滤;exportFilterScope 存储 +├── SwiftDeclarationPrintConfiguration.swift # printExportedDeclarationsOnly;isEnabled 认 SwiftVisibilityOption.printExportedDeclarationsOnly +├── SwiftDeclarationPrinter+ExportFilter.swift # ExportFilterScope、installExportFilterScope、类型 / 协议 verdict 的转发、全部 isExcludedByExportFilter 判定、excludesEveryDeclarationAfterNestedDefinitions +├── SwiftDeclarationPrinter+VisibilityRegions.swift # exportFilterVisibility(excluded:)、bodyAfterNestedDefinitions、SemanticString.visible(under:) +├── SwiftDeclarationPrinter.swift # 三个入口的过滤壳 + printIncluded… 体;成员循环逐项问可见性;exportFilterScope 存储 └── SwiftDeclarationPrinter+Headers.swift # renderModelFields 的字段预筛 -Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift # 四态枚举、两腿裁决、descriptorSymbolName 重整(提案 exported-declaration-flag) -Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift # printRoot 装 scope;全局块 where 过滤 +Sources/Output/SwiftDeclarationRendering/SwiftVisibilityOption.swift # 可见性选项 swift.printExportedDeclarationsOnly +Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift # 裁决枚举、C 导入类型不裁决、两腿裁决、descriptorSymbolName 重整(提案 exported-declaration-flag) +Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift # printRoot 装 scope(标记模式也装);全局块与 ObjC category conformance 块逐项问可见性 Sources/Executables/swift-section/Commands/InterfaceCommand.swift # --exported-only ``` ## 核心算法与数据流 -`printRoot()` → 开关打开则 `installExportFilterScope(types:protocols:)`(只筛各定义已算好的 `exportStatus`)→ `printRootContents()`: +`printRoot()` → 开关打开或标记模式下 `installExportFilterScope(types:protocols:)`(只筛各定义已算好的 `exportStatus`)→ `printRootContents()`。 +每个判定的结果都经 `exportFilterVisibility(excluded:)` 变成「输出 / 略过 / 标记」三者之一(见上文「标记模式」): | 对象 | 判定入口 | 依据 | |------|----------|------| | 全局变量 / 函数 | `isExcludedByExportFilter(globalSymbolNames:)` | `exportVerdict(forSymbolNames:)`(0008 的派生形态查询) | -| 类型 / 协议(含嵌套、特化子类型) | 入口壳 → `TypeDefinition/ProtocolDefinition.exportStatus.isDefinitelyNotExported` | 构造期算好的 `ExportStatus`(描述符 offset 处的符号 → 重整名兜底) | +| 类型 / 协议(含嵌套、特化子类型) | 入口壳 → `TypeDefinition/ProtocolDefinition.exportStatus.isDefinitelyNotExported` | 构造期算好的 `ExportStatus`(C 导入类型不裁决 → 描述符 offset 处的符号 → 重整名兜底 → 私有或局部声明判未导出) | +| Swift 声明的 `@objc` 协议 | `printObjCProtocolDefinition` 入口壳 → `ObjCProtocolDefinition.exportStatus.isDefinitelyNotExported` | 没有描述符,只看名字:私有的或嵌在私有类型里的判未导出,其余不裁决;它的扩展随它打印、随它删除,不进 `ExportFilterScope` | | 扩展 | 入口壳 → `isExcludedByExportFilter(_ extension)`;索引后 `isEmptiedByExportFilter` | `ExportFilterScope` 集合;过滤后内容是否为空 | -| 成员 | `printMembersByOffset` / `ByCategory` 的 `where` | 派生形态查询;`override` / `@objc` 豁免 | +| 成员 | `printMembersByOffset` / `ByCategory` 逐项 | 派生形态查询;`override` / `@objc` 豁免 | | 存储属性 | `renderModelFields` 预筛 `isExcludedByExportFilter(field:)` | accessor 组的派生形态查询;无 accessor 符号 / `override` / `To` 入口豁免 | +| ObjC category conformance | `SwiftInterfaceBuilder` 的 `isExcludedByExportFilter(_ conformance:)` | 被扩展的本镜像类是否被过滤;或者它遵循的协议全是本镜像未导出(私有)的 `@objc` 协议——同 Swift 类型遵循未导出协议的 conformance 一样删;还遵循了别的协议的整条保留 | -特化子类型的名字是 bound-generic 节点,verdict 的两腿都落在未绑定描述符上(第 1 腿直接用描述符 offset,第 2 腿剥 bound-generic 壳)。 +特化子类型的名字是 bound-generic 节点,verdict 的三腿都落在未绑定描述符上(第 1 腿直接用描述符 offset,第 2、3 腿剥 bound-generic 壳)。 ## 与提案的差异 @@ -105,27 +162,36 @@ Sources/Executables/swift-section/Commands/InterfaceCommand.swift # --exported-o 私有类型的 conformance 扩展 / 嵌套私有类型(父级与公开兄弟保留)各一例删除;带约束扩展里的公开嵌套类型保留(回归); 未导出成员删而类型留;未导出全局删;`Tj` 导出、`@objc`、`override` 三类保留;清空的 conformance 扩展留 `{}`; 双 flag 同开零标注;无空行残留;默认输出与从未听说过该开关的 builder 逐字节相同。每条否定断言都先在默认输出上断言其存在。 -- `Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift`(即时编译,`-enable-library-evolution` 且无 `-enable-testing`,7 例): +- `Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift`(8 例,跑在即时编译的 `ExportedOnlyFixture` 上——`Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift`,`-enable-library-evolution` 且无 `-enable-testing`): `SymbolTestsCore` 因 `ENABLE_TESTABILITY` 导出全部 `internal`,所以 `internal` 形态在这里钉:类型(顶层 + 嵌套)、协议及其默认实现、 - 公开类型对内部协议的 conformance 扩展、方法、存储属性(accessor 以本地符号 join 上)、全局;被清空的普通扩展容器整块删、有公开成员的容器保留;枚举 case 保留。 + 公开类型对内部协议的 conformance 扩展、方法、存储属性(accessor 以本地符号 join 上)、全局;被清空的普通扩展容器整块删、有公开成员的容器保留;枚举 case 保留;C 导入类型 `CGPoint` 本身、本镜像给它写的公开扩展与 conformance 保留。 - `Tests/SwiftSectionCommandTests/ExportedOnlyFlagTests.swift`:flag 解析、默认关、`dump` 无此 flag。 +- `Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift`:标记打印按某组配置投影 == 按该配置直接打印(文本、span、identifier), + 每个打印器都装同一个 scope。SymbolTestsCore 进程内覆盖全关、全开与每个选项单开、单关(含 `printExportedDeclarationsOnly`),从文件打印变动四个布局选项; + `ExportedOnlyFixture`(即时编译,`internal` 不导出)逐个定义与整份 `printRoot()` 各对开关开、关投影一次。 + 两个探针确认它们会红:标记模式退回不管导出过滤时三条都红;不去掉 body 末尾的换行时,`Holder` / `FieldHolder` / `Namespace` / `extension Int` + 投影到开关打开都印成 `}}`。 +- 落地前在真实框架上跑过一次临时探针(未提交):本机 macOS 27.2 dyld cache 的 Combine、SwiftUICore、AppKit,每个定义的标记打印按「过滤开 / 关 × + 地址等注释开 / 关」四组配置投影,848 / 14,086 / 2,879 个定义全部与直接打印一致,其中 615 / 9,919 / 1,503 个有被过滤标记的内容。 - 落地前的人工交叉验证(fixture 全量输出):默认 3824 行 → 过滤后 2839 行;标注模式下 378 处 `// not exported` 对应的声明在过滤输出里**零残留**; 过滤输出相对默认输出的新增行只有 conformance 扩展的 `{` → `{}` 改写;无 `\n\n\n`、无 `{\n}`。 - 默认路径零行为改动,不构成 AGENTS.md 意义上的 large refactor,未跑渲染 A/B 脚本;由既有 interface 快照与 `defaultOutputIsUnchanged` 钉住。 ## 已知降级 +- **外层没导出时,导出了的嵌套类型跟着被删。** 嵌套类型只在外层里面打印,外层被过滤,整段一起没了:`--exported-only` 的输出里没有 + Foundation 的 `LocalePreferences.ICUSymbolsAndStrings`,虽然它的描述符导出了。系统框架的导出表由导出清单决定,不跟访问级别走, + 这种形态真实存在;标记模式下它是嵌套定义区域契约的例外(见上文「标记模式」)。单独打印这个嵌套类型(宿主逐个对象打印时)照常输出。 - **引用不改写。** 过滤按声明进行,导出成员的签名里仍可能引用被删的类型(fixture:`typealias Body = Structs.PrivateProtocolTest`)。 这与真实二进制里 `some P` 解析到私有类型的情形同构,属于「输出忠实于二进制」的一面。 -- **`--show-c-imported-types` 下 C 导入类型会被过滤。** `__C.CMTime` 之类外来描述符的 `Mn` 是本地符号(它们不是本镜像导出的),判定为 `false`。 -- **绕过 `printRoot` 的宿主要自己装 scope。** RuntimeViewer 的 per-type 导出若不调 `installExportFilterScope`,类型 / 协议 / 成员照常过滤, - 只有扩展这一腿退化为「全部保留」——fail-open,静默。 +- **绕过 `printRoot` 的宿主要自己装 scope**,标记打印也一样。RuntimeViewer 的 per-type 导出若不调 `installExportFilterScope`,类型 / 协议 / 成员照常过滤, + 只有扩展这一腿退化为「全部保留」——fail-open,静默;标记打印则不标任何扩展。 - **镜像没有导出信息时什么都不过滤**(三态 `nil`),静默。目前没有能构造这种镜像的 fixture(与 0008 同一个缺口)。 - **被清空的普通扩展仍会派发一对 print 事件**(见上文事件契约),事件消费者会看到一个 start / completed 之间零输出的扩展。 ## 延伸阅读 -- 配套提案:[0016](../Evolutions/0016-exported-only-interface.md) +- 配套提案:[0016](../Evolutions/0016-exported-only-interface.md);标记模式与 C 导入类型:[0083](../Evolutions/0083-exported-only-marking-mode.md) - 前篇:[InterfaceHeaderAndExportStatusAnnotations.md](InterfaceHeaderAndExportStatusAnnotations.md)(导出事实层、派生符号形态、两个豁免的来历) - 模块参考:[Modules/SwiftInterface.md](Modules/SwiftInterface.md)(`printRoot()` 的段落与 catch 契约) - 术语:[Glossary.md](../Glossary.md) 的「export status」与「exported-only 过滤」 diff --git a/Documentations/Internal/ExtensionContainerUnification.md b/Documentations/Internal/ExtensionContainerUnification.md index 03107fc18..cb55d87f5 100644 --- a/Documentations/Internal/ExtensionContainerUnification.md +++ b/Documentations/Internal/ExtensionContainerUnification.md @@ -26,11 +26,11 @@ ## 模块结构 ``` -Sources/Declaration/SwiftDeclaration/Components/Definitions/ -├── ExtensionDefinition.swift # + isAttachedToProtocolDefinition / absorbMembers -├── ExtensionDefinition+Indexing.swift # 默认实现打标(markProtocolExtensionDefaults) -├── ProtocolDefinition+Indexing.swift # index():descriptor 合成降级为 fallback -└── {Function,Variable,Subscript}Definition.swift # + isProtocolExtensionDefault +Sources/Declaration/SwiftDeclaration/ +├── Model/Definitions/ExtensionDefinition.swift # + isAttachedToProtocolDefinition / absorbMembers +├── Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift # 默认实现打标(markProtocolExtensionDefaults) +├── Indexing/ProtocolDefinition+Indexing.swift # index():descriptor 合成降级为 fallback +└── Model/Members/{Function,Variable,Subscript}Definition.swift # + isProtocolExtensionDefault Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift # index() 入口四桶重置;unifyExtensionContainers()(桶内同身份合并 + 协议附着); # 变量签名分桶的空 requirement 折叠;updateConfiguration 复位 isPrepared diff --git a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md index faeafeac3..781a537b4 100644 --- a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md +++ b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md @@ -75,6 +75,13 @@ configuration/isGeneric/staticAggregateFieldLayout,不含 `Self`)传递 rend - 注入点:`SwiftDeclarationPrinter` 首次渲染时懒建一次(仅当 reader 是 MachOFile 且开了任一 layout flag) 并注入每类型构造的 `DeclarationRenderConfiguration`;`swift-section dump` 在建好 `dumpConfiguration` 后、循环前建一次。 +- **`updateConfiguration(_:)` 只在 provider 的输入变了时丢掉它**(2026-11-03)。输入只有两样:有没有哪个开关 + 需要 provider(`marksOptionalContent` 或四个布局开关之一),以及 `staticLayoutDependencyResolution`;两者合成 + `StaticFieldLayoutProviderInputs`,建 provider 时随它一起记下,`updateConfiguration` 拿新配置的输入去比。 + RuntimeViewer 每次打印 interface 前都交一次配置,多数时候没变,原先每次都丢(5fe5eb61 为防止「开关变了还用旧 + provider」加的无条件重置),于是离线打印每个 interface 都重建依赖闭包、重新索引依赖镜像的类型。开关的需要 + 变了、或解析方式变了,照旧重建。配置的替换和 provider 读配置都在 provider 的锁里做,所以记下的输入一定是建它的 + 那份配置的(`StaticFieldLayoutProviderReuseTests`)。 `FieldLayoutRenderer.init` 在 reader 为 MachOFile、开了 layout flag、且 provider 存在时,**每类型预算一次** `staticAggregateFieldLayout: AggregateFieldLayout?`(reader 无关数据,存于 facade)。MachOFile 路径的 diff --git a/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md b/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md index a003f56ed..cc5ca7d0c 100644 --- a/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md +++ b/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md @@ -9,13 +9,13 @@ class 成员是否 `final` 决定调用方走 dispatch thunk 还是直接符号 ## 关键设计决策 -**核心不是新解析,是停止丢弃已解析的数据。** stored `var` 的 accessor 符号组早就在 `DefinitionBuilder.variables` 里完成了 method descriptor / vtable slot 解析,只是被 `fieldNames` 去重整组扔掉(避免属性打印两次)。实现把它改成 `variablesProduct`,被抑制的组以 `storedPropertyAccessorsByFieldName` 交还,`TypeDefinition.index` 将其折回 `FieldDefinition.accessors`——`final` 判定、stored var 的 vtable 注释、lazy 的访问器类型三件事都吃这一份数据。 +**核心不是新解析,是停止丢弃已解析的数据。** stored `var` 的 accessor 符号组早就在 `MemberDefinitionBuilder.variables` 里完成了 method descriptor / vtable slot 解析,只是被 `fieldNames` 去重整组扔掉(避免属性打印两次)。实现把它改成 `variablesProduct`,被抑制的组以 `storedPropertyAccessorsByFieldName` 交还,`TypeDefinition.index` 将其折回 `FieldDefinition.accessors`——`final` 判定、stored var 的 vtable 注释、lazy 的访问器类型三件事都吃这一份数据。 -**join key 必须剥掉 `Tu` 的 `.asyncFunctionPointer` 标记(`memberJoinKey`,OverrideSymbolMatcher.swift)。** async 方法的 method descriptor 的 `implementation` 指向 async-function-pointer 常量(`Tu` 符号),其 demangled 树是 `global([asyncFunctionPointer, function(...)])`,而成员符号树是 `global([function(...)])`——按整树结构键 join 永远 miss。这个 miss 在本提案之前就存在(表现为 async 成员没有 vtable 注释、async override 丢 `override` 关键字,都不显眼),`final` 标记让它变成「被子类 override 的方法被标 `final`」的显性错误才被抓到。剥标记后三个症状一起修复。**下次给 join 加新符号形态时,先想它是不是又一个 wrapper-marker 形态**(`needsSkipFirstNodeKinds` 里的 `.asyncSuspendResumePartialFunction`、`.mergedFunction` 是同族;merged function 已由 DefinitionBuilder 的专门去重处理)。 +**join key 必须剥掉 `Tu` 的 `.asyncFunctionPointer` 标记(`OverrideSymbolMatcher.memberJoinKey`)。** async 方法的 method descriptor 的 `implementation` 指向 async-function-pointer 常量(`Tu` 符号),其 demangled 树是 `global([asyncFunctionPointer, function(...)])`,而成员符号树是 `global([function(...)])`——按整树结构键 join 永远 miss。这个 miss 在本提案之前就存在(表现为 async 成员没有 vtable 注释、async override 丢 `override` 关键字,都不显眼),`final` 标记让它变成「被子类 override 的方法被标 `final`」的显性错误才被抓到。剥标记后三个症状一起修复。**下次给 join 加新符号形态时,先想它是不是又一个 wrapper-marker 形态**(`needsSkipFirstNodeKinds` 里的 `.asyncSuspendResumePartialFunction`、`.mergedFunction` 是同族;merged function 已由 MemberDefinitionBuilder 的专门去重处理)。 **`@objc` 且无 descriptor ⇒ `@objc dynamic`,绝不标 `final`。** `@objc dynamic` 成员经 objc_msgSend 派发,没有 vtable 条目,但完全可覆写——按裸判据必然误标。模型路径在 `applyThunkAttributes` 之后标记并按 `attributes.contains(.objc)` 排除(这决定了标记块必须排在 thunk 归因之后、`orderedMembers` 构建之前——OrderedMember 持有值拷贝,晚了改不动);dump 路径用 thunk 成员名集合做同样的排除。非 dynamic 的 `@objc` 成员有 Swift vtable 条目,本来就被 descriptor 判据排除,不受影响。 -**证据门是四层的,宁缺勿错。** (a)只有非 actor class 且 `vTableDescriptorHeader != nil` 才可能标记——actor 不可子类化,没 header 的类与 final class 不可分;(b)stored 属性还要求 accessor 组确实 join 上(`accessors.isEmpty` ⇒ 不标——符号被 strip 时缺席不是证据);(c)`@objc` 排除如上;(d)**`Tq` method-descriptor 符号作负证据**——成员名存在 `Tq` 符号即证明 vtable 条目在场,绝不标 `final`,无论地址 join 说什么。(d)是在真实二进制上抓到的:SourceEditor 把 1128 个空实现 ICF 折叠到同一地址(`SourceEditorView.elide` 等五个类成员在内),descriptor→implementation-symbol 的地址 join 在这种地址上配不上对,函数没有 accessor-join 那样的门,全体误标 `final`;而 `Tq` 是每成员一个、地址唯一的数据符号,不受折叠影响。函数与属性按成员名匹配(重载中任一带 `Tq` 即全组不标——保守方向);下标共名,按 `.subscript` 子树的结构键精确匹配(与 `DefinitionBuilder.subscripts` 的分组键同一抽取,第一版「任一下标 `Tq` 即全部不标」把 fixture 里合法的 `final subscript` 一起挡了)。任何一层不满足都静默降级为不打 `final`。回归钉死在 `FinalKeywordICFRegressionTests`(环境门控于 Xcode 的 SourceEditor 在场)。 +**证据门是四层的,宁缺勿错。** (a)只有非 actor class 且 `vTableDescriptorHeader != nil` 才可能标记——actor 不可子类化,没 header 的类与 final class 不可分;(b)stored 属性还要求 accessor 组确实 join 上(`accessors.isEmpty` ⇒ 不标——符号被 strip 时缺席不是证据);(c)`@objc` 排除如上;(d)**`Tq` method-descriptor 符号作负证据**——成员名存在 `Tq` 符号即证明 vtable 条目在场,绝不标 `final`,无论地址 join 说什么。(d)是在真实二进制上抓到的:SourceEditor 把 1128 个空实现 ICF 折叠到同一地址(`SourceEditorView.elide` 等五个类成员在内),descriptor→implementation-symbol 的地址 join 在这种地址上配不上对,函数没有 accessor-join 那样的门,全体误标 `final`;而 `Tq` 是每成员一个、地址唯一的数据符号,不受折叠影响。函数与属性按成员名匹配(重载中任一带 `Tq` 即全组不标——保守方向);下标共名,按 `.subscript` 子树的结构键精确匹配(与 `MemberDefinitionBuilder.subscripts` 的分组键同一抽取,第一版「任一下标 `Tq` 即全部不标」把 fixture 里合法的 `final subscript` 一起挡了)。任何一层不满足都静默降级为不打 `final`。回归钉死在 `FinalKeywordICFRegressionTests`(环境门控于 Xcode 的 SourceEditor 在场)。 **final class 的成员会获得成员级 `final`,这是接受的行为而非 bug。** final class 因 designated init 的 vtable 条目仍带 vtable header(实测 `Enums.SinglePayloadBoxClass`),门挡不住它。类级 `final` 没有 ABI 位(ClassMemberKeywordRecovery.md 查证过),成员级标记如实反映「无动态派发条目」,对重建场景的链接语义恰好正确;输出比源码啰嗦(源码里 final class 的成员不写 `final`),但诚实。 @@ -26,14 +26,14 @@ class 成员是否 `final` 决定调用方走 dispatch thunk 还是直接符号 ## 模块结构 ``` -Sources/Declaration/SwiftDeclaration/Components/ -├── Definitions/FieldDefinition.swift # + accessors / accessorTypeNode / isFinal / hasVTableAccessor -├── Definitions/VariableDefinition.swift # + isFinal(Function/Subscript 同形) -├── Definitions/TypeDefinition+Indexing.swift # 主干:折回 accessor 组 -├── Definitions/TypeDefinition+ClassDispatch.swift # 证据门 → ClassDispatchLookups.canRecoverFinalMembers -├── Definitions/TypeDefinition+FinalRecovery.swift # final 标记块与它的四道门 -├── Building/DefinitionBuilder.swift # variables → variablesProduct(交还被抑制的 accessor 组) -└── Building/OverrideSymbolMatcher.swift # + memberJoinKey(Tu 标记剥离) +Sources/Declaration/SwiftDeclaration/ +├── Model/Members/FieldDefinition.swift # + accessors / accessorTypeNode / isFinal / hasVTableAccessor +├── Model/Members/VariableDefinition.swift # + isFinal(Function/Subscript 同形) +├── Indexing/TypeDefinition/TypeDefinition+Indexing.swift # 主干:折回 accessor 组 +├── Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift # 证据门 → ClassDispatchLookups.canRecoverFinalMembers +├── Indexing/TypeDefinition/TypeDefinition+FinalRecovery.swift # final 标记块与它的四道门 +├── Indexing/Building/MemberDefinitionBuilder.swift # variables → variablesProduct(交还被抑制的 accessor 组) +└── Indexing/Building/OverrideSymbolMatcher.swift # + memberJoinKey(Tu 标记剥离) Sources/Output/SwiftPrinting/ ├── SwiftDeclarationPrinter+Members.swift # printThrowingField:final 关键字 + fieldTypeNode 取型 ├── SwiftDeclarationPrinter+Headers.swift # renderModelFields:stored var 的 vtable 注释 diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index 798226fc6..c286c56b8 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -30,7 +30,7 @@ CI 上可复现性是唯一判据: `MachOFileName.SymbolTestsCore` 存的是相对路径 `../../Tests/Projects/SymbolTests/DerivedData/...`,**不是**对 CWD 解析,而是对 -`Sources/TestSupport/MachOTestingSupport/Extensions.swift` 的 `#filePath` 解析——`../../` 爬回仓库根再下行。 +`Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift` 的 `#filePath` 解析——`../../` 爬回仓库根再下行。 而构建端 `xcodebuild -derivedDataPath Tests/Projects/SymbolTests/DerivedData` 是对 `xcodebuild` 自己的 CWD 解析。两者对齐**当且仅当**构建从仓库根发起——任何从子目录跑 `xcodebuild` 的 CI 步骤都会悄悄打破对齐。CI 还遇到过第三种形态:runner 上 `xcodebuild` diff --git a/Documentations/Internal/InterfaceHeaderAndExportStatusAnnotations.md b/Documentations/Internal/InterfaceHeaderAndExportStatusAnnotations.md index bd31ff984..1e81b7b55 100644 --- a/Documentations/Internal/InterfaceHeaderAndExportStatusAnnotations.md +++ b/Documentations/Internal/InterfaceHeaderAndExportStatusAnnotations.md @@ -7,7 +7,7 @@ 三件事,一个共同契约(两个 flag 默认关,默认输出字节不变): -1. **导出集**(`MachOSymbols`):`SymbolIndexStore.Storage` 在构建扫描的 export trie 循环里旁路收集导出事实,公开 `isExported(name:in:)` 与 `isExportedIncludingDerivedSymbols(name:in:)`。 +1. **导出集**(`SwiftSymbols`,采集在 MachOKitExtensions 的 `MachOSymbols`):`SwiftSymbolIndexStore.Storage` 持有构建扫描在 export trie 循环里旁路收集的导出事实,公开 `isExported(name:in:)` 与 `isExportedIncludingDerivedSymbols(name:in:)`。 2. **头部组件**(`SwiftPrinting`):`InterfaceHeaderInfo`(纯值)+ `InterfaceHeaderBlock`(public 组件)+ 从 `MachORepresentableWithCache` 读事实的工厂。CLI 经 `--emit-header` 接线(interface 走 `SwiftInterfaceBuilderConfiguration.interfaceHeaderInfo`,dump 在首个声明前打一次);RuntimeViewer 的 per-type 导出可独立调用组件。 3. **`// not exported` 标注**:interface 的 `renderMember` 与 dump 三个 Dumper 的 member-symbol 循环,`--emit-export-status` 门控。 @@ -46,7 +46,7 @@ issue #106 作者的验证法是「该成员的**任何**符号在导出表零 修正后的 dump 侧豁免(`ClassDumper` 专属——struct/enum 成员无 override 无 `@objc`)不依赖模型,从符号层面直接判定: - **override**:`methodOverrideDescriptors` + `methodDefaultOverrideDescriptors` 的 implementation 符号名集合(`collectOverrideImplementationSymbolNames()`,仅 flag 开启时收集),成员区同名符号跳过标注。 -- **`@objc`**:`@objc` 成员的 ObjC 入口是实现符号名追加 `To` 后缀,查 `SymbolIndexStore.containsSymbol(named: name + "To")`(一次 permutation 二分)即可识别,无需 demangle。 +- **`@objc`**:`@objc` 成员的 ObjC 入口是实现符号名追加 `To` 后缀,查 `SwiftSymbolIndexStore.containsSymbol(named: name + "To")`(一次 permutation 二分)即可识别,无需 demangle。 `methodDescriptorMemberSymbols`(`[Method]` 区)的行是 `Tq` 数据符号,查询前**剥掉 `Tq` 后缀**再走派生形态扩展——对 `…Tq` 名字追加 `Tj`/`Tu` 得到的 `…TqTj` 等从不存在,等于退化回本提案自己否掉的裸名查询。实证注:SourceEditor 与 fixture 上「`Tq` local 而成员任何形态导出」的组合均为空集(`Tq` 的导出跟随成员的 public-ness),所以修复前无假阳性实证——但该伴随性质无任何规范保证(`-exported_symbols_list` 手工导出清单即可打破),修复以正确性为准。「修复前失败」形态的复现测试因此不可构造(需要非常规导出清单的 fixture,不值得为此扩展 fixture 矩阵),守护测试钉的是修复后的行为不变性。 @@ -81,7 +81,7 @@ issue #106 作者的验证法是「该成员的**任何**符号在导出表零 ## 测试地图 -- `ExportedSymbolFactsTests`(MachOSymbolsTests):全量 trie 名 sweeping、本地符号阴性、thunk-only public 成员经派生查询转阳、internal 合成 init 全形态阴性、非 nil 契约。 +- `ExportedSymbolFactsTests`(SwiftSymbolsTests):全量 trie 名 sweeping、本地符号阴性、thunk-only public 成员经派生查询转阳、internal 合成 init 全形态阴性、非 nil 契约。 - `InterfaceHeaderTests`(SwiftInterfaceTests):逐行渲染、字段省略、`not detected` 措辞、日期缺席字节稳定、工厂读 Mach-O 事实、`printRoot` 接线 + 默认无头部。 - `ExportStatusAnnotationTests`(SwiftInterfaceTests):三类假阳性各一钉(thunk-only public / `@objc` / `override`),每条负向断言配 store 层正向前提(先证成员确实全形态 trie-miss / thunk-only,「未标注」才必然是豁免的功劳而非 fixture 偶然);true positive 限定在 `AsyncIterator` 块内按精确 trim 行匹配;默认输出零标注。 - `ExportStatusDumpAnnotationTests`(SwiftDumpTests):dump 侧两类假阳性的复现钉(override 实现符号 / `@objc dynamic`,修复前的标注输出留档在任务报告)、`Tq` 行 true positive 保持、默认零标注。 diff --git a/Documentations/Internal/LargeStackTaskExecutorAdoption.md b/Documentations/Internal/LargeStackTaskExecutorAdoption.md index 2e3f185f6..790c4ee78 100644 --- a/Documentations/Internal/LargeStackTaskExecutorAdoption.md +++ b/Documentations/Internal/LargeStackTaskExecutorAdoption.md @@ -113,7 +113,7 @@ release 二进制,宿主 dyld cache(macOS 26.5.2,10 核 Apple Silicon) ## 测试锚点 -- `LargeStackTaskExecutionTests`(MachOSymbolsTests):执行器线程栈 ≥ 16 MB 且线程名前缀 `swift-demangling.task-executor.`;`execute` / `executeAsync` 在体内不跳线程;嵌套 `run` 不换线程;子任务继承;`isEnabled = false` 时留在调用线程;值与错误透传。 +- `LargeStackTaskExecutionTests`(SwiftSymbolsTests):执行器线程栈 ≥ 16 MB 且线程名前缀 `swift-demangling.task-executor.`;`execute` / `executeAsync` 在体内不跳线程;嵌套 `run` 不换线程;子任务继承;`isEnabled = false` 时留在调用线程;值与错误透传。 - `BoundedConcurrentMapTests`(SwiftInterfaceTests):源序、窗口不超、窗口 1 严格串行、窗口内真并发(rendezvous,超时即失败)、首错语义、空输入。 - `SwiftEvolutionInterfaceBuilderTests.parallelPreparationMatchesSerialPreparation` / `preparationWindowIsClampedNotValidated`。 - `DiffCommandValidationTests` / `EvolutionCommandValidationTests`:`--jobs` 解析与下界校验。 diff --git a/Documentations/Internal/Modules/CrossReferenceAnalysis.md b/Documentations/Internal/Modules/CrossReferenceAnalysis.md index a676abb7b..09e529e23 100644 --- a/Documentations/Internal/Modules/CrossReferenceAnalysis.md +++ b/Documentations/Internal/Modules/CrossReferenceAnalysis.md @@ -1,23 +1,60 @@ # CrossReferenceAnalysis -从 arm64 机器码里读出一个镜像的函数表,以及每个函数引用了什么:直接调用与尾调用、ObjC 消息发送、`super` 发送、经桩的跨库调用、间接调用、ObjC 类引用、Swift 类型引用。只在进程内读 `MachOImage`,只支持 arm64 / arm64e。RuntimeViewer 的交叉引用功能(调用者、被调、类型引用)建在它上面。 +从 arm64 机器码里读出一个镜像的函数表,以及每个函数引用了什么:直接调用与尾调用、ObjC 消息发送、`super` 发送、经桩的跨库调用、间接调用、ObjC 类引用、Swift 类型引用。读进程里加载的 `MachOImage`,也读磁盘上的 dyld shared cache 文件与独立 Mach-O 文件(「文件模式」一节),只支持 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。 +- 提案:[0072-cross-reference-analysis](../../Evolutions/0072-cross-reference-analysis.md)(本库这一层)、[0076-objc-runtime-send-entry-points](../../Evolutions/0076-objc-runtime-send-entry-points.md)(libobjc 的发送入口);整体设计、实测数据在 RuntimeViewer 的 [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)。 +- 依赖:MachOKit、MachOKitExtensions 的 `ARM64InstructionDecoding` 与 `MachOCodeReferences`(核心层)、MachOObjCSection 的 `ObjCCodeReferences`(ObjC 层);第二批起还有 `MachOObjCSection`(方法表、类的只读数据)、`MachOSwiftSection` 与 `SwiftInspection`(Swift 元数据与 `SymbolicDemangler`)、`Demangling`——给符号表没有名字的函数起名,以及认出扫描碰到的类与类型(类列表、类型描述符、mangled 名字)。不依赖 Capstone。 + +## 三层与识别器 + +交叉引用分成三个模块,依赖从上到下(提案 [0097-offline-cross-references-and-symbolication](../../Evolutions/0097-offline-cross-references-and-symbolication.md) 第 2 步在本库里拆开,提案 [0098 move-cross-reference-layers](../../Evolutions/0098-move-cross-reference-layers.md) 把下两层搬去各自的落脚处)。三层的代码一起演进,这份文档是它们的总说明;两个下层仓库里的实现说明只讲各自的边界与测试: + +- **`MachOCodeReferences`**(核心层,在 MachOKitExtensions,原名 `CrossReferenceCore`,[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md)):读取层、镜像集 `CodeImageSet`(镜像、路径、内存区间、按镜像缓存的函数表、链接关系与改名再导出)、函数表、指令扫描与寄存器跟踪、按导入名与链接关系预筛、导出表起名,以及识别器扩展点。不认识任何一种语言:源码里不许出现 `objc_` / `swift_` 开头的字面量(MachOKitExtensions 的 `SourceScanTests`)。离线的地址空间、桩链与槽解析在同包的 `MachOAddressResolution`(原 `CodeAddressResolution`,[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOAddressResolution.md)),手写的 A64 解码在 `ARM64InstructionDecoding`([实现说明](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/ARM64InstructionDecoding.md))。 +- **`ObjCCodeReferences`**(ObjC 层,在 MachOObjCSection,原名 `CrossReferenceObjC`,[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/next/Documentations/Internal/ObjCCodeReferences.md)):`objc_msgSend` 系列与 libobjc 专用入口、`__objc_stubs` 与 cache 共用 selector 桩的含义、selector 与接收者、classref / superref / 类对象、ObjC 方法列表起名、按 selector 与类预筛、libobjc 的运行时辅助函数名单。 +- **`CrossReferenceAnalysis`**(Swift 层兼门面,留在本库):Swift 元数据访问器、值类型元数据、mangled name、Swift 类型查询与 Swift 元数据起名、Swift 运行时的辅助函数名单;`CrossReferenceAnalyzer` 把三层拼起来,持有全部公开模型,`@_exported import` 两个下层模块,所以 `import CrossReferenceAnalysis` 照旧看得到 `CodeLocation`、`ReceiverClassHint` 这些下移的类型。下层的其余接口都是 `@_spi(Internals) public`,不经 `@_exported` 漏出去,门面与测试按文件 `@_spi(Internals) import`。 + +**识别器怎么接进扫描。** 核心层定义 `CodeReferenceRecognitionSession` 与 `CodeReferenceRecording` 两个 SPI 协议(`MachOCodeReferences` 的 `Recognition/CodeReferenceRecognition.swift`)。门面每次扫描为 ObjC 层、Swift 层各建一个会话,排成一列交给核心的 `ReferenceScanner`,核心只在五个时机问它们:进入函数(ObjC 会话在 `x0` 打「方法接收者」标记,`RegisterFile` 的标记位是通用的)、解析只有会话认得的调用目标(`__objc_stubs`)、调用点、算出地址、读槽。为了不拖慢扫描:每个不同的调用目标只问一次各会话的角色(`role(of:)`,结果记在扫描器的调用计划里),没有角色的调用——绝大多数——不经过任何会话;地址与槽按地址记住是哪个会话认领的,没人认领的下次直接跳过。会话产出的引用不经核心转手,记到各层的记录协议上,门面里的 `ReferenceCollector` 实现全部三个,造出公开的 `CodeReference` 并按查询的键过滤。 + +**按镜像的缓存挂在函数表上。** 各层按镜像读的东西作为函数表的「附件」(`ImageFunctionTable.attachment(_:makingIt:)`):核心层的导出表名字 `ExportedFunctionNames`、ObjC 层的节范围 `ObjCImageSections` 与方法名 `ObjCMethodNames`、Swift 层的元数据名字 `SwiftMetadataNames`,随表一起留下或释放,`approximateByteCount` 把它们算进表里。类索引与 Swift 类型索引仍由各层的识别器按镜像记住。 + +## 文件模式 + +`CrossReferenceAnalyzer(dyldCache:)` 读一个 cache 文件里的全部镜像(归档的、别的设备的),`CrossReferenceAnalyzer(machOFiles:)` 读一组独立文件(一个 app 的主程序与它自带的框架),公开 API 与进程内一样(提案 [0097-offline-cross-references-and-symbolication](../../Evolutions/0097-offline-cross-references-and-symbolication.md) 第 4 步)。 + +- **镜像与 `__LINKEDIT`**:每个镜像是一个 `CodeImage`,`reader` 是 `MachOImage` 或 `MachOFile`;两种读取器的差别——slide(进程内是镜像的 slide,cache 文件里是 0)、MachOSwiftSection / MachOObjCSection 给出的 offset 落在哪个地址——只在构造它的地方定一次。符号表、间接符号、函数起点、data in code、导出树一律由 `ImageLinkEdit` 按「`__LINKEDIT` 的地址 + 表的偏移 − 段的文件偏移」经读取层读,进程内与文件里是同一个算法;镜像自带的桩按 `S_SYMBOL_STUBS` 的 `reserved1/2` 逐个读字节、按形状认。 +- **读取器专属的 API**:MachOObjCSection 的类、方法表与 MachOKit 的 objc 桩是各读取器一套,ObjC 层经 `asMachOImage` / `asMachOFile` 分两条路读;文件里方法的 `imp` 是读取器 offset,进程内是运行时地址,类在文件里从不 realize。Swift 层经 `MachOSwiftSectionRepresentableWithCache` 泛型读描述符;文件里的 mangled name 经文件的读取上下文解(进程内照旧经 `InProcessContext`)。 +- **地址**:cache 文件里地址就是未滑动地址。一组独立文件按 dyld 的做法错开:与已放下的重叠就滑到其后的下一个 MB 边界(多数框架链接在 0,所以除第一个外都会滑),对外的 `CodeLocation` 仍是各文件自己的地址。 +- **`FileCrossReferenceMemory`**:字节取自 MachOKit 打开文件时的映射(`fileBytes`)。cache 的槽按 mapping 预取的 slide info 解,v5(macOS 14 / iOS 17 起的 arm64e cache)在读取层里直接解,没有 slide info 的(模拟器 cache)与其余版本交给 MachOKit。独立文件的槽经 `SlotResolver`:bind 落到所覆盖文件导出的同名符号上(self-bind 即落到自己),没有就是导入名;链式 fixup 的 rebase 是「`__TEXT` 地址 + 偏移」;没有链式 fixup、靠 opcode rebase 的旧文件,槽里本来就是地址。按名字查,不分 bind 指名的是哪个库。 +- **读取层是值,不持有存储**:经 `any CrossReferenceMemory` 的每次读都复制一次读取层,类或持有引用的值每次复制都要计一次数——第一版这样写,整 cache 建表比进程内慢 6 倍以上。现在它以 `unowned(unsafe)` 引用存储,存储由镜像集持有,读取层只在镜像集活着时有效。 +- **只给一个 app 时的缺口**:经 GOT 槽读别的镜像的类、ivar 或数据,槽里是 bind,眼下不记任何引用(进程内会记成类引用),补在第 5 步;调用照常记成导入符号,`_objc_msgSend` / `_objc_msgSendSuper2` 按名字认成发送。一个 app 连同系统 cache 一起分析还不支持。 + +## 引用种类与路线 + +提案 [0097-offline-cross-references-and-symbolication](../../Evolutions/0097-offline-cross-references-and-symbolication.md) 第 5 步加了三种目标、对导入符号的数据引用,以及每条引用的「路线」。 + +- **ivar**:`.objectiveCInstanceVariable(className:name:)`。代码经 `adrp; ldrsw`(或 ld64 改写出的字面量 `ldrsw`、Swift 的 64 位 `ldr`)读 `__objc_ivar` 里的偏移变量;ObjC 会话把这个节作为「观察的槽」,核心在 32 位与 64 位载入时都问它。名字先取 `_OBJC_IVAR_$_<类>.<变量>` 符号,没有符号再从类的 ivar 列表反查(列表项的第一个字段指向偏移变量,第二个是名字),在 ObjC 层的附件 `ObjCInstanceVariableNames` 里,第一次碰到时读。父类是 `NSObject` 的类,clang 直接用常量偏移,不经偏移变量;Swift 类经 ObjC ivar 列表登记的偏移变量是 `__data` 里的 Swift 字段偏移全局量,不在 `__objc_ivar`,眼下不收。 +- **字符串**:`.cString(String)`(`adrp; add` 或 `adr` 落进 C 字符串节——`__cstring`、`__objc_methname`、`__oslogstring` 等 `S_CSTRING_LITERALS` 节)与 `.constantString(String)`(落进 `__cfstring`,按 `{ isa, flags, characters, length }` 读,`flags & 0x10` 是 UTF-16)。核心层认,默认不记:分析器用 `recordingStringReferences: true` 打开(`recordsStringReferences`),查询里含 `.cString` / `.constantString` 键时那次扫描也会找。减法算出的地址从不当作字符串:Swift 的大字符串字面量是 `adrp; add; sub #0x20`,`add` 已经指到字符串起点,`sub` 之后的地址会落进前一个字符串中间。 +- **对导入符号的数据引用**:从引用槽(GOT 等)读到一个 bind,而它绑到的符号不在分析器覆盖的镜像里——只给一个 app 时读 `_OBJC_CLASS_$_CALayer`、ivar、全局量都是这样——记成 `.importedSymbol(name:)`、`kind == .reference`。进程内槽里都是地址,不会出现。查一个类的全部引用时,调用方还要查 `_OBJC_CLASS_$_<类>` 这个导入名。 +- **路线**:`CodeReference.route`(`CodeReferenceRoute`,核心层定义)说明这条引用是怎么到达目标的,不说明目标是什么。`direct`(`bl` / `b` 直达)、`imageStub`(本镜像的 `__stubs`、`__auth_stubs`、`__objc_stubs`)、`stubIsland`(cache 镜像之间的 stub island,可多跳)、`cacheSharedStub`(macOS / iOS 27 整个 cache 共用的 selector 桩与 GOT 桩)、`pointerSlot`(经指针槽载入:GOT、ObjC 引用节、ivar 偏移变量)、`addressMaterialization`(`adrp; add` 或 `adr` 算地址)、`literalLoad`(字面量 `ldr`)、`indirect`(经寄存器的调用与跳转,认证与否看证据)。调用的路线由 `CallTargetResolver.resolveWithRoute(_:)` 给出,经多跳时取第一种跳板;会话认领的目标按地址落在哪定(本镜像代码直达、本镜像其他节经本镜像桩、镜像之外经 cache 共用桩)。常驻索引把路线存在每条记录 `flags` 的第 5–7 位。 + +## 地址符号化 + +`symbolication(of:)` 回答「这个未滑动地址是什么」(第 6 步):在哪个镜像、段与节,以及在那里的意思——函数体里(起点、名字、偏移;名字的来源与 `functions(inImageAt:)` 相同,含 ObjC 方法表与 Swift 元数据的后备名)、桩或跳板(经过的每一跳与最终目标)、指针槽(种类与里面装的东西)、字符串、最近的符号加偏移、映射着但什么都不是(`.data`),或没有映射。核心层的 `AddressPlace`(MachOKitExtensions 的 `MachOCodeReferences/Symbolication/`)判断结构:先找镜像(按各镜像用到的 slide 逐一试,cache 优先),再看节——`__text` 是函数,`S_SYMBOL_STUBS` 是本镜像的桩(经 `CallTargetResolver` 解目标),镜像之间的可执行映射是跳板链(逐跳读 `ARM64Trampoline`),GOT、懒指针与语言层报上来的引用节是槽(经读取层解槽),C 字符串节与 `__cfstring` 是字符串,其余给最近的符号。门面再补语言层知道的:`__objc_stubs` 的 selector、槽里的类与 Swift 类型、selector 引用的 selector、protocol 引用的名字、`__objc_ivar` 的 ivar。一组独立文件各留自己的地址,两个文件都有的地址取第一个,`symbolication(of:inImageAt:)` 指定镜像。符号化用留存的函数表:地址很少只问一个。 ## 子系统 | 子系统 | 文件 | 分工 | |---|---|---| -| 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()` 让宿主在后台单线程预先读好链接关系与改名再导出表 | +| 0. 读取 | Core `Memory/CrossReferenceMemory`、`Memory/InProcessCrossReferenceMemory` | 分析器读镜像内存的唯一入口:按分析器地址空间里的地址取一段只读字节、问一个指针槽里装着什么(`slotContent(at:)`,去掉签名与标记位)、给出地址掩码;整段读槽与把一组地址换成指针各有批量接口(selector 预筛按块读,不再每个槽一次 existential 调用)。进程内实现直接读本进程内存,槽里是 dyld 已绑定的值;`Memory/FileCrossReferenceMemory` 读文件,在槽上解 fixup(「文件模式」一节)。三个模块里只有进程内实现那一个文件允许把地址变成指针(`MemoryAccessScanTests`) | +| 1. 指令字与跳板 | MachOKitExtensions 的 `ARM64InstructionDecoding` 模块的 `ARM64InstructionWord`、`ARM64Trampoline` | 手写读取少数几类 A64 编码;按形状认 GOT 桩、stub island 与全缓存共用的 selector 桩。与 SwiftThunkAnalysis 共用 | +| 2. 地址空间 | Core `Images/CodeImageSet`、`Images/CodeImage`(含 `ImageLinkEdit`);门面 `CrossReferenceAnalyzer` | 进程里全部镜像(整个共享缓存加缓存外已加载的镜像),或一个 cache 文件、一组独立文件的镜像;各镜像的路径与安装名、`__TEXT` 的内存区间、缓存的可执行与可读映射、运行时库里的辅助函数位置;给函数起名要用的函数表按需建一次并记住。宿主可以预先读好一个镜像起名、查类、查类型要用的一切(`prepareNames(inImageAt:)`),放掉其余镜像的(`releaseImageData(exceptForImagesAt:)`),并估算一个镜像留着多少(`approximateByteCount(ofImageDataAt:)`,`Scanning/ApproximateSize`) | +| 3. 函数表 | Core `Scanning/ImageFunctionTable` | 函数起点(`LC_FUNCTION_STARTS` 与 `__text` 里的符号取并集)、主名与代码合并留下的别名、辅助函数(名单由两个语言层给)、镜像自带的 `__stubs` / `__auth_stubs`、GOT、各段的地址区间;各层的附件 | +| 3a. 补充名字 | Core `Scanning/ExportedFunctionNames`、ObjC `ObjCMethodNames`、Swift `Scanning/SwiftMetadataNames`;门面 `codeFunction(at:in:)` | 符号表没有名字的函数,依次从导出表、ObjC 方法表、Swift 元数据起名;起名时按镜像按需读,扫描不读 | +| 3b. 类索引 | ObjC `ObjectiveCClassIndex`、`ObjCImageSections` | 一个镜像定义的类与元类,按地址;直接读 `__objc_classlist` 与各类的 `isa`。扫描时按需建、ObjC 识别器记住;类名只在报出引用时读。`ObjCImageSections` 是镜像的 `__objc_stubs`、selref、classref 与 superref | +| 3c. 类型索引 | Swift `Scanning/SwiftTypeIndex` | 一个镜像 `__swift5_types` 列出的描述符与各自的元数据访问器;类型的 key 按需算,优先取 `…Mn` 符号;按 key 找类型时只算描述符名字相同的那几个 | +| 4. 扫描 | Core `Scanning/ReferenceScanner`(含 `CallTargetResolver`)、`Scanning/RegisterFile`、`Recognition/`;ObjC `ObjCCodeReferenceRecognizer`;Swift `Scanning/SwiftCodeReferenceRecognizer`;`ObjCRuntimeHelperNames`、`Scanning/SwiftRuntimeHelperNames` | 逐条解码、跟踪寄存器、解析调用目标(核心);发送与类引用(ObjC 会话);Swift 类型引用(Swift 会话) | +| 5. 结果 | `Models/*`(`CodeLocation`、`CodeReferenceKind`、`IndirectCallEvidence` 在核心层,`ReceiverClassHint` 在 ObjC 层) | `CodeLocation`、`CodeFunction`、`CodeReference`、`CodeReferenceTarget`、按目标分组的 `CodeReferenceTable`,以及给宿主常驻用的紧凑版 `CodeReferenceIndex` | +| 6. 预筛与过滤 | Core `Images/CodeImageSet+Linkage`、`Scanning/RenamedReexportIndex`;ObjC `ObjCCodeReferenceRecognizer+Prefiltering`;门面 `CrossReferenceAnalyzer+Prefiltering`、`+Linkage`、`references(to:inImageAt:)` | 按未定义符号(只对 C 与 ObjC 符号,连同别的镜像改名再导出的名字)、链接关系(Swift 符号)、`__objc_selrefs`、类对象上的符号筛出可能引用某个符号、selector 或类的镜像;扫描时只留命中的引用;`preparePrefilters()` 让宿主在后台单线程预先读好链接关系与改名再导出表 | | 7. 类型查询 | `CrossReferenceAnalyzer+SwiftTypes` | Swift 类型的身份、预筛与按类型的扫描;`SwiftTypeQuery` 比对描述符位置与名字里的符号引用 | ## 关键契约 @@ -28,7 +65,7 @@ **镜像的路径是 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 的偏移」不符;当成偏移再加一次基址,会得到范围外的地址、整张表被滤空。 +函数起点由 `ImageLinkEdit` 自己解 `LC_FUNCTION_STARTS`:ULEB128 增量从 `__TEXT` 的 vmaddr 起算,得到的就是未滑动地址。(以前经 MachOKit 在内存镜像上读,它给的 `FunctionStart.offset` 已经是绝对地址,与文档注释「相对 mach header 的偏移」不符,当成偏移再加一次基址会整张表被滤空。) ### 两种桩布局 @@ -36,20 +73,49 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 | 缓存 | ObjC 消息 | 跨库调用 | |---|---|---| -| macOS 15 至 26、iOS 26 及更早的真机,以及 Simulator | 镜像自己的 `__objc_stubs`(经 MachOKit `objcStubs(in:)` 读 selector 引用) | 镜像自己的 `__stubs` / `__auth_stubs`(MachOKit `stubs(in:)` 给出槽位) | +| macOS 15 至 26、iOS 26 及更早的真机,以及 Simulator | 镜像自己的 `__objc_stubs`(经 MachOKit `objcStubs(in:)` 读 selector 引用) | 镜像自己的 `__stubs` / `__auth_stubs`(MachOKit `stubs(in:)` 给出槽位;它读不出的 ld64 改写形态由 `ARM64Trampoline` 补读,见「链接器改写过的代码」) | | 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 槽在进程内已经绑定,读出指针、去掉指针认证位就是目标;读之前先确认槽位落在缓存的映射里。 +**去掉哪些位按平台定。** 从进程内存读出的指针(GOT 槽、selector 引用、类列表与 `isa`、Swift 类元数据 +0x40 与值类型元数据 +8 的描述符)一律经读取层的 `slotContent(at:)` / `pointer(at:)`,进程内用 `InProcessContext.addressMask`,即 MachOKitExtensions 按镜像平台给的 `vmaddrMask`。Mac 的用户地址是 47 位,iPhone 等真机是 36 位,arm64e 的签名从地址宽度之上开始,iPhone 上从第 39 位开始。0.24.0 在六处写死了 Mac 的 47 位掩码,在 iOS、tvOS、watchOS、visionOS 真机上会把签名的第 39–46 位留在地址里,带签名的槽位全都跟不过去(第二轮审查 N1);`AddressMaskScanTests` 扫遍库的源码,不许再出现这种常量。 + 不经桩、直接 `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]` 的调用者时发现。 +### libobjc 的发送入口(提案 [0076-objc-runtime-send-entry-points](../../Evolutions/0076-objc-runtime-send-entry-points.md)) + +clang 把一部分发送编成对 libobjc 专用入口的调用:`[[Foo alloc] init]` 是 `objc_alloc_init(Foo)`,`[Foo alloc]`、`[Foo allocWithZone:nil]`、`[Foo new]` 是 `objc_alloc`、`objc_allocWithZone`、`objc_opt_new`,`[x self]`、`[x class]` 是 `objc_opt_self`、`objc_opt_class`,`[x isKindOfClass:c]`、`[x respondsToSelector:s]` 是 `objc_opt_isKindOfClass`、`objc_opt_respondsToSelector`。这样的发送不经 `objc_msgSend`,镜像里也可能没有这个 selector 的引用。macOS 26.6 的 AppKit 里 `objc_alloc_init` 有 2,488 处,按 selector 发送的 `init` 只有 720 处;`objc_opt_isKindOfClass` 3,369 处、`objc_opt_respondsToSelector` 2,977 处、`objc_opt_new` 590 处,对应的 selector 一次直接发送都没有。0.24.0 只认 `objc_msgSend`,这些都记成对 libobjc 函数的普通调用,查 `init` 的调用者漏掉约 78%,查另外几个一处都查不到(第二轮审查第 2 条)。 + +现在每处这样的调用记成它代表的发送(ObjC 层的 `MessageSendEntryPoints`): + +- 入口按 libobjc 里的位置认,经桩、GOT 或共用桩到达都算;桩跟不过去、只剩导入名时按名字认。 +- 接收者按 `x0` 判断,与 `objc_msgSend` 相同。`objc_alloc_init` 在同一条指令上记 `alloc` 与 `init` 两条发送,`init` 发给 `alloc` 返回的实例,接收者记 `.unknown`。 +- 这些调用不再同时记成对 C 函数的调用:按函数查 `_objc_alloc_init` 的调用者没有结果,按 selector 查才对,与 `objc_msgSend` 的处理一致。 +- `objc_opt_self` 调用之后 `x0` 照旧保留;`objc_opt_class` 只在 `x0` 是类对象时照旧保留(见「类引用」的类字面量接收者)。 +- `objc_retain`、`objc_release`、`objc_autorelease` 不算:ARC 插入的调用与源码里的 `[x retain]` 编出来是同一个调用,分不开,仍是运行时辅助调用。 +- selector 预筛(`imageIndices(referencingSelector:among:)`)对这几个 selector 另外留下导入或定义对应入口的镜像:只经 `objc_alloc_init` 发送 `init` 的镜像,`__objc_selrefs` 里根本没有 `init`。 + +### 链接器改写过的代码(第二轮审查) + +ld64——Xcode 14 及更早的链接器,以及 Xcode 15、16 加 `-ld_classic` 时用的那个——排好地址之后,会按编译器留下的 linker optimization hint 改写指令:槽位在一兆字节以内的 `adrp` / `ldr` 改成 `nop` / `ldr xN, <槽>`,地址在一兆字节以内的 `adrp` / `add` 改成 `adr xN, <地址>` / `nop`,懒绑定的桩改成 `nop` / `ldr x16, <槽>` / `br x16`。Xcode 26 的链接器不做这种改写,Xcode 27 不再带 `ld-classic`,Apple 自己的二进制里也没有;用旧工具链链接的第三方 App 里却常见。抽查的 12 个第三方 App 里有 2 个,其中 Asset Catalog Viewer(macOS 12 SDK)有 357 处 selector 引用和 71 处类引用以字面量 `ldr` 载入,212 个桩全是改写过的形态。 + +扫描把这些形态读成改写之前的样子: + +- 字面量 `ldr` 是从已知槽位载入(`RegisterFile.load(into:fromSlotAt:)`),载入的偏移记成槽位在页内的偏移,与改写前那对指令记下的相同。之后按槽位认 selector、类引用与 `__objc_superrefs`,与 `adrp` / `ldr` 一样。 +- `adr` 与 `adrp` / `add` 一样:算出的地址是类对象、元数据或元数据访问器时,报一处引用。`ARM64InstructionWord.addressMaterialization` 的 `isPageAddress` 区分两者,只给出页地址的 `adrp` 不报。 +- 改写过的桩,MachOKit(0.54.101)的 `stubs(in:)` 读不出槽位,给的是 `.unknown`;`ImageFunctionTable` 这时改用 `ARM64Trampoline` 读桩自己的字节,`ARM64Trampoline` 认字面量 `ldr`。SwiftThunkAnalysis 也经 `ARM64Trampoline` 认桩,同样受益。0.24.0 时这些桩只剩导入名,经它们调用 `objc_msgSend` 的发送一处也认不出来。 + +SwiftThunkAnalysis 自己的 Capstone 解码器原先也把字面量 `ldr` 当成不建模的指令,同一轮补上了 `ThunkOperation.loadFromSlot`,求值时按槽位读,与 `adrp` / `ldr` 相同。0.24.0 之前的设计判断是「缓存与几个缓存外的系统 App 里都没有这两种形态,不解码」,那次只量了 Apple 自己的二进制。 + +`LinkerOptimizationHintTests` 现编两个 dylib,按 ld64 的做法把这几种指令改写好、重新签名后加载,核对四种形态都读对;修复前四个测试都失败。 + ### 读任何目标之前先确认它可读 `__text` 里夹着数据(跳转表之类,缓存镜像的 `LC_DATA_IN_CODE` 是空的),按指令解码会得到指向任意地址的「跳转」。扫描只在目标落在某个镜像的 `__TEXT`、或缓存的可执行映射里时才去读那里的指令;读槽位前确认它在缓存或镜像的映射里。探针第一次全量扫描就崩在没做这一步上。 ### 寄存器跟踪只记确定的事 -`RegisterFile` 只记录 `adrp` / `adr` / `add` 算出的地址、从已知地址加载的槽位、ObjC 方法入口时 `x0` 里的接收者、指针认证常量,以及「这个寄存器的值是从内存读来的」和读取时的偏移。不建模的指令一律作废它写的寄存器(宁可多忘,不留陈旧的值);调用作废 `x0`–`x18` 与 `x30`——原样返回所传类的三个函数例外,`x0` 留着(见「类引用」)。PAC 与 AUT 原地签名或认证,寄存器的含义不变,保留;XPAC 作废。 +`RegisterFile` 只记录 `adrp` / `adr` / `add` 算出的地址、从已知地址加载的槽位(`ldr` 的基址算得出来,或者是字面量 `ldr xN, <槽>`)、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 的两个跟踪器同一轮补上了成对回写的基址。 @@ -63,17 +129,17 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 ### 运行时辅助调用 -`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 里找;镜像内的在该镜像的函数表里标出。结果只打标记,过滤交给宿主。 +名单分在两层维护(ObjC 层的 `ObjCRuntimeHelperNames`、Swift 层的 `SwiftRuntimeHelperNames`):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 里一处都没有,不解码。元类的引用按它的类报。 +一条指令取了某个类对象的地址、但不跳转,就是一处类引用:`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`)、缓存某个类的全局变量都不是对类的静态引用。ld64 改写出的 `adr` 与字面量 `ldr` 也按这三种取法认,见下文「链接器改写过的代码」。元类的引用按它的类报。 **一个值是不是类对象,看它所在的镜像列没列它。** 不能按所在的节判断:缓存里 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 处经它。 +**类字面量接收者。** 发送时 `x0` 里是这样取来的类,接收者记为 `.classLiteral(名字)`(AppKit 35,175 处,发送的 11%)。`objc_opt_self`、`swift_getInitializedObjCClass` 原样返回传入的参数,调用之后 `x0` 不作废:Swift 调 ObjC 类方法先过 `objc_opt_self`,SwiftUI 665 处类字面量接收者里 478 处经它。`objc_opt_class` 返回的是参数的类,只有参数本身是类对象时才等于参数:`x0` 是类字面量、或在类方法(`+[…]`)里是方法自己的接收者时照旧保留;在实例方法里,`[[self class] foo]` 的 `x0` 已是接收者的类而不是接收者,调用之后作废,接下来的发送记 `.unknown`(2026-11-16 体检第 1 条:此前一律保留,把对类方法的发送记成了发给实例,`ClassOfReceiverSendTests`)。`objc_opt_self`、`objc_opt_class` 本身也记成 `self`、`class` 发送(见「libobjc 的发送入口」)。 **super 发送的类**取同一函数里从 `__objc_superrefs` 载入的类:分类方法(`-[NSDictionary(NSKeyValueCoding) valueForKey:]` 得到 `NSDictionary`)、类方法(槽里是元类,按类报)、没有符号的方法都对;没见到这种载入就退回方法符号里的类。这一载入本身不算类引用——它是编译器实现 `super` 的方式,报出来只会让每个调 `super` 的方法都「引用」了自己的类。Swift 代码的 super 发送不经 `__objc_superrefs`,类来自 `self` 的运行时类或元数据访问器的返回值,扫描不知道,类记为空:Foundation 1,803 处 super 发送里有 374 处、AppKit 8,336 处里有 1,133 处是这种,其余都有类。 @@ -93,7 +159,7 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 **表按描述符位置归档**(`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 变体里的同一个类型按位置分开。协议没有类型描述符,不在这一批。 +**查询**(`references(toSwiftType:inImageAt:)`)带一个比对器:访问器与元数据的引用比描述符位置;名字逐字节走,符号引用(`\x01` 直接、`\x02` 经指针)指向的描述符就是这个类型,就算提到了它。只有名字可能直接拼出来的类型——标准库、`_Concurrency`、从 C / ObjC 导入的,key 以 `s` 或 `S` 开头——才解开名字确认;文本子串比对不可靠,mangling 会把同一名字里重复出现的单词换成替身。前提是其他类型在名字里一定以符号引用出现:在 Foundation、SwiftData、libswift_Concurrency、SwiftUI 里逐个解开全部名字核对过,没有例外(AppIntentsServices 有 56 处 key 对不上,原始字节全是符号引用,是那个镜像没有 `…Mn` 符号造成的拼法差别)。导入的类型每个用到它的镜像各有一份描述符,比的是 key,比 key 之前先比描述符给的名字。名字只从类型描述符读(`SwiftTypeIndex.name(ofDescriptorAt:)` 先看标志位低五位的种类是不是 16–31):符号引用指向的也可能是不透明类型(`some View`)的描述符,它在 +8 放的是泛型头,一个参数、一个约束读成偏移就是 64 KiB,在小镜像里读出镜像之外。0.24.0 没有这道检查,查导入类型时可能让宿主崩溃(第二轮审查 11,`importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs` 在子进程里复现到 SIGBUS)。Swift 类同时比它的 ObjC 类对象的位置。macOS 与 Mac Catalyst 变体里的同一个类型按位置分开。协议没有类型描述符,不在这一批。 宿主的用法:类型对象 → 描述符位置(或经 `swiftTypeDescriptorLocations(withKey:inImageAt:)`,先找 `…Mn` 符号)→ `swiftTypeIdentity(ofDescriptorAt:)` → 预筛 → 每个候选镜像 `references(toSwiftType:inImageAt:)`。`swiftTypeKeys(in:)` 解开一个 `SwiftTypeName`,供显示用。 @@ -136,7 +202,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` ### 缓存外镜像的 GOT 槽 -缓存外的镜像(第三方 App 自己的二进制)经自己的 `__stubs` / `__auth_stubs` 调别的镜像,槽位由 dyld 在加载时绑定,按 macOS 11 部署目标、不用 chained fixups 编出来的懒绑定二进制也一样:macOS 27.2 上以 `RTLD_LAZY` 加载,函数第一次被调用之前槽里已经是目标地址。所以扫描直接读槽。`LazyBindingTests` 是这件事的哨兵:哪天 dyld 不再在加载时绑定,槽会指回镜像自己的 `__stub_helper`,测试变红,那时再退回桩上的导入名。 +缓存外的镜像(第三方 App 自己的二进制)经自己的 `__stubs` / `__auth_stubs` 调别的镜像,槽位由 dyld 在加载时绑定,按 macOS 11 部署目标、不用 chained fixups 编出来的懒绑定二进制也一样:macOS 27.2 上以 `RTLD_LAZY` 加载,函数第一次被调用之前槽里已经是目标地址。所以扫描直接读槽。`LazyBindingTests` 是这件事的哨兵:哪天 dyld 不再在加载时绑定,槽会指回镜像自己的 `__stub_helper`,测试变红,那时再退回桩上的导入名。它在 macOS 27.2 与 26.6 上都通过(2026-10-27 第二轮审查据此把「懒绑定的槽指向 `__stub_helper`」判为误报,[ReviewAdjudications A80](../ReviewAdjudications.md))。ld64 链接的懒绑定桩多半是改写过的 `nop` / `ldr x16, <槽>` / `br x16`,槽位由 `ARM64Trampoline` 读出,见上文「链接器改写过的代码」。 ### 缓存、内存与生命周期 @@ -144,7 +210,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` 第二批起分析器还在自己的生命期里留着:扫描碰到的每个镜像的类索引(类与元类按地址,类名读过的记住)与类型索引(描述符与访问器,key 算过的记住),链接关系,以及改名再导出表。它们以缓存里的类与类型的总数为上限(macOS 27.2 有 203,621 个类名),没有单独测过占用;下面那个约 170 MB 的数字是第二批之前测的。宿主想放掉,用 `releaseImageData(exceptForImagesAt:)` 放掉指定镜像以外按镜像留着的一切——函数表连同读过的名字、类索引、类型索引;链接关系与改名再导出表不按镜像,留着——或者换一个分析器。RuntimeViewer 的会话在缓存外的镜像变化时换分析器;起过名的镜像(预先准备的除外)超过 64 个时,只放掉预先准备之外的。2026-10-18 之前后一种情况也是换分析器,预先读好的名字跟着丢了,下一次查询又得重读。 -分析器存活期间若有缓存外的镜像被卸载,再读它会读到已释放的内存;极少见,没有防(A63)。名字的解开一律是瞬时的:类型查询碰到的访问器符号与 mangled 名字不进全局的 `NodeCache`,也不进进程级的 demangle 记忆(交叉引用审查 B2,`TypeNameRetentionTests`),按镜像的 `demangleContext` 记忆随镜像淘汰。 +分析器存活期间若有缓存外的镜像被卸载,再读它会读到已释放的内存;极少见,没有防(A63)。名字的解开一律是瞬时的:类型查询碰到的访问器符号与 mangled 名字不进全局的 `NodeCache`,也不进进程级的 demangle 记忆(交叉引用审查 B2,`TypeNameRetentionTests`)。例外是没有 `…Mn` 符号的类型算 key、起名时用的 `SymbolicDemangler.demangleContext`:它的结果记在按镜像的 `SharedCache` 里,`releaseImageData(exceptForImagesAt:)` 不管它,由宿主调 `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()` 回收,与库里其它按镜像的缓存相同([ReviewAdjudications A78](../ReviewAdjudications.md))。 `CodeReferenceTable` 是值,宿主想留多久就留多久,按 `approximateByteCount` 计预算(不含字符串的堆存储;同一次扫描里重复的名字共用一份)。大镜像的整表很大(GeoServices 约 121 MiB,全缓存合计约 9 GB),28 个线程同时建整表时峰值约 1.5 GB,分配器之后还留着 1.2 GB 脏页不还。**查调用者用 `references(to:inImageAt:)`**:扫描时只留命中的引用,同样扫完全缓存后常驻约 170 MB(4 线程约 106 MB)。 @@ -163,14 +229,42 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` 比第一批多出来的是寄存器状态沿着分支走(约 +10–20%)、类引用与 Swift 类型引用(整表约 +45%,只查 selector 或函数时约 +10%)。「现在」一列是在别的会话同时编译、负载较高的机器上交替跑多轮取的最好值。 +**读取层与拆层的代价**(2026-11-19,同一台 Ultra,release,`ScanThroughputBenchmarkTests` 三方交替各三轮取最好;提案 [0097-offline-cross-references-and-symbolication](../../Evolutions/0097-offline-cross-references-and-symbolication.md) 第 1、2 步): + +| 操作 | 拆分前的 `next` | 第 1 步:读取层 | 第 2 步:三层与识别器 | +|---|---|---|---| +| 建分析器 | 0.054 秒 | 0.055 秒 | 0.055 秒 | +| 每个镜像都建整表(1.274 亿条引用) | 2.42 秒 | 2.54 秒 | 2.52 秒 | +| `init` 的调用者:预筛 2,880 个镜像 + 过滤扫描 | 0.038 + 1.663 秒 | 0.038 + 1.667 秒 | 0.039 + 1.698 秒 | +| `makeKeyAndOrderFront:` 的调用者:105 个镜像 | 0.050 + 0.309 秒 | 0.062 + 0.311 秒 | 0.059 + 0.325 秒 | + +第 2 步相对第 1 步在 −0.5% 到 +3% 之间;整表多出的约 5% 来自第 1 步——每次读槽、读字符串都经读取层的 existential 调用。拆层第一次量时超过 5%,采样后改掉的几处见提案的决策日志:读槽先做区间排除再查认领表、调用计划不持有数组、只调用角色需要的会话方法、热路径上的类属性去掉运行时独占检查、函数表记下各节免得 ObjC 层再遍历 load command、selector 预筛按块批量读槽。 + +**文件模式**(2026-11-19,同一台 Ultra,release,`ScanThroughputBenchmarkTests` 加 `CROSS_REFERENCE_BENCHMARK_DYLD_CACHE`,三轮取最好;第 4 步): + +| 操作 | 进程内(第 4 步) | 归档的 macOS 27.2 cache 文件(外置卷) | +|---|---|---| +| 建分析器 | 0.055 秒 | 0.135 秒 | +| 进程里第一次查 `makeKeyAndOrderFront:` / `init` 的调用者 | — | 0.50 / 1.89 秒 | +| 每个镜像都建整表 | 2.48 秒(1.274 亿条;第 5、6 步之后 2.57–2.66 秒、1.292 亿条,多出的是 ivar 引用) | 2.58 秒(1.263 亿条,4,114 个镜像) | +| `init` 的调用者 | 0.033 + 1.713 秒 | 0.042 + 1.74 秒 | +| `makeKeyAndOrderFront:` 的调用者 | 0.057 + 0.326 秒 | 0.110 + 0.335 秒 | + +读运行中的 cache 文件与外置卷上的归档一样快。文件模式第一版慢得多(整表 37 秒),差在每读一个槽都经 `FullDyldCache` 重新找 mapping、新建子 cache 对象、重读 slide info,以及读取层是类、每次经 existential 复制都计数——修法见「文件模式」一节与提案决策日志。第 4 步对进程内的影响在 ±3% 以内(与第 1 步交替量)。 + 单线程解码 AppKit 约 187 MiB/s,比 Capstone 快 25–50 倍(RuntimeViewer 提案落地第一步的探针)。库比探针慢一些(4 线程扫完整个缓存,探针 4.1 秒,库 5.9–6.3 秒),多出来的是起名、建 `CodeReference` 与 selector 字符串;过滤扫描也是先建好每条引用再丢弃,按键提前跳过是能做的优化。 +**搬家之后**(2026-11-19,同一台 Ultra,Xcode 26.6,release;提案 [0098 move-cross-reference-layers](../../Evolutions/0098-move-cross-reference-layers.md)):核心层与 ObjC 层跨包、接口改成 SPI 之后没有变慢,各项比 `next` 快 1% 到 11%(整 cache 建表进程内 2.67 → 2.53 秒、归档 27.2 cache 文件 2.75 → 2.51 秒),引用逐条一致。逐项数字记在 MachOKitExtensions 的 `Documentations/Internal/MachOCodeReferences.md`「吞吐」一节。 + ## 测试锚点 -- `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。 +- `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。`linkerRewrittenAddressesAndLoads` 与 `linkerRewrittenSlotStub` 核对 ld64 改写出的 `adr`、字面量 `ldr` 与桩。 +- `LinkerOptimizationHintTests`:现编的 dylib 按 ld64 的做法改写后,字面量 `ldr` 载入的 selector 认成发送、载入的类与 `adr` 取的类认成类引用,改写过的桩跟到 libsystem_c 的 `puts`。编译与改写的辅助代码在 `CompiledFixture`。 +- `RuntimeSendEntryPointTests`:现编的 dylib 里八个 libobjc 入口各调用一处,每处都记成对应的发送(`objc_alloc_init` 两条,在同一条指令上),不再有对 libobjc 函数的调用;八个 selector 的预筛都留下这个没有一个 selector 引用的镜像。修复前全部失败。 +- `AddressMaskScanTests`:库的源码里不许出现 33 到 62 位宽的地址掩码常量,指针一律按平台的掩码去掉签名。`AbbreviatedIdentifierScanTests`:`Sources` 与 `Tests` 里不许再用 `pc`、`lhs`、`rhs` 当名字(`Tests/Projects` 的 fixture 源码除外)。 - `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`)。 +- `SwiftTypeReferenceTests`:SwiftUICore 里访问器调用报出的类型与访问器符号全部一致(一万处以上);紧邻的 `adrp` / `add` 取出的地址上若有符号,报出的类型与符号一致;Foundation 的名字取自 `x1` 的记录、落在 `__swift5_typeref`、能解开;Foundation 与 SwiftData 里,查询保留的名字恰是解开后提到该类型的名字(40 个最常被符号引用的类型;另四个标准库类型,查询退回的正是同一套解开,所以它们只守着符号引用不指错描述符);两个 SwiftUI 的同名类型按位置分开;类型预筛(Foundation 的 `URL` 与 `JSONEncoder`、SwiftUICore 的 `Text`)丢掉的镜像里抽样一处引用也没有——按导入符号预筛时三者都漏;Foundation 与 AppKit 的每一个类型,按名字先筛再比 key 的查找与比每个类型的 key 结果相同(`typeLookupsCompareSameNamedTypesOnly`),按名字查导出表与读整个导出表判断导出与否相同(`exportLookupsAgreeWithTheWholeTrie`);查导入类型时不从不透明类型的描述符读名字,子进程里拿一页末尾的假描述符核对(`importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs`,修复前子进程 SIGBUS)。 - `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 的寄存器访问表独立核对这张表;普通读写只作废目标寄存器。 @@ -179,3 +273,12 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` - `LazyBindingTests`:现编一个懒绑定的 dylib,见上文「缓存外镜像的 GOT 槽」。 - `PreparedImageDataTests`(每个测试用自己的分析器):`prepareNames(inImageAt:)` 之后三个来源、类名、类型符号都已读好,给 Foundation 全部函数起的名字与不预读时相同;估算随留着的东西增减,放掉后为零;`releaseImageData(exceptForImagesAt:)` 只留指定镜像(连同读过的名字),其余放掉、之后照样能起名;一个线程预读预筛表、另一个线程同时要用,表只建一次;单线程读与并行读导出表结果相同。 - `CodeReferenceIndexTests`:Foundation 整表的每一个键,索引给出的引用与整表逐条相同、顺序相同,条数等于整表里有键的加上 Swift 类型名;AppKit 里一次查几个键(selector、libswiftCore 的函数、`NSWindow`)与过滤扫描逐条相同;Foundation 里 `URL`、`JSONEncoder`(类,经类对象)与标准库的 `Sa`(名字里拼出来,要解开)从索引查与按类型扫描逐条相同;索引不到整表的一半大;建索引留住函数表;进度从 0 报到函数总数,回答「停」就不建。 +- 层的边界:下层搬走之后 SwiftPM 本身就不让它们 import 本库的模块,原来的 import 白名单测试删了。核心层源码里没有 `objc_` / `swift_` 开头的字面量、只有 `InProcessCrossReferenceMemory` 把地址变成指针、不写地址掩码常量,由 MachOKitExtensions 的 `SourceScanTests` 守着;ObjC 层只经 `CrossReferenceMemory` 读内存、不写 `swift_` 字面量,由 MachOObjCSection 的 `SourceScanTests` 守着;本库的 `MemoryAccessScanTests` 只扫 `CrossReferenceAnalysis`。核心层不装任何语言层也能扫,见 MachOKitExtensions 的 `CoreOnlyScanTests`。 +- `RecognizerExtensionPointTests`:测试里定义的会话(代替一切调用 libobjc 的调用)接进核心的扫描,核心不改就生效;只查 selector 时 Swift 会话不建任何镜像的类型索引。`PublicNameTests`:只 `import CrossReferenceAnalysis` 也看得到下移的 `CodeLocation`、`CodeReference.Kind`、`ReceiverClassHint`、`IndirectCallEvidence`。 +- `FunctionStartOutsideTextTests`:符号表把函数起点放在 `__text` 起点之下的镜像照常扫描(第 1 步曾因此下溢陷入)。 +- 两个按环境变量启用的 A/B 套件,库里没有可存的基线:`ReferenceTableDigestTests`(AppKit、SwiftUICore、Foundation 的整表摘要,在基线检出上生成、在候选上比对,也能整表导出逐行比较)与 `ScanThroughputBenchmarkTests`(上面「读取层与拆层的代价」那张表,release 下跑)。用法写在各自的文档注释里。 +- `FileModeTests`(文件模式,提案第 4 步):运行中的 cache 从文件读与进程内读,AppKit、SwiftUICore、Foundation 的整张引用表逐行一致,函数名、ObjC 方法表与 Swift 元数据给的名字、selector 预筛也一致;cache 的每个指针槽(v5 与没有 slide info 的模拟器 cache)解出的与 MachOKit 一致;归档 27.0、27.2 里 `UINSPasteboardWritingItemProvider` 的两个经 GOT 的调用者;iOS 26.3.1 设备 cache 里经 stub island 的发送;现编的独立文件——`-interposable` 的 dylib(self-bind 落到自己的函数、`puts` 是导入名)、Objective-C 可执行文件(`__TEXT` 在 0x100000000 时 rebase 与 objc 桩都解对)、C++ 的 `retab` 之后的异常清理代码。归档卷不在时相应用例跳过。 +- `StandaloneFileReferenceDumpTests`:按环境变量启用,把一个独立文件(universal 取 arm64e 切片)的全部引用按函数导出成文本,供与反汇编器对照。第 4 步拿它与 IDA 抽样核对过 ControlCenter 26.7。 +- `ReferenceKindAndRouteTests`(第 5 步):现编的 ObjC 库里,读 ivar 的两个方法各有一条 ivar 引用(带符号与剥了符号两种);字符串只在打开时或查字符串键时记;8 位与 UTF-16 的 `CFString` 常量带字符;Swift 大字符串只在 `add` 处记一条;调用、经本镜像桩的调用与发送、字符串的路线;常驻索引与整表对新种类与路线一致;运行中的 cache 里 AppKit 的路线覆盖直达、经槽、算地址、间接与桩;cache 里有一个恰好页对齐的类对象由 `adrp; add #0` 引用。`ARM64InstructionWordTests.decoderDecodesThirtyTwoBitLoadAndLoadSignedWord` 核对 32 位载入的解码,Capstone 对拍。 +- `SymbolicationTests`(第 6 步):26.7 SwiftUICore 的全部 `__auth_stubs` 都解到函数或导入名,其中 5 个经 `ipsw` 独立核对、间接符号表给错名的桩解对;macOS 27 AppKit 经 cache 共用桩的发送,桩要么是 selector 桩(selector 与发送一致),要么是通向 libobjc 入口的 GOT 桩;现编库的 GOT 槽给出导入名与 self-bind 的函数;Matter 里只有方法表起名的函数,地址落在函数体里;cache 文件里 0x10 与 0x7FFF00000000 没有映射;现编库的 C 字符串、`CFString` 与 ivar 偏移变量。 +- 键集合不共享存储(第 7 步):`ReferenceCollector` 把调用方的键集合拷一份自己的,检查时不经闭包捕获。并发扫描共用一个键集合时,每条引用一次 retain/release 曾让整 cache 的调用者查询慢 15 到 70 倍;`ScanThroughputBenchmarkTests` 的 `callersOf` 一行按共用一个集合量,回归会直接反映在数字上。 diff --git a/Documentations/Internal/Modules/MachOCaches.md b/Documentations/Internal/Modules/MachOCaches.md deleted file mode 100644 index 7596f0097..000000000 --- a/Documentations/Internal/Modules/MachOCaches.md +++ /dev/null @@ -1,119 +0,0 @@ -# MachOCaches 模块 - -> 模块参考文档(module reference),随代码维护。读者:维护者。 -> 提案:[0053-shared-cache-composition-and-eviction-registry](../../Evolutions/0053-shared-cache-composition-and-eviction-registry.md)。 - -## 模块定位 - -先说它不是什么:MachOCaches **不是 dyld shared cache 的支持层**。dyld cache 的读取在 `MachOKitExtensions`(`DyldCache` 的镜像查找、进程内镜像是否在 cache 里),按 cache 找依赖镜像在 `MachODependencies`。这个模块名字里的 cache 是「缓存」,撞名是历史遗留,本批未改(提案决策日志有记录)。 - -它回答一个问题:**一个镜像的某种一次性建好的索引放在哪、谁建、谁清。** 符号表(`SymbolIndexStore`)、interned 名字池(`InternedNodeReferenceCache`)、ObjC 方法表(`ObjCClassMethodIndex`)、`_symbolic` 符号索引(`SymbolicManglingIndex`)……每一种都是「按镜像算一次、之后人人共享」的东西,它们的持有者各在自己的模块里,共用的机制在这里: - -- `SharedCache`:按镜像的 get-or-build。同一镜像的并发首次访问只建一次,构建在锁外跑。 -- `SharedCacheKey`:镜像的键,只哈希 UUID(从 dyld cache 读出的镜像再加上所在 cache 的 UUID)或基址。 -- `SharedCacheRegistry` + `SharedCacheEvictionGroup`:谁认领了哪个镜像的哪些缓存、最后一个持有者走了清什么、宿主想在内存压力下清什么。 -- `SharedCacheBuildPromise`:在途构建的会合点,等待者在 `NSCondition` 上睡。 - -依赖只有 `MachOKit` / `MachOKitExtensions`(为了 `MachORepresentableWithCache` 与 `MachOTargetIdentifier`)和 `Utilities`。整个模块以 `@_spi(Internals)` 暴露,下游仓库(RuntimeViewer)不直接用它,经 `SwiftDeclarationIndexer` 与 `SymbolIndexStore` 的实例 API 间接使用。 - -## 文件 → 子系统对照 - -| 子系统 | 文件 | -|---|---| -| 1. get-or-build | `SharedCache`、`SharedCacheBuildPromise` | -| 2. 键 | `SharedCacheKey` | -| 3. 驱逐 | `SharedCacheRegistry`(含 `SharedCacheEvicting` 协议)、`SharedCacheEvictionGroup` | - -## 1. get-or-build(`SharedCache`) - -`storage(in:buildUsing:)` 是唯一的取值入口,三段式:锁内查字典,命中直接返回;有人在建就拿到它的 promise、出锁等;都没有就装一个 in-flight 标记、出锁跑构建闭包、回来在锁内写回并 fulfill 等待者。写回只在「标记还是自己的」时发生:`register(_:for:)` 或 `removeAll()` 可能在构建期间换掉了条目,那时构建者不写回,但仍把自己的结果交给已经在等它的人。构建返回 `nil` 不缓存,下一次重试(`MultiPayloadEnumDescriptorCache` 对非 Swift 读者就返回 `nil`)。 - -**构建闭包在调用点给,不在缓存里。** 缓存位于 `MachOSwiftSection` 之下,看不见 `MachOSwiftSectionRepresentableWithCache`,更看不见 `SwiftInspection` 的 `ObjCImplementationClassReading`;而每个索引的构建都要读描述符或 ObjC 类数据。以前基类的 `open func buildStorage(for: some MachORepresentableWithCache)` 把类型擦到最弱的协议,六个子类只好各自 `as? MachOFile / as? MachOImage` 再分派。现在持有者在自己的 `storage(in:)` 里把读者改一次类型(`SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift` 的 `swiftSectionReader` / `objcImplementationClassReader`,把 `some MachORepresentableWithCache` 转成对应协议的 existential,再交给 `some P` 参数的泛型 `build(in:)` 隐式打开),分派只写一次。查询 API 仍以 `MachORepresentableWithCache` 为参数类型,因为每个消费者手里拿的就是它。 - -每个持有者的固定形状: - -```swift -package final class ObjCClassMethodIndex: @unchecked Sendable { - package static let shared = ObjCClassMethodIndex() - - private let cache = SharedCache(evictionGroup: .objcHierarchy) - - private init() {} - - package func storage(in machO: some MachORepresentableWithCache) -> Storage? { - cache.storage(in: machO) { machO in - machO.objcImplementationClassReader.map { Self.build(in: $0) } - } - } - - package func contains(in machO: some MachORepresentableWithCache) -> Bool { - cache.contains(in: machO) - } - - package func remove(for machO: some MachORepresentableWithCache) { - cache.remove(for: machO) - } -} -``` - -`register(_:for:)` 是「覆盖安装」:`PropertyWrapperTypeCatalogStore` 与 `ObjCAncestorResolverStore` 用它让 indexer 按自己的搜索路径建好的对象顶掉早先某次查询建的默认对象。`contains(in:)` 对在途构建回答 `false`,这是注册表认领规则要的语义:一个 `prepare()` 看到「没有」然后去建,哪怕最后和别人共享了一次构建,也算它建的。 - -**重入**:构建闭包里再对同一个键调 `storage(in:)`,会等一个只有自己返回才 fulfill 的 promise,永远不回来。promise 记下构建线程,`resolve` 在进入等待分支前发现等的是自己线程在建的 promise,直接 `precondition` 崩溃并报出键。只能抓同线程:`SymbolIndexStore` 的 sweep 经 `StackSafeExecutor.withLargeStack` 跳到 8 MB 工作线程,在那上面再重入抓不到。退出测试 `reentrantBuildForTheSameKeyTrapsInsteadOfHanging` 钉住这条。 - -## 2. 键(`SharedCacheKey`) - -`MachORepresentableWithCache` 的两个 conformer(`MachOFile`、`MachOImage`)的 identifier 都是 `MachOTargetIdentifier`:从 dyld cache 读出的镜像按路径、`LC_UUID` 加所在主 cache 的 UUID(`.dyldCacheImage`),其余文件按 `LC_UUID` 加路径(`.uuidFile`),没有 UUID 的文件按 `LC_BUILD_VERSION` 或裸路径,进程内镜像按基址(`.image`)。cache 镜像必须带上 cache:同一次构建可以原样出现在两个 cache 里——macOS 13.5 和 13.6 的 SwiftUI 连 `LC_UUID` 都一样——但两个 cache 把它放在不同地址,经它读出的每个偏移都属于读它的那个 cache。只按 `.uuidFile` 时两份共用一切按镜像的缓存,后读的那份拿着前一份的类对象偏移去读自己的 cache,读到的不是指针,MachOKit 解 rebase 时 trap(MachOKitExtensions 1.1.0 修,`DyldCacheTwinImageTests` 钉住)。用主 cache 的 UUID,同一个镜像无论 cache 是只开主文件还是连子 cache 一起开,都是同一个身份。以前键是 `AnyHashable(machO.identifier)`:`.uuidFile` 的载荷超过 existential 的 24 字节内联缓冲,每次查找一次堆分配,再把整条路径喂给 SipHash——而查找发生在按符号、按 mangled name 的循环里。 - -`SharedCacheKey` 包住 identifier:`.uuidFile` 只哈希 UUID(链接器按构建唯一分配,单独就能区分镜像),`.dyldCacheImage` 只哈希镜像与 cache 的两个 UUID,`.image` 只哈希指针,`.file` / `.versionedFile` 才哈希路径;**等值比较仍比完整值**,路径不同的两个键相等测试不通过,只是哈希相同。identifier 不是 `MachOTargetIdentifier` 的读者(今天没有)走 `.opaque(AnyHashable)` 兜底。`SharedCacheKey(opaque:)` 同时是测试造键的入口。 - -没有直接把协议的 `associatedtype Identifier` 收窄成具体类型,因为协议在 sibling 仓库 `MachOKitExtensions` 里,且要给每个泛型签名加 `where MachO.Identifier == MachOTargetIdentifier`;这里用一次 `as?` 得到同样效果。 - -手里只有 `ReadingContext`、没有读者的 memo(`SymbolicDemangler` 的反混淆缓存、`InternedNodeReferenceCache`)从 context 的缓存范围(`cacheScope`)拿身份:`MachOContext` 答 `.image(identifier:)`,带的就是读者的 `MachOTargetIdentifier`,memo 用 `SharedCacheKey(identifier:)` 建键,与 `SharedCacheKey(machO)` 是同一个键,所以经读者和经 context 存进去的条目是同一条,驱逐也一起走。这个载荷故意是具体类型而不是 `AnyHashable`,理由同上:每次 memo 查找都要问一次范围。详见 [ReadingContextAbstraction.md](../ReadingContextAbstraction.md)「缓存范围」一节。 - -## 3. 驱逐(`SharedCacheRegistry` / `SharedCacheEvictionGroup`) - -每个 `SharedCache` 在创建时声明自己的 eviction group,并向进程级 `SharedCacheRegistry.shared` 登记(弱引用)。**`MachOCaches` 自己不定义任何 group**:`SharedCacheEvictionGroup` 是一个只有名字的结构体,各模块在自己的扩展文件(`SharedCacheEvictionGroup+<模块>.swift`)里声明自己的常量,注册表处理的是「登记过的 group 的集合」,加一个 cache 不需要回来改这个模块。持有别的 group 存储引用的 cache 在创建时用 `follows:` 说明它跟谁走(`SharedCache(evictionGroup: .symbolicMangling, follows: [.symbolStore])`),注册表据此反向建表,同一 group 下多个 cache 的声明取并集。今天的对照: - -| group(声明所在模块) | cache | follows | -|---|---|---| -| `symbolStore`(MachOSymbols) | `SymbolIndexStore` | — | -| `internedNames`(MachOSymbols) | `InternedNodeReferenceCache` | — | -| `symbolicMangling`(SwiftInspection) | `SymbolicManglingIndex`(持有符号表的 `_symbolic` 表) | `symbolStore` | -| `objcImplementationClasses`(SwiftInspection) | `ObjCImplementationClassIndex`(持有指向符号表 arena 的 `NodeReference`) | `symbolStore` | -| `objcHierarchy`(SwiftInspection) | `ObjCClassMethodIndex`、`SwiftClassObjectIndex`、`ObjCClassHierarchyProviderStore`(宿主的弱引用注册,手工遵循 `SharedCacheEvicting`) | `symbolStore` | -| `objcAncestorResolver`(SwiftInspection) | `ObjCAncestorResolverStore` | `symbolStore` | -| `demangleMemo`(SwiftInspection) | `SymbolicDemanglerCache`、`AnonymousContextNameIndex` | `internedNames` | -| `propertyWrapperCatalog`(SwiftDeclarationRendering) | `PropertyWrapperTypeCatalogStore` | — | -| `multiPayloadEnumDescriptors`(SwiftDeclarationRendering) | `MultiPayloadEnumDescriptorCache` | — | -| `dependentMemberProjection`(SwiftDeclarationRendering) | `DependentMemberProjection` 的两个实例 | — | -| `thunkResolution`(SwiftThunkAnalysis) | `MetadataAccessorIndex`、`DependencyImageResolver` | — | - -**认领与驱逐的规则**(PR #103 review 的 M6,原来是 `SwiftDeclarationIndexer.swift` 里的私有注册表,现在下沉到这里并推广到全部 group): - -- 一个持有者(`SwiftDeclarationIndexer`)在 `prepare()` 开头调 `registerLiveOwner(_:for:)`,注册表在自己的锁内采样:这个镜像在哪些登记过的 group 里还没有完成的条目,那些就是它要建的,全部认领。锁内采样是为了关掉一个窗口:采样在锁外做,兄弟 indexer 的注销恰好落在中间,会让它看到缓存都在、什么都不认领、随后重建一切又没有认领可驱逐,符号表就泄漏到进程结束。 -- 只有第一次注册采样。同一持有者再注册(`prepare()` 重跑)看到的是自己刚建的缓存,再采样会反着读。 -- `deregisterLiveOwner(_:for:)` 只在它是这个镜像**最后一个**活着的持有者时驱逐;提早走的兄弟什么都不清,否则幸存者已建好的名字留在孤儿 store 里、新名字落进新 store,`store ===` 快速路径从此分裂。驱逐在注册表锁内做,理由同上。 -- 驱逐认领的 group 时连带跟着它走的 group(`follows` 的反向,传递闭包):按上表,`symbolStore` 带走 `symbolicMangling`、`objcImplementationClasses`、`objcHierarchy`、`objcAncestorResolver`,`internedNames` 带走 `demangleMemo`(memo 的值是指向 interned arena 的引用,留着它 arena 释放不了)。单向:扔 memo 不要求扔 arena。 -- 非持有者(`SwiftLayout`、渲染器、`SwiftSpecialization`)在 `prepare()` 之前填的条目不会被认领,也就不会被 indexer 驱逐;在 indexer 生命周期内填的会随它走(误认领的代价只是事后多建一次)。 -- `evict(groups:for:)` 是显式驱逐,**不展开 followers**:调用方点名要清什么。`ObjCClassHierarchies.removeCache`、`ObjCImplementationClasses.removeCache`、`SymbolicDemangler.removeCache` 三个公开助手都是它的转发。 - -**内存压力**:库不再监听。以前每个 `SharedCache` 实例各挂一个 `MemoryPressureMonitor`,warning 就 `removeAll()`,绕过认领规则,而且清掉的存储被活着的 `NodeReference` 钉着、回收不到内存。现在宿主想清就调 `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()`:清所有出现在任一 cache 里、且没有活持有者的镜像的全部 group。非持有者临时填的镜像也会被清,这是宿主显式调用的后果。 - -**不受驱逐的**:进程作用域的 memo 都是 `static` 存储,不经过按镜像的字典,也不受注册表管: - -- `InternedNodeReferenceCache` 与 `SymbolicDemanglerCache` 给没有 Mach-O 句柄的进程内读取路径用的那两份,大小由进程实际碰到的唯一名字数决定。`SymbolicDemanglerCache` 的这一份里还有一张按地址记的匿名上下文判别符表,`InProcessContext` 查判别符时用(提案 [0067-nested-field-offset-memoization](../../Evolutions/0067-nested-field-offset-memoization.md)):已经在内存里的匿名上下文,答案不会变。 -- `SwiftDeclarationRendering` 的 `NestedFieldOffsetLevelMemo`:进程内嵌套字段偏移展开按 metatype 记下的「一层」(同一提案),大小由进程展开过的唯一 metatype 数决定。它记下了「当时哪些字段类型解析不出」,进程之后加载的镜像可能让它们变得可解析,所以它有清除入口 `RuntimeFieldLayoutMemo.removeAll()`:宿主在进程里加载镜像之后调一次。其余几份没有这个问题,也没有清除入口。 - -## 4. 契约与坑 - -- **新加一个按镜像的 cache**:在自己模块的 `SharedCacheEvictionGroup+<模块>.swift` 里选或加一个 group 常量;持有者按第 1 节的形状写,条目引用了别的 group 的存储就加 `follows:`;在这份文档的对照表登记。`MachOCaches` 不用动。不要再手写 `NSLock` 加字典。 -- **构建闭包里不要查自己的 cache**:同线程会崩,跨线程会挂。需要别的 cache 可以(`buildClosureMayResolveOtherKey` 钉住)。 -- **`MachOSymbols` 里的公开类型布局变了要 `swift package clean`**(AGENTS.md 的既有契约):`SymbolIndexStore` 不再是 `SharedCache` 的子类就是这样一次变化。 -- **测试怎么写**:`SharedCache(evictionGroup:registry:)` 与 `SharedCacheRegistry()` 都是 `package` 可见,测试自建注册表、用 `SharedCacheKey(opaque:)` 造键、用 `resolve(key:)` 驱动,不需要真镜像;端到端规则由 `SwiftIndexingTests/PerImageCacheEvictionTests` 在 fixture 上钉。 -- **CI 跑的套件**:`SharedCacheResolveTests`、`SharedCacheResolveSwiftConcurrencyTests`、`SharedCacheKeyTests`、`SharedCacheRegistryTests`(`macOS.yml` 的 filter)。 - -## 验证 - -- `MachOCachesTests` 四个套件:get-or-build 契约(同键去重、异键并行、异键重入、取消不污染、同键重入崩溃、`register` 覆盖在途构建)、键的哈希与等值、注册表规则。异键并行用两个构建的会合点证明,不看墙钟。 -- `SwiftIndexingTests/PerImageCacheEvictionTests`:indexer 与注册表的端到端。 -- 渲染 A/B:见提案「验证」。 diff --git a/Documentations/Internal/Modules/MachODependencies.md b/Documentations/Internal/Modules/MachODependencies.md deleted file mode 100644 index e8348ef89..000000000 --- a/Documentations/Internal/Modules/MachODependencies.md +++ /dev/null @@ -1,109 +0,0 @@ -# MachODependencies 模块 - -> 模块参考文档(module reference),随代码维护。读者:维护者。 -> 提案:[0017-macho-dependencies-module](../../Evolutions/0017-macho-dependencies-module.md)。 - -## 模块定位 - -MachODependencies 回答一个问题:**一个二进制链接了哪些镜像,去哪里把它们找出来。** 它只读 `LC_LOAD_DYLIB` 家族的 load command,不碰 Swift metadata,因此和 `MachOCaches` / `MachOReading` 一样位于 MachO* 基础层,由 `MachOFoundation` 统一 re-export——凡是 `import MachOSwiftSection` 的模块都直接可用,不必再加 import。 - -它取代了两套各自为政的实现:`SwiftLayout` 里文件私有的传递闭包(BFS + bare name 去重 + cache 一次性索引),和 `SwiftInterface` 里绑定在 `SwiftInterfaceBuilderDependencies` 上的一层直接依赖加载(按 install path 精确匹配)。两处现在都是薄包装,各自的语义保持不变:静态布局要传递闭包,`__C` 类型归属只要直接依赖。 - -下游消费者:`SwiftLayout.ImageUniverse`(三个 `dependencyClosure` 工厂)、`SwiftInterface.SwiftInterfaceBuilderDependencies`(供 TypeIndexing)、`swift-section interface --resolve-c-module-names`、`SwiftIndexing.SwiftDeclarationIndexer`(一个 `SharedDependencyClosure` 同时喂 property-wrapper catalog 与 `SwiftInspection.ObjCAncestorResolver`——独立文件的 ObjC 祖先链,提案 `objc-ancestor-dependency-closure`)。 - -## 文件 → 子系统对照 - -| 子系统 | 文件 | -|---|---| -| 1. 搜索路径与失败记录 | `DependencySearchPath`(含 `DependencySearchPathError` / `DependencySearchPathLoadFailure`) | -| 2. load name 归一 | `DependencyLoadName` | -| 3. 定位器 | `DependencyLocating`(协议 + `InProcessDependencyLocator`)、`FileDependencyLocator`、`DependencyPlatforms`(平台守卫) | -| 4. 闭包遍历 | `DependencyClosure`(含 `DependencyTraversal`)、`SharedDependencyClosure`(一次求值多方共享) | - -## 1. 搜索路径 - -`DependencySearchPath` 四种:显式 Mach-O 文件、显式 dyld shared cache 文件、宿主系统的 cache、**system root**(`.systemRoot(path:)`,2026-09-13 提案 `standalone-file-thunk-resolution` 加入)。system root 是一棵目录树,绝对 install name 直接拼在它下面找文件——iOS 26 及更早的模拟器运行时把系统框架当文件放在 `RuntimeRoot` 里,就是这个形状;`@rpath/…` 这类相对名字永远不在 root 下找。定位器对 system root 不预扫描,第一次问到某个 load name 时才打开对应文件、按根镜像的架构挑切片、记住结果;不是目录的 root 记为 `systemRootIsNotADirectory` 失败。 - -两个便利入口:`DependencySearchPath.inferred(forRoot:)` 从根文件在磁盘上的位置推断搜索路径——沿祖先目录向上找带 `System/Library/Caches/com.apple.dyld/`(iOS 家族与 iOS 27+ 模拟器:`dyld_sim_shared_cache_arm64`)或 `System/Library/dyld/`(macOS)且里面有本架构主 cache 文件的目录,命中即给 `.dyldSharedCache`;没有再看根文件路径是否以自己的 install name 结尾,是就把前缀当 `.systemRoot`;文件系统根目录本身永远不算(宿主 cache 归 `.systemDyldSharedCache`)。`DependencySearchPath(classifyingPath:)` 按形状归类一个用户给的路径:目录 → system root,主 cache 文件名(`dyld_shared_cache_*` / `dyld_sim_shared_cache_*`,不含 `.01` / `.map` 等后缀)→ cache,其余 → Mach-O 文件;`swift-section` 的 `--dependency-search-path` 用它。**`@rpath` / `@loader_path` / `@executable_path` 不展开**——一个不在 cache 里的依赖(sibling framework、测试 helper)必须由调用方以 `.machOFile(path:)` 显式给出。这是从 SwiftLayout 阶段 3 继承的 MVP 边界,未变。 - -打不开的搜索路径**不抛错**,记进 `DependencySearchPathLoadFailure`(附原始 error;系统 cache 不可用时是 `systemDyldSharedCacheUnavailable`)。理由有二:一条坏路径不该让整个解析失败;本模块在事件层(`SwiftIndexEvents`)之下,无法派发事件,只能把失败当数据回传,由上层决定落点——`SwiftInterfaceBuilderDependencies` 把它们派发为 `renderingDegraded(.dependencyLoad)` 事件,CLI 经 `ConsoleEventHandler` 落到 stderr。 - -`.systemDyldSharedCache` 取 MachOKitExtensions 的 `FullDyldCache.cachedHost`:本机 cache 在进程内只打开一次,所有定位器共用。不要直接读 `FullDyldCache.host`:它每读一次就重新打开、映射本机 cache 的全部文件(macOS 27 是 82 个),而定位器是按根构建的,51 个版本的 evolution 因此曾同时开着 4,182 个文件([ProjectEvolutionLog](../ProjectEvolutionLog.md) 第 82 节)。`FileDependencyLocatorTests.locatorsShareOneOpeningOfTheSystemCache` 钉住了共用。共用的后果是几个根会同时第一次读同一个子 cache(`diff` 与 `evolution` 并行准备各个输入):`DyldCache` 与 `MachOFile` 的文件映射和句柄由 MachOReading 懒创建,创建时持锁、只存一次,之后的读取不拿锁;曾经无锁创建,每个抢到的读者各映射一次、互相覆盖(`ConcurrentFileMappingTests`,PR #131 review 第 7 条的横向排查)。 - -## 2. load name 归一(`DependencyLoadName.bareImageName(of:)`) - -load name → bare image name:取末段路径、去**第一个**扩展名(`libobjc.A.dylib` → `libobjc`,`libc++.1.dylib` → `libc++`)。这条规则是**与 MachOKit 的契约**:`MachOImage(name:)` 对进程内每个镜像的路径做同样的归约再比较。把未归一的 load name(dyld 报告的都是绝对路径)直接喂给它永远匹配不到——`SwiftInterfaceBuilderDependencies` 的 `MachOImage` 版初始化器就是这么写的,从诞生起解析结果一直为空,仓库内无人调用所以没被发现(`DependencyLoadNameTests.bareImageNameIsWhatMachOImageLookupMatches` 与 `SwiftInterfaceBuilderDependenciesTests.imageInitializerResolvesTheMappedDirectDependencies` 锁定)。 - -bare name 同时是所有依赖集合的**去重键**:同一个库会被不同镜像以不同拼写链接(sibling 用 `@rpath/…`,系统框架用绝对路径),只有 bare name 跨拼写稳定。 - -## 3. 定位器 - -`DependencyLocating` 只有一个方法 `locate(loadName:)`,收到的是 load command 里的**原始拼写**,归一由实现自己做。这让遍历与「镜像从哪来」解耦:进程内、磁盘搜索路径、测试里手搭的表,都是一个实现。 - -- **`InProcessDependencyLocator`**:归一后查一张「bare name → 镜像」表。系统框架天然从 cache 解析;`@rpath` 依赖只要已映射进进程也能解析;弱链接但未映射的(如 `libswiftCoreAudio`)解析不到,进 `unresolvedLoadNames`。表在定位器构造时建:遍历一遍 dyld 已映射的镜像,同名只留第一个——与 `MachOImage(name:)` 的选择逐个一致(同一条归一规则、同样「第一个匹配,没有 header 就是 nil」),只是不再每次查询都把所有镜像的路径重新拆一遍。改前一个几百个依赖的闭包、在映射了上千个镜像的进程里要拆几十万次路径,RuntimeViewer 并行打印时其余线程都排在第一个建闭包的 catalog 后面(2026-10-13,提案 `faster-lazy-definition-indexing`)。代价:定位器构造之后才映射的镜像它看不到,新建一个定位器就能看到;`DependencyClosure(root: MachOImage)` 每次都新建。 -- **`FileDependencyLocator`**:两步查找,顺序固定: - 1. **install path 精确匹配**——系统框架的 load name 就是 cache 镜像的 `imagePath`,命中即是编译器自己的答案。显式文件同时以「传入的磁盘路径」和「文件的 install name(`LC_ID_DYLIB`,通常 `@rpath/…`)」两种拼写登记,因为 `MachOFile.imagePath` 是 install name 而非磁盘路径。 - 2. **bare name 排序兜底**——`@rpath/…` 或 cache 不认识的路径拼写落到这里。cache 里 leaf name 不唯一:macOS cache 在 `/System/iOSSupport` 下带着 Mac Catalyst 版 SwiftUI,iOS cache 有同名 `.axbundle`。候选按 MachOKitExtensions 的 `DyldCacheImageSearchMode.matchRank` 排序(canonical framework > 普通 dylib > bundle,support root 降级),取最优。**旧的 SwiftLayout 定位器是「枚举顺序首写者胜」**,在 macOS cache 上可能选中 Catalyst 构建——这是合并时消除的潜在错配(`FileDependencyLocatorTests.bareNameFallbackPrefersTheNativeCanonicalFramework` 锁定)。`matchRank` 对多点 leaf(`libc++.1.dylib`)返回 `nil`,此时记为最差 rank 但仍可解析。 - - cache 索引**首次查询时一次性建成**(一遍 `machOFiles()`,同时建 install path 表与 bare name 最优表),之后 O(1)。逐次 `machOFile(by:)` 是 `O(依赖数 × cache 大小)` 的全扫描,阶段 3 实测 551 镜像闭包要 21 秒。`NSLock` 保护惰性索引,定位器可跨任务共享。 - - **平台守卫**(2026-09-21,提案 `objc-ancestor-dependency-closure`):宿主的 macOS cache 是每个 root 的默认搜索路径,而它在 `/System/iOSSupport` 下带着 Catalyst 版的 UIKit / SwiftUI——iOS root 链的 `/System/Library/Frameworks/UIKit.framework/UIKit` 没有精确匹配,裸名兜底又没有原生版可以压过它,于是拿到的是同名类、不同平台的镜像(ObjC 祖先的 selector 集合、instance size 都是另一个平台的)。定位器构造时接收 root 的平台集合(`DependencyPlatforms.platforms(of:)`:全部 `LC_BUILD_VERSION` 的平台,zippered 镜像两个;没有则按 `LC_VERSION_MIN_*` 推;空集合放行),一次性建 cache 索引时把集合不相交的镜像直接跳过——精确路径与裸名两步一起受约束(`/usr/lib/libobjc.A.dylib` 这种两边都精确匹配的也拒)。显式文件与 system root 是调用方自己给的,不过滤。被拒的 load name 落进闭包的 `unresolvedLoadNames`,没有另起通道。`DependencyClosure(root: MachOFile, …)` 自动传 root 的平台(`FileDependencyLocatorTests.cacheImagesOfAnotherPlatformAreNotCandidates` 锁定)。副作用:iOS 二进制在 macOS 宿主上不带搜索路径时,布局引擎与 `__C` 归属也不再拿到 Catalyst 镜像——诚实降级,给 `--dependency-search-path ` 即恢复。 - - **root 自己的 cache 排在所有搜索路径之前**(2026-10-08):从 dyld cache 里读出来的 root,dyld 只会在同一个 cache 里给它找依赖,所以 `DependencyClosure(root: MachOFile, …)` 把 root 所在的 cache 放在最前面查,调用方给的搜索路径排在后面。修复前,没给搜索路径时默认只有宿主 cache:用 `--dyld-shared-cache` 读归档的 macOS 15.5 cache 里的 SwiftUICore,`URL` 就按宿主(macOS 26 起)的 Foundation 算成了 16 字节,而 15.5 的 `URL` 有 `_url`、`_parseInfo`、`_baseParseInfo` 三个字段,是 24 字节。root 经 `FullDyldCache` 打开时(CLI 就是这样),直接把那个实例交给定位器(`rootDyldCache`),不重新打开;搜索路径里再点名同一个 cache 文件、或 root 本来就来自 `FullDyldCache.cachedHost` 时,都不会重复加入。root 只经单个 cache 文件打开时(`DyldCache`),改为把它的主 cache 文件当成第一条 `.dyldSharedCache` 路径,由定位器自己打开。**不能用 `root.fullCache`**:它第一次被读时才打开 cache 并写回 `MachOFile`,没有锁,而同一个 root 的闭包会在多个线程上各自构建;`_cachedFullCache` 只读不写。 - - fat 显式文件取与 root 同架构的 slice(`preferredCPU`:先比 `cpu.type` + 掩掉 capability 位后的 `cpu.subtype`,能分开 arm64 / arm64e;再只比 type;最后 `.first`——旧两处实现都无条件取 `.first`)。注意 MachOKit 的 `CPU ==` 比的是原始值,versioned-ABI 的 arm64e 切片会和普通 arm64e 判不等,所以不能直接比 `header.cpu`。 - -## 4. 闭包遍历(`DependencyClosure`) - -`DependencyClosure(root:traversal:locator:)` 是唯一的遍历实现,两个便利初始化器只是选定位器:`init(root: MachOImage, traversal:)` 与 `init(root: MachOFile, searchPaths:, traversal:)`。 - -- **`.direct`** 只走 root 自己的 load command;**`.transitive`** BFS 递归。 -- **顺序是契约的一部分**:direct 为 load command 顺序,transitive 为 BFS(root 的直接依赖全部在前)。`SwiftLayout.ImageUniverse` 按这个顺序惰性索引依赖、命中即停;DFS 会把 Foundation 整棵子树排在 root 的第二个 Swift 依赖前面(`DependencyClosureTests.inProcessTransitiveClosureExtendsTheDirectPrefixBreadthFirst` 锁定 direct 是 transitive 的前缀)。 -- 按 bare name 去重,root 自身排除(以 root 的 `imagePath` 归一后预置进 visited 集合);**再按镜像身份去重**(`MachORepresentableWithCache.identifier`,文件是 `LC_UUID` 键)——文件定位器把一个显式文件登记在磁盘路径、install name、bare name 三种拼法下,root 若以两个 load name 链到同一个二进制,只按 bare name 去重会把它收两次(`sameImageReachedUnderTwoLoadNamesIsCollectedOnce` 锁定)。 -- 定位不到的 load name 进 `unresolvedLoadNames`(按遇到顺序,同样按 bare name 去重),遍历继续。`images` 与 `unresolvedLoadNames` 恰好是 root 直接依赖的二分(direct 模式下,`DependencyClosureTests.inProcessDirectClosureResolvesMappedDependencies` 锁定)。 - -**`SharedDependencyClosure`**(2026-09-21):包一个 `() -> DependencyClosure` 的求值,首次读 `closure` 时求值一次、锁保护、之后直接返回。给同一个 root 的多个惰性消费者用——indexer 里 property-wrapper catalog 与 ObjC 祖先解析器各自都在第一次跨镜像查询时才要闭包,各自建就是各自把搜索路径里的 cache 整扫一遍。求值闭包里可以顺手派发 `searchPathLoadFailures`(indexer 就是这么做的),本模块自己仍不派发。 - -**为什么 SwiftInterface 保持 `.direct`**:TypeIndexing 按依赖清单逐模块生成 SourceKit 接口,成本随清单线性增长;OS 框架的传递闭包有几百个镜像,会退回提案 0009 之前「全 SDK 生成」的开销。要传递集合的宿主自己构造 `DependencyClosure(…, traversal: .transitive)` 再喂 `init(closure:)`。 - -## 消费入口速查 - -```swift -// 静态布局:传递闭包(默认) -let universe = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.machOFile(path: helperPath), .systemDyldSharedCache]) -// 或先建闭包再共享 -let closure = DependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache]) -let universe = try ImageUniverse.dependencyClosure(closure) -let providerDependencies = SwiftInterfaceBuilderDependencies(closure: closure) // 注意:这里是传递集合 - -// __C 归属:直接依赖 -let providerDependencies = SwiftInterfaceBuilderDependencies(machO: machOFile, searchPaths: [.systemDyldSharedCache], eventHandlers: [ConsoleEventHandler()]) -providerDependencies.unresolvedLoadNames // 精确报告解析不到的依赖 -``` - -已废弃(保留一个版本):`SwiftLayout.LayoutDependencySearchPath`(typealias)、`SwiftInterface.DependencyPath`(case 拼写不同,经 `searchPath` 转换)与 `SwiftInterfaceBuilderDependencies.init(machO:paths:eventHandlers:)`。 - -## 测试锚点 - -- `Tests/MachODependenciesTests/DependencyLoadNameTests.swift` — 归一规则表 + 与 `MachOImage(name:)` 的契约。 -- `Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift` — 进程里每个已映射镜像的路径(加上几个不存在的拼写),定位器的答案与 `MachOImage(name:)` 指向同一个镜像。 -- `Tests/MachODependenciesTests/DependencyClosureTests.swift` — direct / transitive 语义、BFS 前缀、去重、未解析报告、坏搜索路径不抛、自定义定位器收到原始 load name。 -- `Tests/MachODependenciesTests/FileDependencyLocatorTests.swift` — 宿主 cache 上的精确路径优先与 Catalyst 降级(无宿主 cache 时跳过);平台守卫(`LC_BUILD_VERSION` 读取、`areCompatible` 规则、iOSSimulator root 在宿主 cache 上一无所获、zippered root 可取 Catalyst 镜像)。 -- `Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift` — cache 里的 root 在自己的 cache 里找依赖(按 `LC_UUID` 认出找到的是 15.5 的 Foundation,前提是宿主的 Foundation 是另一个构建),两种打开方式各一例;点名同一个 cache 时用的仍是 root 来自的那个实例。没有归档的 15.5 cache 时跳过。 -- `Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift` — 端到端:15.5 cache 里 SwiftUICore 的闭包把 `Foundation.URL` 算成 24 字节。 -- `Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift` — 端到端:独立文件的 ObjC 祖先链经闭包走到 libobjc 的 `NSObject`。 -- `Tests/SwiftInterfaceTests/SwiftInterfaceBuilderDependenciesTests.swift` — 薄包装的 direct 语义、image 版非空回归、`init(closure:)` 保留调用方遍历。 -- `Tests/SwiftLayoutTests/DependencyClosureLayoutTests.swift` — 端到端:闭包驱动的跨模块字段偏移(未改动)。 - -## 已知边界 - -- `@rpath` 等不展开(见 §1)。 -- 依赖种类不过滤:load / weak / reexport / upward / lazy 全收。 -- cache 的 bare name 兜底对多点 leaf 名(`libc++.1.dylib`)只能给最差 rank。 -- 平台守卫只看 cache 镜像;一个 x86_64 时代的模拟器 root 只有 `LC_VERSION_MIN_IPHONEOS`,推成 `.iOS`,会与真机 cache 相容——历史格式的边角,未处理。 -- `MachODependenciesTests` 不在 CI 的 filter 子集里,只在本地全量跑。 - -## 相关文档 - -- [StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md) — SwiftLayout 阶段 3 的原始设计与「落地实测」(惰性索引、BFS、一次性 cache 索引等结论的出处)。 -- [TypeIndexingPipeline.md](../TypeIndexingPipeline.md) — 直接依赖清单在 `__C` 归属管线里的用法。 diff --git a/Documentations/Internal/Modules/MachOSymbols.md b/Documentations/Internal/Modules/MachOSymbols.md deleted file mode 100644 index 73c97e4fa..000000000 --- a/Documentations/Internal/Modules/MachOSymbols.md +++ /dev/null @@ -1,100 +0,0 @@ -# MachOSymbols 模块 - -> 模块参考文档(module reference),随代码维护。读者:维护者。 -> 细节文档见文末[「相关文档」](#相关文档);本文负责全貌与分工,不复述细节。 - -## 模块定位 - -MachOSymbols 是**符号索引**层:把一个镜像的符号表和 export trie 扫成可查询的索引,并把每个 Swift 符号 demangle 成节点树存起来,供上层按偏移、按名字、按类型成员反查。 - -它坐在 ABI 模型**上面一层**。`MachOSwiftSection` 够不到它(演进提案 `self-contained-abi-layer` 的边界):描述符只暴露实现偏移,把偏移归属到符号名是 `SwiftInspection` 的事。符号的**值类型**(`Symbol` / `Symbols` / `SymbolOrElement`)住在 `MachOResolving`,不在这里——「这个偏移上有哪些符号」是一次针对索引的**查询**,不是一次读取,所以 `Symbols` 故意不是 `Resolvable`。 - -模块另外托管一个跟符号无关的东西:`LargeStackTaskExecution`,库入口用来把整个调用链搬到大栈执行器上的开关。它放这儿是因为 demangler 是它唯一的服务对象。 - -## 文件 → 子系统对照 - -| 子系统 | 文件 | -|---|---| -| 1. 索引本体 | `SymbolIndexStore`、`SymbolTable`、`SymbolRowBucket` | -| 2. 符号值与查询出口 | `Symbol`、`DemangledSymbol`、`MachO+Symbol` | -| 3. 节点引用的共享与跨 store 对账 | `InternedNodeReferenceCache`、`StructuralNodeReferenceKey` | -| 4. 大栈执行器接入 | `LargeStackTaskExecution` | -| 5. `_symbolic` 符号表 | `SymbolicManglingSymbols` | - -## 子系统 1:索引本体 - -`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 槽也对不上名字。 - -**STABS 调试条目不决定任何偏移**(`NlistProtocol.isDebuggingEntry`)。带调试映射的镜像里,`N_GSYM` 条目和它描述的符号同名、值为 0。以前它被当成符号收进索引:一来被登记在 mach header 上;二来同名行是「后写覆盖」,排在它前面的本地符号(链接器先写本地符号、后写调试映射)偏移就被改成了 0,`internal` / `private` 的静态存储属性因此打印成 `Address: 0x0`。现在两条 symtab 采集腿对它只调 `SymbolTableBuilder.reserveRow`:名字还没有行时建一行占位,此后不改、也不登记到任何偏移,偏移由真符号决定,不管真符号排在前面还是后面。保留占位建行,是因为调试映射按编译顺序排列,行序跟着它就是源码顺序,打印器按行序列成员;直接丢掉调试条目,成员会改按符号表顺序(导出符号按名字排序)排列,SymbolTestsCore 的 42 个快照随之变化。 - -**成员 / typeInfo / thunk 属性这几个索引的 key 不是单射的**:第一层是打印出来的类型名,用 `.interfaceTypeBuilderOnly` 打印,会剥掉 private discriminator,于是不同文件里同名的 private 类型共用一个名字桶(issue #115:dump 路径按名字查,把两个类型的成员混进了同一个声明)。所以—— - -> 解析**某一个**类型的成员 / 信息 / 属性,必须用带 node 的重载(`memberSymbols(of:for:node:in:)`、`methodDescriptorMemberSymbols(of:for:node:in:)`、`typeInfo(for:node:in:)`、`thunkAttributeMembers(of:for:node:in:)`)。只带名字的那几个重载会故意把所有子桶摊平,只用于「所有打印成这个名字的类型」这种聚合查询。 - -**同一地址上的符号按归属分组**(演进提案 `faster-lazy-definition-indexing`)。identical code folding 会把许多 conformance 内容相同的 witness 实现合并到一个地址上——SwiftUI 里一个 `_destroySelf` 或值 witness 的实现挂着上千个名字。要在这样的地址上找「属于某个 conformance 的那个」或「属于某个协议的那个」,用 `symbols(for:ownedBy:ownerKind:printedWith:in:)`:`SymbolOwnerKind.conformingType` 是符号树里第一个 `protocolConformance` 的第一个子节点,`.protocol` 是第一个 `protocol` 节点,按调用方给的打印预设打印后比较;结果按 `symbols(for:in:)` 的顺序排列,带查询偏移。每个「地址 + 规则 + 预设」第一次被问到时在 `Storage` 上分组一次(锁外计算、锁内先到者胜),之后每次是两次字典查找。以前 `ExtensionDefinition`、`ProtocolDefinition`、`ProtocolConformanceDumper`、`ProtocolDumper` 都是把这个地址的名字逐个 demangle、搜索、打印再比较,每个 conformance 来一次,对别名组大小是平方级:SwiftUI 一个镜像检查 365 万次、只涉及 17,852 个不同的名字。**新的「在别名里找归属」的代码走这个查询,不要再逐个比较。**`ClassDumper.validNode` 与 `OverrideSymbolMatcher` 按声明上下文结构相等来认领,规则不同、实测开销可以忽略,没有改。 - -`Storage` 同时带着镜像的**导出事实**:两条 symtab 采集腿都过滤掉 external 符号,导出符号的行只可能来自 export trie 那条腿,而那条腿的行是有条件产出的,所以 trie 归属在同一趟里单独记(逐行位图加一个给无偏移 re-export 用的名字集合),撑起三态的 `isExported(name:in:)`(`nil` = 这个镜像没有导出信息,**此时绝不标注**)。 - -## 子系统 2:查询出口与 detach - -查询在出口处构造 `DemangledSymbol` / `NodeReference` 值。这些值共享镜像那张 `SymbolTable`——对于一次查询吐出又丢弃的几十万个值,这是对的交换。 - -> **但凡要存进声明模型的 `DemangledSymbol`,必须先 `detachedFromSharedTable()`。** 一个存活的值就钉住整张表(镜像表还会把它对 mapped string table 的读连在加载状态上),`removeSubIndexer(_:)` 想回收的按镜像内存就白回收了。查询路径上**不要** detach。 - -实测(SwiftUI,iOS 18.5):9872 个被存下来的值只引用 5.1% 的行,detach 是拿约 0.6 MB 的小分配换掉整张表的驻留。存的地方一共六处,`SymbolTableRetentionTests` 会在有人新增第七处却忘了 detach 时立刻变红。 - -## 子系统 3:跨 store 对账 - -节点引用的 `Hashable` 是 **store 身份**语义。一个镜像内部同时存在好几个 store——冻结的主符号 store、迟到名字的旁路 store、缓存的各作用域 store,按镜像驱逐还会把某个作用域重建到新 store 上而旧引用仍然钉着旧的(2026-09-28 之前内存压力也会)——所以跨 store 是常态,不是例外。 - -> **任何 key 与查询可能来自不同 store 的 `Dictionary` / `Set`,必须以 `StructuralNodeReferenceKey` 为 key,不能用裸 `NodeReference`。** - -用裸 key 会静默失败,而且各处的失败形态还不一样:override / vtable 查找会丢掉 `override` 关键字和 vtable 偏移注释;下标的 getter 和 setter 分进两个桶,只有 setter 的那个被丢弃;合并的 thunk 会把 `func` / `init` 印两遍;witness 会被认领两次。只有在**一批** `memberSymbols` 内部做分组或去重(单一 hash-consed store,结构相等与索引相等重合)时,裸 key 才是安全的。 - -`InternedNodeReferenceCache` 管的是 `SharedNodeStore` 里**没有**的那部分职责:按 Mach-O 作用域分区和驱逐。metadata 派生的名字树走它。 - -> 批量路径上不要裸调 `NodeReference(interning:)`,走缓存。 - -## 子系统 4:大栈执行器 - -`LargeStackTaskExecution.run(_:)` 在库入口外面把 swift-demangling 的 16 MB `LargeStackTaskExecutor` 设为 task executor preference。demangler 每次调用会拿**调用线程**的剩余栈跟 2 MB 下限比一下决定要不要跳到自己的 8 MB 池;协作线程和 libdispatch 线程只有 512 KB,于是异步打印循环每打印一个符号就要付一次线程往返加信号量等待(实测 8–21 µs,1.14–2.28 倍)。在执行器线程上这个探测每次都过,整条流水线(含同步被调用方)就地跑完。 - -几条容易踩的:嵌套调用是 no-op;**非结构化的 `Task {}` 不继承这个偏好**(SE-0417),所以绝不要在被包裹的入口里起一个;main actor 保留自己的执行器;macOS 15 / iOS 18 以下或非 Darwin 平台原样执行 body。进程级关闭开关 `isEnabled`,由环境变量 `MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR` 播种。 - -## 子系统 5:`_symbolic` 符号表 - -编译器给每条带 symbolic reference 的 mangled name 生成一个链接器去重用的符号(`_symbolic ` / `_default assoc type ` 开头), -名字里按引用顺序写出每个被引用者的完整 mangling。构建扫描的两条 symtab 采集腿各多一个前缀分支,把它们收进 -`Storage.symbolicManglingSymbolTable`——同一个 `SymbolTable` 结构、同样的名字来源与偏移换算,但**不进任何索引**: -`symbols(for:in:)`、`containsSymbol(named:)`、导出事实都看不到它们,这些名字也从不 demangle。唯一的出口是 -`symbolicManglingSymbols(in:)`,解码在 SwiftInspection 的 `SymbolicManglingIndex`(它要读 mangled name 的字节,本模块够不到 -ABI 模型)。 - -> 被引用者不能单独 demangle:同一个 mangler 依次写出它们,后面的会用 substitution 借用前面的。一律经 -> `SymbolicManglingIndex.referentNode(of:in:)` 拿节点。 - -细节与实测:[SymbolicManglingSymbols.md](../SymbolicManglingSymbols.md)。 - -## 关键契约 - -- **不要重新引入带缓存的 demangle**。全模块(以及上层)用 `demangleAsNodeTransient` + `Node.createTransient`;一棵用完即弃的树必须是 transient 的,否则全局 `NodeCache` 会随浏览一路涨。 -- **不要在缓存锁里做可能阻塞的大栈跳转**。迟到名字的 demangle 跑在锁外面,竞争的 misser 各自 intern 进同一个 store,靠结构化去重拿到同一个引用。 -- **改本模块的结构布局要先 `swift package clean`**。SwiftPM 增量构建被观察到链接了陈旧的下游目标文件,症状是运行时在 `outlined destroy` 里 SIGSEGV。公开类型跨模块搬家或翻转依赖边同样会触发(2026-09-12 有一次实例)——先 clean,再诊断。 - -## 相关文档 - -- [NodeStoreMigrationPlan.md](../NodeStoreMigrationPlan.md)——存储形态迁移的完整分阶段计划。 -- [NodeStoreMigrationOpenIssues.md](../NodeStoreMigrationOpenIssues.md)——迁移遗留问题。 -- [SharedNodeStoreMigration.md](../SharedNodeStoreMigration.md)——声明模型持有 `NodeReference` 的那一步。 -- [SymbolIndexStoreMemoryOptimization.md](../SymbolIndexStoreMemoryOptimization.md)——内存优化。 -- [PrivateTypeMemberAttribution.md](../PrivateTypeMemberAttribution.md)——同名 private 类型的成员归属(issue #115)。 -- [LargeStackTaskExecutorAdoption.md](../LargeStackTaskExecutorAdoption.md)——执行器接入与实测数据。 -- [MetadataReaderCacheRetirement.md](../MetadataReaderCacheRetirement.md)——`SymbolicDemangler` 的 demangle memo。 -- [SymbolicManglingSymbols.md](../SymbolicManglingSymbols.md)——`_symbolic` 符号的格式、收集与解码。 -- 演进提案:[0001](../../Evolutions/0001-symbol-name-offsetization.md) 符号名 offset 化 · [0003](../../Evolutions/0003-symbol-row-bucket-flattening.md) 行号桶扁平化 · [0018](../../Evolutions/0018-self-contained-abi-layer.md) ABI 层自包含 · [0019](../../Evolutions/0019-large-stack-executor-and-cross-version-parallelism.md) 大栈执行器。 diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index 2ff1161ae..2d72afbc9 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -22,27 +22,32 @@ | 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 也用) | +| ARM64InstructionDecoding | MachOKitExtensions 的 [ARM64InstructionDecoding.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/ARM64InstructionDecoding.md) | 已搬去 MachOKitExtensions(提案 `move-cross-reference-layers`):手写的指令字读取与跳板形状,CrossReferenceAnalysis 与 SwiftThunkAnalysis 经 `@_spi(Internals)` 用 | +| MachOAddressResolution(原 CodeAddressResolution) | MachOKitExtensions 的 [MachOAddressResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOAddressResolution.md) | 已搬去 MachOKitExtensions:离线的地址空间、桩链、槽解析与 cache 镜像定位,线程读取与交叉引用文件模式共用 | +| MachOCodeReferences(原 CrossReferenceCore) | MachOKitExtensions 的 [MachOCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md) | 已搬去 MachOKitExtensions:交叉引用与语言无关的核心层;总说明仍在 [CrossReferenceAnalysis.md](CrossReferenceAnalysis.md) | +| ObjCCodeReferences(原 CrossReferenceObjC) | MachOObjCSection 的 [ObjCCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/next/Documentations/Internal/ObjCCodeReferences.md) | 已搬去 MachOObjCSection:交叉引用的 ObjC 层;总说明仍在 [CrossReferenceAnalysis.md](CrossReferenceAnalysis.md) | | SwiftAttributeInference | — | 待写 | | SwiftDeclaration | [SwiftDeclaration.md](SwiftDeclaration.md) | ✅ 已写 | | SwiftDeclarationRendering | — | 待写 | | SwiftDump | — | 待写 | -| SwiftInspection | — | 待写 | +| SwiftInspection | — | 待写(ObjC 一侧已拆进 SwiftObjCInterop) | +| SwiftObjCInterop | [SwiftObjCInterop.md](SwiftObjCInterop.md) | ✅ 已写(拆分来历:[0089-swift-objc-interop-module](../../Evolutions/0089-swift-objc-interop-module.md)) | | SwiftLayout | [SwiftLayout.md](SwiftLayout.md) | ✅ 已写(专题:[StaticLayoutEngine.md](../StaticLayoutEngine.md)、[StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md)) | | SwiftDiffing | — | 待写(专题:[ABIDiffDesignAndLimitations.md](../ABIDiffDesignAndLimitations.md)、[ABIEvolutionDesign.md](../ABIEvolutionDesign.md)) | | TypeIndexing | — | 待写(专题:[TypeIndexingPipeline.md](../TypeIndexingPipeline.md)) | | SwiftOutputTransformer | — | 待写(专题:[OutputTransformerMigration.md](../OutputTransformerMigration.md)) | | MachOSwiftSection | — | 待写 | -| MachOFoundation | — | 待写 | -| MachOSymbols | [MachOSymbols.md](MachOSymbols.md) | ✅ 已写(专题:[SymbolIndexStoreMemoryOptimization.md](../SymbolIndexStoreMemoryOptimization.md)) | -| MachOBase | — | 待写(伞模块:ABI 层允许看到的全部——reading / resolving / pointers;见 [SelfContainedABILayer.md](../SelfContainedABILayer.md)) | -| MachOPointers | — | 待写(`SymbolOrElementPointer` 自 `MachOSymbolPointers` 并入,见 [SelfContainedABILayer.md](../SelfContainedABILayer.md)) | -| MachOReading / MachOResolving | — | 待写 | -| MachOCaches | [MachOCaches.md](MachOCaches.md) | ✅ 已写 | -| MachODependencies | [MachODependencies.md](MachODependencies.md) | ✅ 已写 | +| MachOFoundation | — | 由 MachOKitExtensions 提供(2.0.0 起,同名 product):再导出 `MachOBase`、`MachOSymbols`、`MachODependencies` | +| SwiftSymbols | [SwiftSymbols.md](SwiftSymbols.md) | ✅ 已写(Swift 符号索引 `SwiftSymbolIndexStore`;专题:[SymbolIndexStoreMemoryOptimization.md](../SymbolIndexStoreMemoryOptimization.md)) | +| MachOSymbols | — | 由 MachOKitExtensions 提供(2.0.0 起):符号表、采集与 C/C++ 符号索引,实现说明 [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md) | +| MachOBase | — | 由 MachOKitExtensions 提供(2.0.0 起):伞模块,ABI 层允许看到的全部——reading / resolving / pointers,不再再导出 `Utilities`(ABI 模块 `MachOSwiftSection` 自己再导出);边界见 [SelfContainedABILayer.md](../SelfContainedABILayer.md) | +| MachOPointers | — | 由 MachOKitExtensions 提供(2.0.0 起):相对 / 间接指针与 `SymbolOrElementPointer`(自 `MachOSymbolPointers` 并入的来历见 [SelfContainedABILayer.md](../SelfContainedABILayer.md)) | +| MachOReading / MachOResolving | — | 0.25.0 起是 MachOKitExtensions 包的模块(2.0.0 起,同名),实现说明在该包的 `Documentations/Internal/ReadingContextAbstraction.md`;本库怎么用它们见 [ReadingContextAbstraction.md](../ReadingContextAbstraction.md) | +| MachOCaches | — | 由 MachOKitExtensions 提供(2.0.0 起),实现说明 [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md) | +| MachODependencies | — | 由 MachOKitExtensions 提供(2.0.0 起),实现说明 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) | | MachOSwiftSectionC | — | 待写 | -| MachOMacros | — | 待写 | +| SwiftSectionMacros | — | 待写 | | Utilities | — | 待写 | -| MachOFixtureSupport / MachOTestingSupport(C) / baseline-generator | — | 待写(测试基础设施,可合并成一篇) | +| SwiftSectionFixtureSupport / SwiftSectionTestingSupport(C) / baseline-generator | — | 待写(测试基础设施,可合并成一篇) | -(`Demangling` / `Semantic` 来自上游包 swift-demangling / swift-semantic-string,`MachOKitExtensions` / `MachOObjCSection` 是 sibling 外部包,文档归各自仓库。) +(`Demangling` / `Semantic` 来自上游包 swift-demangling / swift-semantic-string,`MachOKitExtensions` / `MachOObjCSection` 是 sibling 外部包,文档归各自仓库——上表标「由 MachOKitExtensions 提供」的模块也一样。) diff --git a/Documentations/Internal/Modules/SwiftDeclaration.md b/Documentations/Internal/Modules/SwiftDeclaration.md index f3304f6ee..ba1c8c402 100644 --- a/Documentations/Internal/Modules/SwiftDeclaration.md +++ b/Documentations/Internal/Modules/SwiftDeclaration.md @@ -13,39 +13,43 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP ## 文件 → 子系统对照 -目录名说什么,里面就只放什么:`Definitions/` 只有声明本体,成员构件与构建期机器各有自己的目录。 +模块分成两棵树,判据是可见性(提案 [draft-swift-declaration-model-indexing-layout](../../Evolutions/draft-swift-declaration-model-indexing-layout.md)):`Model/` 是下游读的公开模型,索引结束后还留着;`Indexing/` 是把模型填满的代码,里面每个声明都是 `package` 或 `internal`,只在 `index(in:)` 与 `SwiftDeclarationIndexer.prepare()` 期间有人调用。新文件按这条判据归位:类型是 `public` 的、会出现在公开 API 的返回值里,进 `Model/`;只在索引期活着,进 `Indexing/`。将来要把索引代码整体挪到 `SwiftIndexing`,边界已经画好了。 | 子系统 | 文件 | |---|---| -| 1. 声明本体 | `Components/Definitions/`(`Definition` / `MutableDefinition` 协议、`TypeDefinition` 及其七个功能扩展、`ProtocolDefinition`、`ExtensionDefinition` 及各自的 `+Indexing`(`ExtensionDefinition` 另有 `+ThunkAttributes`,与 `TypeDefinition+ThunkAttributes` 共用 `Building/MemberAttributeApplication`)、`FunctionDefinition`、`VariableDefinition`、`SubscriptDefinition`、`FieldDefinition`、`WrappedPropertyDefinition`) | -| 2. 成员构件 | `Components/Members/`(`Accessor`、`OrderedMember`、`MemberCategory`、`StrippedSymbolicRequirement`)——模型的一部分,会出现在公开 API 的返回值里 | -| 3. 构建期机器 | `Components/Building/`(`DefinitionBuilder`、`MemberSymbolBucketing`、`OverrideSymbolMatcher`、`ClassDispatchLookups`、`AnnotatedSymbol`、`WrappedPropertyRecovery`、`MemberAttributeApplication`)——全是 `package`,索引结束就不再有人碰 | -| 4. 名字 | `Components/Names/`(`DefinitionName`、`TypeName`、`ProtocolName`、`ExtensionName`) | -| 5. 种类枚举 | `Components/Kinds/` | -| 6. 挂在声明上的独立概念 | `Components/ExportStatus`、`Components/AssociatedTypeWitnessProjection`、`Components/SwiftAttribute` | -| 7. 对上游类型的扩展 | `Extensions/`(按被扩展的类型分文件:`ProtocolConformance+Names`、`TypeContext+Names`、`FieldRecord+DemangledType`、`Node+TypeKind`……) | -| 8. 事件 | `Events/SwiftIndexEvents` | +| 1. 声明本体 | `Model/Definitions/`(`Definition` / `MutableDefinition` 协议、`TypeDefinition`、`ProtocolDefinition`、`ExtensionDefinition`、`ObjCProtocolDefinition`,以及 ObjC 声明导入成 Swift 的 `ObjCImportedClassDefinition`、`ObjCImportedCategoryDefinition`、`ObjCImportedProtocolDefinition`)——只有存储属性、`init` 与 materialize 方法,不含索引逻辑 | +| 2. 成员 | `Model/Members/`:成员定义(`FunctionDefinition`、`VariableDefinition`、`SubscriptDefinition`、`FieldDefinition`、`WrappedPropertyDefinition`、`ObjCProtocolRequirementDefinition`、`ObjCImportedMemberDefinition`)、宏展开的描述 `ObservableMacroExpansion`、成员构件(`Accessor`、`OrderedMember`、`MemberCategory`、`StrippedSymbolicRequirement`),以及三种成员定义上的公开投影 `ResolvedObjCMemberFacts` | +| 3. 名字 | `Model/Names/`(`DefinitionName`、`TypeName`、`ProtocolName`、`ExtensionName`) | +| 4. 种类枚举 | `Model/Kinds/` | +| 5. 挂在声明上的独立概念 | `Model/` 根下的 `ExportStatus`、`SwiftAttribute`、`SwiftAttachedMacro`、`ResolvedAssociatedTypeWitness`、`ObjCCategoryConformance` | +| 6. 各声明的索引 | `Indexing/`:`DefinitionIndexing`(每个定义只索引一次,见下文)、`TypeDefinition/` 下的十个扩展(见下表)、`ExtensionDefinition/` 下的 `+Indexing` / `+ObjCMembers` / `+ThunkAttributes`、`ProtocolDefinition+Indexing`、`ObjCProtocolDefinition+Indexing`、`ObjCImportedDefinitions+Indexing`(三种 ObjC 导入定义) | +| 7. 构建期机器 | `Indexing/Building/`(`MemberDefinitionBuilder`、`MemberSymbolBucketing`、`OverrideSymbolMatcher`、`ClassDispatchLookups`、`StandInMemberSymbolBuilder`、`AnnotatedSymbol`、`WrappedPropertyRecovery`、`ObservableMacroExpansionRecovery`、`ThunkAttributeMatcher`、`ObjCMemberMatcher`、`ObjCProtocolNameBuilder`)——各声明的索引扩展调用的构件;`TypeDefinition+ThunkAttributes` 与 `ExtensionDefinition+ThunkAttributes` 共用 `ThunkAttributeMatcher`,两个 `+ObjCMembers` 共用 `ObjCMemberMatcher`。命名空间按角色取后缀(提案 [draft-swift-declaration-type-naming](../../Evolutions/draft-swift-declaration-type-naming.md)):造出新东西的叫 `…Builder`,拿二进制里另一处的证据(thunk 符号、ObjC 方法表、override 描述符)对到已建好的成员上的叫 `…Matcher`,补回二进制丢掉的事实的叫 `…Recovery`;不用 `…Application`,它会被读成「应用程序」 | +| 8. 对上游类型的扩展 | `Extensions/`(按被扩展的类型分文件:`ProtocolConformance+Names`、`TypeContext+Names`、`FieldRecord+DemangledType`、`Node+TypeKind`、`DemanglingNode+StoredVariable`……) | +| 9. 事件 | `Events/SwiftIndexEvents` | -### TypeDefinition 的七个扩展 +### TypeDefinition 的十一个扩展 -`index(in:)` 串起来的是六件互不相干的事,每件一个文件,主干只剩调用顺序: +本体 `TypeDefinition.swift` 在 `Model/Definitions/`:存储属性、两个 `init`、`materializedTypeContext(in:)`,不含任何索引逻辑。索引代码在 `Indexing/TypeDefinition/`:主干在 `+Indexing`,`index(in:)` 串起来的其余十件互不相干的事每件一个文件,主干只剩调用顺序: | 文件 | 负责 | |---|---| -| `TypeDefinition.swift` | 存储属性、两个 `init`、`materializedTypeContext(in:)`——不含任何索引逻辑 | -| `+Indexing` | `index(in:)` 主干、字段记录 → `FieldDefinition`、accessor 组回折 | +| `+Indexing` | `index(in:)` 主干、字段记录 → `FieldDefinition`、accessor 组回折、源码给类起的 ObjC 运行时名字 | +| `+InitAccessors` | SE-0400 init accessor 初始化哪些字段的推断 → `VariableDefinition.initializedFieldNames`(规则在 SwiftInspection 的 `InitAccessorFieldInference`) | | `+ClassDispatch` | vtable / override / defaultOverride 三张表 → `ClassDispatchLookups`;另为本类每个 `Tq` 能命名的 vtable 槽造一个替身成员符号 | | `+MemberIndexing` | 六类成员与两个 `deinit` 符号;实现符号缺席的 vtable 成员用替身补上 | -| `+FinalRecovery` | 提案 0006 的 `final` 恢复与它的四道门 | | `+ThunkAttributes` | `@objc` / `@nonobjc` / `@distributed` 的交叉引用 | +| `+ObjCMembers` | 类自己的 ObjC 方法表 join 到成员上:`@objc`、`override`、显式 selector(经 `Building/ObjCMemberMatcher`) | +| `+FinalRecovery` | 提案 0006 的 `final` 恢复与它的四道门 | | `+SynthesizedMembers` | 自动合成成员的去重 | | `+WrappedProperties` | property wrapper 用法的恢复 | +| `+ObservableMacro` | `@Observable` 展开的恢复 → `observableMacroExpansion`(规则在 `Building/ObservableMacroExpansionRecovery`) | +| `+ObjCProtocols` | 类的 `class_ro_t` 列出的 ObjC 协议 → `objcProtocolNames`(经 `Building/ObjCProtocolNameBuilder`) | -**主干里的顺序是有约束的,不能随手调**:`final` 恢复要在 `applyThunkAttributes` 之后(它要 `@objc` 证据)且在 `orderedMembers` 之前(那一步会把成员值复制走);wrapped property 恢复要在字段回折与成员构建都完成之后。每个步骤方法的 doc comment 各自写明了自己依赖什么。 +**主干里的顺序是有约束的,不能随手调**:`final` 恢复要在 `applyThunkAttributes` 与 `applyObjCMembers` 之后(两者都给它 `@objc` 证据,它据此排除 `@objc dynamic`),且在 `orderedMembers` 之前(那一步会把成员值复制走);init accessor 的推断同样要在 `orderedMembers` 之前,紧跟在字段回折之后;wrapped property 恢复要在字段回折与成员构建都完成之后;`@Observable` 展开的恢复又要在它之后,wrapper 的存储字段不归宏。每个步骤方法的 doc comment 各自写明了自己依赖什么。 ### 每个定义只索引一次,可以被并发打印 -三个 Definition 的 `index(in:)` 是**同步**函数,都经 `DefinitionIndexing.swift` 执行(提案 [0066-concurrent-definition-printing](../../Evolutions/0066-concurrent-definition-printing.md))。进程级一把锁守着两样东西:一张「正在索引」的表(按 `ObjectIdentifier(定义)`),和每个定义自己的 `hasCompletedIndexing`。首个调用者认领后在自己的线程上跑完索引体;同时到来的调用者在认领者的 promise(复用 `SharedCacheBuildPromise`,载荷是 `Result`)上阻塞等待,拿到同一个结果。索引体抛错时定义回到未索引、错误交给全部等待者,下次调用重试。`isIndexed` 是只读的计算属性,读的就是锁下的那个标志。 +七个 Definition(`TypeDefinition`、`ProtocolDefinition`、`ExtensionDefinition`、`ObjCProtocolDefinition` 与三种 ObjC 导入定义)的 `index(in:)` 是**同步**函数,都经 `Indexing/DefinitionIndexing.swift` 执行(提案 [0066-concurrent-definition-printing](../../Evolutions/0066-concurrent-definition-printing.md))。进程级一把锁守着两样东西:一张「正在索引」的表(按 `ObjectIdentifier(定义)`),和每个定义自己的 `hasCompletedIndexing`。首个调用者认领后在自己的线程上跑完索引体;同时到来的调用者在认领者的 promise(复用 `SharedCacheBuildPromise`,载荷是 `Result`)上阻塞等待,拿到同一个结果。索引体抛错时定义回到未索引、错误交给全部等待者,下次调用重试。`isIndexed` 是只读的计算属性,读的就是锁下的那个标志。 阻塞等待不会死锁,靠两条前提,改索引时要守住: @@ -74,11 +78,15 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP ### 导出状态在构造时定死 -每个 `TypeDefinition` / `ProtocolDefinition` 带一个四态 `ExportStatus`(`exported` / `notExported` / `imageHasNoExportInformation` / `descriptorSymbolNameUnresolvable`),在构造时从声明自己的描述符符号解析一次,存成 `let`。所以 `SwiftDeclarationIndexer.prepare()` 一返回,整张表就都有值了,宿主可以逐行标注而不必抱着 Mach-O。 +每个 `TypeDefinition` / `ProtocolDefinition` 带一个 `ExportStatus`(`exported` / `notExported` / `imageHasNoExportInformation` / `descriptorSymbolNameUnresolvable` / `declarationIsCImported`),在构造时从声明自己的描述符解析一次,存成 `let`。描述符属于 `__C` 或 `__C_Synthesized` 模块时直接是 `declarationIsCImported`,不查 trie:编译器给 Clang 声明的是非唯一链接,每个用到这个 C 类型的模块各自生成一份描述符、谁都不导出,它说明不了类型能不能被外部使用,而本镜像给它写的扩展可以是公开 API(提案 [0083-exported-only-marking-mode](../../Evolutions/0083-exported-only-marking-mode.md))。描述符上没有符号、名字又不能可信地重整(镜像没留本地符号,声明在带约束的扩展里)时,私有或局部声明判 `notExported`,其余是 `descriptorSymbolNameUnresolvable`。`ObjCProtocolDefinition` 只能看名字:Swift 声明的 `@objc` 协议没有描述符,也没有任何自己的符号,私有的(或嵌在私有类型里的)判 `notExported`,其余是 `declarationHasNoSymbol`(提案 `export-verdict-without-local-symbols`)。所以 `SwiftDeclarationIndexer.prepare()` 一返回,整张表就都有值了,宿主可以逐行标注而不必抱着 Mach-O。 + +`TypeDefinition.wrappedProperties` 是索引在 `index(in:)` 末尾算出的 property wrapper 用法(提案 [0041-interface-hides-compiler-synthesized-members](../../Evolutions/0041-interface-hides-compiler-synthesized-members.md)):每个存储字段 `_x`,只要它的 nominal 类型有 `wrappedValue` accessor——先查本镜像符号索引(internal wrapper 也算),再经 `SwiftDeclarationRendering.PropertyWrapperTypeCatalog` 查本镜像与依赖闭包各镜像的导出 trie(SwiftUI 的 `@State` 用在 app 里)——就记一条 `WrappedPropertyDefinition`:属性名、`_x` / `$x` 的名字、attribute 类型节点(wrapper 恰一个泛型实参且等于被包装类型时省略实参;比较用 SwiftInspection 的 `StoredTypeMatching.declaredType(_:matchesStoredType:)`,撇开 `sending`——编译器 mangle 声明自身的函数类型时不写它,字段记录里照写),以及来源:`x` 自己的 accessor 符号还在就是 `declaredMember`;被 strip 了就 `synthesized(declaredTypeNode:hasSetter:)`,类型由 wrapper 的 `wrappedValue` 类型代入 `_x` 的泛型实参得到。`fields` 与 `variables` 里的 `_x`、`$x` 原样保留——diff / snapshot 的记录来自它们——只有 interface 打印器改按这张表渲染。目录由 `SwiftDeclarationIndexer.prepare()` 用索引配置里的 `dependencySearchPaths` 登记、随索引器一起释放(`PerImageCacheEvictionRegistry` 的 `propertyWrapperCatalog` claim);没登记过的镜像退化成查系统 cache。 + +`@Observable` 宏分两层进模型(提案 [0093-observable-macro-folding](../../Evolutions/0093-observable-macro-folding.md))。`TypeDefinition.attachedMacros` 在构造时算出,和 `ExportStatus` 一样 `prepare()` 一返回就在:类里有类型正是 `Observation.ObservationRegistrar` 的 `_$observationRegistrar` 字段、又没有 SwiftData `@Model` 留下的 `_$backingData`,就记 `.observable`。规则只读字段记录(`SwiftInspection.ObservableMacroRecognition`),所以剥过符号的镜像照样认得出;特化出来的定义沿用泛型定义的值。`SwiftAttachedMacro` 用 struct 加静态成员而不是 enum,以后识别别的宏,宿主的 `switch` 不会编不过。索引器建 conformance extension 时,给宏生成的 `extension X: Observation.Observable {}` 记上 `ExtensionDefinition.generatingMacro`。 -`TypeDefinition.wrappedProperties` 是索引在 `index(in:)` 末尾算出的 property wrapper 用法(提案 [0041-interface-hides-compiler-synthesized-members](../../Evolutions/0041-interface-hides-compiler-synthesized-members.md)):每个存储字段 `_x`,只要它的 nominal 类型有 `wrappedValue` accessor——先查本镜像符号索引(internal wrapper 也算),再经 `SwiftDeclarationRendering.PropertyWrapperTypeCatalog` 查本镜像与依赖闭包各镜像的导出 trie(SwiftUI 的 `@State` 用在 app 里)——就记一条 `WrappedPropertyDefinition`:属性名、`_x` / `$x` 的名字、attribute 类型节点(wrapper 恰一个泛型实参且等于被包装类型时省略实参),以及来源:`x` 自己的 accessor 符号还在就是 `declaredMember`;被 strip 了就 `synthesized(declaredTypeNode:hasSetter:)`,类型由 wrapper 的 `wrappedValue` 类型代入 `_x` 的泛型实参得到。`fields` 与 `variables` 里的 `_x`、`$x` 原样保留——diff / snapshot 的记录来自它们——只有 interface 打印器改按这张表渲染。目录由 `SwiftDeclarationIndexer.prepare()` 用索引配置里的 `dependencySearchPaths` 登记、随索引器一起释放(`PerImageCacheEvictionRegistry` 的 `propertyWrapperCatalog` claim);没登记过的镜像退化成查系统 cache。 +`index(in:)` 在 wrapped property 恢复之后算 `TypeDefinition.observableMacroExpansion`:哪些 `_x` 是被跟踪属性 `x` 的存储、来源(`x` 的 accessor 还在镜像里是 `declaredMember`,否则 `synthesized`)与认定它的证据,哪些存储的 `var` 是 `@ObservationIgnored`,以及宏生成的方法——按名字、参数标签与形状认:`access(keyPath:)`、`withMutation(keyPath:_:)` 是泛型、第一个参数是 `KeyPath`,`shouldNotifyObservers(_:_:)` 是泛型、两个参数;源码在同名下写的别的形状(无参的 `shouldNotifyObservers()`、`access(keyPath: String)`)是源码自己的,宏会在旁边另加自己的那份(体检第 6 条:此前只比名字与标签,这样的方法在折叠形态里被藏掉)。成员 `x` 的类型与 `_x` 不同时 `_x` 不归 `x`(`weak` 之类的引用存储先剥掉,`sending` 照上面撇开,SwiftUI 的 `makeFileCoordinator` 就是这种)。证据依次是:`x` 的 init accessor;镜像里成员 `x` 的 setter 或 `_modify`;初始值表达式挂在 `x` 名下。`_x` 自己的初始值表达式、或 `_x` 有 accessor 而 `x` 一个都没有,把它排除;什么都没有时只凭存储字段名认作被跟踪,这一档会把 `@ObservationIgnored var _y` 读成被跟踪的 `y`。镜像带不带本地符号不分流:系统框架链接时 dead-strip,SwiftUI 带本地符号却没有 init accessor,缺了不代表没有。初始值表达式不进成员桶;init accessor 进了(它是所属属性的 `AccessorKind.initAccessor`,见下文),这里照旧和初始值表达式一样,用 `symbols(of: .initAccessor)` / `symbols(of: .initializer)` 按类型筛,先比名字再比上下文——按 kind 的索引对每个符号都记一行,进不进成员桶都不影响它。初始值表达式只在 accessor 定不下来时才查,每个类最多一次。和 wrapped property 一样,`fields`、`variables`、`functions` 原样保留,只有 interface 打印器按这份描述折叠。 -两个「没有结论」的态**作用域不同**,不要混:`imageHasNoExportInformation` 是镜像级的(根本没有 export trie,此时把它读成「未导出」会把一个 `.o` 文件的每个声明都报成未导出);`descriptorSymbolNameUnresolvable` 是声明级的(trie 没问题,但这一个名字的 remangle 不可信)。 +四个「没有结论」的态**作用域不同**,不要混:`imageHasNoExportInformation` 是镜像级的(根本没有 export trie,此时把它读成「未导出」会把一个 `.o` 文件的每个声明都报成未导出);`descriptorSymbolNameUnresolvable` 是声明级的(trie 没问题,但这一个名字的 remangle 不可信);`declarationHasNoSymbol` 也是声明级的,但不是读不出,是本来就没有可查的符号;`declarationIsCImported` 同样是声明级的,符号倒是有,只是那是本镜像的一份副本,不是声明自己的。 对外投影只有两个:`isExported: Bool?` 和 `isDefinitelyNotExported`——**过滤和标注只能依据后者**。 @@ -98,19 +106,38 @@ Handler 的调用是**进程级串行**的(跨所有 dispatcher 一把递归 ### `@objc @implementation` 类挂在 extension 上 -SE-0436 的类在 `__swift5_*` 里没有身影,模型里它就是那个 `__C.X` 的 `ExtensionDefinition`:`objcImplementation` 装 `SwiftInspection.ObjCImplementationClassFacts`(证据档位、ivar 与 `Wvd` 的 join、方法表),`VariableDefinition.objcImplementationStorage` 标出由访问器符号建出来却是存储属性的成员。这个事实**不进** ABI 快照的容器 key。详见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 +SE-0436 的类在 `__swift5_*` 里没有身影,模型里它就是那个 `__C.X` 的 `ExtensionDefinition`:`objcImplementation` 装 `SwiftObjCInterop.ObjCImplementationClassFacts`(证据档位、ivar 与 `Wvd` 的 join、方法表),`VariableDefinition.objcImplementationStorage` 标出由访问器符号建出来却是存储属性的成员。这个事实**不进** ABI 快照的容器 key。详见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 ### 成员从符号建,vtable 槽补上缺席的那些 -成员定义是符号驱动的:`FunctionDefinition.symbol`、`Accessor.symbol` 都不是可选值,`DefinitionBuilder` 的每个构造点都从一个 `DemangledSymbol` 出发。class 的 vtable 成员是例外来源:library evolution 模块只导出 public class 方法的 `Tj` / `Tq`,实现符号是 local 的,镜像的 local 符号被剥掉之后(系统 dyld shared cache 里的 AppKit、`strip -x` 过的二进制)这些成员没有符号可建。`classDispatchLookups` 为本类每个 `Tq` 能命名、实现指针非 null 的槽造一个替身符号——名字是 `Tq` 名去掉后缀(实现函数本来的 mangled 名),偏移是实现偏移(async 方法再跳到函数入口)——`indexMembers` 经 `ClassDispatchLookups.supplementing(_:in:)` 只补真实符号没有声明的成员。替身按实现符号的样子造,所以导出判定、ObjC 方法表 join、ABI 身份都不用分支。ABI 墓碑、modify / read 协程、override 槽不补。打印时 class 的 vtable 成员(有槽号的成员)按槽号排在最前(`OrderedMember.vtableOrdered`)。详见 [DescriptorOnlyVTableMembers.md](../DescriptorOnlyVTableMembers.md)。 +成员定义是符号驱动的:`FunctionDefinition.symbol`、`Accessor.symbol` 都不是可选值,`MemberDefinitionBuilder` 的每个构造点都从一个 `DemangledSymbol` 出发。class 的 vtable 成员是例外来源:library evolution 模块只导出 public class 方法的 `Tj` / `Tq`,实现符号是 local 的,镜像的 local 符号被剥掉之后(系统 dyld shared cache 里的 AppKit、`strip -x` 过的二进制)这些成员没有符号可建。`classDispatchLookups` 为本类每个 `Tq` 能命名、实现指针非 null 的槽造一个替身符号——名字是 `Tq` 名去掉后缀(实现函数本来的 mangled 名),偏移是实现偏移(async 方法再跳到函数入口)——`indexMembers` 经 `ClassDispatchLookups.supplementing(_:in:)` 只补真实符号没有声明的成员。替身按实现符号的样子造,所以导出判定、ObjC 方法表 join、ABI 身份都不用分支。ABI 墓碑、modify / read 协程、override 槽不补。打印时 class 的 vtable 成员(有槽号的成员)按槽号排在最前(`OrderedMember.vtableOrdered`)。详见 [DescriptorOnlyVTableMembers.md](../DescriptorOnlyVTableMembers.md)。 + +优化构建是另一个例外来源:整模块优化会把 internal 成员的实现符号删掉,只留下同一个成员的另一个入口——`@objc` 成员只剩它的 ObjC thunk(`$s…To`,函数体内联在里面),class 的 initializer 只剩 initializing entry point(`…fc`,allocating entry point 内联进了调用方),Swift 6.4 连它也只剩函数签名特化副本(`…fcTf…`)。`StandInMemberSymbolBuilder` 从这几种入口造替身,规则与 `Tq` 替身相同:名字与成员树照实现符号的样子(thunk 去掉 `To` 与 `objCAttribute`,initializing entry point 把 `constructor` 改写成 `allocator`、`fc` 换成 `fC`,特化副本先去掉 `Tf…` 后缀再照 initializing entry point 处理),偏移是镜像里留下的那个入口。类成员经 `StandInMemberSymbolBuilder.TypeMembers`,extension 成员经 `supplementingExtensionMembers`,都排在真实符号与 `Tq` 替身之后,只补没人声明的成员;去重键 `declaredEntityKey(of:)` 三种替身共用。详见 [ThunkOnlyObjCMembers.md](../ThunkOnlyObjCMembers.md)。 ### ObjC 方法表给出的成员事实:`@objc`、`override`、显式 selector -`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)。 +`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/ObjCMemberMatcher` 在 `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 声明的 `@objc` 协议与类对 ObjC 协议的遵循 + +这种协议没有 protocol descriptor,所以不是 `ProtocolDefinition`(把它的 `protocolDescriptor` 改成可选会破坏下游),而是独立的 `ObjCProtocolDefinition`:名字是 `Type > Protocol`,与 Swift 协议同形,本镜像对它的 `extension` 因此落进它的 `defaultImplementationExtensions`;`index(in:)` 读出继承的协议与要求(`ObjCProtocolRequirementDefinition`:selector、setter selector、实例还是类、required 还是 optional、类型编码、声明的 node、签名来源)。签名来源是 `.selector`(按 importer 规则推出名字,打印时钉住 selector)或 `.conformer(className:)`(实现它的类的成员,声明的上下文已换成协议)。索引期只读成员表,不索引实现者的 `TypeDefinition`。 + +类对 ObjC 协议的遵循没有 conformance record:`TypeDefinition.objcProtocolNames` 是类的 `class_ro_t` 列的协议(同模块 extension 写的也在里面),在 `index(in:)` 里读;extension 别的模块的类时的 category 遵循是 indexer 的 `objcCategoryConformances`(`ObjCCategoryConformance`)。两者都去掉了某个 Swift 遵循隐含的 ObjC 协议。这些事实都**不进** ABI 快照。详见 [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md)。 + +### ObjC 声明按 Swift 导入的样子 + +镜像里的 ObjC 类、category 与协议,按 Swift 导入它们的样子建成 `ObjCImportedClassDefinition`、`ObjCImportedCategoryDefinition`、`ObjCImportedProtocolDefinition`(提案 [0090-objc-imported-declarations](../../Evolutions/0090-objc-imported-declarations.md))。一个镜像的 ObjC 类动辄上千,所以它们不随 `prepare()` 建,而是由 `SwiftDeclarationIndexer` 的 `objcImportedClassDefinition(named:)` 等方法按名字现建,第一次打印时索引自己:从 SwiftObjCInterop 的记录建出成员(`ObjCImportedMemberDefinition`)、父类与协议的名字。名字保持 `__C` 下的 ObjC 名,与 mangling 一致,Swift 里改了名的交给打印时的类型名提供者。 + +类与 category 定义带着实现它们的 Swift 定义:桥接出去的 Swift 类带 `swiftClassDefinition`,`swiftExtensions` 是本镜像里这个类的 Swift extension。成员与 Swift 成员的配对在打印器里做(SwiftPrinting 的 `ObjCImplementingSwiftMembers`),模型不记:先认索引期按符号记下的 `objcMember`,再认按名字记下的 override,剩下的在打印时按名字配——系统框架剥掉 thunk 符号、`-O` 把函数体内联进 thunk,前两档配不上多少(提案 [0096](../../Evolutions/0096-swift-first-imported-declarations.md))。属性成员带着 ObjC 属性表里的名字(`objcPropertyName`),宿主按它给头文件的 `@property` 标注。建这两样时有两个容易踩的坑: + +- **同一模块里 extension 的成员在 mangling 里就是类型自己的成员**(extension 没有约束时不带 extension 上下文),所以它们已经在 `TypeDefinition` 里,`typeExtensionDefinitions` 里没有对应的 extension。 +- **`TypeDefinition.extensions` 没有人填**,一直是空的。要一个类型在本镜像里的 extension,按 `typeName.extensionName` 去查 indexer 的 `typeExtensionDefinitions` 与 `conformanceExtensionDefinitions`。 ### 访问器种类与关联类型的抑制(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)还没有接。 +`AccessorKind` 除 get / set / read / modify 外还有 SE-0507 的 `borrowAccessor` / `mutateAccessor`(符号后缀 `vb` / `vz`)。只声明了这两种访问器的属性、下标与协议要求没有 getter 符号,`MemberDefinitionBuilder` 因此把 getter 与 `borrow` 都当作「读访问器」来选声明节点;打印出的访问器块由 `hasBorrowAccessor` / `hasMutateAccessor` 决定(`{ borrow mutate }`),旁边编译器为满足协议合成的 getter / setter 不盖掉它们。`yielding borrow` / `yielding mutate`(SE-0474)还没有接。 + +SE-0400 的 init accessor 是 `AccessorKind.initAccessor`(符号后缀 `vi`,提案 [0094-init-accessor-recovery](../../Evolutions/0094-init-accessor-recovery.md))。编译器把它的访问级别写死为 `internal`,只有 `@usableFromInline` 的才导出,所以优化过、链接时 dead-strip 的镜像里通常只剩导出的那几个,`hasInitAccessor == false` 不说明源码里没有。它在同名那组 accessor 里排最后(`accessors.first` 代表属性,例如它的 witness table 偏移),不参与成员排序(`OrderedMember.minSymbolOffset`:镜像留不留它随构建而变),也不算 `final` 恢复的证据(它从不进 vtable)。声明节点照旧取 getter 或 `borrow`;名字与某个存储字段相同的组照旧回折到字段上——SwiftUICore 为兼容旧客户端,在已改回存储属性的 `_GeometryActionModifier.value` 上留了一个同名函数。二进制不记录 `@storageRestrictions`:`initializedFieldNames` 只在类型有名叫 `_<属性名>`、类型与属性相同的存储字段时给出 `["_<属性名>"]`,其余为 `nil`,`accesses:` 从不还原。类型照 `StoredTypeMatching` 比:`weak` / `unowned` 先剥掉,`sending` 撇开(声明自身的 mangling 不写它,字段记录写)。比较的类型取 init accessor 自己的符号,不取 getter 的:getter 可能被 `@_silgen_name` 钉在旧 mangling 上(SwiftUICore 的 `_GeometryActionModifier2.value` 少了 `@Sendable`)。规则在 SwiftInspection 的 `InitAccessorFieldInference`(`initializedFieldNames(ofInitAccessorSymbol:)`),dump 直接读字段记录、对同一个符号套用同一条规则;`StoredTypeMatching` 也在 SwiftInspection,`@Observable` 展开的恢复与 wrapper attribute 的写法共用它。这个推断**不进** ABI 快照;init accessor 本身进(`|acc:` 标签里的 `init`,快照格式 13)。 `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)。 @@ -123,4 +150,6 @@ SE-0436 的类在 `__swift5_*` 里没有身影,模型里它就是那个 `__C.X - [PerConformanceAttribution.md](../PerConformanceAttribution.md)——逐 conformance 的归属。 - [ExportedOnlyInterfaceFiltering.md](../ExportedOnlyInterfaceFiltering.md)、[InterfaceHeaderAndExportStatusAnnotations.md](../InterfaceHeaderAndExportStatusAnnotations.md)——导出状态的两种消费方式。 - [DescriptorOnlyVTableMembers.md](../DescriptorOnlyVTableMembers.md)——实现符号被剥掉的 class vtable 成员怎么从 `Tq` 补回来,以及 vtable 顺序打印。 +- [ThunkOnlyObjCMembers.md](../ThunkOnlyObjCMembers.md)——优化构建删掉实现符号后,成员怎么从 `@objc` thunk 或 initializing entry point 补回来。 +- [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md)——Swift 声明的 `@objc` 协议与类对 ObjC 协议的遵循。 - 演进提案:[0002](../../Evolutions/0002-declaration-model-descriptor-slimming.md) 描述符化瘦身 · [0005](../../Evolutions/0005-event-based-degradation-reporting.md) 事件化上报 · [0023](../../Evolutions/0023-type-import-info-identity.md) C 导入类型的身份 · [0024](../../Evolutions/0024-exported-declaration-flag.md) 导出标志。 diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index cd038dd30..804696264 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -33,19 +33,25 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 **运行线程**:`prepare()` 与 `printRoot()` 的函数体都包在 `LargeStackTaskExecution.run` 里(提案 `large-stack-executor-and-cross-version-parallelism`),整段 task 跑在 demangler 的 16 MB 大栈执行器上,打印路径每个符号不再付一次线程往返;输出与执行器无关。`SwiftDiffableInterfaceBuilder.prepare()`、evolution builder 的 `prepare` / 渲染入口、diff renderer 的两个入口同样如此。见 [LargeStackTaskExecutorAdoption.md](../LargeStackTaskExecutorAdoption.md)。 -**`collectModules()`**:import 列表不来自 load command,而是扫全部符号的 demangle 树收 `.module` 节点——binary 里真正被引用的模块才进 import。过滤 `__C` / `__ObjC` / stdlib 三个伪模块;`internalModules`(`Swift`、`_Concurrency`、`_StringProcessing`、`_SwiftConcurrencyShims`)恒定并入。 +**`collectModules()`**:import 列表不来自 load command,而是扫全部符号的 demangle 树收 `.module` 节点——binary 里真正被引用的模块才进 import。扫描交给 `SwiftSymbolIndexStore.moduleNamesInAllSymbols(in:)`:在节点池里沿各符号的根做一次前序遍历,共享的子树只进一次,名字与首次出现的顺序同逐棵树遍历一致(演进提案 `machofile-performance`;逐棵树遍历让 SwiftUI 的准备阶段多花约 450 亿条指令)。过滤 `__C` / `__ObjC` / stdlib 三个伪模块;`internalModules`(`Swift`、`_Concurrency`、`_StringProcessing`、`_SwiftConcurrencyShims`)恒定并入。 -**`printRoot()` 的段落与 catch 契约**:组成顺序是 header(提案 0008,flag-gated 默认缺席)→ imports → 全局变量 → 全局函数 → 根类型 → 特化变体(`specializedChildren` 挂在各 `TypeDefinition` 上,indexer 对用户驱动的特化保持无知,所以这里全量走查 `allTypeDefinitions`)→ 根协议 → **嵌套**协议的 default-implementation 扩展块(extension 不能嵌进父体,顶层补印;这个循环在提案 0007 之前是死代码)→ 四桶 extension(`isAttachedToProtocolDefinition` 的已附着定义被过滤,避免 issue #106 §5 的重复块)。贯穿全部段落的契约是**逐定义 catch**:一个定义打印抛错只丢它自己,绝不空掉整块(历史上块级 catch 让一个旧 binary 的全部类型被抹白;由 `LegacyDyldInfoBindTests` 与 `corruptNestedChildDropsOnlyItself` 钉住)。两个全局块例外地不带定义上下文——`printVariable`/`printFunction` 本身不抛、各自派发过失败事件,块级包裹只是保险带。 +**`printRoot()` 的段落与 catch 契约**:组成顺序是 header(提案 0008,flag-gated 默认缺席)→ imports → 全局变量 → 全局函数 → 根类型 → 特化变体(`specializedChildren` 挂在各 `TypeDefinition` 上,indexer 对用户驱动的特化保持无知,所以这里全量走查 `allTypeDefinitions`)→ 根协议 → Swift 声明的 `@objc` 协议(`indexer.objcProtocolDefinitions`,各自带着默认实现扩展;嵌套在类型里的打进 `extension 父类型 { … }`)→ **嵌套**协议的 default-implementation 扩展块(extension 不能嵌进父体,顶层补印;这个循环在提案 0007 之前是死代码)→ 四桶 extension(`isAttachedToProtocolDefinition` 的已附着定义被过滤,避免 issue #106 §5 的重复块)→ category 的 ObjC 协议遵循(`indexer.objcCategoryConformances`,每个 category 一个 `extension X: P {}`,类被 exported-only 过滤掉时跟着不打)。后两样与类头部的 ObjC 协议都只在单版本接口里打,diff 与 evolution 不打,ABI 快照也不记(提案 `swift-declared-objc-protocols`,见 [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md))。贯穿全部段落的契约是**逐定义 catch**:一个定义打印抛错只丢它自己,绝不空掉整块(历史上块级 catch 让一个旧 binary 的全部类型被抹白;由 `LegacyDyldInfoBindTests` 与 `corruptNestedChildDropsOnlyItself` 钉住)。两个全局块例外地不带定义上下文——`printVariable`/`printFunction` 本身不抛、各自派发过失败事件,块级包裹只是保险带。 **exported-only 过滤的接线**(提案 0016):`printRoot()` 现在是一个普通函数壳,开关 -`printExportedDeclarationsOnly` 打开时先用 `indexer.allTypeDefinitions` / `allProtocolDefinitions` 调 +`printExportedDeclarationsOnly` 或标记模式(`marksOptionalContent`)打开时先用 `indexer.allTypeDefinitions` / `allProtocolDefinitions` 调 `printer.installExportFilterScope(types:protocols:)`,再进入 builder 体 `printRootContents()`。类型 / 协议 / 成员由 printer 自行裁决, 扩展的「目标是不是本镜像内未导出声明」只有索引器的表能回答(strip 过的镜像里未导出类型零符号),所以 scope 在这里装; -两个全局块各带一个 `where !printer.isExcludedByExportFilter(globalSymbolNames:)`。绕过 `printRoot` 的宿主要自己装 scope,否则扩展一腿 fail-open。 +两个全局块与 ObjC category conformance 块逐项问 `printer.exportFilterVisibility(excluded:)`:过滤掉的项普通打印时略过, +标记模式下包进只在过滤关着时可见的区域(提案 [0083-exported-only-marking-mode](../../Evolutions/0083-exported-only-marking-mode.md))。 +绕过 `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` 有打开注释的变体)。也不跟名字里的上下文比:局部类型名字的上下文是声明它的函数,函数不打印在它上方。 +**注释结构标记**(提案 [0084-comment-structure](../../Evolutions/0084-comment-structure.md)):`marksCommentStructure` 打开时,每条注释包进 swift-semantic-string 的 `AnnotationRegion`,种类是 SwiftDeclarationRendering 在 `AnnotationRegion.Kind` 上扩展的常量,各段是 `AnnotationSegment`。每条注释的文字只在 `StructuredComment` 的工厂里写一次,关着时打印成原来那一个 `.comment` 原子;打开时同一段文字拆成一个 `AnnotatedAtom` 的几片,分离时并回那一个原子,所以分离后与关着时逐个相同。打印点经 printer 的 `comment(_:as:)` 或渲染配置的同名方法决定标不标,跨几行的区域(字段偏移与它的树、枚举 case 块、元组 Type Layout、条件 witness)由调用点用 `commentRegion(_:content:)` 包住。`printRoot()` 里的文件头由 `InterfaceHeaderBlock(_:marksCommentStructure:)` 标成 `note`,两个全局块照常经 printer 标记。漏标与写走样由 `CommentStructureContractTests` 抓(分离后与关着时的打印比较,并要求每个注释字节落在某个区域里),`CommentConstructionScanTests` 禁止这四个模块里再直接构造注释原子。 + +**宏展开的折叠**(提案 [0093-observable-macro-folding](../../Evolutions/0093-observable-macro-folding.md)):`@Observable` 展开的类默认按源码的样子打印——类型头上一行 `@Observation.Observable`,被跟踪的属性在它存储字段 `_x` 的位置印成 `var x: T`(字段的偏移与布局注释照旧;`declaredMember` 来源带上 computed `x` 的 vtable 与地址注释,`synthesized` 来源在上方加 note 写明是从哪个存储字段合成的),宏不跟踪的存储 `var` 上方加一行 `@Observation.ObservationIgnored`(单独占一行、与声明同样缩进;property wrapper 的属性也各占一行,`lazy` 留在声明行;提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)),registrar、computed `x`、生成的方法与生成的 conformance 都不印。`expandsMacros` 打开时逐字节回到折叠之前的样子。打印器每次打印从 `TypeDefinition.observableMacroExpansion` 算一份视图(`SwiftDeclarationPrinter+ObservableMacro.swift`),接在字段块、两种成员排序、导出过滤、类型头与 `printExtensionDefinition` 上;`marksOptionalContent` 打开时两种形态都印,各自在 `SwiftVisibilityOption.expandsMacros` 的区域里,`VisibilityRegionProjectionTests` 对 fixture 的四个变体与进程内镜像验证投影。`printMacroExpansion(of:attachedTo:level:)` 用同一套逐字段、逐成员的渲染把展开单独印成一块,`printMacroExpansionParts(of:attachedTo:)` 按 Xcode 放 attached macro 展开的位置拆成几块,供宿主做内联展开。它照宏自己的分层分两层(提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)):展开 `@Observable` 得到每个被跟踪属性一块 `@Observation.ObservationTracked`(`.trackedPropertyAttribute`,放在折叠声明上方),加上闭合括号上方的成员块与下方的 conformance 块;属性块的 `nestedExpansions` 给出这个属性在块里的 UTF-8 范围与展开它的分块,也就是 accessor 块加存储的 `.trackedProperty`,放在折叠声明下方。两层的 `anchorKind` 都是那个折叠声明的区域。两者里被跟踪属性的 computed `x` 与 accessor 块都照宏的写法印 `@storageRestrictions(initializes: _x) init`、`get`、`set` 三行(`init` 那一行与别处的 accessor 块共用 `AccessorBlockKeywords.InitAccessorLine`,提案 [0094-init-accessor-recovery](../../Evolutions/0094-init-accessor-recovery.md)),不看镜像里还剩哪些 accessor(AppKit 剥光、SwiftUI 只剩 getter 的都有);`marksAttachedMacros` 把宏属性包进 `AnnotationRegion.Kind.attachedMacro(_:)` 的区域、把每个被跟踪属性折叠出的声明包进 `attachedMacroTrackedProperty(_:named:)` 的区域,配合 `marksNestedDefinitions`,最内层的 `DefinitionRegion` 指明是哪个类型的宏。diff 与 evolution 渲染器不走这条路,始终印展开。 + **`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 元数据索引都需要依赖镜像清单)。 @@ -54,7 +60,7 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 把 `some P` 的占位还原成带 primary associated type 实参的完整拼写(`some Collection & Sendable`)。领域细节已有两篇专文——[OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md)(descriptor 编码、anchor/塌缩机制、字节级调试)与 [OpaquePrimaryAssociatedTypeAttribution.md](../OpaquePrimaryAssociatedTypeAttribution.md)(提案 0011 的实现说明)——本节只给文件分工: -- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:usesModuleSelectors:)` 回查;最后一个参数来自打印配置的 `usesModuleSelectors`,为真时交回的文字写成 `some Swift::Collection`,而用来匹配协议事实的名字始终是 `opaqueTypeBuilderOnly` 的点号写法——见提案 [0064-module-selectors](../../Evolutions/0064-module-selectors.md))。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 +- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:spellingOptions:)` 回查;最后一个参数是打印配置打开的拼写选项(`DemangleOptions.interfaceSpellingOptions` 里的 `useModuleSelectors` 与 `useExistentialAny`),交回的文字随之写成 `some Swift::Collection`、`some Swift.Sequence`,而用来匹配协议事实的名字始终是 `opaqueTypeBuilderOnly` 的点号写法,协议名本身也只认模块选择器——见提案 [0064-module-selectors](../../Evolutions/0064-module-selectors.md) 与 [0092-existential-any](../../Evolutions/0092-existential-any.md))。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:深度是 descriptor 自己层布局的最内一层(`GenericParameterDepthLayout.make(forOpaqueType:genericContext:in:)`,连 Debug 构建把属性的 opaque 类型挂上的匿名上下文一起数);没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,层数算不出时也一样,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败与层数算不出 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 - **`OpaqueSameTypeConstraint`** / **`OpaqueDependentMemberProjection`**:从 requirement 节点里挖出来的单条 same-type 约束(区分正向 pin `τ.Name == X` 与反向 pin `outer == τ.Name`,后者渲染期经 `SubstitutionMap` 回溯)及其解析器。 - **`ProtocolFactsResolver`**:按「可达 descriptor 优先、内置表兜底」的链条解析协议事实(自声明的 associated type 名、refine 闭包),`refineClosureContainsAnchor` 对不完整闭包返回三态(命中 / 完整排除 / `nil` 不可证)。 - **`BuiltinStandardLibraryProtocolFacts`**:冻结的 stdlib 协议表——**primary associated type 名单与顺序的唯一来源**(SE-0346 不留运行时痕迹),也是离线 bind-only 外部协议的兜底。无 associated type 的协议也登记空条目,让归属能说「确定不附着」而非降级。 @@ -66,6 +72,7 @@ diff 与 evolution 两条比较渲染路径的公共结构核心。分工是这 - **`InterfaceUnionWalker` 拥有结构**:N 版本按 `ABIKey` 匹配(与 `ABIDiffer` 冻结进 snapshot 的同一套键构造,所以渲染视图与数据视图的匹配永远一致);并集排序 = 最新版本的声明顺序做脊柱,缺席声明按「最后携带它的版本」的顺序追加;每版本键 first-wins(**含发射**——同键后来者不会被发射第二次)。extension 桶按 `ABIDiffer.extensionContainerKey` 拆成 per-(target, protocol, where, retroactive) 容器;成员经 `UnionRenderableMember`(identity/payload 键取自 differ 冻结的同一 `MemberRecord` 投影)构造;类别调度走 `MemberCategory.allCases`;body 组装顺序镜像 `printTypeDefinition`,只有一处不同:单版本 interface 里 class 的 vtable 成员按槽号排在最前(提案 `0054-interface-descriptor-only-vtable-members`),多版本渲染没有统一的槽号顺序可依(各版本的 vtable 可能不同),仍全按类别。 - **`InterfaceUnionEmitting` 策略拥有呈现**:五个定制点——type/protocol header 解析(返回 `nil` 则整个声明连体丢弃:没有 header 行的成员不是合法 Swift)、extension header 包装、成员发射(一个 match 出零到多个 unit)、容器组装。真正双侧语义(`HeaderOutcome` 配对)留在 diff 策略、注解锚定留在 evolution 策略,绝不上提进 walker。 - **`InterfaceVersionRendering` / `InterfaceVersionUnit`**:版本抽象缝。每个版本 = 一个 `SwiftDiffableInterfaceBuilder` + 一个共享其事件 dispatcher 的 printer(dispatcher 共享是修过的坑:裸 `.init(in:)` 的 printer 没有 sink,diff 路径曾整条静默吞失败)。reader 泛型在此擦除且无损——walker 对 printer 的全部消费就是「把这个成员渲染成 `SemanticString`」,没有任何 `MachO` 类型的值跨缝。 +- **`InterfaceVersionGroupUnit`**(演进提案 `image-group-evolution`):一个版本由一组 image 组成时,缝后面是每个 image 一个 `InterfaceVersionUnit`。模型是各 image 的声明合在一起;walker 渲染一个定义之前先用 `renderingUnit(for:)` 取索引它的那个 image 的单元,成员跟着所属定义走,全局声明经 `globalRenderingUnits` 按 image 逐个列——打印器从建它的那个 image 读事实,用错 image 会丢属性、地址与 opaque 解析。一个 image 在另一个 image 定义的类型上声明的普通 extension(没有协议、没有 `where`)不进 extension 桶,经 `foldedExtensionDefinitions(of:)` 在类型体里渲染,判据与 SwiftDiffing 的并回一致。单 image 的单元对这三处都回答「自己」或空,diff 路径的输出不受影响。 - **成员一律在 printer level 0 渲染**:变量/下标 printer 会按 `level` 绝对烘焙 accessor 块内部缩进,而两个格式层又按行自缩进——真实 level 渲染会让 `get`/`}` 双重缩进(diff 路径在统一前正是带着这个缺陷;`DiffMemberIndentationTests` 钉住)。 ## 子系统 4:两侧 diff 渲染 @@ -82,12 +89,14 @@ diff 与 evolution 两条比较渲染路径的公共结构核心。分工是这 N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解。承重决策是**事实与文本的分工**: -- **注解事实只来自 `ABIEvolution`**:`prepare(maximumConcurrentPreparations:)` **并行**索引各版本(窗口默认取核数、`1` 即旧的串行顺序;各版本是不同文件、缓存按 UUID 键控,结果与窗口无关,由 `parallelPreparationMatchesSerialPreparation` 钉住)→ 冻结 snapshot → `ABIEvolutionBuilder` 建 lineage 矩阵;渲染期经 `EvolutionAnnotationIndex` 按键查询,**查不到即是「全程在场、从未变化」的裁决**(`ABIEvolution` 只物化有变化的 lineage),渲染为无注解。策略自己绝不重推事件,所以注解接口、lineage 报告、JSON 三个视图永不打架。 +- **注解事实只来自 `ABIEvolution`**:`prepare(maximumConcurrentPreparations:)` **并行**索引各版本(窗口默认取核数、`1` 即旧的串行顺序;各版本是不同文件、缓存按 UUID 键控,结果与窗口无关,由 `parallelPreparationMatchesSerialPreparation` 钉住)→ 冻结 snapshot → `ABIEvolutionBuilder` 建 lineage 矩阵;渲染期经 `EvolutionAnnotationIndex` 按键查询,**查不到即是「全程在场、从未变化」的裁决**(`ABIEvolution` 只物化有变化的 lineage,以及有版本看不见它的 lineage),渲染为无注解。策略自己绝不重推事件,所以注解接口、lineage 报告、JSON 三个视图永不打架。 - **渲染文本来自活模型**:每个声明由最后携带它的版本的 printer 渲染(modified 成员只显示最新一代,旧形态进注解短语 `modified in 26.0: old → new`;箭头两侧相同则塌回裸短语)。header 解析是「最新可渲染」:从新到旧找第一个渲染成功的版本,每次失败都在其版本自己的 dispatcher 上派发,全部失败才整体丢弃(diff 的 drop-whole 规则推广到 N 侧)。 - **公开面是两个类型**:`AnySwiftEvolutionInterfaceBuilder` 是类型擦除的 runtime-N 主力(同构数组 init + 异构 pack init 都全平台可用——pack 在*函数*位不需要可用性门槛),CLI 与宿主的用户选版场景都走它;`SwiftEvolutionInterfaceBuilder` 是 pack 泛型 façade(类型位的 pack 需要 Swift 5.9 运行时,故 `@available(macOS 14…)`;构造即擦除,行为逐字节一致,由 `packGenericFacadeMatchesTheErasedBuilder` 钉住)。工具链尚不支持 `repeat each MachO == M` 的同元素约束,所以数组 init 上不了 pack 类型——这是两个类型并存的直接原因。 - **格式层 `EvolutionMarking`**(+ `EvolutionContainerAssembler`):legend 头两行(轴 + bitmap 位置对照)、注解列按块对齐、上限 72 列(超限换行缩一级)、锚点规则(成员注解锚**首行**——attribute 内联,computed property 的注解不能沉到 accessor 块闭括号;容器 header 锚**末行**——带 `{` 的那行)、镜像 `ABIEvolutionReporter` 措辞的 warnings 尾巴。与 `DiffMarking` 故意不合并:marker 按行、注解按 unit 锚定,是真不同语义。 - **真 `@available` 属性**(提案 [0060-evolution-interface-available-annotations](../../Evolutions/0060-evolution-interface-available-annotations.md)):两个 builder 都有 `availabilityAnnotationPlatform: String?`,默认 `nil` 表示关闭,输出与没有这项功能时逐字节相同。设了平台名之后,生命周期能**完整**写成一个属性的声明,上方会多一行 `@available(<平台>, introduced: …, obsoleted: …)`:成员按自己的缩进放在声明行上方,容器放在 header 上方。「能完整写成」要三条同时成立:presence bitmap 只有一段连续的在场区间(`○ᵃ●ᵇ○ᶜ`;消失后又回来的 `●○●` 不行);涉及的版本标签都能解析成 1–3 段的数字版本;至少有一个边界落在轴内(从第一个版本起就在场的声明没有「引入」这个事实)。modified 事件在 `@available` 里没有对应的写法,不进属性。有一条不满足就不发属性,位图注释无论如何都承载完整事实;设了平台时 legend 多出第三行,说明 `introduced:` 指轴上第一个带有该声明的版本,不一定是真正引入它的系统版本。属性有意做成**补充**而不是替代:提案 0013 否决的是用伪 `@available` **取代**注解格式。 -- **结构化流**:`@_spi(Support) annotatedBlocks()` → `[[EvolutionLine]]`(`EvolutionAnnotation` 是纯数据——presence bitmap + `LineageEvent`s;设了平台时也包含 `@available` 属性行),宿主可自行着色/折叠。 +- **看不见的版本**(演进提案 `evolution-unobservable-presence`):镜像没有 local Swift 符号的版本(macOS 13.0–14.8 的 SwiftUI)看不到只靠非导出符号才出现的成员。这类位置在位图里画 `◍`(看不见,但前后观测到的版本都有它,推断存在)或 `◌`(看不见、不作推断);跨过这类版本的变化写成 `removed between 12.7 and 15.0`,推断存在的区段另写 `inferred present in 13.0–14.8`,挨着轴端或两侧观测不同、又没有事件覆盖的区段写 `not observable in 13.0`,两侧都不在的区段只画 `◌`、不写短语;所有短语按轴的顺序排列;legend 多一行列出这些版本和两个符号的含义。看不见的区段挨着轴端或两侧观测不同时边界不确定,不发 `@available`;两侧都在按在场算,两侧都不在按不在算。只因容器看不见而看不见的成员不单独标注,由容器的注解交代,与增删容器的成员一样;只在两侧都不在的区段看不见、又没有事件的成员也不标注。事实同样只来自 `ABIEvolution`:这类 lineage 即使没有事件也会被物化(带 `presenceStates`),所以「查不到 = 全程在场、从未变化」的裁决仍然成立。规则本身在 SwiftDiffing(见 [ABIEvolutionDesign.md](../ABIEvolutionDesign.md) 第六批),这里只负责画;着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain。 +- **一个版本由一组 image 组成**(演进提案 `image-group-evolution`):`AnySwiftEvolutionInterfaceBuilder(…, imageGroups:labels:…)` 收每个版本的 `SwiftEvolutionInterfaceImage` 列表,主 image 在前(SwiftUI 与 SwiftUICore)。注解多一种短语 `moved in 15.0: SwiftUI → SwiftUICore`,与其他短语按版本顺序用 ` · ` 连接,同一版本里排在事件之后;只有搬家的声明也带注解。legend 在位图位置那行之后列出 `// Image group:` 与每个 image 的在场位图,放在 `@available` 说明之前。搬家不影响 `@available` 的判断。合并、并回与搬家的规则在 SwiftDiffing(见 [ABIEvolutionDesign.md](../ABIEvolutionDesign.md) 第七批)。 +- **结构化流**:`@_spi(Support) annotatedBlocks()` → `[[EvolutionLine]]`(`EvolutionAnnotation` 是纯数据——presence bitmap + `LineageEvent`s,有看不见的版本时再加逐版本的 `presenceStates`,组内搬过家时再加 `imageMoves`;设了平台时也包含 `@available` 属性行),宿主可自行着色/折叠。 限制:输入必须全是 binary(snapshot 没有可渲染接口);协议的 `pwtslot:` 记录不渲染(没有对应声明,与 `diff --interface` 一致,变化仍见于 lineage 报告与 JSON)。 diff --git a/Documentations/Internal/Modules/SwiftLayout.md b/Documentations/Internal/Modules/SwiftLayout.md index 25741a343..95a1f2660 100644 --- a/Documentations/Internal/Modules/SwiftLayout.md +++ b/Documentations/Internal/Modules/SwiftLayout.md @@ -7,7 +7,7 @@ SwiftLayout 是**静态聚合布局引擎**:不加载进程、不调用 metadata accessor,直接从 Mach-O 文件算出 struct / class 的存储属性偏移与类型的整体布局(size / stride / alignment / extra inhabitants / bitwise-takable)。它是离线 ABI 分析路径的底座——`swift-section dump` 和 `interface` 在读文件(而非进程内镜像)时,字段偏移注释、type layout 注释、enum layout 注释全部由它算出来。 -它在模块图里是 `SwiftInspection` + `MachOSwiftSection` 的**平级消费者**(另加 `MachOObjCSection` 用于取 Objective-C 祖先类的实例尺寸),上游是 `SwiftDeclarationRendering` 的 `FieldLayoutRenderer`。同一个 renderer 按 reader 分叉:`MachOImage` 路径读进程内活 metadata,`MachOFile` 路径走本模块静态计算,两条腿产出同一套注释。 +它在模块图里是 `SwiftObjCInterop`、`SwiftInspection` 与 `MachOSwiftSection` 的**平级消费者**(另加 `MachOObjCSection` 用于取 Objective-C 祖先类的实例尺寸),上游是 `SwiftDeclarationRendering` 的 `FieldLayoutRenderer`。同一个 renderer 按 reader 分叉:`MachOImage` 路径读进程内活 metadata,`MachOFile` 路径走本模块静态计算,两条腿产出同一套注释。 **能力边界一句话**:凡是二进制里带着的事实,它都能算;凡是需要泛型实参而二进制没记的,它诚实降级成 `FieldResolution.unknown(<原因>)`,绝不编一个看起来合理的偏移出来。 @@ -68,7 +68,9 @@ libswiftCore 的 builtin 段还多一类记录:编译器 builtin 叶子类型 `ObjCClassIndex` 读 `class_ro_t.instanceSize`(Swift 子类第一个字段的起点),并索引每个静态发出的 Swift 类自己的 `instanceStart`——实际祖先变大时这个值会被 ObjC runtime 滑移(objc4 的 `moveIvars`),dyld cache 里的镜像带的已是滑移后的终值。是否在 classlist 里决定走哪套规则。 -`ImageUniverse` 是五个解析 seam 的统一查找面(类型、协议类约束、ObjC 类实例尺寸、assocty witness、ObjC 协议声明),可以是单镜像,也可以是**依赖闭包**——根镜像急切索引,依赖按解析顺序**惰性**折进来,所以几百个镜像的系统闭包不会被急切 demangle 一遍。闭包本身由 `MachODependencies` 提供,本模块只是薄封装。assocty witness 这个 seam 有一个返回**节点**而非布局的公开入口 `projectedAssociatedTypeWitness(base:associatedTypeReference:)`(2026-09-18,提案 0045-opaque-reference-spelling-and-member-projection):`SwiftDeclarationRendering` 用它把展开后的 opaque archetype 的成员(`IndexingIterator<[Int]>.Element`)投影成 witness 类型,逻辑与 `DependentMemberTypeBridge` 一致,只是不往下算布局。`projectingConcreteMembers(in:)`(2026-10-01)在它之上把整棵节点里所有 base 已具体的成员投影掉、投影结果再投影(有跳数上限):展开偏移树用它命名和展开字段(`[Swift.Int].Element` 显示为 `Swift.Int` 并继续展开,与运行时的遍历一致),离线泛型特化用它代换字段类型与约束检查的两侧。 +`ObjCProtocolIndex` 认存在类型里的 Swift 声明 `@objc` 协议(它没有 protocol descriptor,只在 `__objc_protolist` 里有记录):每条 `_TtP<模块><名字>_` 记录(本镜像的,加上它引用的别的模块协议的副本),并上 `SwiftObjCInterop.SwiftDeclaredObjCProtocolIndex` 给出的本镜像协议——改过名的与嵌套在类型里的(`_TtPC…`)只有后者认得出(2026-10-28,提案 `swift-declared-objc-protocols`)。 + +`ImageUniverse` 是四个解析 seam 的统一查找面(类型、协议、ObjC 类实例尺寸、assocty witness),可以是单镜像,也可以是**依赖闭包**——镜像按解析顺序(根镜像在前)**惰性**折进来,而且四种查找各折各的:类型查找只把镜像折进类型索引,协议、ObjC 类、assocty witness 查找各自折进自己的索引,所以几百个镜像的系统闭包不会被急切 demangle 一遍,一次类型查找也不会顺带读路过的每个镜像的 ObjC 协议表。每个镜像的七张表(`ImageReference`)各自第一次被读时才建,读失败的表当空表,不再连累整个镜像;同一个镜像的 `ImageReference` 经 `ImageReference.shared(for:)` 按镜像缓存,所有 universe 共用(2026-11-06,演进提案 `machofile-performance`:本机 cache 里的 SwiftUI 打开布局注释,打印阶段 2000 亿条指令降到 1530 亿)。协议这个 seam(`resolveProtocol(byQualifiedTypeName:)`)每折进一个镜像就同时查 Swift 协议描述符和 ObjC 协议记录,哪张先认出就停:Swift 声明的 `@objc` 协议没有描述符,原先先问描述符、落空后才查记录,等于每个这种协议都要把整个闭包折一遍(2026-11-06,RuntimeViewer 离线读 DockHelper 时一个根读了五百多个镜像)。闭包本身由 `MachODependencies` 提供,本模块只是薄封装。assocty witness 查找一律经 `resolveAssociatedTypeWitness(conformingName:protocolName:associatedTypeName:)`:遵循类型是类约束泛型参数的替身(`GenericArgumentEnvironment.classBoundParameterPlaceholderQualifiedName`,即 `Swift.AnyObject`)时直接答没有——没有哪个名义类型叫这个名字,任何镜像都不会有它的一致性记录,而照常去查要先把整个闭包折进 witness 索引才能答出「没有」:SwiftUI 的布局里只有一个这样的成员,就把 552 个依赖镜像的 witness 表全建了一遍(2026-11-06,同一提案)。assocty witness 这个 seam 有一个返回**节点**而非布局的公开入口 `projectedAssociatedTypeWitness(base:associatedTypeReference:)`(2026-09-18,提案 0045-opaque-reference-spelling-and-member-projection):`SwiftDeclarationRendering` 用它把展开后的 opaque archetype 的成员(`IndexingIterator<[Int]>.Element`)投影成 witness 类型,逻辑与 `DependentMemberTypeBridge` 一致,只是不往下算布局。`projectingConcreteMembers(in:)`(2026-10-01)在它之上把整棵节点里所有 base 已具体的成员投影掉、投影结果再投影(有跳数上限):展开偏移树用它命名和展开字段(`[Swift.Int].Element` 显示为 `Swift.Int` 并继续展开,与运行时的遍历一致),离线泛型特化用它代换字段类型与约束检查的两侧。 ## 关键契约 @@ -86,4 +88,4 @@ libswiftCore 的 builtin 段还多一类记录:编译器 builtin 叶子类型 - [NestedFieldOffsetCycleGuard.md](../NestedFieldOffsetCycleGuard.md)——嵌套展开的环路保护。 - [EnumLayoutAuditFixes.md](../EnumLayoutAuditFixes.md)——枚举布局逐行审计(`SwiftInspection` 侧,本模块复用其计算器)。 - [FieldLayoutRendererReaderSpecialization.md](../FieldLayoutRendererReaderSpecialization.md)——渲染层如何按 reader 分叉消费本模块。 -- [Modules/MachODependencies.md](MachODependencies.md)——依赖闭包本体。 +- MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)——依赖闭包本体(`MachODependencies` 自 0.25.0 起由 MachOKitExtensions 提供)。 diff --git a/Documentations/Internal/Modules/SwiftObjCInterop.md b/Documentations/Internal/Modules/SwiftObjCInterop.md new file mode 100644 index 000000000..5b6c5065d --- /dev/null +++ b/Documentations/Internal/Modules/SwiftObjCInterop.md @@ -0,0 +1,99 @@ +# SwiftObjCInterop 模块 + +> 模块参考文档(module reference),随代码维护。读者:维护者。 +> 模块从 SwiftInspection 拆出的来历见提案 [0089-swift-objc-interop-module](../../Evolutions/0089-swift-objc-interop-module.md);各子系统的来历见下文各节链接的提案与实现说明。本文负责全貌与分工。 + +## 模块定位 + +本模块回答「一个 Swift 类型在 Objective-C 一侧留下了什么」:Swift 类的 class object(`__objc_classlist` 与 `class_ro_t`)、`@objc @implementation` 类、Swift 里声明的 `@objc` 协议(`protocol_t`)、类的 ObjC 方法表与祖先链,把 selector 翻回 Swift 名字的 ClangImporter 命名规则,以及镜像里的 ObjC 类、category 与协议按 Swift 导入它们的样子读出的成员。dump 与 interface 里的 `@objc`、`override`、`@objc(selector)`、`@objc @implementation`、改过的 ObjC 类名、`@objc` 协议与 ObjC 协议遵循,都从这里取事实。 + +它在依赖层级上紧挨在 SwiftInspection 之上。用到 SwiftInspection 的只有三样:`SymbolicDemangler`(从描述符造类型名)、`NodeTypeNaming`(节点 → 限定名)与 `GenericParameterDepthLayout`(泛型类的参数分层);SwiftInspection 反过来不用本模块的任何东西。MachOObjCSection 从这一层进入 Swift 侧的模块栈,SwiftInspection 及其以下都不依赖它。 + +消费方: + +- SwiftLayout:Swift 子类排字段时,改过运行时名的类的 `instanceStart` 从 `SwiftClassObjectIndex` 取;existential 布局认 `@objc` 协议时,source 里改过名的那些靠 `SwiftDeclaredObjCProtocolIndex` 认出来。 +- SwiftThunkAnalysis:`ObjCMembers` 把方法表的每一项联结到它的 Swift 成员。联结要解码 thunk(Capstone),所以它留在 SwiftThunkAnalysis,表本身(`ObjCMemberTable`)在本模块。 +- SwiftDeclaration 与 SwiftIndexing 把这些事实写进声明模型;SwiftDump、SwiftPrinting、SwiftDeclarationRendering 打印它们;SwiftSectionKit 的 `dump` 有自己的 ObjC 段。 + +## 文件 → 子系统对照 + +| 子系统 | 文件 | +|---|---| +| 1. Swift 类在 ObjC 一侧的样子 | `SwiftClassObjectIndex.swift`、`SwiftClassWithoutClassObjectIndex.swift`、`CustomObjCClassName.swift`、`ObjCRuntimeNames.swift`、`ClassHierarchyDumper.swift` | +| 2. `@objc @implementation` 类 | `ObjCImplementationClassIndex.swift`、`ObjCImplementationClassFacts.swift` | +| 3. ObjC 协议 | `SwiftDeclaredObjCProtocolIndex.swift`、`ObjCProtocolAdoptionIndex.swift`、`ObjCProtocolRecord.swift`、`ObjCProtocolRequirements.swift` | +| 4. 方法表、祖先链与成员 | `ObjCClassHierarchy.swift`、`ObjCClassMethodIndex.swift`、`ObjCAncestorResolver.swift`、`ObjCMember.swift`、`ObjCMemberShape.swift` | +| 5. 命名规则与类型编码 | `ObjCImporterNaming.swift`、`ObjCImporterVerbs.swift`、`ObjCTypeEncoding.swift` | +| 6. ObjC 声明导入成 Swift | `ObjCImportedContainerIndex.swift`、`ObjCImportedMemberBuilder.swift`、`ObjCImportedMemberNodes.swift`、`ObjCImportedTypes.swift` | +| 公共 | `SharedCacheEvictionGroup+SwiftObjCInterop.swift`(三个淘汰分组)、`Extensions/MachORepresentableWithCache+ObjCReaderKinds.swift`(`objcImplementationClassReader`) | + +## 子系统速览 + +### 1:Swift 类在 ObjC 一侧的样子 + +- `SwiftClassObjectIndex`:source 用 `@objc(Name)` 或 `@_objcRuntimeName(Name)` 改过运行时名的 Swift 类,运行时名 demangle 不出任何东西,所以经类元数据的描述符指针(resilient 父类的类走 metadata pattern)配回它的描述符。按名字查 Swift 类的 ObjC 侧查找,查不到时都回退到它。`@objc(Name)` 与 `@_objcRuntimeName(Name)` 怎么区分、为什么只在查不到时回退,见 [CustomObjCClassNames.md](../CustomObjCClassNames.md)。 +- `SwiftClassWithoutClassObjectIndex`:`__objc_classlist` 不列出的 Swift 类——泛型类,以及 `__objc_stublist` 登记的类——它们的 `class_ro_t` 从 Swift 元数据读出来。ObjC 成员表读它们,SwiftIndexing 把它们作为 `ObjCSuppliedClass` 交给 MachOObjCSection 的索引器。泛型类的名字是不带私有鉴别符的限定名加泛型参数(`Module.Box`),两个文件里同名的 private 泛型类因此同名:两个都登记在限定名下(成员表据此认定有歧义、不归属任何成员),按名字查不到任何一个(体检第 5 条:此前只留第一个,它的成员表被套到两个定义上)。见 [ClassesWithoutClassObjects.md](../ClassesWithoutClassObjects.md)。 +- `ObjCRuntimeNames`:ObjC 运行时认识协议与类的名字(`_TtP…`、`_TtC…`、改过的名字),读回成 Swift 的节点。从文件里读,给别的镜像的 Swift 类写的 category 指向的不是 `_TtC…`,而是它绑定到的类元数据符号 `_$s…CN`;这三种写法都由 `NodeTypeNaming.swiftClassNode(fromRuntimeName:)`(SwiftInspection)认,`dump` 的 category 行与 ObjC 成员表的所属名也用它(2026-11-16 体检第 4 条之前,这种 category 在 interface 里印成 `extension __C._$s…`,它的 witness 也找不到)。 +- `ClassHierarchyDumper`(SPI,只用于进程内的 `MachOImage`):沿 Swift 类的元数据一路走进 ObjC 父类,列出整条继承链。RuntimeViewer 用它。 + +### 2:`@objc @implementation` 类 + +SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没有 Swift 的 nominal type descriptor 与 field descriptor。`ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表认出它们,给出 `ObjCImplementationClassFacts`:证据分 definitive 与 inferred 两档,ivar 按偏移值与 `Wvd` 符号配对,还有方法表。见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 + +### 3:ObjC 协议 + +- **Swift 里声明的 `@objc` 协议没有协议描述符**:只有一条 kind 为 `ObjCProtocol` 的 `__swift5_fieldmd` 记录和一个 ObjC `protocol_t`,两者按名字配对。记录上的 IsSwift 标志不是证据:Swift 给它引用的别的协议也发带这个标志的副本。`SwiftDeclaredObjCProtocolIndex` 做配对;`ObjCProtocolRecord` 读 `protocol_t`,方法表、属性表与扩展类型编码按下标读整张表(MachOObjCSection 的 `extendedMethodTypes(in:)` 只返回第一条);`ObjCProtocolRequirements` 把读到的记录变成 requirement。扩展类型编码按方法在四张表里的位置一一对应,读不出的表会让后面每个方法错配到别的方法的编码上,所以 `ObjCProtocolRecord.make` 逐个核对:擦掉类名、协议名与 block 签名后要与方法表的编码相同,有一个对不上就整组不用(体检第 8 条)。 +- **类对 ObjC 协议的遵循没有 conformance record**:`class_ro_t` 列出它(同一模块里 extension 声明的遵循也折进这里),只有给别的模块的类写的 category 才另外列出。`ObjCProtocolAdoptionIndex` 读这两处。 +- 只剩 selector 的 requirement 由 `ObjCImporterNaming` 起名,再用 `@objc(selector)` 钉住 selector。 + +见 [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md)。 + +### 4:方法表、祖先链与成员 + +- `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore`:按镜像的接缝,宿主把它已经建好的 ObjC 类层级交进来——RuntimeViewer 的索引器,或 SwiftIndexing 包装 `ObjCIndexing.ObjCInterfaceIndexer` 的适配器。 +- `ObjCClassMethodIndex`:接缝背后库自己的惰性读取器,读类、元类与同一镜像里 category 的方法表、祖先链、采纳的协议的 selector。 +- `ObjCAncestorResolver` / `ObjCAncestorResolverStore`:独立文件里父类或 category 的目标是 bind 时,按名字到它的依赖闭包里找,先查 export trie,再查 class list。indexer 与 `dump` 按镜像、在配置的搜索路径上各注册一个;没注册的文件默认走系统 cache;进程内镜像不需要。这样独立文件的链也能一路走到 libobjc 的 `NSObject`,和 cache 里的镜像一样。 +- `ObjCMember` / `ObjCMemberTable`:每个类的 ObjC 成员表,方法表里的每一项联结到它的 Swift 成员,`@objc`、`override` 与显式 selector 三个事实放在一处。 +- `ObjCMemberShape`:成员在 selector 层面的形状。importer 的命名规则作为正向检查用,编译器自己从 Swift 名推导 selector 的规则移植过来,用于判定显式 selector。 + +见 [ObjCMemberRecovery.md](../ObjCMemberRecovery.md) 与 [ThunkOnlyObjCMembers.md](../ThunkOnlyObjCMembers.md)。 + +### 5:命名规则与类型编码 + +`ObjCImporterNaming`(词表在 `ObjCImporterVerbs`)移植自 Swift 仓库 `lib/Basic/StringExtras.cpp` 的 `omitNeedlessWords` 与 `lib/ClangImporter/ImportName.cpp`;`ObjCTypeEncoding` 解析 ObjC 协议记录里方法与属性的类型编码,包括 Swift 发出的扩展编码(`@"NSString"`、`@""`、block 签名)。这三个文件不读 Mach-O。导入命名按 selector 的冒号数与编码的参数一一配对,所以编码必须先过 `ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`:参数个数对不上的编码不导入,类成员与协议要求两条路径都走它(体检第 2 条:协议要求那条路径曾漏掉这一步,个数对不上时越界崩溃)。 + +为类与 category 的成员,`ObjCImporterNaming` 还有三条只在那里用到的规则:返回对象的类方法、selector 开头与类名末尾对得上时按工厂方法导入成初始化器(`ImportedName.Kind.factoryInitializer`,传 `factoryInitializerClassName`);属性名经 `importedPropertyName`,`BOOL` 属性取 getter 名,开头的缩写词改小写,再按属性的规则删减(不删本类型名);error 约定只认 selector 里名为 `error` 的那一段。 + +### 6:ObjC 声明导入成 Swift + +镜像里的 ObjC 类、category 与协议按 Swift 导入它们的样子读出来,交给 SwiftDeclaration 的 `ObjCImportedClassDefinition` / `ObjCImportedCategoryDefinition` / `ObjCImportedProtocolDefinition`(提案 [0090-objc-imported-declarations](../../Evolutions/0090-objc-imported-declarations.md))。 + +- `ObjCImportedContainerIndex`(`SharedCache`,`.objcHierarchy` 分组):每个类与 category 的记录——方法、属性、协议、父类、Swift 位——只存名字与编码,按运行时名或 `uniqueName` 查。协议记录沿用 `ObjCProtocolRecord`,同名时取 Swift 发出的那份。 +- `ObjCImportedMemberBuilder`:把一条记录建成成员(`ObjCImportedMember`):属性排在 getter 的位置、getter 与 setter 不单列;不导入的 selector 跳过;参数类型先取类采纳的协议里同一 selector 的扩展编码,参数个数对不上时退回方法表的编码,再对不上就不建这个成员;所有权、是否要 `@objc(selector)` 也在这里定。 +- `ObjCImportedMemberNodes`:方法、属性、subscript 的 demangle 树,0079 的协议要求也经它建。 +- `ObjCSwiftTypeCompatibility`:按名字把 ObjC 成员配给 Swift 成员时的类型核对(提案 [0096](../../Evolutions/0096-swift-first-imported-declarations.md))。只认明显对不上的两种:对象(`@`)对实现它的模块自己定义的 struct / enum,标量对类或 existential;别的模块的值类型可能桥接(`String`、`Data`、`UTType`),不判。它也是「同名的 Swift 属性是另一个声明」的证据——头文件标了 `NS_REFINED_FOR_SWIFT` 的属性,Swift 里叫 `__name`,原名留给一个纯 Swift 的属性。`ObjCMemberShape.removingRefinedForSwiftPrefix` 去掉这个 `__`(属性名、方法基名、初始化器第一个标签)再比 selector。 +- `ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`:存储属性对应的 ObjC 属性(`V`)。`-O` 下 setter 常被内联进 thunk、不留符号,可写与否、是否 `weak` 要看它的特性串,interface 不再把这样的属性打成 `let`。 +- `ObjCImportedTypes`:编码里的类型换成 Swift 的类型树(对象是 `T!`,`NSString` 这类桥接成值类型;`r*` 即 `const char *` 是 `UnsafePointer`,`*` 是 `UnsafeMutablePointer`;C 数组照 ClangImporter 导入成元组,单元素的是元素本身,超过 4,096 个元素的导入不了、指针指向它时是 `OpaquePointer`,嵌套数组展开超过 65,536 个元素也按导入不了处理);`ObjCBridgedStructures` 记哪些类导入成值类型,`@NSCopying` 据此判断。 + +## 关键契约 + +- **SwiftInspection 不依赖本模块。** 新的 ObjC 侧代码放在这里,不放回 SwiftInspection:放回去会让 SwiftInspection 重新依赖 MachOObjCSection。 +- **按名字查 Swift 类的 ObjC 侧查找,查不到时回退到 `SwiftClassObjectIndex`**:改过运行时名的类,按 Swift 名字推出的运行时名是查不到的。 +- **按镜像的索引都是 `SharedCache`**,淘汰分组在 `SharedCacheEvictionGroup+SwiftObjCInterop.swift`:`objcImplementationClasses`、`objcHierarchy`、`objcAncestorResolver`,都跟随 `swiftSymbolStore`(0.25.0 之前叫 `symbolStore`,那个名字现在属于 MachOKitExtensions 的 C/C++ 符号索引)。这三个分组的字符串从 SwiftInspection 时期起没变。 +- **build closure 经 `objcImplementationClassReader` 转型读取器**:得到 `MachOFile`、`MachOImage`,或宿主包装器底下的那个读取器;不写 `as? MachOFile` / `as? MachOImage`。`ObjCImplementationClassReading` 是本模块自己的协议,外面的包装器无法遵循。 +- **导入一个类只读类自己的表**:dyld cache 预先把 category(含别的镜像的)附加到类上,类的表成了「多张表的表」,类自己的那张是本镜像的最后一张(`importedMethods(of:)` / `importedProperties(of:)` / `importedProtocolNames(of:)`);`methods(of:)` 读全部,是成员表要的,导入不用它。 +- **同镜像的 category 早被链接器并进了类**:给本镜像的类写的 category(ObjC 的、Swift `extension` 编出来的、`@objc(Name) @implementation` 的)不会出现在 `__objc_catlist` 里,事后也分不出来;只有给别的镜像的类写的 category 还是 category。夹具(`ObjCImplementationFixture`)因此整个没有 `__objc_catlist`。 +- **日志的 subsystem 仍是 `com.machoswiftsection.swift-inspection`**:RuntimeViewer 按 subsystem 与 category 过滤日志流,拆模块时有意没改。 + +## 测试锚点 + +- `SwiftObjCInteropTests`:`ObjCImporterNamingTests`、`ObjCImporterNamingClassMemberTests`、`ObjCImportedMemberBuilderTests`(进程内的 AppKit)、`ObjCSwiftTypeCompatibilityTests`(SceneHosting 的符号)、`ObjCProtocolRequirementBuilderTests`、`SwiftClassObjectIndexTests`、`SwiftClassWithoutClassObjectIndexTests`、`SwiftDeclaredObjCProtocolIndexTests`。 +- 经过 dump 与 interface 的端到端测试:SwiftDumpTests 的 `ObjCMemberDumpTests`、`SwiftDeclaredObjCProtocolDumpTests`、`CustomObjCClassNameDumpTests`;SwiftInterfaceTests 的 `ObjCMemberRecoveryTests`、`ObjCImplementationClassRecognitionTests`、`CustomObjCClassNameInterfaceTests`、`ObjCImportedDefinitionTests`(ObjC 声明导入成 Swift,含与 Swift 合并)。 +- 缓存:SwiftIndexingTests 的 `PerImageCacheEvictionTests`(淘汰);SwiftInspectionTests 的 `DyldCacheTwinImageTests`(同一构建在两个 dyld cache 里不串用 `ObjCClassMethodIndex` 的缓存)。 + +## 相关文档 + +- 拆分:[0089-swift-objc-interop-module](../../Evolutions/0089-swift-objc-interop-module.md) +- 各子系统的提案:[0046](../../Evolutions/0046-objc-implementation-class-recognition.md)(`@objc @implementation`)、[0047](../../Evolutions/0047-objc-ancestor-override-recovery.md)(祖先链与 `override`)、[0048](../../Evolutions/0048-objc-member-selector-recovery.md)(成员与显式 selector)、[0049](../../Evolutions/0049-objc-ancestor-dependency-closure.md)(祖先链走依赖闭包)、[0052](../../Evolutions/0052-objc-custom-class-name.md)(改过的 ObjC 类名)、[0078](../../Evolutions/0078-objc-classes-without-class-objects.md)(没有 class object 的类)、[0079](../../Evolutions/0079-swift-declared-objc-protocols.md)(Swift 声明的 `@objc` 协议)、[0090](../../Evolutions/0090-objc-imported-declarations.md)(ObjC 声明导入成 Swift)、[0096](../../Evolutions/0096-swift-first-imported-declarations.md)(Swift 实现的类以 Swift 一侧为准) +- 实现说明:[ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)、[ObjCMemberRecovery.md](../ObjCMemberRecovery.md)、[ThunkOnlyObjCMembers.md](../ThunkOnlyObjCMembers.md)、[CustomObjCClassNames.md](../CustomObjCClassNames.md)、[ClassesWithoutClassObjects.md](../ClassesWithoutClassObjects.md)、[SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md) +- 联结方法表与 Swift 成员的那一半:[SwiftThunkAnalysis.md](SwiftThunkAnalysis.md) diff --git a/Documentations/Internal/Modules/SwiftSectionKit.md b/Documentations/Internal/Modules/SwiftSectionKit.md index 9fef0f58b..ed27ddca0 100644 --- a/Documentations/Internal/Modules/SwiftSectionKit.md +++ b/Documentations/Internal/Modules/SwiftSectionKit.md @@ -20,6 +20,7 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 | 3. 输入 | `Inputs/Architecture`、`MachOSource`(含 `DyldSharedCacheImage` / `MachOSourceError`)、`SnapshotSource`(含 `SnapshotSourceError` / `BinaryLoadingOptions`) | | 4. Swift 侧请求 | `Swift/DumpRequest`(含 `DumpSection` / `FieldOffsetComments`)、`InterfaceRequest`、`ABISnapshotRequest`、`ABIDiffRequest`、`ABIEvolutionRequest`(含 `AvailabilityAttributes` / `AvailabilityPlatformInferenceError`)、`TransformerRequests`;共用的 `ABISnapshotLoading`、`DependencySearchPathUsage`、`CommentTransformerApplication` | | 5. ObjC 侧请求 | `ObjC/ObjCInterfaceSession`(含 `ObjCDeclarationKind`)、`ObjCDumpRequest`、`ObjCInterfaceRequest`(含 `ObjCDeclarationLookupError`)、`ObjCAPIRequests`(snapshot / diff / evolution 与 `ObjCAPISnapshotLoading`) | +| 6. 交叉引用请求 | `CrossReferences/CrossReferenceInput`(含 `CrossReferenceRequestError`、按名字或路径找镜像)、`ReferencesRequest`(含 `CrossReferenceSubject` / `CrossReferenceDirection` / `CrossReferenceOutputFormat` / `ReferencesResult`)、`SymbolicateRequest`、`CrossReferenceFormatting`(文本与 JSON 的拼写,JSON 名字即契约) | | CLI 包装层 | `Sources/Executables/swift-section/`:各命令的 `makeRequest()` + `run()`、`Models/CommandLineSupport`(flag → `MachOSource`、错误翻译、`ExpressibleByArgument`)、`Output/StandardStreamOutput` | ## 1. 输出端 @@ -38,7 +39,8 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 - **名字只在 `.output` 目的地才算**,而且在声明本身 dump 成功之后:写文件时产物根本不经过输出端,算了也没人要。算名字失败只置 `name: nil`,不报诊断,否则命令行的 stdout 会多出错误行。 - **conformance 的名字用 `extension` 那一行的完整拼法**(`ProtocolConformance.dumpedTypeName(isFull: true, …)`,`package` 级),不用公开的 `dumpTypeName`。后者按 interface-type 选项打印,会去掉文件级 private 类型的判别符,而类型自己的名字带着它:fixture 里 `AlphaProtocolWitness` 的类型名是 `SymbolTestsCore.(AlphaProtocolWitness in _82F1…)`,用 `dumpTypeName` 拿到的却是 `SymbolTestsCore.AlphaProtocolWitness`,宿主就会把它和它的 conformance 分进两个文件。`filePrivateTypeAndConformanceShareName` 钉住这一点(换成 `dumpTypeName` 的单点变异实测变红)。associated type 用公开的 `dumpTypeName`,它和 `AssociatedTypeDumper` 的 `extension` 行本来就是同一个函数。 -- header 和「No @objc @implementation classes recognized」那行注释不是声明,照旧走 `write(_:)`;`objc dump` 每个声明后面那个 `.text("")` 空行也是。 +- header 和「No @objc @implementation classes recognized」那行注释不是声明,照旧走 `write(_:)`;`objc dump` 每个声明后面那个 `.text("")` 空行也是,`protocols` 段末尾那行「没有协议认领的 ObjC 协议记录」注释也是。 +- Swift 声明的 `@objc` 协议(`SwiftObjCInterop.SwiftDeclaredObjCProtocol`)归 `.protocols`,名字是协议的 Swift 名;category 的 ObjC 协议遵循(`ObjCCategoryProtocolAdoption`)归 `.protocolConformances`,名字是被 extension 的类(提案 `swift-declared-objc-protocols`)。两种排序都带上它们。 - 代价是每个 Swift 声明多解析一次名字,命令行用不上也要付;落地前用 release 版对大镜像实测了耗时,见提案的决策日志。 ## 2. 环境 @@ -53,6 +55,12 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 `SnapshotSource.path` 是 `snapshot` / `diff` / `evolution` 的输入:snapshot 文档(JSON)或二进制,按文件第一个非空白字节区分(`{` 即文档)。annotated interface 只能吃二进制,`SnapshotSource.requireBinaries` 在加载任何输入之前就逐个检查,出错抛 `SnapshotSourceError.binaryRequired(path:)`。`BinaryLoadingOptions` 只作用于二进制输入:`dyldSharedCacheImage` 一旦给出,每个二进制输入都按 cache 文件处理、从中取同名镜像。 +`refs` 与 `symbolicate` 读的是一批镜像的机器码,不是一个镜像的元数据,所以不走 `MachOSource`,走 `CrossReferenceInput`:一组一起读的文件(胖文件同样必须给架构,复用 `MachOSource.file(…).load()`,不默默挑切片)、整个 cache 文件、或宿主 cache(`FullDyldCache.cachedHost`,经文件读,地址是未滑动的)。`--in-image` 按路径或文件名找镜像,一个文件名在 macOS cache 里可能对上两个(Mac Catalyst 变体),两个都算。 + +## 交叉引用请求 + +`ReferencesRequest` 先把主体解析成「要找哪些键、在哪些镜像里找」,再在候选镜像上并发扫描(`DispatchQueue.concurrentPerform` 放在一个私有串行队列里起,原因见 AGENTS.md 关于同步等待的规则),最后一次性给函数起名(`functions(containing:)`,每个镜像的函数表用完即丢)。各主体的候选镜像:selector 用 `__objc_selrefs` 预筛;符号先按导出表与符号表找定义(`locations(ofSymbolNamed:among:)`),函数的调用者经 `imageIndices(callingFunctionAt:…)`(C 名字看导入,Swift 名字看链接关系),没有定义的按导入名找;类先找 `_OBJC_CLASS_$_` 符号,找不到再读各镜像的类表,并按类对象位置过滤同名类;ivar 看定义它的类所在镜像与导入 `_OBJC_IVAR_$_` 的镜像;字符串不预筛。`--function` 在 cache 里只有一个地址空间;一组文件各有各的,几个文件都在那个地址有函数时报 `ambiguousFunction`,要 `--function-image` 指名。`limit` 在过滤之后按镜像、函数、指令顺序截断,`isTruncated` 如实标出;一行摘要以 note 发到诊断通道。JSON 由 `CrossReferenceJSONValue` 编码,键排序、地址一律是十六进制字符串。 + ## 4. 请求的设计约定 - **按用途建模**:互斥的选项用 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()`,原文不动。 @@ -70,9 +78,11 @@ 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`(两个方法都实现,按顺序记下每块产物和它带的声明)。`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*` 都会变红。 +- `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)`,测试目标因此依赖 `SwiftSectionTestingSupport`。 +- `ClassesWithoutClassObjectsRequestTests`:对测试时现编的 `ClassesWithoutClassObjectsFixture` 跑 `objc dump`,钉住两处 ObjC 请求把没有 class object 的 Swift 类(`ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`)交给 ObjC 索引器:泛型类与 `__objc_stublist` 登记的类连同 MachOObjCSection 写的注释一起列出,没有 ObjC 祖先的 Singleton 类不列(提案 `objc-classes-without-class-objects`)。 +- `CrossReferenceRequestTests`:`refs` 与 `symbolicate` 对宿主 cache(经文件读)端到端跑——JSON 的地址是十六进制字符串、`limit` 截断与 `isTruncated`、函数的被调用者、符号与类(含 `_OBJC_CLASS_$_` 写法与类名写法结果一致)、错误;归档的 macOS 27.2 cache 上整 cache 查 selector;独立的胖可执行文件(TextEdit)必须给架构。 +- `Tests/SwiftSectionCommandTests/`:`CrossReferenceCommandTests`(`refs` 恰好一个查询、恰好一个输入,各 flag 到请求的映射,需要别的 flag 才成立的组合,`symbolicate` 的地址解析;`--in-image` 与 `--function-image` 的错误译成退出码 64);原有的解析测试;`CommandRequestMappingTests`(flag → 请求)、`CommandLineErrorTranslationTests`(库错误 → 历史文案与退出码)、`StandardStreamOutputTests`(内存流读回字节;`Rainbow.enabled` 与 `outputTarget` 是进程全局量,套件 `.serialized` 并在测试内钉住、用完还原)、`CommandLineStreamWriteScanTests`。 +- `PrintFailureEventTests.libraryModulesWriteToNoProcessStream` 的豁免名单只有 `swift-section` 和 `SwiftSectionTestingSupport`,`SwiftSectionKit` 自动被扫描:库里出现任何 `print` / `fputs` / `FileHandle.standard*` 都会变红。 ## 7. 加一个 flag / 子命令 diff --git a/Documentations/Internal/Modules/SwiftSymbols.md b/Documentations/Internal/Modules/SwiftSymbols.md new file mode 100644 index 000000000..4289fd20d --- /dev/null +++ b/Documentations/Internal/Modules/SwiftSymbols.md @@ -0,0 +1,111 @@ +# SwiftSymbols 模块 + +> 模块参考文档(module reference),随代码维护。读者:维护者。 +> 细节文档见文末[「相关文档」](#相关文档);本文负责全貌与分工,不复述细节。 +> 2026-11 之前本模块叫 `MachOSymbols`,符号表与采集也在这里;与语言无关的那一半已迁到 MachOKitExtensions 的同名模块 `MachOSymbols`,本模块只留 Swift 部分(MachOKitExtensions 提案 move-macho-infrastructure-modules)。 + +## 模块定位 + +SwiftSymbols 是 **Swift 符号索引**层:在 MachOKitExtensions `MachOSymbols` 的一趟采集上取出一个镜像的 Swift 符号,把每个 Swift 符号 demangle 成节点树存起来,按成员、类型、witness、thunk 归类,供上层按偏移、按名字、按类型成员反查。入口类型是 `SwiftSymbolIndexStore`。 + +与语言无关的底层——16 字节的紧凑符号表、按偏移分桶、符号值到偏移的换算、对符号表与导出表的单趟采集(`SymbolSweep`)、语言判断(`SymbolLanguage`)——在 MachOKitExtensions 的 `MachOSymbols` 里,说明见它的 [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md)。那边还有一个只收 C、C++、Objective-C 名字的 `SymbolIndexStore`;它与本模块的 `SwiftSymbolIndexStore` 查询方法同名,但互不相干(见「关键契约」)。 + +它坐在 ABI 模型**上面一层**。`MachOSwiftSection` 够不到它(演进提案 `self-contained-abi-layer` 的边界):描述符只暴露实现偏移,把偏移归属到符号名是 `SwiftInspection` 的事。符号的**值类型**(`Symbol` / `Symbols` / `SymbolOrElement`)住在 `MachOResolving`(MachOKitExtensions),不在这里——「这个偏移上有哪些符号」是一次针对索引的**查询**,不是一次读取,所以 `Symbols` 故意不是 `Resolvable`。 + +模块另外托管一个跟符号无关的东西:`LargeStackTaskExecution`,库入口用来把整个调用链搬到大栈执行器上的开关。它放这儿是因为 demangler 是它唯一的服务对象。 + +## 文件 → 子系统对照 + +| 子系统 | 文件 | +|---|---| +| 1. 索引本体 | `SwiftSymbolIndexStore`、`SwiftSymbolTableRouting`、`SharedCacheEvictionGroup+SwiftSymbols`(`.swiftSymbolStore`、`.internedNames`) | +| 2. 符号值与查询出口 | `Symbol`、`DemangledSymbol`、`MachO+Symbol` | +| 3. 节点引用的共享与跨 store 对账 | `InternedNodeReferenceCache`、`StructuralNodeReferenceKey` | +| 4. 大栈执行器接入 | `LargeStackTaskExecution` | +| 5. `_symbolic` 符号表 | `SymbolicManglingSymbols` | + +## 子系统 1:索引本体 + +**采集交给 MachOKitExtensions**。建索引的第一段(见下文「建索引分两段」)由 `SymbolSweep(sweeping:routing: SwiftSymbolTableRouting())` 一趟扫完符号表与导出表:`SymbolLanguage` 判为 Swift 的名字里,`_symbolic ` / `_default assoc type ` 开头的进 `.symbolicMangling` 表(`.nameOnly`,不建偏移索引),其余进 `.swift` 表(`.byOffset`);非 Swift 名字不收。routing 声明了 `mayReferenceStringTablesOfLoadedImages`(dyld 不卸载带 Swift 内容的镜像),所以 `MachOImage` 的行直接指进镜像的字符串表。采集的通用规则——每个唯一名字一行 16 字节、名字的两种来源(零拷贝的字符串表或私有缓冲)、规范化偏移的口径与 `SymbolValueOffsetConverter`、STABS 调试条目只占行不定偏移、导出事实与本地符号事实的采集——都写在 MachOKitExtensions 的 [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md),这里不复述。对本模块要记住的只有两条后果:`MachOKit` 给 `MachOFile` 符号的 `offset` 是原始 `n_value`(虚拟地址,不是它文档注释说的文件偏移),进索引一律经换算,主可执行文件(`__TEXT` 在 0x100000000)上弄错会让每个成员地址都高出一个基址(`ExecutableImageSymbolOffsetTests` 钉住);调试条目保留占位行是为了让行序跟着调试映射走,即源码顺序——打印器按行序列成员,丢掉它们会让 SymbolTestsCore 的 42 个快照变化。 + +`SwiftSymbolIndexStore.Storage` 里**不驻留 `Node` 类树,也不驻留符号名 `String`**。建索引时每个符号 demangle 到一棵临时树上,分类完就 intern 进这个镜像的 `NodeStoreBuilder`;全局 `NodeCache` 全程不参与,`Storage` 一放,整个镜像的内存占用就跟着走。 + +**建索引分两段**(演进提案 `machofile-performance`)。`storage(in:)` 建出来的只有第一段:符号表、按偏移的行索引、`_symbolic` 符号表和导出事实,一个名字也不 demangle。第二段 `Storage.DemangledIndex`——每一行的节点树和按树分类的各个索引——在第一次有查询要用到树时才建,建在大栈上、持锁只建一次,并发的第一批读者等同一次构建。`symbols(for:in:)`、`containsSymbol(named:)`、`offset(ofSymbolNamed:)`、导出判定、`hasLocalSwiftSymbols` 与 `symbolicManglingSymbols(in:)` 只读第一段。原因是只为别的镜像而读的镜像:静态布局引擎经匿名上下文描述符上的符号给依赖镜像的私有类型起名,以前这一查就把整个依赖镜像的名字全部 demangle 一遍,生成 SwiftUI 的 interface 27.8 秒里有 7.7 秒花在这上面。`prepare(in:)`、`prepareWithProgress(in:)` 与 `buildStorage(for:)` 照旧把两段都建好,进度只报第二段(第一段太快,不值得报)。字段仍以原名从 `Storage` 上读,第二段的字段经转发属性取;逐行的循环先取一次 `demangledIndex` 再读,不要每行都经转发属性。 + +**第二段的 demangle 分到多个线程**(同一提案)。建第二段的线程按行号顺序一批一批地驻留、分类,`DemanglingWave` 提前一批把下一批的名字分给机器上同时运行的线程去还原成树(每批最多 16 × 512 行,每 512 行跳一次大栈),两批在内存里交替。驻留和分类仍只在建索引的线程上按行号顺序做,节点池与各个索引因此和单线程建出来的逐位相同;一行的树只由它的名字决定,哪个线程还原的不影响结果(`everyRowHoldsTheTreeOfItsOwnName` 钉住)。不要把驻留挪进线程里,也不要让线程按别的顺序交回结果:节点序号就是驻留顺序,打印与快照都依赖它。每一批由一个私有串行队列起头、在里面 `concurrentPerform`,不交给 `DispatchQueue.global()`:建索引的线程要同步等这一批,而当协作线程池的线程全都同步阻塞在读索引的大栈跳转上时,它们仍占着同一 QoS 的并发额度,全局队列(以及挂在同一根队列上的私有并发队列)分不到线程,整个进程就停住了——2026-11-16 在 10 核机器的并行全量里两次卡死(代码库体检第 10 条)。私有串行队列挂在 overcommit 根队列上,总能拿到线程;`concurrentPerform` 的调用线程自己也执行迭代,没有别的线程加入时照样做完,正常时仍用满所有核(`firstReadersOnEveryCooperativeThreadAllFinish` 钉住)。本机 SwiftUI 的第二段墙钟时间减半;CPU 时间的代价取决于 demangler 自己的引用计数开销——swift-demangling 0.7.2 的 `Demangler` 在 `require(pop())` 这类写法上会整份复制自身,多线程同时复制节点栈时互相抢引用计数,CPU 时间约为单线程的 2.3 倍,修掉这处复制后只多约四分之一。 + +**interface 的 import 列表从节点池里收**(同一提案)。`moduleNamesInAllSymbols(in:)` 沿每个符号的根节点在节点池里做前序遍历,每个节点只进一次:同样的子树在池里是同一个节点,第二次遇到时它能贡献的模块名第一次都已收过,所以名字和它们第一次出现的顺序都与逐棵树完整遍历相同(`moduleNamesMatchAWalkOfEveryTree` 钉住)。以前 `SwiftInterfaceBuilder.collectModules()` 对 `allSymbols(in:)` 的每棵树做一次泛型的整树遍历,SwiftUI 的 interface 准备阶段因此多出约 450 亿条指令。 + +成员与全局变量按入口节点归类:getter、setter,SE-0507 的 `borrow` / `mutate` 访问器(`vb` / `vz`),以及 SE-0400 的 init accessor(`vi`)都算属性或下标的成员符号——只声明 `borrow` / `mutate` 的属性没有 getter 符号,漏了它们整个成员就不见了。`_read` / `_modify` 及其新 ABI 版本不收进成员桶。新加一种进成员桶的 accessor 要改两处名单:分桶 switch 之前还有一道 `Node.Kind.isMember`(`SwiftSymbolIndexStore.swift` 末尾),不在名单里的入口节点直接被丢掉,什么错误也不报。按 kind 的索引(`symbols(of:)`)不受这两处影响,每个符号都记一行。 + +`@objc` thunk(`$s…To`)不是成员符号,成员索引不收它;它照旧进 thunk 属性的标记表(只记成员名,供 `applyThunkAttributes` 打 `@objc`),此外按它进入的成员归进第四个成员索引 `objcThunkMemberSymbolRowsByKind`,与实现符号、`Tq`、protocol witness 三个索引的键相同,存的是 thunk 自己的行(`objcThunkMemberSymbols(of:…)`)。这个索引是给优化构建用的:成员的 Swift 函数体被内联进 thunk、Swift entry point 被删掉之后,thunk 是这个成员仅剩的符号,声明模型从它造替身成员([ThunkOnlyObjCMembers.md](../ThunkOnlyObjCMembers.md))。`…ToTm`(合并后的 thunk 函数体)以 `mergedFunction` 开头,不进这个索引。 + +**成员 / typeInfo / thunk 属性这几个索引的 key 不是单射的**:第一层是打印出来的类型名,用 `.interfaceTypeBuilderOnly` 打印,会剥掉 private discriminator,于是不同文件里同名的 private 类型共用一个名字桶(issue #115:dump 路径按名字查,把两个类型的成员混进了同一个声明)。所以—— + +> 解析**某一个**类型的成员 / 信息 / 属性,必须用带 node 的重载(`memberSymbols(of:for:node:in:)`、`methodDescriptorMemberSymbols(of:for:node:in:)`、`objcThunkMemberSymbols(of:for:node:in:)`、`typeInfo(for:node:in:)`、`thunkAttributeMembers(of:for:node:in:)`)。只带名字的那几个重载会故意把所有子桶摊平,只用于「所有打印成这个名字的类型」这种聚合查询。 + +**同一地址上的符号按归属分组**(演进提案 `faster-lazy-definition-indexing`)。identical code folding 会把许多 conformance 内容相同的 witness 实现合并到一个地址上——SwiftUI 里一个 `_destroySelf` 或值 witness 的实现挂着上千个名字。要在这样的地址上找「属于某个 conformance 的那个」或「属于某个协议的那个」,用 `symbols(for:ownedBy:ownerKind:printedWith:in:)`:`SymbolOwnerKind.conformingType` 是符号树里第一个 `protocolConformance` 的第一个子节点,`.protocol` 是第一个 `protocol` 节点,按调用方给的打印预设打印后比较;结果按 `symbols(for:in:)` 的顺序排列,带查询偏移。每个「地址 + 规则 + 预设」第一次被问到时在 `Storage` 上分组一次(锁外计算、锁内先到者胜),之后每次是两次字典查找。以前 `ExtensionDefinition`、`ProtocolDefinition`、`ProtocolConformanceDumper`、`ProtocolDumper` 都是把这个地址的名字逐个 demangle、搜索、打印再比较,每个 conformance 来一次,对别名组大小是平方级:SwiftUI 一个镜像检查 365 万次、只涉及 17,852 个不同的名字。**新的「在别名里找归属」的代码走这个查询,不要再逐个比较。**`ClassDumper.validNode` 与 `OverrideSymbolMatcher` 按声明上下文结构相等来认领,规则不同、实测开销可以忽略,没有改。 + +`Storage` 同时带着 `.swift` 表的**导出事实**(`SymbolExportFacts`,采集方式见 MachOKitExtensions 的 [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md)),撑起三态的 `isExported(name:in:)`(`nil` = 这个镜像没有导出信息,**此时绝不标注**)。注意 `NlistProtocol.isExternal` 只指**未定义的导入**(`N_EXT` 加 `N_UNDF`),导出的定义同样带 `N_EXT`,不要拿它当「是否导出」。成员级的判定走 `isExportedIncludingDerivedSymbols(names:in:)`:成员任一入口(自身或 `Tj` / `Tq` / `Tu` 派生形式)导出即为导出,interface 的 `// not exported` 注释和 ABI 快照的 `MemberRecord.isExported` 都问这一处。 + +同一趟还记下镜像**有没有 local Swift 符号**(`hasLocalSwiftSymbols(in:)`,取自 `.swift` 表的 `hasLocalSymbols`,演进提案 `evolution-unobservable-presence`):收到的 Swift 符号里,只要有一个 `N_EXT` 位为 0(`NlistProtocol.isLocal`,调试用的 STABS 条目不算)就是 `true`。被剥掉 local 符号的镜像——macOS 13.0–14.8 dyld shared cache 里的 SwiftUI——只剩导出的 Swift 名字,非导出的声明在这里根本没有名字,evolution 与 diff 据此把它们记为看不见而不是删除。判据不能用 `!isExternal`:导出符号同样过得了那道过滤。 + +## 子系统 2:查询出口与 detach + +查询在出口处构造 `DemangledSymbol` / `NodeReference` 值。这些值共享镜像那张 `SymbolTable`——对于一次查询吐出又丢弃的几十万个值,这是对的交换。 + +> **但凡要存进声明模型的 `DemangledSymbol`,必须先 `detachedFromSharedTable()`。** 一个存活的值就钉住整张表(镜像表还会把它对 mapped string table 的读连在加载状态上),`removeSubIndexer(_:)` 想回收的按镜像内存就白回收了。查询路径上**不要** detach。 + +实测(SwiftUI,iOS 18.5):9872 个被存下来的值只引用 5.1% 的行,detach 是拿约 0.6 MB 的小分配换掉整张表的驻留。存的地方一共六处,`SymbolTableRetentionTests` 会在有人新增第七处却忘了 detach 时立刻变红。 + +## 子系统 3:跨 store 对账 + +节点引用的 `Hashable` 是 **store 身份**语义。一个镜像内部同时存在好几个 store——冻结的主符号 store、迟到名字的旁路 store、缓存的各作用域 store,按镜像驱逐还会把某个作用域重建到新 store 上而旧引用仍然钉着旧的(2026-09-28 之前内存压力也会)——所以跨 store 是常态,不是例外。 + +> **任何 key 与查询可能来自不同 store 的 `Dictionary` / `Set`,必须以 `StructuralNodeReferenceKey` 为 key,不能用裸 `NodeReference`。** + +用裸 key 会静默失败,而且各处的失败形态还不一样:override / vtable 查找会丢掉 `override` 关键字和 vtable 偏移注释;下标的 getter 和 setter 分进两个桶,只有 setter 的那个被丢弃;合并的 thunk 会把 `func` / `init` 印两遍;witness 会被认领两次。只有在**一批** `memberSymbols` 内部做分组或去重(单一 hash-consed store,结构相等与索引相等重合)时,裸 key 才是安全的。 + +`InternedNodeReferenceCache` 管的是 `SharedNodeStore` 里**没有**的那部分职责:按 Mach-O 作用域分区和驱逐。metadata 派生的名字树走它。 + +> 批量路径上不要裸调 `NodeReference(interning:)`,走缓存。 + +## 子系统 4:大栈执行器 + +`LargeStackTaskExecution.run(_:)` 在库入口外面把 swift-demangling 的 16 MB `LargeStackTaskExecutor` 设为 task executor preference。demangler 每次调用会拿**调用线程**的剩余栈跟 2 MB 下限比一下决定要不要跳到自己的 8 MB 池;协作线程和 libdispatch 线程只有 512 KB,于是异步打印循环每打印一个符号就要付一次线程往返加信号量等待(实测 8–21 µs,1.14–2.28 倍)。在执行器线程上这个探测每次都过,整条流水线(含同步被调用方)就地跑完。 + +几条容易踩的:嵌套调用是 no-op;**非结构化的 `Task {}` 不继承这个偏好**(SE-0417),所以绝不要在被包裹的入口里起一个;main actor 保留自己的执行器;macOS 15 / iOS 18 以下或非 Darwin 平台原样执行 body。进程级关闭开关 `isEnabled`,由环境变量 `MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR` 播种。 + +## 子系统 5:`_symbolic` 符号表 + +编译器给每条带 symbolic reference 的 mangled name 生成一个链接器去重用的符号(`_symbolic ` / `_default assoc type ` 开头), +名字里按引用顺序写出每个被引用者的完整 mangling。`SwiftSymbolTableRouting` 把它们分进采集的 `.symbolicMangling` 表,存为 +`Storage.symbolicManglingSymbolTable`——同一个 `SymbolTable` 结构、同样的名字来源与偏移换算,但**不进任何索引**: +`symbols(for:in:)`、`containsSymbol(named:)`、导出事实都看不到它们,这些名字也从不 demangle。唯一的出口是 +`symbolicManglingSymbols(in:)`,解码在 SwiftInspection 的 `SymbolicManglingIndex`(它要读 mangled name 的字节,本模块够不到 +ABI 模型)。 + +> 被引用者不能单独 demangle:同一个 mangler 依次写出它们,后面的会用 substitution 借用前面的。一律经 +> `SymbolicManglingIndex.referentNode(of:in:)` 拿节点。 + +细节与实测:[SymbolicManglingSymbols.md](../SymbolicManglingSymbols.md)。 + +## 关键契约 + +- **Swift 层不要写裸的 `SymbolIndexStore`**。那是 MachOKitExtensions 里只收 C/C++/ObjC 名字的 store,查询方法与 `SwiftSymbolIndexStore` 同名,写错会照样编译、却查不到任何 Swift 名字。`SymbolIndexStoreNamingScanTests` 扫 `Sources/` 与 `Tests/` 钉住。对应的名字:驱逐组是 `.swiftSymbolStore`(C/C++ store 用 `.symbolStore`),`DependencyValues` 的键是 `swiftSymbolIndexStore`。 +- **不要重新引入带缓存的 demangle**。全模块(以及上层)用 `demangleAsNodeTransient` + `Node.createTransient`;一棵用完即弃的树必须是 transient 的,否则全局 `NodeCache` 会随浏览一路涨。 +- **不要在缓存锁里做可能阻塞的大栈跳转**。迟到名字的 demangle 跑在锁外面,竞争的 misser 各自 intern 进同一个 store,靠结构化去重拿到同一个引用。 +- **改本模块的结构布局要先 `swift package clean`**。SwiftPM 增量构建被观察到链接了陈旧的下游目标文件,症状是运行时在 `outlined destroy` 里 SIGSEGV。公开类型跨模块搬家或翻转依赖边同样会触发(2026-09-12 有一次实例)——先 clean,再诊断。 + +## 相关文档 + +- MachOKitExtensions [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md)——符号表、采集(`SymbolSweep` / `SymbolTableRouting`)与 C/C++ 符号索引。 +- [NodeStoreMigrationPlan.md](../NodeStoreMigrationPlan.md)——存储形态迁移的完整分阶段计划。 +- [NodeStoreMigrationOpenIssues.md](../NodeStoreMigrationOpenIssues.md)——迁移遗留问题。 +- [SharedNodeStoreMigration.md](../SharedNodeStoreMigration.md)——声明模型持有 `NodeReference` 的那一步。 +- [SymbolIndexStoreMemoryOptimization.md](../SymbolIndexStoreMemoryOptimization.md)——内存优化。 +- [PrivateTypeMemberAttribution.md](../PrivateTypeMemberAttribution.md)——同名 private 类型的成员归属(issue #115)。 +- [LargeStackTaskExecutorAdoption.md](../LargeStackTaskExecutorAdoption.md)——执行器接入与实测数据。 +- [MetadataReaderCacheRetirement.md](../MetadataReaderCacheRetirement.md)——`SymbolicDemangler` 的 demangle memo。 +- [SymbolicManglingSymbols.md](../SymbolicManglingSymbols.md)——`_symbolic` 符号的格式、收集与解码。 +- 演进提案:[0001](../../Evolutions/0001-symbol-name-offsetization.md) 符号名 offset 化 · [0003](../../Evolutions/0003-symbol-row-bucket-flattening.md) 行号桶扁平化 · [0018](../../Evolutions/0018-self-contained-abi-layer.md) ABI 层自包含 · [0019](../../Evolutions/0019-large-stack-executor-and-cross-version-parallelism.md) 大栈执行器。 diff --git a/Documentations/Internal/Modules/SwiftThunkAnalysis.md b/Documentations/Internal/Modules/SwiftThunkAnalysis.md index bfef02a2a..646298397 100644 --- a/Documentations/Internal/Modules/SwiftThunkAnalysis.md +++ b/Documentations/Internal/Modules/SwiftThunkAnalysis.md @@ -22,9 +22,9 @@ SwiftThunkAnalysis 干一件事:**不执行 thunk,把它算出来**。 | 1. 指令解码 | `Instructions/CapstoneThunkDecoder`、`Instructions/ThunkInstruction` | | 2. 符号求值 | `Analysis/ThunkTypeEvaluator`、`Analysis/ThunkTypeExpression`、`Analysis/ThunkRegisterTracker` | | 3. thunk 形状识别 | `Analysis/AccessorThunkAnalyzer`、`Analysis/AccessorThunkProgram` | -| 4. 环境与调用目标解析 | `Resolution/MachOThunkEnvironment`、`Resolution/MetadataAccessorIndex`、`Resolution/DependencyImageResolver`、`Resolution/ThunkAddressSpace` | +| 4. 环境与调用目标解析 | `Resolution/MachOThunkEnvironment`、`Resolution/MetadataAccessorIndex`、`Resolution/DependencyImageResolver`;地址空间、桩链、槽解析与 cache 镜像定位在 MachOKitExtensions 的 [MachOAddressResolution](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOAddressResolution.md)(原 `Resolution/ThunkAddressSpace` 与 `CacheImageResolver`,提案 `offline-cross-references-and-symbolication` 第 3 步抽成本库的 `CodeAddressResolution`,提案 `move-cross-reference-layers` 搬去 MachOKitExtensions,交叉引用的文件模式共用) | | 5. 对外读取面 | `Resolution/AccessorThunkReader`、`Resolution/AccessorThunkOwnerLayout`、`Resolution/ThunkTypeNodeBuilder`、`SwiftThunkAnalysis` | -| 6. ObjC 成员表联结 | `ObjCMembers/ObjCMembers`、`ObjCMembers/ObjCMethodThunkReferences` — 复用子系统 1 的解码器与 2 的寄存器跟踪,把一个 ObjC 方法的 IMP 反汇编、收它引用的地址换成 Swift 符号,把类的每一条 ObjC 方法联结到实现它的 Swift 成员——`@objc`、`override`、显式 selector 三个事实的第二档证据(提案 `objc-ancestor-override-recovery` 与 `objc-member-selector-recovery`;hierarchy 与接缝在 SwiftInspection,只有联结表在这里,因为解码器在这里)。见 [ObjCMemberRecovery.md](../ObjCMemberRecovery.md) | +| 6. ObjC 成员表联结 | `ObjCMembers/ObjCMembers`、`ObjCMembers/ObjCMethodThunkReferences` — 复用子系统 1 的解码器与 2 的寄存器跟踪,把一个 ObjC 方法的 IMP 反汇编、收它引用的地址换成 Swift 符号,把类的每一条 ObjC 方法联结到实现它的 Swift 成员——`@objc`、`override`、显式 selector 三个事实的第二档证据(提案 `objc-ancestor-override-recovery` 与 `objc-member-selector-recovery`;hierarchy 与接缝在 SwiftObjCInterop,只有联结表在这里,因为解码器在这里)。见 [ObjCMemberRecovery.md](../ObjCMemberRecovery.md)。`ObjCMembers/ObjCProtocolWitnesses` 在这张表上替 Swift 声明的 `@objc` 协议找实现每条要求的成员:Swift 类的表按 Swift 全名取(按运行时名取的是 ObjC 类的表,strip 后联结不上 Swift 类的成员),声明的上下文换成协议,显式 selector 按编译器的推导判断。见 [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md) | ## 当前能读到什么 @@ -32,7 +32,7 @@ SwiftThunkAnalysis 干一件事:**不执行 thunk,把它算出来**。 | 输入 | 状态 | |---|---| -| dyld shared cache 里的镜像(macOS 14.7 – 26.6、iOS 设备 cache、iOS 27 模拟器 cache) | 完整解析。跨镜像调用是 rebase 地址或镜像间跳板(读槽的 stub / 算地址的 stub island),都跟得下去;跳板的形状由 `ARM64InstructionDecoding` 的 `ARM64Trampoline` 认,与 CrossReferenceAnalysis 共用一份(此前用 Capstone 加寄存器跟踪认,行为相同) | +| dyld shared cache 里的镜像(macOS 14.7 – 26.6、iOS 设备 cache、iOS 27 模拟器 cache) | 完整解析。跨镜像调用是 rebase 地址或镜像间跳板(读槽的 stub / 算地址的 stub island),都跟得下去;跳板的形状由 MachOKitExtensions 的 `ARM64InstructionDecoding` 里的 `ARM64Trampoline` 认,与 CrossReferenceAnalysis 共用一份(此前用 Capstone 加寄存器跟踪认,行为相同) | | 独立文件(第三方 app、iOS 26 及更早的模拟器运行时、即时编译的 fixture) | 完整解析,前提是给得出依赖搜索路径。跨镜像调用全是 GOT bind(只有名字),靠依赖镜像的 export trie + accessor 索引解名 | | 编译器合并的 `…MaTm` accessor | 跟进函数体求值(真正的 accessor 从 `x3` 传入,函数体只查缓存再 `blr x3`) | | 按名字引用的、属于**别的镜像**的 opaque 类型 | 重新 mangle 出描述符符号名、定位镜像、在那个镜像里展开 | @@ -57,6 +57,8 @@ Capstone 自己的 `writeback` 标志——那个标志对任何绑定操作数 寄存器列表中同样不能判定写回,因为 `ldr x0, [x0]` 也会写 `x0`。后索引的访问偏移为零,更新量不是本次访问 的偏移。现有求值器仍保守处理写回的成对访存,未新增栈更新模拟。 +字面量 `ldr xN, .Middle.Inner` 里的 `Middle`。它有 generic context(继承了 `A`),却不开新层:`B` 在第 1 层。 - extension 本身也不声明参数,但它的 generic context 带着被扩展类型的全部参数,可能跨好几层:`extension Outer.SecondMiddle where A == Int` 一个上下文覆盖 `Outer` 的第 0 层和 `SecondMiddle` 的第 1 层,里面声明的 `DeepConstrainedInner` 的 `B` 在第 2 层。 -`GenericParameterDepthLayout`(SwiftInspection)给出每层几个参数:类型或 opaque type 上下文增加参数就开一层;extension 增加的参数按被扩展类型(extended context 的 mangling 里每个声明了参数的层各带一个参数列表)拆成几层。拆不开时(读不到、个数对不上)退回「这一级算一层」,不做超出父链的猜测。 +`GenericParameterDepthLayout`(SwiftInspection)给出每层几个参数:类型或 opaque type 上下文增加参数就开一层;extension 增加的参数按被扩展类型(extended context 的 mangling 里每个声明了参数的层各带一个参数列表)拆成几层。拆不开时(读不到、个数对不上)退回「这一级算一层」,不做超出父链的猜测。opaque type 另有入口 `make(forOpaqueType:genericContext:in:)`:它的父链上还有声明它的函数——Debug 构建里还有属性——的匿名上下文,这些上下文同样会增加参数,所以照运行时的 `_gatherGenericParameterCounts` 沿整条父链数,匿名上下文增加参数也开一层。写在 extension 里的属性,匿名上下文直接挂在模块下、一次带来被扩展类型的全部参数,要靠被扩展类型的描述符拆层;找不到描述符时返回 `nil`,由调用方降级,不退回「这一级算一层」——少算一层会把类型的参数当成 opaque 自己的([OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md) §1.3)。类型的层布局不受影响:Swift 不允许在泛型函数里声明类型,类型的父链上不会有带参数的匿名上下文。 此前有五处按「每个泛型祖先一层」计数,全部改用它: @@ -38,7 +38,7 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) | `AccessorThunkOwnerLayout` | thunk 从参数缓冲区读到的第二个字被标成 `(2, 0)`,是没有字段会引用的坐标 | | `GenericArgumentEnvironment.make(forInstantiatedTypeNode:)`(SwiftLayout) | 节点遍历在 extension 节点处停下,`Outer.ConstrainedInner` 只收到最内层的实参,把 `String` 绑到第 0 层,引用它的字段整体降级 | -`TargetGenericContext.depth`(ABI 模型)保留原义——泛型祖先的个数,baseline 仍记录它——只是不再拿它命名参数。`AccessorThunkOwnerLayout(genericContext:)` 留作没有 descriptor 时的形式,改为跳过不增加参数的祖先;extension 跨层的情况只有带 `depthLayout` 的新初始化方法能处理,库内调用点全部改用后者。opaque type 的 descriptor 可能在进程内、本镜像或别的镜像里读出,它的父链必须在读它的那个上下文里遍历,所以 `Node+OpaqueType` 在读出 descriptor 的地方就算好 `AccessorThunkOwnerLayout`(`ReadOpaqueType`)。 +`TargetGenericContext.depth`(ABI 模型)保留原义——泛型祖先的个数,baseline 仍记录它——只是不再拿它命名参数。`AccessorThunkOwnerLayout(genericContext:)` 留作没有 descriptor 时的形式,改为跳过不增加参数的祖先;extension 跨层的情况只有带 `depthLayout` 的新初始化方法能处理,库内调用点全部改用后者。opaque type 的 descriptor 可能在进程内、本镜像或别的镜像里读出,它的父链必须在读它的那个上下文里遍历,所以 `Node+OpaqueType` 在读出 descriptor 的地方就用 `make(forOpaqueType:genericContext:in:)` 的层布局算好 `AccessorThunkOwnerLayout`(`ReadOpaqueType`);层布局算不出时退回不带 `depthLayout` 的形式,按位置分层。 ## 实参按层绑定:`GenericArgumentBinding` @@ -90,7 +90,7 @@ extension 上下文有一处有意与运行时不同。运行时只给被扩展 ## 验证 -`GenericSpecializationFixture`(MachOTestingSupport)现场编译一个 dylib,同一个文件按 `MachOFile` 读(离线)、`dlopen` 后按 `MachOImage` 读(在线)。`OfflineSpecializationParityTests` 对 struct、final class、泛型父类的 class、单 payload 与多 payload 泛型 enum、关联类型字段、非声明层下的嵌套泛型、派生的嵌套类型、自带参数的嵌套泛型、私有类型和 `.boundGeneric` 实参,两条路径分别特化、打开全部布局注释后打印,要求逐字节相同。 +`GenericSpecializationFixture`(SwiftSectionTestingSupport)现场编译一个 dylib,同一个文件按 `MachOFile` 读(离线)、`dlopen` 后按 `MachOImage` 读(在线)。`OfflineSpecializationParityTests` 对 struct、final class、泛型父类的 class、单 payload 与多 payload 泛型 enum、关联类型字段、非声明层下的嵌套泛型、派生的嵌套类型、自带参数的嵌套泛型、私有类型和 `.boundGeneric` 实参,两条路径分别特化、打开全部布局注释后打印,要求逐字节相同。 有三处两条路径按设计就不同,未特化的类型也一样,对照的形状避开了它们: diff --git a/Documentations/Internal/OpaqueReturnTypeResolution.md b/Documentations/Internal/OpaqueReturnTypeResolution.md index 3add4ef5b..988dd75e4 100644 --- a/Documentations/Internal/OpaqueReturnTypeResolution.md +++ b/Documentations/Internal/OpaqueReturnTypeResolution.md @@ -106,7 +106,22 @@ descriptor(或其 GOT 槽)。本模块协议(ProtocolTest)走 `\x02 `some Sendable` 在 descriptor 里只剩下参数本身:marker protocol(Sendable、Copyable、Escapable、BitwiseCopyable)从不进 generic requirements(`swift/lib/IRGen/GenMeta.cpp` 里 "Marker protocols do not record generic requirements at all"),`some Any` 本来就没有约束,`some AnyObject` 只有一条 layout 约束(kind `0x1F`),`SwiftInterfaceBuilderOpaqueTypeProvider` 不读 layout。这三种形状里 `numRequirements` 与父级相同,全部是继承来的。 -因此 provider 定位参数**只能按坐标,不能按位置**:opaque 自己的参数全在同一深度,下标就是它在声明里的序号(`Qr` 是 0,`QR` 是 n + 1,见 `ASTMangler::appendOpaqueTypeArchetype`)。深度从 descriptor 算:沿父链找到最近的类型或 extension,取它的 `GenericParameterDepthLayout` 层数(非泛型嵌套类型不占层;extension 按被扩展的类型拆层,一个 extension 可以带来好几层,与运行时 `_gatherGenericParameterCounts` 换成被扩展类型来数一致),声明自己泛型再加一层(type 节点套着 `dependentGenericType`)。中间的匿名上下文是泛型声明自己签名所在的地方,它那一层由「声明自己泛型」那一项算,所以跳过;直接拿 descriptor 的父上下文来算,会把 `Outer.generic() -> some Equatable` 的方法那层数两次。曾经按「父级每让参数总数增长一次算一层」来数:`extension Outer.SecondMiddle where A: Hashable` 一次带来 `Outer` 的 `A` 和 `SecondMiddle` 的 `C` 两层,被数成一层,约束落在 `τ_2_0` 上、超出算出的层号,debug 构建在 provider 里 trap,release 打出裸 `some`(PR #131 review 第 8 条,回归测试 `OpaqueParameterInMultiDepthExtensionTests`)。**不要**从声明的 mangled 签名数层——`swift-demangle -expand` 看 `Outer.generic() -> some Equatable` 的 `QOMQ` 符号,签名里只有一个 `DependentGenericParamCount`,外层类型那一层被 `appendGenericSignatureParts` 省掉了;也不要用 `GenericContext.depth`,它对每个带泛型上下文的父级都加一。 +因此 provider 定位参数**只能按坐标,不能按位置**:opaque 自己的参数全在同一深度,下标就是它在声明里的序号(`Qr` 是 0,`QR` 是 n + 1,见 `ASTMangler::appendOpaqueTypeArchetype`)。深度是 descriptor 自己的层布局里最内的一层,由 `GenericParameterDepthLayout.make(forOpaqueType:genericContext:in:)` 算,opaque 改写那条路径(`ReadOpaqueType`,给引用的实参分层)用的也是它。算法照运行时 `_gatherGenericParameterCounts` 的走法:沿 descriptor 的整条父链往上,每个让参数总数增长的祖先开一层,匿名上下文也算;非泛型嵌套类型不让总数增长,不占层;extension 按被扩展的类型拆层,一个 extension 可以带来好几层。 + +opaque 的父链上会出现带参数的匿名上下文,类型的父链上不会(Swift 不允许在泛型函数里声明类型),所以这条算法单独给 opaque 用,类型照旧走 `make(for:ownedBy:in:)`。匿名上下文有两种: + +- **泛型函数、subscript 的上下文**:放在声明所属的类型或 extension 里,多出来的就是声明自己的参数,正好一层。 +- **属性的上下文**:只在 Debug 构建里出现。driver 给不优化的 `-g` 构建加上 `-enable-anonymous-context-mangled-names`,这时 IRGen 把属性的 opaque 类型挂在一个以属性命名的匿名上下文下(`OpaqueTypeDescriptorBuilder::getParent`)。这个上下文带着属性所在类型或 extension 的泛型签名,自己的父级却是那个类型的父级(`AnonymousContextDescriptorBuilder::getParent` 取的是属性声明上下文的父级),类型本身不在链上。属性写在 extension 里时,extension 的父级是模块,这个上下文一次带来被扩展类型的全部参数:`extension Outer.Inner { var values: some Sequence }` 把 `Outer` 的 `A` 和 `Inner` 的 `B` 并成一团。这种上下文一定带着自己的 mangled 名字,从中取出被扩展的类型,按它的 `…Mn` 符号找到描述符,再按描述符拆层:按文件读时查这个镜像的符号索引;进程内先查描述符所在镜像,再经 `dlsym` 找别的镜像导出的描述符(跨模块扩展的类型一定是 public 的)。找不到描述符(stripped 镜像里的内部类型,按文件读时别的镜像声明的类型)就返回 nil,provider 打出裸 `some`。少算一层会把类型的参数当成 opaque 参数,印出不存在的约束。 + +过去的错误: + +- 曾经按「父级每让参数总数增长一次算一层」来数:`extension Outer.SecondMiddle where A: Hashable` 一次带来 `Outer` 的 `A` 和 `SecondMiddle` 的 `C` 两层,被数成一层,约束落在 `τ_2_0` 上、超出算出的层号,debug 构建在 provider 里 trap,release 打出裸 `some`(PR #131 review 第 8 条,回归测试 `OpaqueParameterInMultiDepthExtensionTests`)。 +- 之后改成只看父链上最近的类型或 extension,再给泛型声明加一层,跳过中间的匿名上下文。这漏掉了 Debug 构建里属性所在的类型:`KeychainStorage.publisher` 的 opaque 参数是 `τ_1_0`,算出来的层号却是 0。RuntimeViewer 给静态链接了 FoundationToolbox 的 Debug 测试 bundle 建 Find 语料时,在 provider 里 trap。release 构建打出裸 `some`。更糟的是 `some Any` 这种 opaque 参数没有约束、而类型参数有约束的写法,会读到 `Value: Storable` 那条约束,印成 `some Storable`。 +- 同一个做法里,「声明是否自己开一层」看的是声明的类型节点有没有套 `dependentGenericType`。可是只带上下文 `where` 子句的函数也有自己的泛型签名,却没有自己的参数:`static func build() -> some Sequence where Value: Hashable` 被多算一层,任何构建里都打出裸 `some`。macOS 27.2 的 SwiftUICore 里 `KeyframesBuilder.buildBlock()` 就是这样。按参数总数是否增长来数,这一条自然算对。 + +后两条的回归测试是 `OpaqueParameterDepthTests`(2026-10-31):fixture 以 `-g -Onone` 现场编译,文件读法与进程内读法各打印一次 interface,另核对层布局本身。 + +**不要**从声明的 mangled 签名数层——`swift-demangle -expand` 看 `Outer.generic() -> some Equatable` 的 `QOMQ` 符号,签名里只有一个 `DependentGenericParamCount`,外层类型那一层被 `appendGenericSignatureParts` 省掉了;也不要用 `GenericContext.depth`,它对每个带泛型上下文的父级都加一。 查不到就返回 nil,printer 打出裸 `some`。这是有意的:`some Any` 会把 `some Sendable` 写成一个不对的类型,裸 `some` 至少不撒谎,而且与 `swift-section interface` 不带 `--parse-opaque-return-type`(默认)时的输出形态一致。回归测试是 `Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift`(2026-09-18,RuntimeViewer 批量导出 PhotosUIFoundation 在 `PhotosGroupingItemListManager.GroupItem.value` 上崩溃的复现)。 diff --git a/Documentations/Internal/PerConformanceAttribution.md b/Documentations/Internal/PerConformanceAttribution.md index b18b8d319..dafd08e23 100644 --- a/Documentations/Internal/PerConformanceAttribution.md +++ b/Documentations/Internal/PerConformanceAttribution.md @@ -50,9 +50,9 @@ conformance / extension 容器按 **(target, protocol, where 指纹, isRetroacti ```swift public let conformingProtocolName: ProtocolName? // conformance extension 才非 nil -public package(set) var resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] +public package(set) var resolvedAssociatedTypeWitnesses: [ResolvedAssociatedTypeWitness] -public struct AssociatedTypeWitnessProjection: Sendable, Codable, Equatable { +public struct ResolvedAssociatedTypeWitness: Sendable, Codable, Equatable { public let name: String // associated type 名 public let substitutedTypeText: String // witness 类型的 demangle 打印 } @@ -61,7 +61,7 @@ public struct AssociatedTypeWitnessProjection: Sendable, Codable, Equatable { ### 2. SwiftIndexing(接线) - conformance extension 创建点把循环里的 `protocolName` 传入; -- 同处把 `associatedType`(若有)的 records 解析成 `AssociatedTypeWitnessProjection` +- 同处把 `associatedType`(若有)的 records 解析成 `ResolvedAssociatedTypeWitness` (machO 在手;解析失败的 record 跳过并走既有 event 告警路径); - typealias-only 块(无 conformance 的剩余 associated types)protocol 保持 nil, P1-9 的 typealias-only 归并逻辑不动。 diff --git a/Documentations/Internal/PrivateTypeMemberAttribution.md b/Documentations/Internal/PrivateTypeMemberAttribution.md index 8b5e75ad6..eb051e4ae 100644 --- a/Documentations/Internal/PrivateTypeMemberAttribution.md +++ b/Documentations/Internal/PrivateTypeMemberAttribution.md @@ -4,7 +4,7 @@ ## 不变量:成员索引的字符串 key 会把同名私有类型折叠成一个桶 -`SymbolIndexStore` 的成员类索引统一是三层结构: +`SwiftSymbolIndexStore` 的成员类索引统一是三层结构: ``` memberSymbolRowsByKind[MemberKind][打印后的类型名 String][interned 上下文节点 NodeIndex] → SymbolRowBucket diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 1d694fcd4..1ac4bda96 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2692,6 +2692,696 @@ - **关联文档**:[Changelogs/0.24.0.md](../../Changelogs/0.24.0.md)。 - **对应版本**:0.24.0。 +## 108. 交叉引用分析第二轮审查的修复 + +- **时间段**:2026-10-27,分支 `fix/cross-reference-review-findings`(worktree `.worktrees/MachOSwiftSection-CrossReferenceReviewFixes`,基于 `next`),当天本地合入 `next`。 +- **动机**:对 0.24.0(`0.23.0..0.24.0`,重点是新加的交叉引用分析)做第二轮审查,12 条候选逐条核实,另外发现一条更严重的;用户批准修建议修的五条。详见 [2026-10-27 审查记录](../../Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md)。 +- **关键决策**: + - **按平台的地址掩码**:模块六处写死的 Mac 47 位掩码在 iOS 系真机上会留下签名的第 39–46 位,改为统一用 `InProcessContext.addressMask`(改为 `package` 可见),经新的 `StoredPointer.address(in:)`;`AddressMaskScanTests` 防止常量回来。 + - **ld64 改写过的代码**:字面量 `ldr` 记成从已知槽位载入、`adr` 像 `add` 一样报类引用;横向排查发现 ld64 改写过的桩 MachOKit 读不出槽位(第三方 App 里经桩的发送因此一处也认不出),改由 `ARM64Trampoline` 补读;SwiftThunkAnalysis 的解码器同样补上字面量 `ldr`(`ThunkOperation.loadFromSlot`)。复现测试现编 dylib 后按 ld64 的做法改写指令,因为 Xcode 26 的链接器不做这种改写、Xcode 27 不再带 `ld-classic`。 + - **libobjc 的发送入口**:`objc_alloc_init` 等八个入口记成它们代表的发送,按轻量档写了提案 [0076-objc-runtime-send-entry-points](../Evolutions/0076-objc-runtime-send-entry-points.md),用户批准后实现。 + - **导入类型查询的越界读**:`SwiftTypeIndex.name(ofDescriptorAt:)` 只从类型描述符读名字;审查原本建议的 `describesType` 要为扫到的每个镜像建类型索引,没有采用。 + - **缩写**:`pc` 与全仓库的 `lhs` / `rhs` 改成完整的名字,`AbbreviatedIdentifierScanTests` 钉住;fixture 源码里的 `test(lhs:rhs:)` 是参数标签、进了快照基线,不动。 + - 判为不修或误报的五条登记 ReviewAdjudications A76–A80;横向排查到的两条——MachOKit 的 `StubDecoder` 读不出改写过的桩、单字母的泛型参数——用户定暂不处理,登记 A81、A82;已暂缓的 A64 在 macOS 26.6 上核过仍复现不了,补记。 +- **落地模块**:CrossReferenceAnalysis、ARM64InstructionDecoding、SwiftThunkAnalysis、MachOReading(`InProcessContext`、`AddressArithmetic` 的参数名),以及 `lhs` / `rhs` 改名涉及的 SwiftInspection、SwiftDeclaration、SwiftIndexing、SwiftDeclarationRendering、SwiftDiffing、MachOResolving、MachOSymbols、MachOSwiftSection、MachOFixtureSupport。 +- **验证**: + - 每条修复都先写了修复前会失败的测试。前四条的 9 个测试在原始代码上一起跑过一次,全部失败(导入类型查询那条的子进程以 SIGBUS 结束),两个只核对扫描逻辑本身的测试通过;第 2 条的两组测试(16 个用例)在前四条修好、它自己还没修的代码上全部失败。这两轮在公司的 Mac Studio(macOS 26.6)上跑,交叉引用与 thunk 分析两个测试目标里其余测试都过,只有 4 个本机原本就红的(按 macOS 27.2 的缓存挑镜像)。 + - 全量 `swift test --skip IntegrationTests` 按用户要求改到 JHs-Mac-Studio-Ultra 上跑(macOS 27.2,Xcode 26.6,只走远端依赖,版本与 0.24.0 发版审计相同: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;fixture 用发版审计时按 CI 方式 ad-hoc 签名编的那份):2588 个测试 / 497 个套件全部通过,原始退出码 0。0.24.0 时是 2574 / 493,多出的 14 个测试、4 个套件是这次新加的;整个缓存上的 selector 预筛测试加了 `isKindOfClass:`,也通过。 + - 渲染 A/B 没有跑:打印、索引与读取层的改动只有运算符与闭包参数的改名和 `InProcessContext.addressMask` 的可见性,行为不变,由全量测试覆盖。 +- **关联文档**:审查记录、提案 [0076-objc-runtime-send-entry-points](../Evolutions/0076-objc-runtime-send-entry-points.md)、[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)「libobjc 的发送入口」「链接器改写过的代码」与「两种桩布局」、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、ReviewAdjudications A64、A76–A82。 +- **对应版本**:0.25.0。 + +## 109. 只剩 `@objc` thunk 或 initializing entry point 的成员 + +- **时间段**:2026-10-27,分支 `fix/thunk-only-objc-members`(worktree `.worktrees/MachOSwiftSection-ThunkOnlyMembers`,基于 `next` b4d76a3b),当天合入 `next`。 +- **动机**:逆向 Xcode 27.2 菜单栏助手的会话报来 issue #137:`Xcode Service` 里 `MenuBarPanelWindow.canBecomeKey` 这类成员在 dump 与 interface 里都不见了,只有 `nm` 能看到。triage 发现范围更大:7 个类、22 个 `@objc` 成员只剩 `To` thunk,`__objc_classlist` 里的普通类也一样;另有 9 个 class initializer 只剩 initializing entry point,interface 里也不见(issue #138)。成员模型只从实现符号(和提案 0054 的 `Tq` 替身)建成员,整模块优化删掉实现符号后就无从建起。用户批准本库与 MachOObjCSection 两边并行开工。 +- **关键决策**: + - 沿用提案 0054 的替身成员符号:照实现符号的样子造(mangled 名、成员树),偏移用镜像留下的入口。thunk 去掉 `To` 与 `objCAttribute`;initializing entry point 把 `constructor` 改写成 `allocator`、`fc` 换成 `fC`,因为 builder、vtable 槽、ObjC 方法表与 ABI 身份都按 allocator 记。 + - 符号索引给 `To` thunk 加第四个成员索引,存 thunk 自己的行;原来只记成员名的标记表不变。 + - #138 并入同一份提案:thunk 替身里的 `init` 来自 `…fcTo`,依赖模型先接受 initializing entry point。 + - 造替身之前先按名字查实现符号是否存在,没被优化掉的镜像几乎不付代价;结构相等的去重仍是最终判据。 + - 泛型类与 stub-list 类的 ObjC 方法表(`override` 与显式 selector 的证据)另立提案,与 MachOObjCSection 协作:那边让 `ObjCInterfaceIndexer` 接受宿主补进来的类,本库从 Swift 元数据算出这些类的 `class_ro_t`。 + - ABI snapshot 格式版本加一。 + - 顺带修掉一个旧问题:一个 initializer 有 `@objc` thunk,整个类的 initializer 都被打成 `@objc`(0.24.0 把 `NSHostingView` 的泛型 `init(rootView:)` 印成 `@objc override init(rootView:)`)。改为按每个 initializer 自己的 thunk 名判断;横向排查发现重载的方法有同一个问题(Swift-only 的重载也被打成 `@objc`),一并改为按符号名判断。 +- **落地模块**:MachOSymbols(第四个成员索引与查询)、SwiftDeclaration(`StandInMemberSymbols`、`indexMembers`、`ClassDispatchLookups` 的去重键挪走)、SwiftIndexing(extension 成员)、SwiftDump(`[ObjC Thunk]` 一节)、SwiftDiffing(格式版本)、MachOTestingSupport(`ThunkOnlyMemberFixture`)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 26.6,远端依赖)。 + - 修复前:只有测试的提交上 7 个暴露问题的测试全部失败(24 处),3 个只核对前提的测试通过;两处 `@objc` 误标的测试在各自的修复之前也都失败。 + - 修复后:新增两个套件 11 个测试通过;全量 2599 个测试 / 499 个套件,唯一的变化是 SymbolTestsCore interface 快照里三个泛型 initializer 不再带 `@objc`,快照已更新。 + - `Xcode Service`:与 `next` 基线对比,dump 只增不减,interface 只删掉两个误标的 `@objc`;报告里的成员全部打出,地址是 thunk 或 `fc` 的地址。 + - 渲染 A/B:96 对里 61 对一致、35 对不同,逐对归了类:dump 全是新增;interface 的差异是补回的成员、去掉不可能成立的 `@objc`(随之有几处 `final`)、属性补回了访问器。细节见 [ThunkOnlyObjCMembers.md](ThunkOnlyObjCMembers.md)「验证」。 + - 顺带看到两个与本次无关的旧问题,未修,另开 issue:#139(property wrapper 识别把下划线开头的普通存储属性当成 backing storage,打出 `@Swift.String? var phase: Any?` 这种属性,SwiftUICore 的 `TextAnimator` 等);#140(dump 给类方法的 ABI 墓碑槽打 `class func static …`,关键字重复)。 +- **关联文档**:提案 [0077-thunk-only-objc-members](../Evolutions/0077-thunk-only-objc-members.md)、[ThunkOnlyObjCMembers.md](ThunkOnlyObjCMembers.md)、[ObjCMemberRecovery.md](ObjCMemberRecovery.md)「边界与已知限制」、[DescriptorOnlyVTableMembers.md](DescriptorOnlyVTableMembers.md)「什么时候不补」、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)、ReviewAdjudications A13 的 2026-10-27 复核。 +- **对应版本**:0.25.0。 +- **补记(2026-11-10,分支 `fix/specialized-initializing-entry-points`)**:Xcode 27.2(Swift 6.4.2)成了 Ultra 上的默认工具链后,`-O -wmo` 把夹具 `InitializingEntryOnlyHolder.init(values:)` 的初始化入口也只留成函数签名特化副本(`…tcfcTf4gn_n`),`fc` 与 `fC` 都没有了,interface 里这个 initializer 消失,`ThunkOnlyObjCMemberTests` 红 4 处(`next` 基线同样红)。符号索引加第五个索引,按 initializer 归档初始化入口的特化副本;替身构建在 `fc` 与 `fC` 都没有时从副本造 initializer(名字去掉 `Tf…` 后缀,`specializedInitializerName(of:)`)。测试的前提改成两种形状都认,地址测试取实际留下的入口,另加名字推导的单元测试(`SpecializedInitializerNameTests`);ABI snapshot 格式升到 11。验证在 Ultra(Xcode 27.2)上:`ThunkOnlyObjCMemberTests` 8 个全过,全量 `swift test --skip IntegrationTests` 原始退出码 0。细节见 [ThunkOnlyObjCMembers.md](ThunkOnlyObjCMembers.md)「Swift 6.4:initializer 只剩签名特化副本」。 + +## 110. 没有 class object 的 Swift 类 + +- **时间段**:2026-10-27,分支 `feature/objc-classes-without-class-objects`(worktree `.worktrees/MachOSwiftSection-ClassesWithoutClassObjects`,基于 `next` d68e6c10),当天合入 `next`。 +- **动机**:issue #137 的 ObjC 侧。泛型类、父类在别的 resilience domain 的类、父类是本模块泛型类的类都不在 `__objc_classlist` 里,`swift-section objc` 列不出它们,本库的 ObjC 方法表也读不到它们,`Xcode Service` 的 `MenuBarPanelWindow` 的 `canBecomeKey` 这类覆写因此只有 `@objc`、没有 `override`。用户批准本库与 MachOObjCSection 两边并行开工;MachOObjCSection 新增了让宿主补进类的 `ObjCSuppliedClass`(它那边的提案 0014,随 0.8.201 发布)。 +- **关键决策**: + - 新的 `SwiftClassWithoutClassObjectIndex` 从类型描述符读出三种类的 `class_ro_t`:泛型类从 generic metadata pattern 的 extra-data pattern(照运行时 `initializeClassMetadataFromPattern` 的偏移算法),Resilient 策略从 `ResilientClassMetadataPattern`,Singleton 策略从静态的 incomplete metadata。绝对指针一律经 MachOObjCSection 的读取器解。 + - 名字:泛型类用 Swift 限定名加泛型参数(模板里的名字是空指针),另外两种用 `class_ro_t` 里的运行时名。父类给运行时名的地方都给运行时名,链能接着走;别的镜像里的 Swift 父类只给 Swift 写法,链在那里断(运行时名要用旧式 mangling 拼,本库没有旧式 remangler)。 + - 交给 MachOObjCSection 的是全部泛型类与 `__objc_stublist` 登记的类:编译器只给有 ObjC 祖先的非泛型类登记 stub,MachOObjCSection 给它们写的注释也是这个意思。本库自己的方法表不过滤。 + - Singleton 类的 stub 是非公开的,只有完整 stub 的私有符号 `…CMt`,isa 字段在它后面一个字;`…CMs` 别名只给公开 stub 定义(起初按 `…CMs` 找,测试抓到后用探针确认)。 + - 祖先解析器在进程内也按名字到已加载的镜像里找 ObjC 父类:没有 class object 的类只有父类的名字。起初把这一点记成已知限制,已有的「进程内与文件打印出同样的声明」测试红了,于是补上。 + - 打印父类名起初用了 `.interfaceType` 预设,它去掉泛型实参,`MenuBarLabelHostingView` 的父类读成了 `SwiftUI.NSHostingView`;改用 `.interface`,fixture 加了一个父类是别的模块泛型类的例子。 +- **落地模块**:SwiftInspection(`SwiftClassWithoutClassObjectIndex`、`ObjCClassMethodIndex` 的查询与祖先链、`ObjCAncestorResolver` 的进程内按名字查找)、MachOSymbols(按名字查符号偏移)、SwiftIndexing(`ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`、provider 查 `suppliedClassGroup(forName:)`)、SwiftSectionKit(两处构造 ObjC 索引器时传入)、MachOTestingSupport(`ClassesWithoutClassObjectsFixture`);依赖 MachOObjCSection 升到 0.8.201。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 26.6,远端依赖)。 + - 修复前:只有测试的提交(4212fe49)上 4 个行为套件全部失败(16 个测试、20 处断言),其中一处是剥过符号的泛型类成员被 `final` 还原误标成 `final`。 + - 修复后:目标套件与相关的 ObjC 成员恢复套件 12 个、74 个测试通过;全量 `swift test --skip IntegrationTests` 2610 个测试 / 502 个套件,唯一的变化是 SymbolTestsCore 的两份快照:interface 里三个继承 `NSObject` 的泛型类,编译器合成的 `init()` 成了 `@objc override init()`,dump 里它们多了 `// ObjC ancestor chain: NSObject` 与 `init` 的覆写注释,与非泛型类一致(快照已更新)。 + - `Xcode Service`:`objc dump` 列出 `MenuBarPanelWindow : NSPanel`(9 个方法,与 MachOObjCSection 那边的测试一致)与 `MenuBarLabelHostingView : SwiftUI.NSHostingView`;interface 里 `MenuBarPanelWindow` 的 8 个 ObjC 成员都成了 `@objc override`。 + - 渲染 A/B:96 对里 66 对一致、30 对不同,都在 SwiftUI 与 SwiftUICore,逐行归类后全部是预期中的改进:interface 只多出 `override`(1576 处)、`static` 改成 `override class`(14 处)、剥过符号的模拟器腿上的 `@objc` 与 12 处显式 selector,没有删掉的声明,也没有类型变化;dump 只多出方法表与祖先链的注释。显式 selector 逐个核过,都与基线对有 class object 的类的判定一致,或是方法表里的真实 selector(`NSHostingView` 的 `springLoadingHighlightExited:`,看起来是 SwiftUI 的笔误)。两侧渲染耗时相同。细节见 [ClassesWithoutClassObjects.md](ClassesWithoutClassObjects.md)「验证」。 +- **关联文档**:提案 [0078-objc-classes-without-class-objects](../Evolutions/0078-objc-classes-without-class-objects.md)、[ClassesWithoutClassObjects.md](ClassesWithoutClassObjects.md)、[ObjCMemberRecovery.md](ObjCMemberRecovery.md)「边界与已知限制」、[ThunkOnlyObjCMembers.md](ThunkOnlyObjCMembers.md)「边界」、[ObjCCommandLine.md](../ObjCCommandLine.md) 第 5 条。 +- **对应版本**:0.25.0。 + +## 111. Swift 声明的 `@objc` 协议与类对 ObjC 协议的遵循 + +- **时间段**:2026-10-28,分支 `feature/swift-declared-objc-protocols`(worktree `.worktrees/MachOSwiftSection-SwiftDeclaredObjCProtocols`,基于 `next` 5f09ca46),当天合入 `next`。 +- **动机**:RuntimeViewer 会话转来的需求,样本是 Xcode 的 DVTFoundation。Swift 源码声明的 `@objc` 协议在 `dump` 与 `interface` 里都不出现:编译器不给它生成 protocol descriptor,本库只从 protocol descriptor 认协议。同一个原因带出第二个缺口:ObjC 协议没有 witness table,类对它的遵循也没有 conformance record,interface 里 Swift 类对任何 ObjC 协议的遵循全部丢失(`class DVTIconReference: __C.NSObject` 少了 `DVTResourceReference, NSCopying`)。用户决定两件一起做。 +- **关键决策**: + - 本镜像声明了哪些以 `__swift5_fieldmd` 里 kind 为 `ObjCProtocol` 的 field descriptor 为准,`protocol_t` 的 IsSwift 位不算证据:Swift 会给引用到的别的模块协议生成带这一位的副本,clang 经 `-Swift.h` 生成的副本这一位是 0。配对只看名字。 + - 要求没有任何 Swift 符号(探针确认,与访问级别、library evolution 无关)。有本镜像的类实现时照抄那个成员;没有时移植 ClangImporter 的 `omitNeedlessWords` 从 selector 推出 Swift 名,再加一步去掉 Swift 插入的 `With`,用 `@objc(selector)` 钉住(用户决定,先用探针拿真实 importer 的输出核对过)。 + - 找实现者时 Swift 类的成员表要按 Swift 全名取:按运行时名取的是 ObjC 类的表,strip 过的镜像里联结不上 Swift 类的成员——测试在 strip 变体上红了才发现。 + - 同一模块里的 extension 被编译器并进类自己的 `class_ro_t`,只有 extension 别的模块的类才生成 category(探针确认)。类头部列 `class_ro_t` 的协议;每个 category 打成 `extension X: P {}`,范围因此从「本镜像的类」改成所有 category。隐含的协议(类遵循的 Swift 协议继承的 ObjC 协议)按遵循记录剔除,只认本镜像的 Swift 协议。 + - 导入的协议在 `__C` 里保留 ObjC 名(`__C.NSObject`),与编译器的 mangling 和现有输出一致,不加 `Protocol` 后缀。别的模块改过名的协议只对「Swift 生成、本镜像不认领」的记录名到依赖闭包里找,只查带反射元数据的镜像,锁外建索引。 + - 独立的 `ObjCProtocolDefinition`,不动 `ProtocolDefinition`;新增 `ExportStatus.declarationHasNoSymbol`。类头部的协议与 category 遵循只在单版本 interface 里打,diff、evolution 与 ABI 快照都不收录。 +- **落地模块**:MachOSwiftSection(`fieldDescriptors`、`FieldDescriptor.actualSize`)、SwiftInspection(`SwiftDeclaredObjCProtocolIndex`、`ObjCProtocolRecord`、`ObjCTypeEncoding`、`ObjCImporterNaming`、`ObjCProtocolRequirements`、`ObjCRuntimeNames`、`ObjCProtocolAdoptionIndex`、`ObjCAncestorResolver` 的跨镜像协议查找)、SwiftThunkAnalysis(`ObjCProtocolWitnesses`)、SwiftDeclaration(`ObjCProtocolDefinition`、`ObjCCategoryConformance`、`TypeDefinition.objcProtocolNames`、`ExportStatus.declarationHasNoSymbol`)、SwiftIndexing(`objcProtocolDefinitions`、`allObjCProtocolDefinitions`、`objcCategoryConformances`)、SwiftPrinting / SwiftInterface(协议声明、类头部、category 遵循)、SwiftDump 与 SwiftSectionKit(`protocols` 与 `protocolConformances` 两段、类的 `// ObjC protocols:` 行)、SwiftLayout(`ObjCProtocolIndex` 认改过名与嵌套的协议)、MachOTestingSupport(`SwiftDeclaredObjCProtocolsFixture`)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 26.6,远端依赖)。 + - 全量 `swift test --skip IntegrationTests`:510 个套件、2648 个测试全部通过;已有测试只动了 SymbolTestsCore 的两份快照(新增三个 `@objc` 协议的声明与一个类头部的协议)与 `ExportStatusTests` 的穷举 `switch`。 + - 渲染 A/B(基线 `next` 5f09ca46):96 对里 32 对一致、64 对不同,逐行归类全部在预期内——769 处类头部只多了 ObjC 协议,35 行是挪到协议声明后面的 protocol extension,1979 行新增是协议声明、注释与 category 的 `extension`;没有删掉或改动任何已有的声明。两侧渲染耗时持平。 + - DVTFoundation:11 个协议都打出来,`DVTIconReference` 的头部是 `__C.NSObject, DVTFoundation.DVTResourceReference, __C.NSCopying`。细节见 [SwiftDeclaredObjCProtocols.md](SwiftDeclaredObjCProtocols.md)「验证」。 +- **后续修复(2026-10-29)**:分支 `fix/private-objc-protocol-bare-names`。私有协议在 interface 的声明头里、以及 dump 不带父名时的名字里带出了私有鉴别器,是 RuntimeViewer 验收时在 AppKit 的私有协议 `TextShadowViewControllerDelegate` 上看到的(`@objc protocol (TextShadowViewControllerDelegate in _05EA…) {`)。两处都改成与 Swift 协议的声明头一样只打裸名;ABI diff 路径与无名局部类型的位置名有意显示鉴别器,不动。fixture 原先没有私有的 `@objc` 协议,现在补了一个文件级 private 的,interface 与 dump 各加一条回归测试,修复前这两条都红。列举全部协议的五处断言也补上了它,四种读取情形(完整文件、strip 过的文件、已加载镜像、没有反射元数据的文件)都认得出这个协议。Ultra 上(Xcode 26.6,远端依赖)全量 `swift test --skip IntegrationTests` 510 个套件、2660 个测试全部通过。改动只影响私有 `@objc` 协议的名字,不算大重构,没有跑渲染 A/B。 +- **关联文档**:提案 [0079-swift-declared-objc-protocols](../Evolutions/0079-swift-declared-objc-protocols.md)、[SwiftDeclaredObjCProtocols.md](SwiftDeclaredObjCProtocols.md)、[ObjCMemberRecovery.md](ObjCMemberRecovery.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)。 +- **对应版本**:0.25.0。 + +## 112. MachOObjCSection 下限抬到 0.8.202:macOS 11 的 dyld cache 读出正确的方法名 + +- **时间段**:2026-10-28,直接在 `next` 上改。 +- **动机**:用户想看 AppKit 从 macOS 11.0 起的 Objective-C API 演进。对卷上 52 个归档 cache(11.0.1 → 27.2)跑 `objc snapshot` 与 `objc evolution` 时发现,11.0.1–11.7 里类与分类的方法名全部读错:每个版本约 7.6 万个成员里有 4.8–4.9 万个 selector 带控制字符,其余看似正常的是空串或单个字符,与 12.0.1 一个都对不上;协议的方法、属性、ivar、父类与协议遵循都是对的。演进报告因此在 11.7 → 12.0.1 报出约 4.7 万处移除、5.3 万处新增。根因在 MachOObjCSection:方法列表的 flag `0x40000000` 在 macOS 11(dyld-832、objc4-818,objc_opt v15)里表示 selector 偏移从 name 字段自身算起,macOS 12(dyld-940、objc4-838,objc_opt v16)起才改为从 cache 的 selector 基址算起。macOS 11 的 cache 没有这个基址,读取器以 0 兜底,就从 cache 开头去读。这个兜底从 MachOObjCSection 最初支持 cache 方法列表时就在。 +- **关键决策**: + - 修复放在 MachOObjCSection,由负责那个仓库的会话完成:按 objc 优化数据的版本选基址(v16 与新格式用 selector 基址,v12、v13、v15 从字段自身算起,读不到优化数据时方法名留空、不再猜),进程内路径在 macOS 12 / iOS 15 之前的系统上同样从字段自身算起。发了 0.8.202。 + - 本库只抬下限、不改代码:`objc` 子命令经 SwiftSectionKit 调 MachOObjCSection,本库读方法列表也都经它的 `methods(in:)`,没有第二份同样的解码。 +- **落地**:`Package.swift`(MachOObjCSection `"0.8.202" ..< "0.9.0"`)。MachOObjCSection 的 tag 0.8.202 指向 `e804bd1`(`next` 与 `main` 都在这个提交上),修复提交是 `f40359a`,回归测试 `DyldCacheRelativeMethodNameTests` 读 11.0.1、12.0.1、13.0 的 AppKit。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(macOS 27.2,Xcode 27.2,远端依赖)。 + - `swift package update machoobjcsection` 只把 MachOObjCSection 从 0.8.201 换成 0.8.202,`workspace-state.json` 里是 `remoteSourceControl`、revision `e804bd1`;release 构建的 `swift-section` 0 warning。 + - 用它对 52 个版本的 AppKit 重做快照,与已安装的 0.24.0 release 版的快照逐一比较:每个版本带乱码的 selector 都是 0;11.x 的类、协议与分类集合不变,约 1,860 个容器的方法名改对了(NSView 1,731 个成员,有 `initWithFrame:` 与 `drawRect:`);12.0.1–13.7 完全一致;14.0 起只多出 11–35 个容器,都是第 110 节交给 MachOObjCSection 的没有 class object 的 Swift 类,共有容器的成员没有差异。 + - `objc diff` 11.7 → 12.0.1 降到 1,193 行移除、1,402 行新增(含类与协议本身的行),与 MachOObjCSection 那边直接读 cache 的结果一致;52 个版本的演进报告里,11.x 各步只有几十到一百多处变化。 + - 没有跑全量测试:本地 `next` 上的 7e42d054 改了 SymbolTestsCore 的源码,而这个 worktree 链接的 fixture 二进制是 8 月 27 日编的,已经过期,全量跑会出与本次无关的红。本库测试用到的输入(宿主 macOS 27.2、带 selector 基址的新格式 cache、fixture 里经 selref 的方法列表)走的解码路径都没有变。 +- **对应版本**:0.25.0。发版说明要写:`objc` 读 macOS 11 的 dyld cache 时,类与分类的方法名不再是乱码。 + +## 113. ObjC API 演进的集成测试 + +- **时间段**:2026-10-28,直接在 `next` 上改。 +- **动机**:用户要一套和 Swift 一样的集成测试来检查 Objective-C 的演进。`swift-section objc evolution` 的整条流水线(MachOObjCSection 的 `ObjCInterfaceIndexer` → `ObjCAPISnapshotBuilder` → `ObjCAPIEvolutionBuilder` / `ObjCAPIEvolutionReporter`)原先只能经 CLI 跑,IntegrationTests 里没有对应的人工检查套件。 +- **关键决策**: + - 照 `ABIEvolutionTests` 的结构写:每个版本建一个索引器,和 `objc snapshot` 一样补进没有 class object 的 Swift 类;快照经 JSON 存取一次再交给 evolution;只有两个版本时,附上 `ObjCAPIDiffer` 的结论做对照。ObjC 没有带标注的接口视图,所以产物只有报告和 JSON(`-ObjCEvolution.txt` / `.json`),与 Swift 的产物一起写进 `~/Documents/SwiftInterfaceTests/`。 + - 两个套件都读 AppKit。`DyldCacheTests` 用 Swift 套件默认的三版本轴(15.5 → 26.5.2 → 27.0);`ArchivedDyldCacheTests` 直接引用 `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests` 的 `cachePaths`,版本和标签只在那里维护一份。没有加 27.2:那张表止于 27.0,加进去会让 Swift 的 51 版测试变成 52 版,而它的内存峰值已经贴着 5 GB。 + - `ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests` 里「镜像有 `__swift5_*` 节才上轴」改成可覆写的 `isOnAxis(_:)`,默认行为不变;ObjC 套件改看 `__objc_*` 节,AppKit 在每个 cache 里都有。 + - 不写提案:只加人工检查用的测试,不改产品行为,按低一档处理。 +- **落地**:`Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift`(新增)、`Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift`、`Package.swift`(`IntegrationTests` 加 MachOObjCSection 的 `ObjCDiffing`、`ObjCIndexing`、`ObjCInterface`、`ObjCMetadataSource` 四个 product)。 +- **验证**:在 JHs-Mac-Studio-Ultra 上(Xcode 27.2,远端依赖)`swift build --target IntegrationTests` 编译通过,原始退出码 0,新文件没有警告。按项目规定,IntegrationTests 不由 agent 运行;同一条流水线已用 CLI 在 52 个版本上跑过(上一节)。 +- **对应版本**:0.25.0(只有测试代码,不进发版说明)。 + +## 114. `objc evolution --interface`:带演进标注的合并 ObjC 头文件 + +- **时间段**:2026-10-28 至 10-29,分支 `feature/objc-evolution-interface`(worktree `.worktrees/MachOSwiftSection-ObjCEvolutionInterface`,基于 `next` 66c42e8a),10-29 合入 `next`。 +- **动机**:`objc evolution` 只输出逐条变化的报告和 JSON,读 AppKit 这种有几千个类的框架时看不出全貌。用户要的是像 Swift 的 `evolution --interface` 那样,直接在头文件上标出演进。 +- **关键决策**: + - 合并和标注的渲染放在 MachOObjCSection(`ObjCEvolutionInterfaceBuilder`),那边的提案和实现由负责那个仓库的会话完成。本库只做接线:CLI 选项、SwiftSectionKit 的请求、集成测试和文档。 + - 声明沿用 `objc dump` 的渲染,这是用户选定的。所以 `--interface` 只接受二进制或 cache,传快照会报用法错误。标注取自同样的快照和 `ObjCAPIEvolutionBuilder`,和报告、JSON 一致。 + - 各版本逐个建索引,交给 builder 后立即释放,不让 N 个索引器同时留在内存里。 + - 可用性宏的平台名按宏自己的写法(`macos`、`ios`、`macCatalyst`、`driverkit`),推断失败有 ObjC 自己的错误类型;`--platform` 不校验拼写,与 Swift 一侧一致。 + - 写文件时补上打印时会加的那个换行,让两种输出的字节完全相同。 +- **落地**:SwiftSectionKit(`ObjCAPIEvolutionRequest.Report.annotatedInterface`、`AvailabilityAttributes`、`ObjCAvailabilityPlatformInferenceError`);CLI(`objc evolution --interface` / `--emit-available` / `--platform` 及错误翻译);IntegrationTests(`ObjCEvolutionInterfaceTestSuite`,输出 `-ObjCEvolutionInterface.h`);文档(`ObjCCommandLine.md` 及 `_zh`、README、agent 插件的 skill、术语表里 union interface 一条)。提案见 [0080-objc-evolution-interface](../Evolutions/0080-objc-evolution-interface.md)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(macOS 27.2)。 + - 开发期间(Xcode 27.2,本地兄弟依赖,MachOObjCSection `next` 29f4f9a):SwiftSectionKitTests 86 个、SwiftSectionCommandTests 110 个测试全部通过,原始退出码 0;`IntegrationTests` 编译通过(按项目规定不运行)。release 构建的 CLI 渲染 AppKit 跨 52 个归档 macOS cache(11.0.1 → 27.2):193 秒,内存峰值(footprint)1.98 GB;输出 17 万行,其中 26,964 条标注、14,637 处 `API_AVAILABLE`、2,615 处 `API_OBSOLETED`。 + - 用 Xcode 26.6 跑全量测试时编译停在上游:MachOObjCSection 新代码里一个局部常量和它初始化闭包里调用的方法同名,Swift 6.3.3 的类型检查器因此崩溃(`failed to produce diagnostic for expression`),Swift 6.4 能编过。上游改名修复,发了 0.8.204;0.8.203 在修复之前已经打了 tag,保留不动、不用。本库的依赖下限因此直接抬到 0.8.204。 + - 落地前(`next` ad5bc459,Xcode 26.6,远端依赖:MachOObjCSection 0.8.204、MachOKit 0.55.100、MachOKitExtensions 1.3.0、swift-demangling 0.7.2、swift-semantic-string 0.5.0;fixture 用 Xcode 26.6 重新编译、ad-hoc 签名):全量 `swift test --skip IntegrationTests` 共 2,658 个测试、510 个套件全部通过,原始退出码 0,比第 111 节落地时多出的 10 个正是这次新加的测试。 + - skill 里提到的每个选项都能在 CLI 的 `--help` 里找到。 +- **对应版本**:0.25.0。依赖下限:MachOObjCSection 0.8.204。发版说明要写:`objc evolution --interface` 把多个版本合并成一份带演进标注的头文件,`--emit-available` 再补上可用性宏。 + +## 115. evolution 与 diff 区分「不存在」和「看不见」 + +- **时间段**:2026-10-24 至 10-25 实现,分支 `feature/evolution-unobservable-presence`(worktree `.worktrees/MachOSwiftSection-EvolutionUnobservablePresence`,基于 `next` 80ef4cc5);10-29 把 `next` 合进分支解冲突后合入 `next`。 +- **动机**:macOS 13.0–14.8 dyld shared cache 里的 SwiftUI 被剥掉了全部 local Swift 符号,非导出的函数、计算属性、初始化器在这些版本里一个都看不到,代码却都在。macOS 27.0 SwiftUI 跨 51 个版本的 evolution 因此有 5,189 条声明在 12.7 和 15.0 都在、中间却显示为缺席,多数印成 `removed in 13.0 · added in 15.0`;对 12.7 和 13.0 做 diff 也会把它们报成删除、判为 breaking。 +- **关键决策**: + - 快照多记两件事:镜像有没有 local Swift 符号(`ABISnapshot.hasLocalSwiftSymbols`),每个靠符号撑起的成员是否导出(`MemberRecord.isExported`)。两者都只是判定用的元数据,不进 key。 + - 被剥的版本里,只靠非导出符号才看得见的成员、以及只由这类成员撑起的普通 extension 记为看不见,不记为删除。一段看不见的版本两侧都在就推断为在(位图画 `◍`),两侧不同就记成区间事件(`removed between 12.7 and 15.0`),挨着轴端的一段不推断(`◌`)。 + - 规则放在 SwiftDiffing 的 `UnobservablePresence.swift`,evolution 与 diff 共用,两个版本时两条路径给出的变化一致;`diff --interface` 的渲染不动。 + - 模型只增不改:`presence` 保留,另加逐版本的状态、区间事件的起点、无事件 lineage 的签名,值为空时不编码,没有被剥版本的轴 `evolution --json` 输出逐字节不变。 + - 快照格式版本加一。起草时是 7 升到 8,合入时 8 已被 0077(thunk-only-objc-members)占用,改为 9;skill 里写明两次升级都在 0.25.0 出去,格式 8 只在开发分支上存在过。 +- **落地**:SwiftDiffing(`UnobservablePresence.swift`、evolution 与 diff 的判定、两个文本报告)、MachOSymbols(`SymbolIndexStore.hasLocalSwiftSymbols(in:)`)、SwiftInterface(`EvolutionAnnotation` 的状态与区间、`EvolutionMarking` 的新符号、短语、图例与 `@available` 规则)、SwiftSectionKit(注解着色认 `… between`)、测试 fixture `UnobservablePresenceFixture`、文档(`ABIEvolutionDesign.md` 第六批、`ABIDiffDesignAndLimitations.md` 第 6 节、`Modules/SwiftInterface.md`、术语表 unobservable、agent 插件的 skill)。提案见 [0081-evolution-unobservable-presence](../Evolutions/0081-evolution-unobservable-presence.md)。 +- **验证**: + - 实现期间(JHs-Mac-Studio-Ultra):全量 `swift test --skip IntegrationTests` 在最终提交上 2,581 个测试全过,原始退出码 0;每次收紧规则都做了变异检验。51 版 SwiftUI 的 `evolution --interface --emit-available` 与 `next` 逐行对比:5,189 条假缺口里 5,097 条(98.2%)变成推断存在,`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条,峰值内存 4.46 GB 对 4.41 GB。细节见提案决策日志。 + - 合入前(`next` 合进分支之后,JHs-Mac-Studio-Ultra,Xcode 26.6,远端依赖:MachOObjCSection 0.8.204、MachOKit 0.55.100、MachOKitExtensions 1.3.0、swift-demangling 0.7.2、swift-semantic-string 0.5.0;fixture 用 0.24.0 发版审计时编的那份,此后 fixture 源码只改过注释):全量 `swift test --skip IntegrationTests` 2,700 个测试、514 个套件,只有 `next` 后加的 `AbbreviatedIdentifierScanTests` 抓到本分支代码里的 `lhs` / `rhs`;改名为 `left` / `right` 后重跑该扫描与 SwiftDiffingTests,112 个测试全过,原始退出码 0。 +- **对应版本**:0.25.0。发版说明要写:evolution 与 diff 不再把被剥符号版本里看不见的成员报成删除;ABI 快照格式升到 9,旧快照要重新生成。 + +## 116. 一个版本由一组 image 组成的演进 + +- **时间段**:2026-10-29,分支 `feature/image-group-evolution`(worktree `.worktrees/MachOSwiftSection-ImageGroupEvolution`,基于 `next` e1221a02),当天合入 `next`。 +- **动机**:用户要 ObjC 演进的集成套件支持多个 image。Apple 拆框架时声明在 image 之间搬家(AppKit 的类挪进 UIFoundation、CollectionViewCore,SwiftUI 的类型在 macOS 15 挪进 SwiftUICore),一个版本只读一个 image 时,搬走的报成删除、搬来的报成新增,看不出它们其实没有消失。 +- **关键决策**: + - ObjC 侧由 MachOObjCSection 的会话实现(它的提案 0016,随 0.8.205 发布),本库做 Swift 侧与集成测试;两边约定同一套输入形状(每个版本一个有序的单 image 快照列表)、搬家记录(`ImageMove`,成员跟着容器挪的不另记)与报告文案。 + - 先把改同一批文件、已完成待合并的 `feature/evolution-unobservable-presence` 合进 `next`(第 115 节),再从 `next` 切本分支。 + - 报告、JSON 与联合接口都支持,命令行不接。 + - 顺带修掉单 image 的漏收:SwiftUI 给 SwiftUICore 类型加的、mangling 不带 extension 上下文的成员原先在 SwiftUI 的 interface 与快照里整个消失;现在收进 `extension <类型>`,快照格式升到 10(dump 不经这条路径)。判据收紧过两次:第一版只按名字排除本 image 的类型,SymbolTestsCore 的 interface 快照抓到误收的协议符号与带约束 extension 里的嵌套类型,改成只认「模块 → struct、class、enum 一路下来」的上下文;渲染 A/B 又抓到 image 里带着的别的模块的成员(标准库内联的代码、ClangImporter 给 C 枚举合成的成员),再要求类型的模块是本 image 自己的 Swift 模块。同一模块里没有类型描述符的内部命名空间等原先同样被丢掉的成员也一并收进来。 + - 组里定义了的类型,另一个 image 给它加的普通 extension 并回类型本体比较,否则类型搬家那一版会报成「类型里删掉、extension 里新增」。 +- **落地**:SwiftIndexing(`indexExtensions()` 收别的 image 的类型的成员)、SwiftDiffing(`ImageGroups.swift`、`ABIEvolutionBuilder.evolution(ofImageGroups:versions:)`、报告、collision 的 image 名)、SwiftInterface(`InterfaceVersionGroupUnit`、`AnySwiftEvolutionInterfaceBuilder(…, imageGroups:…)`、注解短语与图例)、测试 fixture `ImageGroupFixture`、IntegrationTests(`MultiVersionDyldCacheImageTests.cacheImageNames` 与 SwiftUI + SwiftUICore 的报告和联合接口套件)、文档(`ABIEvolutionDesign.md` 第七批、`Modules/SwiftInterface.md`、术语表 image group、agent 插件 skill 的快照格式一段)。提案见 [0082-image-group-evolution](../Evolutions/0082-image-group-evolution.md)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 26.6,远端依赖同第 115 节)。 + - 漏收成员的复现测试(`MembersOfAnotherImagesTypeTests`)在修复前 3 处失败、修复后通过;第一版判据让全量里 SymbolTestsCore 的 interface 快照变红,收紧后转绿。 + - 第一到第三步合在一起:全量 `swift test --skip IntegrationTests` 2,729 个测试、518 个套件全部通过,原始退出码 0;IntegrationTests 编译通过(按项目规定不运行)。 + - 第一次渲染 A/B 抓到别的模块的成员被印成 extension(标准库内联的代码、ClangImporter 给 C 枚举合成的成员);加上模块判据后,回归测试修复前变红、修复后转绿,全量 2,731 个测试、518 个套件全部通过,原始退出码 0。 + - 第二次渲染 A/B(基线 `next` e1221a02,候选 a0a7dc27,两侧共用一份 `Package.resolved`):96 对里 77 对逐字节一致,所有 dump 一致;差异只在 SwiftUI、SwiftUICore、Combine 的 interface,全部只增不减,新 extension 全在本 image 自己的模块上,别的模块的 extension 块两侧逐字节一致。macOS 26.6 cache 的 SwiftUI 多出 1,222 行、52 个 extension(`Text.accessibilityTextContentType(_:)` 等);拆分之前的 iOS 15.5 SwiftUI 也多出 191 行,是没有类型描述符的内部命名空间之类本模块原先丢掉的成员;Combine 多出 `Combine.CombineFeatures` 的一个静态成员。 + - MachOObjCSection 的会话对照两边实现,核出三处不一致:联合接口的 collision 警告没写 image 名、搬家按数组比较、image 名与签名数量对不上时 `zip` 截掉签名。三处各加一条修复前变红的回归测试;最终代码上全量 2,734 个测试、518 个套件全部通过,原始退出码 0。 + - ObjC 的两个集成套件等 MachOObjCSection 0.8.205 发布后接上,依赖下限随之抬到 0.8.205:只把 MachOObjCSection 解析到 0.8.205、其余依赖不变,全量 2,734 个测试、518 个套件全部通过,原始退出码 0;IntegrationTests 编译通过(按项目规定不运行)。 +- **对应版本**:0.25.0。发版说明要写:interface 补上本模块里没有哪个定义收到的成员(SwiftUI 给 SwiftUICore 类型加的那批、内部命名空间的静态成员);ABI 快照格式升到 10;evolution 能以一组 image 为一个版本比较、记录组内搬家(目前经库 API,命令行未接);MachOObjCSection 的依赖下限是 0.8.205。 + +## 117. 导出过滤进入标记模式,C 导入类型不再判成未导出 + +- **时间段**:2026-10-30 至 10-31,分支 `feature/exported-only-marking-mode`(worktree `.worktrees/MachOSwiftSection-ExportedOnlyMarkingMode`,基于 `next` e4b5595c),10-31 合入 `next`。 +- **动机**:RuntimeViewer 要加「只看导出的声明」(它的提案 `draft-exported-declarations-filter`)。内容区打开 `printExportedDeclarationsOnly` 就行,Find 的语料却是标记模式打印的,而导出过滤不在标记模式里,开着这个选项照样搜得到未导出的成员。排查中还发现 C 导入类型被判成未导出:它们的描述符是本镜像自己生成的副本,判成未导出会让 `--exported-only --show-c-imported-types` 连 C 类型本身和本镜像给它写的公开扩展一起删掉。 +- **关键决策**: + - C 导入类型在裁决源头改为不给结论(`ExportStatus.declarationIsCImported`,看描述符的模块是不是 `__C` / `__C_Synthesized`),不在扩展那一腿特判;宿主读 `exportStatus` 的地方一起正确。 + - `printExportedDeclarationsOnly` 成为可见性选项 `swift.printExportedDeclarationsOnly`;标记模式下过滤器原本不输出的每一处(三个打印入口、被清空的普通扩展、成员、存储属性、`printRoot` 的全局块与 ObjC category conformance 块)照常打出,只在开关关着时可见;`printRoot()` 在标记模式下也装 `ExportFilterScope`。 + - `DeclarationBlock` 的闭合换行按全量打印的 body 决定,导出过滤会改变 body 的最后一个字节:在打印器里处理(嵌套定义之后的声明全被过滤时去掉末尾换行,交给块补一个条件换行),不改 swift-semantic-string。 + - 2026-10-31 RuntimeViewer 接入时报告:Foundation 的 `LocalePreferences` 没导出、嵌套的 `ICUSymbolsAndStrings` 却导出了(系统框架按导出清单导出,不跟访问级别走),标记打印里从外层取出的这个嵌套定义区域多带了外层的条件,`marksNestedDefinitions` 的契约不成立。现有编码下修不掉,写进契约作为例外(宿主单独打印这种嵌套定义),`ExportedOnlyFixture` 用 `-unexported_symbol` 造出同样形态,契约测试按例外严格检查。 +- **落地**:SwiftDeclaration(`ExportStatus`)、SwiftDeclarationRendering(`SwiftVisibilityOption`)、SwiftPrinting(`SwiftDeclarationPrinter+ExportFilter.swift`、`+VisibilityRegions.swift`、`+Headers.swift`、`SwiftDeclarationPrinter.swift`)、SwiftInterface(`printRoot`)、MachOTestingSupport(共享的现场编译模块 `ExportedOnlyFixture`)。 +- **关联文档**:提案 [0083-exported-only-marking-mode](../Evolutions/0083-exported-only-marking-mode.md),[ExportedOnlyInterfaceFiltering.md](ExportedOnlyInterfaceFiltering.md)「C 导入类型不裁决」与「标记模式」两节。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(默认 Xcode 27.2,远端依赖)。 + - C 导入类型的复现测试(`cImportedTypeIsNotRuledOnAndItsPublicExtensionsAreKept`)修复前四条断言全红,修复后通过。 + - 投影测试的两个探针:标记模式退回不管导出过滤时三条投影测试都红;不去掉 body 末尾的换行时,`ExportedOnlyFixture` 的四种形态投影到开关打开都印成 `}}`。 + - 全量 `swift test --skip IntegrationTests`(d49bf523):2,738 个测试、518 个套件,只红 `ThunkOnlyObjCMemberTests` 4 条,原始退出码 1。同一工具链下 `next` e4b5595c 的快照(两侧共用一份 `Package.resolved`)同样这 4 条、同样的行号红;换 CI 的 Xcode 26.6(Swift 6.3.3)它是绿的:现场编译的 fixture 随编译器漂移,是既有问题,不是本分支引入的。IntegrationTests 编译通过(按项目规定不运行)。 + - Xcode 26.6 下本分支编译通过,`ThunkOnlyObjCMemberTests`、`VisibilityRegionProjectionTests`、`ExportedOnlyLibraryEvolutionFixtureTests`、`ExportStatusTests`、`ExportedOnlyInterfaceTests`、`SymbolTestsCoreInterfaceSnapshotTests`、`NestedDefinitionRegionContractTests` 等 9 个套件 44 个测试全过,原始退出码 0。 + - 真实框架探针(临时测试,未提交):从本机 macOS 27.2 的 dyld cache 读 Combine、SwiftUICore、AppKit,每个定义的标记打印按「过滤开 / 关 × 地址等注释开 / 关」四组配置投影,与直接打印比较:848、14,086、2,879 个定义全部一致,其中 615、9,919、1,503 个有被过滤标记的内容。 + - 未跑渲染 A/B:普通打印的路径在构造上逐字节不变(`.always` 不打标,`VisibilityRegion(.always)` 就是原内容),SymbolTestsCore 的 interface 快照逐字节通过,改动不属于 AGENTS.md 所说的大重构。 + - 与第 118 节的 opaque 修复一起合进本地 `next`(d20ba205)后跑全量:2,743 个测试、519 个套件,同样只红这 4 条,原始退出码 1;合并结果(09684869)用 Xcode 26.6(Swift 6.3.3)连同测试目标编译通过,原始退出码 0。 + - RuntimeViewer 接入后核对:打开 `printExportedDeclarationsOnly` 时,3,996 个 Swift 条目的标记打印投影与内容区直接打印逐字一致;Find 只在开关关着时搜得到未导出的成员。 +- **对应版本**:0.25.0。发版说明要写:`ExportStatus` 新增 `declarationIsCImported`(穷举 `switch` 的宿主要补一个分支);`--exported-only --show-c-imported-types` 不再删 C 类型和本镜像对它的公开扩展;标记模式覆盖 exported-only 过滤,宿主逐个定义打印时要给标记打印器也装 `ExportFilterScope`;`marksNestedDefinitions` 契约有一个例外:被过滤的定义里没被过滤的嵌套定义要单独打印。 + +## 118. opaque 结果的层号按每个加参数的上下文来数 + +- **时间段**:2026-10-31,分支 `fix/opaque-parameter-depth`(worktree `.worktrees/MachOSwiftSection-OpaqueParameterDepth`,基于 `origin/next` e4b5595c),当天合入 `next`。 +- **动机**:RuntimeViewer 用 Debug 构建给一个静态链接了 FoundationToolbox 的测试 bundle 建 Find 语料时,在 `SwiftInterfaceBuilderOpaqueTypeProvider` 的断言上 trap:`KeychainStorage.publisher : some Publisher` 的约束落在 `τ_1_0`,算出的 opaque 层号却是 0。 + - 根因:Debug 构建(`-g -Onone`,driver 因此加上 `-enable-anonymous-context-mangled-names`)把属性的 opaque 类型挂在一个以属性命名的匿名上下文下。这个上下文带着类型的泛型签名,父级却是类型的父级。provider 跳过匿名上下文、只数父链上最近的类型或 extension,于是找不到类型。 + - release 构建同样算错:打出裸 `some`;opaque 参数自己没有约束、类型参数却有约束时(`some Any`),读到类型参数的约束,印出不存在的 `some Storable`。 + - 修好之后在系统框架上做前后对比,又发现同一处的另一个错误,任何构建都有:provider 凭类型节点套没套 `dependentGenericType` 判断声明是否自己开一层,只带上下文 `where` 子句的函数有签名、没参数,被多算一层,打出裸 `some`(SwiftUICore 的 `KeyframesBuilder.buildBlock()`)。 +- **关键决策**: + - 在 `GenericParameterDepthLayout` 加 `make(forOpaqueType:genericContext:in:)`,照运行时 `_gatherGenericParameterCounts` 沿整条父链数层,每个让参数总数增长的上下文开一层,匿名上下文也算。provider 与 opaque 改写(`ReadOpaqueType`,给引用的实参分层、给 kind-9 thunk 的实参取名)都改用它,provider 原先的 `enclosingDepthCount` 与 `declaresOwnGenericParameters` 删掉,`where` 子句那一条随之算对。 + - 属性写在嵌套泛型类型的 extension 里时,它的匿名上下文直接挂在模块下,一次带来被扩展类型的全部参数。这时从匿名上下文的 mangled 名字取出被扩展的类型,按 `…Mn` 符号找到描述符再拆层:先查描述符所在镜像的符号索引;读的是本进程里已加载的镜像时(`MachOImage`,或进程内地址),被扩展类型在别的镜像就经 `dlsym` 找它导出的描述符(跨模块扩展的类型一定是 public 的)。按文件读、类型又在别的镜像时拆不了,返回 nil,provider 打裸 `some`,改写按位置分层:少算一层会印出别的参数的约束,宁可不印。 + - 类型的层布局不动:Swift 不允许在泛型函数里声明类型(泛型类型的方法也算),类型的父链上不会有带参数的匿名上下文。 +- **落地**:SwiftInspection(`GenericParameterDepthLayout.make(forOpaqueType:genericContext:in:)`),SwiftInterface(`SwiftInterfaceBuilderOpaqueTypeProvider`),SwiftDeclarationRendering(`ReadOpaqueType`),回归测试 `OpaqueParameterDepthTests`(两个现场编译的模块:一个声明嵌套泛型类型,另一个以 `-g -Onone` 编译、在 extension 里给它加属性;文件读法与进程内读法各打印一次 interface,另核对层布局本身),文档 [OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md) §1.3、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑。 + - 修复前:两个 exit test(文件读法、进程内读法)都以 `SIGTRAP` 结束,正是 RuntimeViewer 报的那个断言;层布局 6 个声明全错。修复后全部通过,既有的 `OpaqueParameterInMultiDepthExtensionTests` 照旧通过。`where` 子句那条用两份 CLI 在 `-O` 与 `-g -Onone` 编的探针上核过:修复前都是裸 `some`,修复后都印出约束。 + - 最终代码上 opaque 相关的单元测试套件全部通过(SwiftInterfaceTests 5 个套件 18 个测试、opaque 改写 3 个套件 10 个测试、ABI 层 opaque fixture 测试);其中别的镜像声明的被扩展类型,按文件读印成裸 `some`,进程内读印出约束。 + - Xcode 26.6(CI 的 Swift 6.3)编译通过,opaque 相关的 13 个套件 39 个测试全部通过,原始退出码 0。 + - 合进本地 `next`(d20ba205,与第 117 节的导出过滤在一起)后跑全量 `swift test --skip IntegrationTests`:2,743 个测试、519 个套件,只有 `ThunkOnlyObjCMemberTests` 的 4 条失败,原始退出码 1。这 4 条是默认 Xcode 27.2 现场编译 fixture 的漂移,`next` 基线 e4b5595c 上同样失败,Xcode 26.6 下通过。 + - 前后对比:基线 `origin/next` e4b5595c 与修复分支的 debug CLI,对本机 dyld cache 里 TipKit、Charts、SwiftData、WidgetKit、AppIntents、Combine、SwiftUICore、SwiftUI 各跑 `interface --parse-opaque-return-type` 与 `dump`。16 组输出里 15 组逐字节一致;SwiftUICore 的 interface 只差一行,就是上面 `KeyframesBuilder.buildBlock()` 印出了 SDK 里那个约束(`some SwiftUI.KeyframeTrackContent`)。 + - 合并结果(09684869)用 Xcode 26.6(Swift 6.3.3)连同测试目标编译通过,原始退出码 0。 + - RuntimeViewer 用 Debug 构建核对(对着 d20ba205):临时改回给整个 Core 测试 bundle 建 Find 语料,4,210 个对象 78 秒建完,断言一次也没触发。同一份 RuntimeViewer 代码配修复前(3323c163)与修复后的本库,Foundation 建语料修复后两次都是 40 秒,修复前一次 42 秒(另一次 77 秒是在机器负载 75 时测的,不算数),没有变慢。它的 Core 与 Packages 测试除满载时的等待超时外都通过,超时的套件单独重跑也通过。 +- **后续**:只带上下文 `where` 子句的方法,函数头多印了一个泛型参数表(`static func build() -> … where A: Swift.Hashable`,SDK 写的是 `buildBlock() -> … where Value : …`),修复前后都这样,与层号无关,这次没动。 +- **对应版本**:0.25.0。发版说明要写:Debug 构建的镜像里,泛型类型的属性返回 `some` 时,interface 印出它自己的约束,不再印成裸 `some` 或别的参数的约束;只带上下文 `where` 子句的方法返回 `some` 时也印出约束;用 Debug 构建的宿主(RuntimeViewer)不再在这里崩溃。 + +## 119. 打印器给每条注释标出种类和各段角色 + +- **时间段**:2026-10-31,分支 `feature/comment-structure`(worktree `.worktrees/MachOSwiftSection-CommentStructure`,基于 `next` 849a0b21),当天合入 `next`。 +- **动机**:RuntimeViewer 要在 SourceEditor 面板里把 interface 的注释画成标签,把字段偏移树和枚举布局做成可折叠的(它的提案 `draft-source-editor-comment-annotations`)。定下来的分工是注释的结构由生成器输出,RuntimeViewer 不解析注释文本;而在这之前,每条注释在 `SemanticString` 里只是一个 `.comment` 原子,种类、段、树的层级都没有留下。载体是 swift-semantic-string 新增的注释区域(`AnnotationRegion` / `AnnotationSegment` / `AnnotatedAtom`,已落进它的 `next` 2698750,未发版),ObjC 一侧由 MachOObjCSection 按同一套约定做。 +- **关键决策**: + - 每条注释的文字只在 `StructuredComment` 的工厂里写一次,写成带角色的段。开关 `marksCommentStructure` 关着时,各段拼成原来那一个 `.comment` 原子;打开时拆成一个 `AnnotatedAtom` 的几片,分离时并回那一个原子,所以分离后与关着时的打印逐个相同(文本、span、identifier)。 + - 种类是 `AnnotationRegion.Kind` 的静态成员:本库扩展 21 种公开的,另有 3 种只有 dump 输出、定为 package 级;`note` 来自 swift-semantic-string。跨行的结构用区域的嵌套表达:字段偏移的根区域包住整棵树,每个树节点包住自己的后代;枚举 case 块每行一个子区域;元组的 Type Layout 每个元素一个子区域;条件 witness 每个分支一个子区域。 + - 区域首尾的空白原子由 swift-semantic-string 在分离时裁掉,所以现有 helper 输出的「缩进 + 注释 + 换行」可以整个包进区域,不必重排原子(重排会改变换行字节的可见性标记)。 + - transformer 闭包的输出整个记为一个 `text` 段,按占位符分段留给后续提案。dump 不标记:共享 helper 也改走 `StructuredComment`,但开关只由打印器设置。 + - 开发期依赖 swift-semantic-string 的 `next`(`branch: "next"`),只换这一个依赖,不开 `USING_LOCAL_DEPENDENCIES`,免得把别的兄弟库未发版的内容一起带进来。落地前不带着分支依赖进 `next`:先请它发版(0.6.0),改回 `from: "0.6.0"` 再合并。 +- **落地**:SwiftDeclarationRendering(`StructuredComment` 与它的工厂、`AnnotationRegionKind+SwiftComments.swift`、`DeclarationRenderConfiguration` 的 `comment(_:as:)` 与 `commentRegion(_:content:)`、两个字段布局后端、元组的 Type Layout);SwiftPrinting(`marksCommentStructure`、各个打印点、`InterfaceHeaderBlock`,`bodyAfterNestedDefinitions` 判断末尾换行时改认 `BreakLine` 原子);SwiftInterface(`printRoot` 的文件头与两个全局块);SwiftInspection(`summaryFacts`、`formattedFixedByteRuns()`);MachOTestingSupport(`CommentStructureContract`)。测试有 `StructuredCommentTests`、`CommentConstructionScanTests`、`CommentStructureContractTests`、`CommentStructureShapeTests`、`ConditionalWitnessCommentStructureTests` 五个新套件,`NestedDefinitionRegionContractTests` 多一个变体,六个现场编译 fixture 的套件加了契约断言,新套件都进了 CI 的筛选清单。 +- **关联文档**:提案 [0084-comment-structure](../Evolutions/0084-comment-structure.md),[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「注释结构标记」,[术语表](../Glossary.md)「comment structure」,AGENTS.md 打印器一节的规则行。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(默认 Xcode 27.2,远端依赖;两侧的 `Package.resolved` 只差 swift-semantic-string 一项)。 + - 第 1 步只改注释的构造方式,输出不变:全量与 `next` 849a0b21 的快照逐条一致,只多出新套件。 + - 契约测试能抓到漏标:把 `ExportStatusComment` 临时改成不标记,`CommentStructureContractTests` 变红,并列出每一处落在区域外的 `// not exported`。 + - 全量 `swift test --skip IntegrationTests`(718c9f29):2,773 个测试、524 个套件,只红 `ThunkOnlyObjCMemberTests` 4 条,原始退出码 1。`next` 849a0b21 的快照是 2,743 个测试、519 个套件,红的是同样这 4 条;两边只在多了新测试的两个测试目标上不同。 + - Xcode 26.6(CI 的 Swift 6.3.3)连同测试目标编译通过,受影响的 16 个套件 151 个测试全部通过(包括在 27.2 下红的 `ThunkOnlyObjCMemberTests`),原始退出码 0。条件 witness 的现场编译 fixture 用 26.6 编出来同样读得出两个分支。 + - 渲染 A/B(两侧 release 预构建后带 `--skip-build` 跑,基线是 `next` 849a0b21 的 `git archive` 沙盒,所以基线缓存不可用、两侧都全量渲染):96 对输出全部逐字节一致,原始退出码 0。覆盖归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器 runtime、进程内 `MachOImage` 三种读取方式的 dump 与 interface;iOS 27.0 模拟器 runtime 里找不到这些框架文件,两侧都跳过,旧 runtime 里没有的框架(如 15.5 的 SwiftData)同样跳过。 + - 性能(开关关着,量的是每条注释多建一个段数组的开销):两侧 release CLI 对本机 dyld cache 里的 SwiftUI 打开全部注释选项生成 interface(`--emit-header`、偏移、地址、vtable、展开的偏移树、Type Layout、枚举布局、导出状态、私有声明来源、`--parse-opaque-return-type`),交替各跑两轮。四份输出逐字节一致(14.3 MB)。instructions retired 基线 926.4 G / 927.5 G,本分支 936.1 G / 930.4 G,平均多 0.7%(逐轮 1.1% 与 0.3%,本分支自己两轮相差 0.6%);峰值 footprint 两侧都在 594–642 MB;墙钟基线 92 / 87 秒,本分支 110 / 87 秒(110 秒那轮机器上别的会话正忙)。开销可以忽略,不改成关着时直接拼字符串。 + - RuntimeViewer 接入后核对(对着本地合并后的 `next` b6c37d31,加 swift-semantic-string 2698750、MachOObjCSection 635fe17):用测试包里的嵌套 struct、多载荷 enum、open class 打印,开关开与关的文本、span、identifier 完全相等;每条注释都在注释表里、从注释符号开始,区域层层嵌套,出现的 kind 与 role 都在约定清单内;字段树和 case 块在它的 App 里都能收起(RuntimeViewer 提交 c3ad6ca7)。 + - 依赖改回 swift-semantic-string 0.6.0(`fd7e93c`,相对 2698750 只改了 README 与 `docs/AnnotationRegions.md` 各一行)后重新解析、连同测试目标编译通过,受影响的 17 个套件 147 个测试全过,原始退出码 0;全量、A/B 与性能沿用上面的结果。 +- **后续**: + - transformer 模板按占位符分段(见提案「装了 transformer 的注释」)。 + - thunk 读取器不解析两个分支各自直接加载一个类型、编成 `csel` 的可用性条件 witness;interface 路径不用 `memberAddressTransformer`。两条都与本提案无关,见提案「顺带发现」。 +- **对应版本**:0.25.0。发版说明要写:`SwiftDeclarationPrintConfiguration.marksCommentStructure`(默认关)给 interface 的每条注释标出种类和各段的角色,宿主用 swift-semantic-string 的 `separatingAnnotationRegions()` 取出注释表;依赖的 swift-semantic-string 下限抬到 0.6.0。 + +## 120. 离线打印不再每次重建静态布局 provider,dyld cache 的镜像目录进程内共享 + +- **时间段**:2026-11-03,分支 `feature/static-layout-provider-reuse`(worktree `.worktrees/MachOSwiftSection-StaticLayoutProviderReuse`,基于 `next` 1dcc0c08)。性能修复,用户批准直接做,不写提案。 +- **动机**:RuntimeViewer 离线读 dyld cache 里的镜像(`MachOFile`)、打开字段偏移 / Type Layout / 枚举布局注释打印 interface 时极慢。它每次打印前都调 `SwiftDeclarationPrinter.updateConfiguration(_:)`,多数时候配置没变;而 `updateConfiguration` 无条件把记住的静态布局 provider 置回未计算(5fe5eb61,为防止布局开关变了还用旧 provider)。于是下一次取 provider 就重建 `MachOFileStaticFieldLayoutProvider`:新的依赖闭包、新的 `FileDependencyLocator`——它的第一次查询把搜索路径里每个 cache 的约 3,500 个镜像各做一个 `MachOFile`、读一遍平台——再加一个从头惰性索引依赖类型的新 `ImageUniverse`。`MachOImage` 的打印器不建 provider,所以只有离线路径慢。 +- **关键决策**: + - **只在 provider 的输入变了时丢掉它。** 输入只有两样:有没有开关需要 provider(`marksOptionalContent`、`printFieldOffset`、`printTypeLayout`、`printEnumLayout`、`printExpandedFieldOffsets`),以及 `staticLayoutDependencyResolution`。两者合成 `StaticFieldLayoutProviderInputs`(不需要时只记 nil),建 provider 的地方和 `updateConfiguration` 共用这一处判断;建好的 provider 带着它的输入记下,`updateConfiguration` 拿新配置的输入比,不同才丢。5fe5eb61 的保证不变:需要与否变了、解析方式变了都重建。替换配置与 provider 读配置都放进 provider 的锁里,记下的输入一定是建它那份配置的(原先先取配置快照再上锁,中间插进一次 `updateConfiguration` 会留下按旧配置建的 provider)。 + - **dyld cache 的镜像目录每个进程每个 cache 只读一次**(`DyldCacheImageDirectory`,MachODependencies)。目录只存数据:每个镜像的 install path、bare name 与 rank、平台集合、header 的未滑动地址;按根的平台集合过滤出的两张查找表在目录里按平台集合各建一次。键是主 cache 文件的标准化路径加主 header 的 UUID。注册表先在全局锁里取每个 cache 的槽、再在槽自己的锁里读,同一个 cache 的并发首查只读一遍,不同 cache 互不等待。 + - **不共享 `MachOFile` 实例。** MachOKit 的 `MachOFile` 有不加锁的懒状态(`_fullCache`、`_cache`),读取共用一个文件句柄;每个定位器只为自己定位到的镜像、经自己打开的 cache 做新的 `MachOFile`(`FullDyldCache.cacheAndFileOffset(for:)`,与 `machOFiles()` 同样的 cache 文件、偏移与路径),记下来重复交回。目录不持有任何 cache 或映射。 + - **查找结果与顺序不变**:root 自己的 cache 在前、搜索路径按序在后;install path 由第一个有它的 cache 回答;bare name 取所有 cache 里 rank 最好的,平局时前面的 cache 胜、同一个 cache 里先出现的镜像胜;平台过滤照旧。 + - **没有按路径共享 `FullDyldCache(url:)` 的打开**(任务里的可选项):它的映射表与 symbol cache 也是不加锁的懒状态,`cachedHost` 是先读好再共享的;按路径共享其它 cache 会让并行的根在同一个实例上首次写这些状态,而 RuntimeViewer 的离线路径本来就不重复打开(root 的 cache 用 root 来自的实例,宿主 cache 走 `cachedHost`)。 +- **落地**:SwiftPrinting(`SwiftDeclarationPrinter` 的 `StaticFieldLayoutProviderInputs`、`staticFieldLayoutProvider()`、`updateConfiguration(_:)`),MachODependencies(新增 `DyldCacheImageDirectory`,`FileDependencyLocator` 改读它),测试 `StaticFieldLayoutProviderReuseTests`(加进 CI 的筛选清单)与 `DyldCacheImageDirectorySharingTests`,文档 [Modules/MachODependencies.md](Modules/MachODependencies.md) §3、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md) §2。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(默认 Xcode 27.2,`USING_LOCAL_DEPENDENCIES=1`,兄弟库取各自的 `next` 检出)。 + - 修复前:两个新套件都红,原始退出码 1。`StaticFieldLayoutProviderReuseTests` 4 个测试全红(配置不变或只多开一个布局开关时 provider 都换了实例);`DyldCacheImageDirectorySharingTests` 的共享测试红(未修复的代码临时加了一个返回每个定位器自己索引身份的测试入口,两个定位器各是各的),其余三个照旧通过——参考实现就是旧算法。 + - 修复后两个套件全过,原始退出码 0。把跨 cache 的平局规则临时改成 `<=`,root 的 cache 在前的比对测试变红,证明比对能抓到顺序错误。 + - 宿主 cache 上定位器第一次查询的耗时(仅供参考):修复前第一个定位器 0.513 秒、第二个 0.273 秒,修复后 0.298 秒与 0.006 秒。 + - MachODependenciesTests、SwiftLayoutTests、SwiftPrintingTests、SwiftDeclarationRenderingTests 四个测试目标 280 个测试全过,原始退出码 0。 + - 全量 `swift test --skip IntegrationTests`:2,781 个测试、526 个套件(比第 119 节多出本次的 8 个测试、2 个套件),只红 `ThunkOnlyObjCMemberTests` 4 条,原始退出码 1。同一次构建配置下在未修改的 `next` 1dcc0c08 上单跑这个套件,红的是同样 4 条(原始退出码 1),是 Xcode 27.2 现场编译 fixture 的旧漂移。 +- **对应版本**:0.25.0。发版说明要写:离线(`MachOFile`)打印 interface 时,宿主每次交回同样的布局配置不再重建静态布局引擎;多个根共用同一个 dyld cache 时,cache 的镜像只扫描一次。 + +## 121. ABI 层的 flag word 改用 `@BitField`,修掉三个读错位的访问器 + +- **时间段**:2026-11-05,分支 `feature/abi-flag-words-bit-field`(worktree `.worktrees/MachOSwiftSection-ABIFlagWordsBitField`,基于 `next` 463b2209)。提案 [0085-abi-flag-words-bit-field](../Evolutions/0085-abi-flag-words-bit-field.md);宏本身是 FrameworkToolbox 的提案 0015,随 FrameworkToolbox 0.17.0 发布。 +- **动机**:ABI 层照 Swift 运行时的 C++ 头文件手写了 24 个 flag word 类型,其中 17 个在一个整数里混排单比特与多位字段,写法有四种。三个访问器把位读错了:`ExistentialTypeFlags.classConstraint` 与 `ProtocolDescriptorFlags.classConstraint` 只掩码不移位,`FunctionTypeFlags.convention` 把整个字直接转成 `UInt8`。读 `Any` 的 metadata、不限定 class 的协议、任何 escaping 函数类型都会让进程停下;从 2025-10 首次提交起就在,测试为绕开它专门改用 `AnyObject.self`。 +- **关键决策**: + - 17 个类型的访问器改成 `@BitField(bits:)` 声明,位置照抄原来的掩码,逐位对过 Swift 6.4 的 `MetadataValues.h`,除上述三处外没有错位。读的转换由属性的类型经重载决议选出,typealias(`RawValue`、`StoredSize`)与泛型存储(`FunctionTypeFlags`)照常可用。 + - 会随编译器增长的 kind 改成可选,认不得的值得到 `nil`(用户选定):三个 `kind`、两个 `TypeReferenceKind` 字段、`specialProtocol` / `specialProtocolKind`、`dispatchStrategy`、`convention`。单比特的三个 `classConstraint` 与 `ContextDescriptorFlags.kind` 经 `default:` 保持原类型。 + - `GenericRequirementDescriptor.content` 与 `ProtocolConformanceDescriptor.typeReference` 遇到认不得的 kind 照旧停下,换成带说明的 `preconditionFailure`:返回类型没有能装下它的 case,要不停得给 `GenericRequirementContent` / `TypeReference` 加分支,留作后续。 + - `SpecialProtocolKind` 有 `none` case,字段改成可选后裸写 `.none` 意味着 `nil` 且只给警告;全仓库只有 `ExistentialTypeMetadata.representation` 一处,写成 `.some(.none)`。 + - `ClassFlags` 从「每个 case 是一个掩码的枚举」改成 `@FlagSet` 的选项集合,`InvertibleProtocolSet` 也改用 `@FlagSet`,`InvertibleProtocolKind` 留作 `InvertibleProtocolSet.Flag` 的 typealias(raw value 变成 `UInt16`)。`@FlagSet` 生成的成员不在源码里,覆盖率清单不再登记它们。 + - 不迁移:要 setter 的 `MetadataRequest`、存储不叫 `rawValue` 的四处描述符字段、本来就正确的三个纯单比特 `OptionSet`;仓库自己的 `FlagSet` 协议保留。 +- **落地**:MachOSwiftSection(17 个 flag word、`ClassFlags`、`InvertibleProtocolSet`、`ExistentialTypeMetadata`、`GenericRequirementDescriptor`、`ProtocolConformanceDescriptor`);改成可选的字段的调用方在 SwiftInspection、SwiftLayout、SwiftSpecialization、SwiftDeclaration、SwiftDump,dump 里认不得的方法 kind 印成 `[unknown kind, flags 0x…]`;`Package.swift` 要求 FrameworkToolbox 0.17.0;`AGENTS.md` 的 ABI 层一段加了 flag word 的规则。下游 MachOKitUI 的对应改动在它的 `feature/optional-flag-word-kinds`,对新旧两版 MachOSwiftSection 都能编(对本分支的那一版在 Ultra 的沙盒里实测编过)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上用 Xcode 26.6 跑,依赖走远端版本(FrameworkToolbox 0.17.0)。 + - 修复前:新加的 `FlagWordDecodingTests` 三条逐条运行都让进程停下(两条 `Not enough bits to represent the passed value`,一条强制解包遇到 `nil`);修复后三条都过。 + - 每一步后清空构建产物重编,`MachOSwiftSectionTests` 852 个测试全过(含覆盖率检查)。 + - `ClassFlags`、`InvertibleProtocolSet` 两份照生成器手改的 baseline,用 `regen-baselines` 重新生成后与提交的一致,`git diff` 为空。 + - 全量 `swift test --skip IntegrationTests`:2,784 个测试、527 个套件全过(比第 120 节多出本次的 3 个测试、1 个套件),原始退出码 0。 + - 渲染 A/B(基线 `next` 463b2209,两侧共用同一份 `Package.resolved`):96 对 `dump` / `interface` 输出逐字节一致——归档 cache 15.5 与 26.6 共 24 对,iOS 15.5–26.5 模拟器文件 48 对,进程内 `MachOImage` 24 对;跳过的都是该运行时里没有的框架。 +- **对应版本**:0.25.0。发版说明要写:三个 flag word 访问器不再读错位、不再让进程停下;会增长的 kind 变成可选(源码不兼容,`switch` 要补 `nil` 分支);`ClassFlags` 从枚举变成选项集合;`InvertibleProtocolKind` 的 raw value 变成 `UInt16`;依赖 FrameworkToolbox 0.17.0。 + +## 122. 读 dyld cache 时每个文件只映射一次,`@objc` 协议不再先索引整个依赖闭包 + +- **时间段**:2026-11-05 至 11-06,分支 `fix/shared-cache-file-mappings`(worktree `.worktrees/MachOSwiftSection-SharedCacheFileMappings`,基于 `next` 565fac44)。缺陷修复,用户批准直接做,不写提案。 +- **动机**:RuntimeViewer 的离线服务读 `Dock.app`(配对本机 dyld cache)、给 DockHelper 建 Find 语料时,停在 `MachOReading/Extensions/DyldCache+.swift:50` 的 `try! MemoryMappedFile.open`:`system error 24`(`EMFILE`)。停住的进程开着 2,560 个描述符——launchd 给 XPC 服务的 256,加 CoreFoundation 第一次有人碰 `CFSocket` 时自动加的 2,304,正好是它的上限——其中 2,548 个只指向 85 个 cache 文件,`.26.dyldreadonly` 一个文件开了 343 次。 +- **根因**: + - `MachOFile.fileIO` 与 `DyldCache.fileIO` 是挂在实例上的关联对象:每个实例第一次读时自己 mmap 一遍所在文件,映射一直攥着一个描述符。实例却很多:`FullDyldCache.machOFiles()` 给每个不在主文件里的镜像新建一个 `DyldCache`(`cache(atIndex:)`),MachOKitExtensions 的子 cache 表按 `MachOFile` 各建一套子 cache 实例,依赖定位器给每个根各做一批依赖 `MachOFile`。描述符于是随读过的镜像数线性增长,与 cache 有几个文件无关。 + - 放大它的是协议查找的顺序。DockHelper 的 `DockHelperDelegate.helperClient` 是 `Optional`,一个 Swift 声明的 `@objc` 协议(定义在 Dock 可执行文件里,DockHelper 持有它的 ObjC 协议记录副本)。`ExistentialLayoutBridge` 与 `ClassBoundGenericParameterAnalysis` 先问 `resolveProtocolClassConstraint`——这种协议没有 Swift 描述符,必然落空,落空前先把根的整个依赖闭包索引进来——之后才问 `isObjCProtocolDeclared`,而根自己就有那条记录。 + - `try!` 把打开失败变成了宿主进程停下。 +- **以前修过吗**:第 82 节修子 cache 查找时已经看到「本库按实例缓存的文件映射」每换一个实例就重开,当时让同一个 `MachOFile` 每次拿回同一个子 cache 实例,跨 `MachOFile` 的重复没有处理;07993a5f 给映射加了创建锁,仍按实例。先问 Swift 描述符的顺序是静态布局引擎阶段 8 加第五个 seam 时定的,那时只为认出这种协议,没考虑落空的代价。 +- **关键决策**: + - **映射按一次打开共享,不按实例。** 键用 MachOKit 的 `@_spi(Support) fileHandleIdentity`:同一次打开的 cache 文件,MachOKit 组装出的每个 `DyldCache` 与 `MachOFile` 都带同一个身份。映射作为关联对象挂在身份上(新类型 `SharedFileMapping`),MachOKit 释放句柄时身份随之释放,映射跟着关掉。MachOObjCSection 的 `FileHandleHolder` 早就这样做。描述符数从「读过的镜像数乘二到三」变成「打开的 cache 文件数」。 + - **映射在锁里建、只建一次、从不替换**,沿用 07993a5f 的保证:并发的首次读只拿到一个映射,读者手里的映射不会被换掉后释放。之后的读不加锁。 + - **`fileIO` 改为抛错。** 打开失败(文件已删、描述符用完)让这次读取失败,不再停掉宿主。`Readable` 的方法本来就 `throws`,只改了 `MachOFile+Readable.swift` 的调用处。 + - **删掉 `fileHandle`。** `MachOFile` 与 `DyldCache` 的 Foundation `FileHandle` 访问器同样按实例各开一个描述符、带 `try!`,库里已没有调用方、只剩测试在测,连同 `ConcurrentFileMappingTests` 的两条一起删。 + - **协议名两张表一起问。** `ImageUniverse.resolveProtocol(byQualifiedTypeName:)` 取代 `resolveProtocolClassConstraint` 与 `isObjCProtocolDeclared`:每索引进一个镜像就同时查 Swift 描述符和 ObjC 记录,谁先认出就停;同一时刻两张表都有时 Swift 描述符优先,即原先的先后。两个调用方都改用它。 +- **落地**:MachOReading(新增 `SharedFileMapping`;`MachOFile.fileIO`、`DyldCache.fileIO` 改为按身份共享、抛错;删 `fileHandle`),SwiftLayout(`ImageUniverse.resolveProtocol`,测试用的只读计数 `indexedDependencyImageCount`;`ExistentialLayoutBridge`、`ClassBoundGenericParameterAnalysis` 改用新查找),测试 `SharedFileMappingTests`(三条:子进程里压到 256 个描述符后连读本机 cache 的 400 个 Swift 镜像;同一文件的各个读者拿到同一个映射;文件被删后读取抛错)与 `SwiftDeclaredObjCProtocolExistentialLayoutTests.objCProtocolExistentialsResolveWithoutIndexingDependencies`,`ConcurrentFileMappingTests` 随之调整;`AGENTS.md` 加一条规则;文档 [Modules/SwiftLayout.md](Modules/SwiftLayout.md)、[StaticLayoutEngine.md](StaticLayoutEngine.md)。RuntimeViewer 一侧(配对本机 cache 改用 `cachedHost`、离线服务读文件前抬高描述符上限)在它的 `fix/offline-descriptor-exhaustion`。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 27.2,依赖走远端版本)。 + - 复现回路:`( ulimit -Hn 256; ulimit -Sn 256; swift-section dump --architecture arm64e --sections types --emit-field-offsets -o … )`。硬上限要一起压,只压软上限时 CoreFoundation 会把它抬上去,同一条命令在 100 下也能跑完。`next` 565fac44 的 CLI 两次都以 133(`SIGTRAP`)退出,报同一行;修复后退出码 0,输出与修复前不设上限的输出逐字节一致。 + - 修复前新加的 4 条测试全红:两条 exit test 以 `SIGTRAP` 结束;共享映射那条 4 处断言都不是同一个对象;`@objc` 协议那条索引了全部 513 个依赖镜像、耗时 64 秒。修复后全过,原始退出码 0;`@objc` 协议那条 0.19 秒、零个依赖。 + - 全量 `swift test --skip IntegrationTests` 跑了两次,原始退出码都是 1: + - 第一次用默认 Xcode 27.2 新编的 fixture:2,786 个测试、528 个套件(比第 121 节多出本次的 4 个测试、1 个套件,少了删掉的 2 个),红 `MachOSwiftSectionTests` 195 处(偏移类 baseline)与 `ThunkOnlyObjCMemberTests` 4 条。565fac44 用同一份 fixture 跑这两个套件,失败点与次数完全相同:baseline 记的是 Xcode 26.6 编出的偏移,新 worktree 的 fixture 要照 CI 的参数编(Xcode 26.6、`ARCHS=arm64`、ad-hoc 签名)。`ThunkOnlyObjCMemberTests` 是测试现场用默认 Xcode 27.2 编自己的 fixture,旧漂移。 + - 第二次换成照 CI 编的 fixture:`MachOSwiftSectionTests` 853 个全过,仍只红 `ThunkOnlyObjCMemberTests` 那 4 条。另外 `MachOSymbolsTests` 的测试进程在满载下以 `SIGTRAP` 停了一次(它的 58 个测试因此没计入),停时在跑 `concurrentInterningSharesOneWinner` 与 `derivedFormQueryRecognizesThunkOnlyExportedMember`。单跑 3 次全过;8 路并发各跑 24 次,本分支 24 次全过,565fac44 崩 1 次、停在同样两条上——本次之前就有的偶发崩溃,没查,记在后续里。 + - 输出对比:565fac44 与本分支的 debug CLI,`dump`(字段偏移、类型布局、枚举布局全开)跑本机 cache 的 Combine、WidgetKit、TipKit、SwiftData、AppIntents、Charts 与 Dock、DockHelper 两个文件,`interface`(偏移注释全开)跑 DockHelper 与 TipKit:10 组共约 10.8 万行逐字节一致。没跑完整的渲染 A/B(归档 cache、模拟器文件、进程内三条读取路径):本次不改解码与打印,只改映射挂在哪、协议按什么顺序查。 +- **后续**: + - 依赖定位器仍按根重开两类文件:根是独立文件、配对的是非本机 cache 时,每个根的定位器把那份 cache 整个再开一次(`FullDyldCache(url:)`);`.machOFile(path:)` 搜索路径上的每个文件也是每个根各开一次。描述符随根数增长。第 120 节有意不共享这两样(MachOKit 对象的懒状态不加锁),要改得先定设计。已在第 124 节做完。 + - `MachOSymbolsTests` 满载下偶发的 `SIGTRAP`(见上):根因在 MachOKitExtensions,见第 125 节。 +- **对应版本**:0.25.0。发版说明要写:读 dyld cache 时每个 cache 文件只映射一次,读多少个镜像都不再多占描述符;文件打不开时读取报错,不再让宿主进程停下;字段类型是 Swift 声明的 `@objc` 协议时,算字段偏移不再先索引整个依赖闭包。 + +## 123. 离线读独立文件不再每读一次就重开文件,thunk 读取的镜像级表格按镜像只建一次 + +- **时间段**:2026-11-05~06,分支 `fix/offline-reading-performance`(worktree `.worktrees/MachOSwiftSection-OfflineReadingPerformance`,基于 `next` 565fac44);配套 MachOKit fork 的 `fix/standalone-file-cache-probe` 与 MachOKitExtensions 的 `fix/fixup-resolution-cache`。性能修复,用户批准按 bug 修复处理,不写提案。 +- **动机**:RuntimeViewer 离线(`MachOFile`)读二进制的 Swift 部分,加载要转很久。在 Ultra 上用 release CLI 读三个输入并用 `sample` 采样: + - **独立文件**(iOS 18.5 模拟器的 SwiftUI,97 MB):约三分之二的 CPU 花在反复 `open` / `mmap` / `munmap` 同一个文件上(建索引阶段 78%,打印阶段 67%)。MachOKit 的 `MachOFile.cache` 对没交过 cache 的文件会把文件路径当成 dyld cache 打开,失败不记、下次再试;本库 `MachOFile+Readable.swift` 每读一个元素都先问它这个偏移在哪个 cache 文件里。3 MB 的 SwiftData 模拟器文件上 sys 时间(0.73 秒)比 user 时间(0.52 秒)还多。 + - **dyld cache 里的镜像**(本机 SwiftUI)离线本来就不慢:同一个 `RenderingVerificationTests` 里 dump 39 秒对进程内 37 秒,interface 22 秒对 17 秒。差出来的主要是 thunk 读取:`AccessorThunkReader.read` 每读一个 thunk 新建一个 `MachOThunkEnvironment`,环境上的 lazy 表每次重建——整张符号表(22 万个 Swift 符号的镜像)重扫一遍,约占 interface 工作量的六分之一;cache 全部镜像的地址表重读一遍、目标镜像重开一遍,又占 thunk 读取的一成。 + - **只影响 CLI**:`ConsoleEventHandler.handle(event:)` 对每个事件(包括不打印的)都调 `DateFormatter.localizedString`,每次新建一个格式器,约占 CLI 读本机 SwiftUI 时间的四分之一。 + - 读取原语本身(关联对象查找、子 cache 定位、内存映射读)合计约 3%,不是瓶颈;符号索引的耗时是 demangle 与 intern,两种读取器一样。 +- **来历**:本库原先自带一个先判 `isLoadedFromDyldCache` 再找 cache 的 `MachOFile.cache`。2025-11-24 升 MachOKit 0.42.0 时,MachOKit 公开了同名属性,本地这个被注释掉、后来删除,此后用的是 MachOKit 那个不判断的版本,读独立文件就一直在反复重开。上游 p-x9/MachOKit 至今同样写法;用户决定只修 fork,不提上游。 +- **关键决策**: + - **独立文件不问 cache,两层都改**:MachOKit fork 的 `cache` / `fullCache` 对 `!isLoadedFromDyldCache` 的文件直接答 `nil`,不碰文件系统(MachOKitExtensions、MachOObjCSection 与 MachOKit 自己的 `fileOffset(of:)` 里其余直接问 `cache` 的地方一并受益);本库五个读函数也先判 `isLoadedFromDyldCache`,不依赖 MachOKit 的版本。 + - **thunk 读取的镜像级表格进 `thunkResolution` 组的按镜像缓存**:镜像自带运行时符号表(`SharedCache<[UInt64: String]>`)与 `CacheImageResolver`(`resolver(cacheOf:)`)。`CacheImageResolver` 会被多个环境共用,它记下的已打开镜像与导出入口表加 `@Mutex`,查找在锁外做、先存者胜。环境本身仍每个 thunk 一个,它记的调用目标与解码过的函数不跨 thunk 共享。 + - **CLI 只为要打印的事件取时间**:`message(for:)` 先判断,返回非 nil 才格式化时间戳;行格式不变(`line(for:timestamp:)` 照旧给测试用)。时间来源做成可注入的(`package init(label:timestamp:)`),测试拿它数调用次数。 + - **MachOKitExtensions 的 fixup 解析记忆表移进 `MachOCacheStorage`**:`resolveRebase(fileOffset:)` / `resolveBind(fileOffset:)` 原先把字典存在关联对象里,每记一条都整份拷贝,耗时随槽位数平方增长(夹具 5 万个 bind 槽位,最后 2000 个比最先 2000 个慢约 50 倍),且 `.nonatomic` 关联对象在并发下不安全;改成锁内原地插入。 + - 横向排查:同一写法(关联对象里逐条插入的字典)三个仓库里只有这两处;`TypeDefinition` 的 `_specializedChildren` 只在用户手动特化时追加、条数很少,不算同类。thunk 环境上按环境重建镜像级数据的,除符号表外只有 `CacheImageResolver`,一并修了。 +- **落地**:MachOReading(`MachOFile+Readable.swift`),SwiftThunkAnalysis(`MachOThunkEnvironment.swift` 的符号表与 `CacheImageResolver`、`SharedCacheEvictionGroup+SwiftThunkAnalysis.swift`),SwiftIndexing(`ConsoleEventHandler`);测试 `StandaloneFileReadingTests`、`ThunkEnvironmentImageTablesTests`、`ConsoleEventHandlerLineTests` 新增一条,三个套件加进 CI 的筛选清单;文档 [ReadingContextAbstraction.md](ReadingContextAbstraction.md)「性能」、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)「环境每个 thunk 一个,镜像级的事实按镜像缓存」、[Modules/MachOCaches.md](Modules/MachOCaches.md) 的缓存组表。MachOKit fork:`MachOFile.swift` 与测试 `StandaloneFileDyldCacheTests`;MachOKitExtensions:`MachOCacheStorage`、`MachOFile+.swift`、测试 `FixupResolutionMemoTests`,提案 0001 的决策日志补了一条。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(默认 Xcode 27.2,依赖走远端版本;MachOKit 与 MachOKitExtensions 用 `swift package edit` 指向各自的修复分支)。 + - MachOKit:`StandaloneFileDyldCacheTests` 修复前两条红(`cache`、`fullCache` 都按路径打开了换上去的 cache 头),修复后三条全过。fork 全量 200 个测试只红 5 个既有的环境失败(归档夹具文件缺失、macOS 27 的 cache 没有 PreBuildLoaderSet)。 + - MachOKitExtensions:`FixupResolutionMemoTests` 修复前最后一批比最先一批慢 54 倍(bind)、49 倍(rebase,要配修好的 MachOKit 才显出来),修复后 1.2 倍、1.3 倍;全量 26 个测试全过。 + - 本库三个新套件修复前全红:路径换成 cache 头之后读取抛错;新环境第一次查调用目标要 66 毫秒,直接遍历一遍符号表才 51 毫秒;不打印的两个事件取了两次时间。`CacheImageResolver` 那条修复前 9.4 毫秒,直接读一遍镜像列表 2.4 毫秒。修复后全过。 + - 全量 `swift test --skip IntegrationTests`:2,788 个测试,只红 `ThunkOnlyObjCMemberTests` 4 条(Xcode 27.2 现场编译 fixture 的旧漂移,第 120 节在未修改的 `next` 上也是这 4 条),原始退出码 1。 + - 渲染 A/B(基线是 `next` 565fac44 的 `git archive`,两侧远端依赖版本相同,候选侧只把 MachOKit 与 MachOKitExtensions 换成修复分支):96 对逐字节一致——归档 cache 15.5 与 26.6 各 12 对,iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器文件共 48 对,进程内 `MachOImage` 24 对。 + - 耗时(release CLI 的 `interface --show-c-imported-types`,基线、候选、候选、基线交替跑,负载 13–16):iOS 18.5 模拟器的 SwiftUI 50.8 秒 → 11.0 秒(sys 32 秒 → 0.12 秒,建索引约 26 秒 → 5 秒);同一运行时的 SwiftData 1.33 秒 → 0.29 秒;本机 cache 里的 SwiftUI 22.8 秒 → 14.4 秒(含只影响 CLI 的时间戳那一项)。两侧输出逐字节一致。 +- **对应版本**:0.25.0。依赖下限抬到 MachOKit 0.55.101、MachOKitExtensions 1.3.1(2026-11-06 发布)。发版说明要写:离线读不在 dyld cache 里的 Mach-O 文件(app、bundle 里的框架、模拟器运行时文件)快很多——此前每读一个元素都把整个文件重新映射一次;读 opaque 类型的 accessor thunk 不再每次重扫符号表、重读 cache 的镜像列表;CLI 不再为每个不打印的事件格式化时间。 + +## 124. 依赖定位器共享按路径打开的 cache 与 Mach-O 文件 + +- **时间段**:2026-11-06,分支 `feature/shared-dependency-openings`(worktree `.worktrees/MachOSwiftSection-SharedDependencyOpenings`,基于 `next` 4b08e02a)。提案 [0086-shared-dependency-openings](../Evolutions/0086-shared-dependency-openings.md)(轻量档)的两步:先 cache,后显式文件。 +- **动机**:第 122 节后续的第一条。`FileDependencyLocator` 每建一个,就把 `.dyldSharedCache(path:)` 搜索路径上的 cache 整个打开一次,而每个依赖闭包的使用方都按根建定位器。DockHelper 配对归档的 macOS 27.0 cache 跑一次 `interface --emit-offset-comments`,那份 cache 的 80 个文件上同时开着 369 个描述符,单个文件最多 7 个;RuntimeViewer 离线读一个配对非本机 cache 的 bundle,每个 bundle 镜像都是一个根。 +- **关键决策**: + - **共享打开,不共享定位器。** 定位器建完闭包就释放,缓存它没用;要留住的是打开本身。 + - **弱引用。** 定位器交出的镜像经它的 cache 留住这份打开,镜像都放掉就关掉,`evolution` 跨几十份 cache 时不会每份都一直开着(第 80 节常驻 51 份宿主 cache 开过 4,182 个文件)。键是文件身份(设备号、inode、大小、修改时间),文件换了就开新的。 + - **先读好懒状态再交出去。** `FullDyldCache` 的映射表、带滑动信息的映射表与 symbol cache 不加锁地懒填,第 120 节当初因此不共享;现在照 `cachedHost` 的做法,打开后先把这三样读好。 + - **放在 MachODependencies 内部,不加公开 API**(用户选定)。RuntimeViewer 的目录自己另开一份,配对的 cache 在一个进程里最多两份。 + - **显式文件第二步做**(用户定的顺序):`.machOFile(path:)` 与系统根下的文件按文件身份加挑 slice 用的 CPU 原始值共享,同样弱引用(`SharedMachOFileOpenings`)。前提是 MachOKit 0.55.101 去掉了独立文件的 `cache` 探测——在那之前,每读一次都把文件当 cache 探测、并且不加锁地写回结果,同一个实例不能交给多个线程。挑 slice 的规则随之搬进共享表。 +- **落地**:MachODependencies(新增 `DependencyFileIdentity`、`SharedDyldCacheOpenings`、`SharedMachOFileOpenings`;`FileDependencyLocator` 改用后两者,同一个定位器的搜索路径里同一份打开只加一次),测试 `SharedDyldCacheOpeningTests`、`SharedMachOFileOpeningTests`,文档 [Modules/MachODependencies.md](Modules/MachODependencies.md) §3。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 27.2,依赖走远端版本,fixture 照 CI 的参数编)。 + - 修复前 `SharedDyldCacheOpeningTests` 红两条:两个按同一路径搜索的定位器拿到不同的实例;子进程里压到 256 个描述符后,六个定位器有的定位不到 libobjc。第三条(没人持有之后会释放)本来就绿,守的是弱引用的约定。修复后 3 条全过,`MachODependenciesTests` 35 条全过。 + - DockHelper 那条命令:那份 cache 上同时开着的描述符 369 → 205,单个文件最多 7 → 4,`interface` 输出逐字节一致。这次运行只建了两个定位器(静态布局、ObjC 祖先解析),改前各开一份、改后共用一份;剩下的是 MachOKit、Swift 读取层、ObjC 读取层各自的映射。根越多省得越多。 + - 显式文件:修复前 `SharedMachOFileOpeningTests` 红两条(两个定位器各拿一个实例;子进程里压到 256 个描述符后,300 个同时存活的定位器有的打不开文件),没人持有就释放那条本来就绿。修复后 3 条全过,`MachODependenciesTests` 38 条全过。测试读的是 fixture 里 `SymbolTestsHelper` 的临时拷贝,不与别的套件争同一个文件。 + - 全量 `swift test --skip IntegrationTests`:只做 cache 时 2,793 个测试、531 个套件,两步都做完 2,796 个测试、532 个套件,每次都只红 `ThunkOnlyObjCMemberTests` 4 条(Xcode 27.2 现场编译 fixture 的旧漂移),原始退出码 1,没有测试进程崩溃。 + - 用户用 RuntimeViewer 离线打开 Dock.app(配对本机 cache)验证通过。 +- **对应版本**:0.25.0。发版说明要写:依赖解析按路径点名的 dyld cache 与 Mach-O 文件,同一份在进程里只打开一次,各个根与各个使用方共用。 + +## 125. MachOKitExtensions 下限抬到 1.3.2:多个线程首读同一个文件时 `identifier` 会被提前释放 + +- **时间段**:2026-11-06。修复在 MachOKitExtensions(分支 `fix/concurrent-first-reads`,发布为 1.3.2),本库只抬下限,按 bug 修复处理,不写提案。 +- **动机**:第 122 节后续的第二条。`MachOSymbolsTests` 满载下偶发的 `SIGTRAP` 出在 MachOKitExtensions:`MachOFile.identifier` 存在 `.retain(.nonatomic)` 的关联对象里,先读、没有就算、再写,读写之间不加锁。几个线程同时首读一个新文件时各写一份,后写的把先写的释放掉,而 nonatomic getter 交出值时不 retain,别的线程手里的那份就成了悬空对象,arm64e 上停在 `swift_getObjectType` 的 isa 检查。本库每次查 `SharedCache` 都经 `SharedCacheKey.init` 读 `identifier`,所以 `concurrentInterningSharesOneWinner` 以 5000 次重复跑时几秒内必崩。同一个文件里 LC_DYLD_INFO 的 bind 索引是同一种写法。修复是 `identifier` 在锁里只写一次、此后不再替换,bind 索引改记在 `MachOCacheStorage` 里;回归测试 `ConcurrentFirstReadTests` 与数据记在 MachOKitExtensions 提案 0001 的决策日志里。 +- **对本库的影响**:代码不动,只把 `Package.swift` 里 MachOKitExtensions 的远程下限从 `1.3.1` 抬到 `1.3.2`,并删掉同一段注释里过时的半句:`DyldCache.fileIO` 的映射自第 122 节起挂在 MachOKit 的 `fileHandleIdentity` 上,不再按 sub-cache 实例取。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑(Xcode 27.2)。 + - 修复前:`concurrentInterningSharesOneWinner` 以 5000 次重复跑 10 次,对 1.3.1 全红。 + - 抬下限后只用远端依赖构建,解析到 MachOKitExtensions 1.3.2:`MachOSymbolsTests` 58 个、`MachODependenciesTests` 38 个测试全过;`concurrentInterningSharesOneWinner` 以 5000 次重复跑 10 次全过。 +- **对应版本**:0.25.0。发版说明要写:多个线程同时开始读同一个文件时偶尔会崩溃,已修复。 + +## 126. `@ResolvableLocatableLayoutWrapper`:样板宏改名并补上遵循 + +- **时间段**:2026-11-06,分支 `refactor/resolvable-locatable-layout-wrapper-macro`(worktree `.worktrees/MachOSwiftSection-ResolvableLocatableLayoutWrapperMacro`,基于 `next` 3e28c2ec)。提案 [0087-resolvable-locatable-layout-wrapper-macro](../Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md)(轻量档)。 +- **动机**:0027 的 `@LocatableLayoutWrapping` 只生成 `layout` / `offset` / `init(layout:offset:)`,遵循要在声明处另写。98 个贴了宏的 struct 全是 `ResolvableLocatableLayoutWrapper`,宏与遵循总是成对出现,用户要求把遵循收进宏、宏改名。 +- **关键决策**: + - **宏名就是它带来的遵循**(用户选定):`@ResolvableLocatableLayoutWrapper`,与 `@Observable` 宏对 `Observable` 协议同一思路;搜索协议名仍能找到全部遵循者,0027 保留声明处协议名的理由随之消失。 + - **加 extension 角色,只补缺的协议**:编译器只把类型还没有的 `LocatableLayoutWrapper` / `Resolvable` 交给宏。直接写了 `: ResolvableLocatableLayoutWrapper` 的 51 处删掉它;经 `MetadataProtocol` 这类子协议遵循的 46 处照旧写子协议(它带着 `Layout` 约束),宏不再生成扩展。 + - **宏声明搬进 MachOSwiftSection**:`conformances:` 要写出这些协议,`Utilities` 看不到它们;`MachOSwiftSection` 直接依赖 `MachOMacros`。 + - **`conformances:` 写出整条协议链**(`LocatableLayoutWrapper, Resolvable, LayoutWrapper, Equatable, Sendable`):只写顶上两个时,`LayoutWrapper` 只是隐含,Swift 6.3 下 `TypeMetadataRecord.layoutSize` 在一个文件里报不遵循 `LayoutWrapper`、同一行在另一个文件里编过,取决于编译顺序。 + - **宿主文件都 `import MachOKit`**:扩展里写着 `LayoutWrapper`,只有 MachOKit 转出口它,33 个原来只 import `MachOBase` 的宿主文件补上。漏了时报「cannot find type 'LayoutWrapper' in scope」,指在宏展开里;中途一度把这条报错误判成编译器丢了遵循,查明后撤回了绕开编译器缺失清单的写法。 + - `GlobalActorReference`、`MetadataBounds`、`ClassMetadataBounds` 由此新增 `Resolvable` 遵循,默认实现与它们原本的读法相同。下游仓库没有用到旧宏名,不留别名。 +- **落地**:MachOMacros(`ResolvableLocatableLayoutWrapperMacro`,原 `LocatableLayoutWrappingMacro`),Utilities(删掉旧宏声明),MachOSwiftSection(宏声明与 98 个宿主,33 个文件补 `import MachOKit`),MachOFixtureSupport(`PublicMemberScanner` 认新宏名),`Package.swift`,`AGENTS.md` 的 ABI 层一段,0027 的决策日志补一行。 +- **验证**:在 JHs-Mac-Studio-Ultra 上用 Xcode 26.6 跑,依赖走远端版本,fixture 照 CI 的参数编。全量 `swift test --skip IntegrationTests`:合并前 2,793 个测试、531 个套件全过;与远端 `next`(第 124、125 节)合并后重跑,2,796 个测试、532 个套件全过,原始退出码都是 0(多出的是第 124 节的测试,本次没有新增);`MachOSwiftSectionCoverageInvariantTests` 在内,`__Baseline__/` 与 allowlist 零改动,宏没有发出「成员已手写」的 warning。没跑渲染 A/B:生成的存储成员与改前逐字相同,只多了遵循。 +- **对应版本**:0.25.0。发版说明不必写:宏只在本库内部使用,生成的存储成员不变;三个类型多出的 `Resolvable` 遵循是增量变化。 + +## 2026-11-06 SwiftDeclaration 的目录分成公开模型与索引代码两块(节号落地时取) + +- **时间段**:2026-11-06,分支 `refactor/swift-declaration-layout`(worktree `.worktrees/MachOSwiftSection-SwiftDeclarationLayout`,基于 `next` d5368156)。提案 [draft-swift-declaration-model-indexing-layout](../Evolutions/draft-swift-declaration-model-indexing-layout.md)(轻量档)。 +- **动机**:0042 整理过这个模块之后,新增的 ObjC 相关文件都放进了 `Components/Definitions/`,那里攒到 25 个文件,声明本体、成员定义、索引扩展混在一起;`Components/` 这一层不区分任何东西;三个类型藏在别人的文件里。用户要求重新整理。 +- **关键决策**: + - **按可见性分两棵树**(用户在三个布局里选定):`Model/` 放公开模型,`Indexing/` 放全是 `package` / `internal` 的索引代码。沿用 0042 「`Members/` 是模型、`Building/` 是索引期机器」的分界,推到整个模块;九个 `TypeDefinition+…` 与三个 `ExtensionDefinition+…` 各进一个子目录。 + - **只搬文件**:`git mv` 保留历史;`ObjCProtocolRequirementDefinition`、`ObjCProtocolNames`、`isStoredVariable` 原样剪切成独立文件,没有改动任何代码。 +- **落地**:SwiftDeclaration(`Components/` 下 52 个文件改位置,新增 3 个文件,`Events/` 与 `Extensions/` 原有文件不动)。文档:[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md) 的文件对照表与 `TypeDefinition` 扩展表重写(补上漏掉的 `+ObjCMembers`、`+ObjCProtocols`),术语表与四份实现说明里的完整路径改成新路径;历史记录里的旧路径不改。`AGENTS.md` 的 SwiftDeclaration 条目加一句归位规则(新的索引步骤放 `Indexing/`,不放在 `TypeDefinition.swift` 旁边)。 +- **验证**:在 JHs-Mac-Studio 上用默认工具链(Xcode 27.2)从空 scratch 编译库与全部测试 target(`swift build --build-tests`,本地兄弟依赖),原始退出码 0,SwiftDeclaration 没有新增警告。没跑测试和渲染 A/B:没有一行代码改变,源码扫描类测试按模块名取文件、不看目录层级。 +- **对应版本**:0.25.0。发版说明不必写:模块的公开 API 与输出都不变。 + +## 2026-11-06 SwiftDeclaration 的类型名按角色统一后缀(节号落地时取) + +- **时间段**:2026-11-06,接着上一节在同一分支 `refactor/swift-declaration-layout` 上做。提案 [draft-swift-declaration-type-naming](../Evolutions/draft-swift-declaration-type-naming.md)(轻量档)。 +- **动机**:目录整理之后,用户指出这个模块的类型名不成套:`Indexing/Building/` 的六个命名空间用了四种起名法,`OverrideSymbolMatcher.swift` 里没有这个类型,「声明从哪来」一个叫 `Origin` 一个叫 `Source`,`AssociatedTypeWitnessProjection` 的「Projection」只此一处。 +- **关键决策**: + - **命名空间按角色取后缀**(用户选定):造新东西的叫 `…Builder`(`MemberDefinitionBuilder`、`StandInMemberSymbolBuilder`、`ObjCProtocolNameBuilder`),拿二进制里另一处的证据对到已建好的成员上的叫 `…Matcher`(`ThunkAttributeMatcher`、`ObjCMemberMatcher`、`OverrideSymbolMatcher`),补回丢掉的事实的叫 `…Recovery`(`WrappedPropertyRecovery`)。 + - **不用 `…Application`**:用户指出它会被读成「应用程序」,改用与已有的 `OverrideSymbolMatcher` 同类的 `…Matcher`。 + - **三个公开名字**:`AssociatedTypeWitnessProjection` → `ResolvedAssociatedTypeWitness`(与属性 `resolvedAssociatedTypeWitnesses` 同名),`ConditionalWitnessCandidate` 嵌进去成为 `ConditionalCandidate`,`ObjCProtocolRequirementDefinition.Source` / `source` → `Origin` / `origin`(与 `WrappedPropertyDefinition` 同一个词)。旧名留 deprecated 别名,与 0057 的转发一起在 0.25.0 删除。 + - **事件命名空间另开一批**:`SwiftIndexEvents` 的 payload case 改名留不了别名,改动量也大几倍。 +- **落地**:SwiftDeclaration(六个文件改名,两个自由函数收进 `enum OverrideSymbolMatcher`,并把原来叠在一起的两段文档注释各归各位),SwiftIndexing、SwiftDiffing、SwiftDump、SwiftPrinting 的调用点,测试套件 `AssociatedTypeWitnessProjectionTests` → `ResolvedAssociatedTypeWitnessTests`。文档:模块参考写上后缀规则,术语表与另外十份现行文档(实现说明与一份译注参考)换成新名;历史文档里的旧名不改。 +- **验证**:在 JHs-Mac-Studio 上用 Xcode 27.2 增量编译库与全部测试 target,原始退出码 0,没有出现指向旧名的弃用警告(仓库里已没有调用点用旧名)。没跑测试和渲染 A/B:只改名字,行为不变。 +- **对应版本**:0.25.0。发版说明要写:`AssociatedTypeWitnessProjection`、`ConditionalWitnessCandidate`、`ObjCProtocolRequirementDefinition.Source` / `.source` 改名,旧名仍可用但已废弃。 + +## 127. 离线读取追平进程内:依赖镜像不再整个 demangle,读取直取 MachOKit 的映射,符号名多线程还原 + +- **时间段**:2026-11-06~08,分支 `perf/machofile-performance`(worktree `.worktrees/MachOSwiftSection-MachOFilePerformance`,基于 `next` a13712ae);配套 MachOKit fork 与 MachOObjCSection 的同名分支,以及 swift-demangling 的 `perf/demangler-self-copy`。提案 [0088-machofile-performance](../Evolutions/0088-machofile-performance.md)(轻量档)。 +- **动机**:第 123 节修掉四处根因之后,本机 cache 里的 SwiftUI 打开全部布局注释(RuntimeViewer 的默认)生成 interface,离线仍要约 27.8 秒 CPU,进程内约 15.9 秒。采样显示差距几乎全在离线独有的计算上:给依赖镜像建索引 12 秒,在 cache 里定位 ObjC 方法表 1.7 秒,读取原语约 1.4 秒。用户要求尽可能追平进程内,两种读取器共用的部分也一起压。 +- **关键决策**: + - **先有基准程序再改**:测试进程的墙钟被 swift-dependencies 的 `dlsym` 污染(占采样忙碌时间 45–60%),新增开发用可执行目标 `reader-benchmark`(不是 product),在普通进程里分段报告两种读取器的 CPU、墙钟与 instructions retired,每一步改动前后各量一次。 + - **符号索引分两段**:第一段只有符号表、按偏移的行索引、`_symbolic` 表与导出事实,不 demangle;第二段(每行的节点树与按树分类的索引)第一次有查询要用树时才建。依赖镜像只为给匿名上下文起名查一个地址上的符号,不再 demangle 整个镜像。没有改成沿描述符父链自己拼名字:那要逐条复刻 `demangleContext` 的规则,查找两侧未必一致。 + - **依赖镜像的七张表各自用到才建、四种查找各折各的、按镜像共享**(`ImageReference.shared(for:)`,淘汰组 `layoutImageIndexes`):每种查找折叠的镜像与顺序不变,答案不变。 + - **读取直取 MachOKit 打开文件时的映射**(fork 新增 `@_spi(Support) fileBytes`),删掉本库自己的 `SharedFileMapping`:不再每读一次查关联对象、做动态类型转换、分配 `Data`,也少占一份描述符。 + - **MachOObjCSection 在 cache 里按地址、按序号找镜像改为查表**:每个 cache 只建一次按地址排序的区间表与「镜像序号 → 镜像」对照表,挂在 cache 文件的 `fileHandleIdentity` 上;同一地址落在几个镜像里时仍取原来遍历顺序里的第一个。 + - **符号名多线程还原、按行号顺序驻留**:每批最多 16 × 512 行,提前一批分给各线程还原成树,驻留与分类留在建索引的线程上,节点序号与原来相同。 + - **import 列表在节点池里遍历一次**(`SymbolIndexStore.moduleNamesInAllSymbols(in:)`),共享子树只进一次,名字与首次出现的顺序不变。 + - **两处热点**:`MangledName.resolve` 不再每个字符调一次 `String(format: "%c")`;类约束泛型参数的替身 `Swift.AnyObject` 查 assocty witness 时直接答没有——它是 SwiftUI 布局里唯一一次查不到的 witness 查找,却让 552 个依赖镜像全部建了 witness 表。 + - **swift-demangling 也改并发版**(用户批准,走它自己的提案 0018,随 0.7.3 发布):`try require(pop())` 里 `require` 不是 `mutating`,编译器先整份复制 `Demangler` 再求参数,之后每次 `pop()` 都写时复制节点栈,多线程时抢引用计数;`require` 与复合的 `createNode` 改为 `mutating`,`Remangler` 的节点哈希缓存不再逐格销毁。并行建索引的 CPU 从约 11.4 秒回到约 6.3 秒。 + - **MachOKit 懒缓存的竞态只修 fork、不提上游**(用户定):`DyldCache`、`FullDyldCache`、`MachOFile` 把映射表与 main / full / symbol cache 记在不加锁的属性里,两个线程第一次同时读同一个镜像会 use-after-free;`ImageReference` 共享之后同一个镜像会被并发建表,SwiftInterfaceTests 约一半的运行在 `mappingInfo(for:)` 里 SIGSEGV。映射表改为打开 cache 时读好的常量,组装镜像时就带的 `DyldCache` 改为常量,其余经 `MemoizedReference` 在锁外计算、只在仍为空时发布;热路径上不多一次加锁。 + - **类型查找按模块定向不做**(用户定为后续项):Foundation、SwiftUICore 都扩展了 `Swift` 里的类型,查 `Swift.*` 时它们仍要建表,收益有限。 +- **落地**: + - 本库:MachOSymbols(`SymbolIndexStore` 两段、`DemanglingWave`、`moduleNamesInAllSymbols(in:)`),SwiftLayout(`ImageReference`、`ImageUniverse`、新增 `LazilyBuiltIndex` 与 `SharedCacheEvictionGroup+SwiftLayout`,替身 witness 的短路),MachOReading(`MachOFile+Readable.swift` 改读 `fileBytes`,删 `SharedFileMapping.swift` 与 `MachOFile+`、`DyldCache+`、`FileIO+` 三个扩展文件),SwiftInterface(`collectModules()`),MachOSwiftSection(`MangledName`),新增 `reader-benchmark`;`Package.swift` 的下限抬到 MachOKit 0.55.102、MachOObjCSection 0.8.206、swift-demangling 0.7.3。 + - 测试:新增 `SymbolIndexDemangledIndexTests`、`SymbolIndexModuleNameTests`、`ImageUniverseLazyFoldingTests`;`SharedFileMappingTests` 改名 `FileMappingTests`(CI 的筛选清单随之改名),「删掉的文件读取要抛错」改为「照样读得到」并加越界读取抛错;删 `ConcurrentFileMappingTests`。 + - 文档:`AGENTS.md` 的按文件状态一条(字节经 `fileBytes` 读)与并发一段(`MachOFile` 不能并行打印的旧理由已不成立,如实写成尚未验证、规则不变);[Modules/MachOSymbols.md](Modules/MachOSymbols.md)、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)、[Modules/SwiftLayout.md](Modules/SwiftLayout.md)、[Modules/MachOCaches.md](Modules/MachOCaches.md)、[ReadingContextAbstraction.md](ReadingContextAbstraction.md)。 + - 上游:MachOKit fork 0.55.102(`fileBytes`、竞态修复与 `DyldCacheConcurrentReadTests`),MachOObjCSection 0.8.206(`CacheImageAddressTable`),swift-demangling 0.7.3(提案 0018)。MachOKitExtensions 不用改。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑。 + - 全量 `swift test --skip IntegrationTests`(默认 Xcode 27.2):约 2,800 个测试,只红 `ThunkOnlyObjCMemberTests` 4 条,原始退出码 1。改动前的 `next`(a13712ae)上同一套件在同一工具链下红同样 4 条、断言位置相同;用 Xcode 26.6 跑这个套件 8 条全过(测试现场编译 fixture 的工具链漂移,第 122、123 节也是这 4 条),这一步同时是本库的 Xcode 26.6 编译检查。 + - 新测试修复前红、修复后绿:`ImageUniverseLazyFoldingTests.aWitnessOfTheClassBoundPlaceholderFoldsNothing`(去掉短路时,替身的查找把依赖镜像折了进来);MachOKit 的 `DyldCacheConcurrentReadTests` 两条在 TSan 下修复前报竞态。SwiftInterfaceTests 修复前 5 次运行崩约 2 次,修复后 5 次都不崩。 + - 渲染 A/B(基线为本分支切出时的 `next`,固定在旧的上游版本;候选用新发布的上游):96 对逐字节一致——归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器文件、进程内 `MachOImage` 三条读取路径。 + - 上游:swift-demangling 全量 645 个测试跑两次全过(8 个已知问题);MachOKit fork 204 个测试只红 5 个既有的环境失败;MachOKit 与 MachOObjCSection 的 CI 绿;三个上游都用 Xcode 26.6 编过。 + - 耗时(`reader-benchmark`,release,上游用发布版,instructions retired / 墙钟;三份 interface 与基线逐字节相同):本机 cache 的 SwiftUI 离线只建索引 86 G / 6.4 秒 → 64 G / 3.8 秒(进程内 59 G / 3.1 秒),准备 131 G → 64 G(进程内 60 G),打印(五类布局注释)304 G / 21 秒 → 86 G / 6.2 秒(进程内 61 G / 4.5 秒);iOS 18.5 模拟器的 SwiftUI 只建索引 100 G → 71 G,准备 139 G → 73 G,打印 111 G → 70 G。 +- **后续**:类型查找按模块定向;依赖镜像的符号表第一段再拆出只按偏移查的一段(跳过按名字排序、去重哈希与导出 trie 遍历);测试进程里 swift-dependencies 的 `TestContext.current` 每次都 `dlsym`。剩下的离线差距里最大的一块是类型查找为找到四个类型把前面的依赖镜像全建了类型表(约占离线打印 4%)。 +- **对应版本**:0.25.0。依赖下限抬到 MachOKit 0.55.102、MachOObjCSection 0.8.206、swift-demangling 0.7.3(2026-11-07 发布)。发版说明要写:离线读取(`MachOFile`)生成 interface 快很多,本机 cache 里的 SwiftUI 打开全部布局注释时指令数不到原来的三成,只建索引的墙钟也少约四成;多个线程第一次同时读同一个 dyld cache 镜像时偶尔崩溃,已修复。 + +## 128. 把 SwiftInspection 的 ObjC 部分拆成 SwiftObjCInterop 模块 + +- **时间段**:2026-11-09,分支 `refactor/swift-objc-interop-module`(worktree `.worktrees/MachOSwiftSection-SwiftObjCInterop`,基于 `next` a7b151d3);RuntimeViewer 的 `feature/swift-objc-interop-module`。提案 [0089-swift-objc-interop-module](../Evolutions/0089-swift-objc-interop-module.md)(完整档)。 +- **动机**:SwiftInspection 的 39 个源文件里有 19 个、约 6100 行讲 Swift 类型在 ObjC 一侧的样子——Swift 类的 class object、`@objc @implementation` 类、Swift 声明的 `@objc` 协议、ObjC 方法表与祖先链、ClangImporter 命名规则——是 0046 到 0079 几份 ObjC 功能提案各自就近放进来的。模块只为这一半依赖 MachOObjCSection,`AGENTS.md` 里它的条目是所有模块里最长的,模块参考也一直没法写成一篇。用户指出 ObjC 内容太多。 +- **关键决策**: + - **拆成独立模块 `SwiftObjCInterop`**(用户选定,没选只在模块内分子目录):放在 SwiftInspection 正上方、SwiftLayout 与 SwiftThunkAnalysis 之下。依赖只有一个方向——ObjC 一侧用 `SymbolicDemangler`、`NodeTypeNaming`、`GenericParameterDepthLayout`,核心不用 ObjC 一侧——所以不成环,也不用放宽任何访问级别。 + - **只换模块**:类型名、访问级别、日志 subsystem(`com.machoswiftsection.swift-inspection`,RuntimeViewer 按它过滤)与缓存淘汰分组的字符串都不变。两个共用文件拆开,三个 ObjC 淘汰分组与 `objcImplementationClassReader` 跟着走。 + - **`ObjCMembers/` 留在 SwiftThunkAnalysis**:它用 Capstone 解码 thunk,搬下来会让 SwiftLayout 间接依赖 Capstone。 + - **留不了过渡别名**:新模块依赖 SwiftInspection,反向的 typealias 会成环,所以公开类型换模块是源码破坏;RuntimeViewer 的两处同批改(用户选定)。 +- **落地**: + - 本库:新 target `SwiftObjCInterop` 与同名 library product(19 个文件 `git mv`,另有拆出的两个文件);SwiftInspection 去掉 MachOObjCSection;SwiftLayout、SwiftThunkAnalysis、SwiftDeclarationRendering、SwiftDump、SwiftDeclaration、SwiftIndexing、SwiftPrinting、SwiftSectionKit 加依赖,34 个源文件加 import;5 个纯 ObjC 套件搬进新测试 target `SwiftObjCInteropTests`,13 个测试文件加 import。 + - RuntimeViewer:`RuntimeObjCSection.swift` 与 `RuntimeLoadedImageReading.swift` 加 import,`RuntimeViewerCore/Package.swift` 加 `SwiftObjCInterop` product。 + - 文档:新写模块参考 [Modules/SwiftObjCInterop.md](Modules/SwiftObjCInterop.md);`AGENTS.md` 的层级图与两条模块说明;术语表、七份实现说明、五份模块参考与模块参考的索引、`ProjectMap.md` 的分层表、两份 README 索引、公开的 `README.md` 改成新模块。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上跑。 + - 全量 `swift test --skip IntegrationTests`(Xcode 26.6,fixture 用 Xcode 26.6 编的 `SymbolTestsFixture-Xcode26.6`):2804 个测试、534 个套件全部通过,原始退出码 0。 + - 渲染 A/B(基线为分支切出时的 `next` a7b151d3,两侧同一份 `Package.resolved`、同一套 Xcode 26.6 的 release 预构建):96 对逐字节一致——归档 cache 15.5 与 26.6、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器文件、进程内 `MachOImage` 三条读取路径。跳过的只有旧 runtime 里本来没有的框架。 + - RuntimeViewerCore:在沙盒里把 MachOSwiftSection 换成本分支的副本,其余依赖走远端的 `next`(`swift-helper-service`、`swift-injection-peer` 照 RuntimeViewer 平时的做法走本地),`swift build` 通过。 +- **后续**:RuntimeViewer 的三行改动已单独推到它的 `next`(cherry-pick `cf32c2e7`,2026-11-09);它本地 `next` 里别的会话合进来的 Tuist 改动不在其中,照常等用户看。 +- **对应版本**:0.25.0。发版说明要写迁移:`ObjCImplementationClasses`、`ObjCImplementationClassFacts`、`ObjCMember`、`ObjCMemberTable`、`ObjCMemberShape`、`ObjCClassHierarchy`、`ObjCClassHierarchyProviding`、`ObjCClassHierarchyProviderStore`、`ObjCClassHierarchies`、`ObjCAncestorResolver`、`ObjCAncestorResolverStore`、`CustomObjCClassName` 与 SPI 的 `ClassHierarchyDumper` 从 `SwiftInspection` 移到新模块 `SwiftObjCInterop`,名字与形状不变;直接用到它们的下游加 `import SwiftObjCInterop`(`ClassHierarchyDumper` 要 `@_spi(Internals)`)和 `SwiftObjCInterop` product。 + +## 129. ObjC 类、category 与协议按 Swift 导入的样子打印 + +- **时间段**:2026-11-10,分支 `feature/objc-imported-declarations`(worktree `.worktrees/MachOSwiftSection-ObjCImportedDeclarations`,基于 `next` bd1df364)。提案 [0090-objc-imported-declarations](../Evolutions/0090-objc-imported-declarations.md)(轻量档)。 +- **动机**:RuntimeViewer 要做 Xcode 的 Generated Interface,把一个 ObjC 类显示成 Swift 导入它之后的样子;Swift 实现的类要和 Swift 一侧的信息合在一起。本库此前只为 Swift 声明的 `@objc` 协议(0079)移植过 ClangImporter 的命名规则。 +- **关键决策**: + - **扩展已有的移植,不在运行时调用编译器**(用户选定)。先拿 macOS 27.2 的 AppKit 量准确率:只凭运行时元数据 80.8 % 的成员与 SDK 的 Swift 名一致,换上 SDK 的类型上限 86.3 %;据此补了三条规则(属性名开头缩写词小写、属性名删减、error 约定只认名为 `error` 的那段)。测量程序在临时分支 `probe/objc-importer-naming-accuracy`,不合并。 + - **类只读自己的表**:dyld cache 预先附加的 category(含别的镜像的)不算类的成员。**链接器已把同镜像的 category 并进类**,所以 category 声明只剩给别的镜像的类写的;夹具因此整个没有 `__objc_catlist`。 + - **与 Swift 的配对在打印器里做**,按 Swift 成员的 `objcMember`;前两档证据都没有时也认只按名字的第三档。不打访问级别;只读属性不打所有权;`@NSCopying` 只给导入成类的类型。 + - **名字保持 `__C` 下的 ObjC 名**:`Protocol` 后缀这类 Swift 改名照本库惯例交给类型名提供者,`--swift` 还没接它,记为后续项。 +- **落地**: + - SwiftObjCInterop:`ObjCImportedContainerIndex`、`ObjCImportedMemberBuilder`、`ObjCImportedMemberNodes`、`ObjCImportedTypes`,`ObjCImporterNaming` 加工厂初始化器与属性名规则,`ObjCProtocolRequirements` 加 `DeclaringLanguage`,读取器加只读类自己的表的三个方法。 + - SwiftDeclaration / SwiftIndexing / SwiftPrinting:三种模型与 `ObjCImportedMemberDefinition`,`SwiftDeclarationIndexer` 的按名字查找,`SwiftDeclarationPrinter` 的三个打印入口。 + - SwiftSectionKit 与 CLI:`ObjCInterfaceRequest.printsSwiftImport`,`swift-section objc interface --swift`;agent 插件的 skill 同批写上。 + - 文档:提案、两份模块参考、命令行指南(中英)、术语表两条、`AGENTS.md` 的 SwiftObjCInterop 条目。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2)上跑。全量 `swift test --skip IntegrationTests` 只有 `ThunkOnlyObjCMemberTests` 4 处失败,切到 `next` bd1df364 跑同一组同样失败:Swift 6.4.2 的 `-O -wmo` 把夹具 `InitializingEntryOnlyHolder.init(values:)` 的初始化入口只留成签名特化副本(`…tcfcTf4gn_n`),与本批无关,另开修复。新增与相关的套件(`ObjCImportedDefinitionTests`、`SwiftObjCInteropTests`、`ObjCRequestTests`、`ObjCSectionCommandTests`)全部通过。 +- **后续**:见提案的「后续项」;RuntimeViewer 一侧(它的草案 `draft-objc-generated-interface`)等本库发版后抬 pin 接入。 +- **补记(2026-11-10)**:RuntimeViewer 一侧没等发版,把按分支依赖的 pin 抬到含本节的 `next` 修订就接上了,落地为它的提案 0084-objc-generated-interface。 +- **对应版本**:0.25.0。发版说明写新增的公开 API:三种 `ObjCImported…Definition` 与 `ObjCImportedMemberDefinition`、`SwiftDeclarationIndexer.objcImportedClassDefinition(named:)` 等查找方法、`SwiftDeclarationPrinter.printObjCImported…Definition(_:level:)`、`ObjCInterfaceRequest.printsSwiftImport` 与 `objc interface --swift`。 + +## 130. 没有本地符号的镜像里,扩展中的类型与私有 `@objc` 协议也给出导出结论 + +- **时间段**:2026-11-10,分支 `feature/export-verdict-without-local-symbols`(worktree `.worktrees/MachOSwiftSection-ExportVerdictWithoutLocalSymbols`,基于 `next` bd1df364)。提案 [0091-export-verdict-without-local-symbols](../Evolutions/0091-export-verdict-without-local-symbols.md)(轻量档)。 +- **动机**:RuntimeViewer 把未导出的类型设为排除后,仍列出 AppKit 的私有类型。macOS 27.2 dyld shared cache 里的 AppKit 只留导出、导入与 `_symbolic` 符号,写在 ObjC 类扩展里的未导出类型都落到重整名一腿,又被「拒绝一切扩展上下文」挡住,约 45 个没有结论;Swift 声明的私有 `@objc` 协议则从来不裁决。 +- **关键决策**: + - 重整名一腿只拒绝带约束的扩展:不带约束的扩展节点重整后与编译器的拼法一致,夹具上逐个比对过。 + - 加第三条腿:前两条判不了时,私有或局部声明判未导出,看名字或描述符外层的匿名上下文;`-enable-private-imports` 编出的镜像由第一条腿先认出导出。 + - 私有 `@objc` 协议判未导出(用户选定),打印器照常过滤;只遵循这类协议的 ObjC 类别在 `--exported-only` 时一并去掉,同 Swift 类型遵循未导出协议一样。 + - 夹具三个变体分别编译:各镜像的缓存按 `LC_UUID` 认文件,从一次编译复制的变体会读到彼此的符号索引。 +- **落地**: + - SwiftDeclaration:`ExportStatus` 的三条腿与 `isPrivateOrLocal(_:)`,`ObjCProtocolDefinition.exportStatus`;MachOSymbols:包内的 `SymbolIndexStore.hasExportInformation(in:)`。 + - SwiftPrinting / SwiftInterface:`printObjCProtocolDefinition` 的导出过滤,`SwiftInterfaceBuilder` 的类别规则。 + - 测试:`ExtensionContextExportFixture` 与 `ExtensionContextExportStatusTests`,`SwiftDeclaredObjCProtocolInterfaceTests` 加一条,`ObjCProtocolDefinitionIndexingTests` 的断言随之改。 + - 文档:提案、`ExportedOnlyInterfaceFiltering.md`、`Modules/SwiftDeclaration.md`、术语表一个词条、README 与 `--exported-only` 的帮助文字。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2)上跑。撤掉修复时 8 组回归测试变红、恢复后全绿;用新编的 swift-section 跑 AppKit 的 `interface --exported-only`,带私有鉴别器的声明从 25 个类型、32 个扩展降到 0。全量测试的失败与 `next` bd1df364 一致:`ThunkOnlyObjCMemberTests` 4 处(第 129 节已记),以及现编夹具带来的一批 ABI 偏移类失败,两侧相同。 +- **后续**:RuntimeViewer 一侧抬 pin,`@objc` 协议条目读 `exportStatus`,它自己打印的类别 conformance 照做类别规则。 +- **对应版本**:0.25.0。 + +## 131. existential 写上 `any`,constrained existential 字段印回它的类型 + +- **时间段**:2026-11-11,分支 `feature/existential-any`(worktree `.worktrees/MachOSwiftSection-ExistentialAny`,基于 `next` 577eadf2),当天合入 `next`;swift-demangling 同名分支(基于它的 `next` 6489476),快进合入它的 `next`。提案 [0092-existential-any](../Evolutions/0092-existential-any.md)(轻量档),swift-demangling 一侧是它的提案 0020。 +- **动机**:本库印 existential 一律不写 `any`——`any P` 印成 `P`,`(any P).Type` 印成 `P.Protocol`——而编译器写 `.swiftinterface` 时除 `Any`、`AnyObject` 外都写,有 associated type 的协议不写还会被编译器警告。查的时候又发现 constrained existential 的存储属性印错了类型:`any Boxed` 在 interface 里是 `var boxed: Swift.Int`,dump 与 ABI 快照里是 `symbolic existential type (non-unique) 0x0 `,ABI diff 因此分不开协议不同、实参相同的两个字段。 +- **关键决策**: + - 默认打开,打印配置与 CLI 都留关闭开关;写法照编译器(`any Any.Type`、`(any P).Type`、`(any P)?`、`any (P & Q).Type`)。 + - swift-demangling 加 `DemangleOptions.useExistentialAny`,不进任何预设,预设的输出仍与官方 demangler 逐字节一致;dump 由 CLI 与 `DumpRequest` 的默认值打开。 + - 两个打印器都按节点身份缓存打印片段,而 `any` 是唯一取决于父节点的写法:「外层已经写了 `any`」的位置(existential 元类型的实例、`any P` 的协议列表)直接印成员,不经 `printName`。 + - bug 在 `SymbolicDemangler` 修:把实参代回 extended existential 的 shape,得到与 getter 符号同形的 `constrainedExistential`;ABI 快照格式升到 12。顺带让 `any P.Type` 按元类型布局——原先那条分支走不到,字段被当成值容器(40 字节,应为 16)。 + - `OpaqueTypeResolving.opaqueType` 的拼写参数由布尔值换成 `DemangleOptions`(`interfaceSpellingOptions`),`some Sequence` 才印得出来;`SwiftDeclarationPrinter` 上的旧签名留作废弃的转发。 +- **落地**: + - swift-demangling:`DemangleOptions.useExistentialAny`、`NodePrinter`(三种 protocol list、existential 元类型、元类型、constrained existential 与括号判断)、`ExistentialAnyPrintingTests`。 + - SwiftInspection:`ExtendedExistentialTypeResolution`,`SymbolicDemangler` 在名字带 shape 引用时调用它;SwiftLayout:`StaticTypeLayoutResolver`、`ExistentialLayoutBridge`;SwiftDiffing:`ABISnapshotDocument` 格式 12。 + - SwiftPrinting:`SwiftDeclarationPrintConfiguration.usesExistentialAny`、`TypeNodePrintable` / `BoundGenericNodePrintable`、`SwiftDeclarationPrintConfiguration+Spelling`;SwiftInterface:opaque type provider;SwiftSectionKit 与 CLI:`InterfaceRequest.usesExistentialAny`、`interface --no-existential-any`、`dump --disable-existential-any`、`DumpRequest` 的默认值。 + - 测试:`ExistentialAnyFixture` 与 `ExistentialAnyInterfaceTests` / `ExistentialAnyDumpTests`,`ConstrainedExistentialFieldTests` / `ConstrainedExistentialFieldDumpTests`,命令映射测试;12 份 fixture 快照重新录制。 + - 脚本:渲染 A/B 加三个只给候选一侧的参数,`RenderingVerificationTests` 认 `bareExistentials`。 + - 文档:提案、`Modules/SwiftInterface.md`、`StaticLayoutEngine.md`、`SystemFrameworkRenderingVerification.md`、`AgentPlugins/swift-section` 的 skill。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上跑,细节见提案第 6 步。swift-demangling 全量 651 个测试通过,语料对照证明选项关闭时输出不变。本库全量 2843 个测试 / 543 个套件只剩两条单独跑都通过的偶发,其中映射测试那条基线上同样失败。渲染 A/B 96 对:候选关掉 `any` 时,差异只有 constrained existential 字段(54 对、185 行,含 SwiftUICore 三处布局注释由 40 字节改为 16 字节);打开后改动 50207 行,归一化掉 `any`、括号与 `.Protocol` 后全部相同。复现测试在修复前全部失败。 +- **后续**:swift-demangling 发版后抬本库的版本下限——在那之前,走远端依赖的构建编不过;ABI 快照要用新版重新生成;RuntimeViewer 用打印配置的默认值,升级后直接显示 `any`,要不要给它加设置项另议;两处拼写仍按 `.default` 走、不写 `any`(未展开 opaque 引用的实参、展开字段偏移注释里的嵌套类型名,见提案决策日志)。 +- **对应版本**:0.25.0。 + +## 132. 识别 `@Observable` 宏:interface 默认折叠它的展开 + +- **时间段**:2026-11-11 至 2026-11-12,分支 `feature/observable-macro`(worktree `.worktrees/MachOSwiftSection-ObservableMacro`,基于 `next` cd8472b2),分几次在本地合进 `next` 供用户查看,11-12 正式落地。提案 [0093-observable-macro-folding](../Evolutions/0093-observable-macro-folding.md)(轻量档)。 +- **动机**:`@Observable` 类在二进制里只剩宏展开的结果——存储 `_x`、computed `x`、registrar、`access(keyPath:)`、`withMutation(keyPath:_:)`、`shouldNotifyObservers(_:_:)` 重载与 conformance——interface 原样印出来,与源码对不上。RuntimeViewer 要在侧边栏标出这类类型、在折叠与展开之间切换,之后又要做 Xcode 式的内联展开。 +- **关键决策**: + - 识别在构造时只读字段记录:有类型正是 `Observation.ObservationRegistrar` 的 `_$observationRegistrar`、又没有 SwiftData `@Model` 的 `_$backingData`。剥过符号的镜像照样认得出;`SwiftAttachedMacro` 用 struct 加静态成员,以后加别的宏不会让宿主的 `switch` 编不过。 + - 哪些 `_x` 是被跟踪属性的存储由索引期按证据定:init accessor、成员的 setter 或 `_modify`、挂在 `x` 名下的初始值表达式;`_x` 自己有初始值表达式、或只有 `_x` 有 accessor 时排除;都没有就凭字段名。镜像带不带本地符号不分流:SwiftUI 带本地符号,却被 dead-strip 去掉了 init accessor。 + - 类型比对撇开 `sending`:编译器 mangle 声明自身的函数类型时不写它,字段记录照写,SwiftUI 三个类的 `makeFileCoordinator` 因此没折叠。wrapped property 的属性写法用同一个比较。 + - interface 默认折叠,`expandsMacros` / `--expand-macros` 关掉折叠后与之前逐字节相同,标记模式两种形态都印;dump 只在类头加 `@Observation.Observable`。 + - 宿主的内联展开:`printMacroExpansion` 整块,`printMacroExpansionParts` 照 Xcode 的位置分块,`marksAttachedMacros` 标出宏属性与每个被跟踪属性折叠出的声明;类型的闭合括号靠定义区域定位,不改 swift-semantic-string。accessor 块一律照宏的写法 `{ get set }`,不看镜像里还剩哪些 accessor。 +- **落地**: + - SwiftInspection:`ObservableMacroRecognition`。SwiftDeclaration:`SwiftAttachedMacro`、`TypeDefinition.attachedMacros` / `observableMacroExpansion`、`ExtensionDefinition.generatingMacro`、`ObservableMacroExpansionRecovery`。SwiftIndexing 标出宏生成的 conformance。 + - SwiftPrinting:`expandsMacros`、`marksAttachedMacros`、`MacroExpansionPart`、`AnnotationRegion.Kind.attachedMacro(_:)` / `attachedMacroTrackedProperty(_:named:)`。SwiftDump:类头。SwiftSectionKit 与 CLI:`InterfaceRequest.expandsMacros`、`interface --expand-macros`。 + - 测试:现场编译的 `ObservableMacroFixture`(debug、release、dead-strip、strip 四个变体),覆盖识别、证据、折叠与展开、投影、分块、dump、Kit 与 CLI 映射。 + - 文档:提案、`Modules/SwiftDeclaration.md`、`Modules/SwiftInterface.md`、术语表 macro folding、`SystemFrameworkRenderingVerification.md`、`AgentPlugins/swift-section` 的 skill。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上跑。最终全量 2889 个测试,只红两条:`FileMappingTests`,基线上同样失败;`BoundedConcurrentMapTests` 的时限超时,是 Ultra 全量下的既有偶发,失败发生在任何新测试开始之前。渲染 A/B 96 对:关掉折叠时 interface 全部一致,dump 只差 28 个类的类头。修复 `sending` 前后渲染 SwiftUI、SwiftUICore、SwiftData 的折叠形态,只有那三处变了。 +- **后续**: + - getter 被 `@_silgen_name` 钉成旧 mangling 的属性不折叠,已裁决不处理。 + - 完全剥光符号的 internal 类会把 `@ObservationIgnored var _y` 读成被跟踪属性。 + - `@Model` 等别的宏还没有识别。 + - 发版要先发 swift-demangling。 + - init accessor 提案([0094-init-accessor-recovery](../Evolutions/0094-init-accessor-recovery.md))在这之上给 accessor 块加了 `init` 一行,并把类型比对挪进 SwiftInspection 的 `StoredTypeMatching`。 +- **对应版本**:0.25.0。 + +## 133. 还原 SE-0400 的 init accessor + +- **时间段**:2026-11-12,分支 `feature/init-accessor-recovery`(worktree `.worktrees/MachOSwiftSection-InitAccessorRecovery`,基于 `next` 096970e7),中途三次合进本地 `next` 上 `@Observable` 的改动,做完先在本地合进 `next` 供用户查看,当天与第 132 节一起正式落地;RuntimeViewer 的同名分支只补 `kindString` 一行。提案 [0094-init-accessor-recovery](../Evolutions/0094-init-accessor-recovery.md)(轻量档)。 +- **动机**:SE-0400 的 init accessor 在二进制里只留下符号(后缀 `vi`),`@storageRestrictions` 的名单与参数名都不留。库原先把这个符号整个丢掉:dump 不列,ABI diff 看不到,interface 只印 `get` / `set`。起因是 SwiftUICore 导出的 `_GeometryActionModifier2.value.init`,编译器自己的 `.swiftinterface` 印成 `@storageRestrictions(initializes: _value) init(initialValue)`;`@Observable` 展开里每个被跟踪属性也都缺这一行。 +- **关键决策**: + - init accessor 是 `AccessorKind` 的一个 case,与 SE-0507 的 `borrow` / `mutate` 一样:dump 的成员循环、地址注释与 ABI diff 沿着 `accessors` 自动带上它,代价是 RuntimeViewer 的穷举 `switch` 要同批补一行。它排在同名一组的最后,不参与成员排序(release 里它的地址可能在 getter 前面),也不算 `final` 的证据(它从不进 vtable)。 + - 不从机器码推 `initializes:` / `accesses:`:指针直接指向存储,只数得出个数。名单只按「同名的 `_x`、类型与属性相同(先剥掉 `weak` / `unowned`)」推断,推不出就只印 `init`,声明上一行注明二进制没有记录;只看名字会把 SwiftData `@Model` 那种类型不同的 `_name` 也认进来。 + - 比较的类型取 init accessor 自己的符号,不取 getter 的:SwiftUICore 用 `@_silgen_name` 把 `_GeometryActionModifier2.value` 的 getter 钉在没有 `@Sendable` 的旧 mangling 上,渲染 A/B 抓到了这一处。声明自身的 mangling 不写 `sending`,比较照 `@Observable` 那边的修法撇开它;比较函数下沉到 SwiftInspection 的 `StoredTypeMatching`,`@Observable` 的展开恢复、wrapper attribute 的写法与本推断三处共用。 + - `@Observable` 的整块与分块展开照宏的写法,总是印 `@storageRestrictions(initializes: _x) init`,与别处的 accessor 块共用 `AccessorBlockKeywords.InitAccessorLine`;`--expand-macros` 照镜像。 +- **落地**: + - MachOSymbols:`.initAccessor` 进成员桶;分桶之前的 `Node.Kind.isMember` 名单也要加,漏了就一个都不进桶、不报错。SwiftDeclaration:`AccessorKind.initAccessor`、`hasInitAccessor`、`VariableDefinition.initializedFieldNames`、索引步骤 `TypeDefinition+InitAccessors`。SwiftInspection:`InitAccessorFieldInference`、`StoredTypeMatching`。 + - SwiftPrinting:accessor 块的 `init` 一行。SwiftDeclarationRendering:注释工厂 `initAccessorFieldsNotRecorded` / `initAccessorInitializedFields(_:)` 与注释种类 `initAccessorFields`。SwiftDump:每条 init accessor 前的推断结果。SwiftDiffing:token `init`,ABI 快照格式 13。 + - 测试:现场编译的 `InitAccessorFixture`(debug、release、dead-strip、strip 四个变体),模型、interface、dump、ABI diff 各一组;`ObservableMacroInterfaceTests` 补上 `init` 那一行。 + - RuntimeViewer:`kindString` 补 `case .initAccessor`,随 RuntimeViewer 的 `@Observable` 改动一起推。 + - 文档:提案、`Modules/SwiftDeclaration.md`、`Modules/MachOSymbols.md`、`Modules/SwiftInterface.md`、`AgentPlugins/swift-section` 的 skill(推断出的名单;快照格式的说明改到 13)。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上跑。最终全量 2908 个测试,红 5 条,在不含本分支的 `@Observable` 全量里都同样出现:`FileMappingTests` 一条,`SharedCacheTests` 一条与 `BoundedConcurrentMapTests` 三条是满负载下超时,单独重跑都过。渲染 A/B 96 对:80 对逐字节相同,16 对只多出新行(init accessor 的符号行、推断注释、`init` 一行与它的地址注释);interface 里 SwiftUICore 的 `_GeometryActionModifier2.value` 与官方 `.swiftinterface` 只差参数名。RuntimeViewerCore 带上 `kindString` 那一行,对着本分支编译通过。 +- **后续**: + - 一个属性初始化几块存储(`initializes: _x, _y`)、初始化的不是 `_x`、只写 `accesses:` 的写法推不出,只印 `init` 加注释;参数名与 `accesses:` 一律不印。 + - `propertyWrappedFieldInitAccessor`(mangling 里的 `fF`)不在范围内。 + - 旧的 ABI 快照要用新版重新生成。RuntimeViewer 的 `next` 等它那边 `@Observable` 的改动做完再推,`kindString` 那一行跟着一起上。 +- **对应版本**:0.25.0。 + +## 134. `@Observable` 的展开分两层,`@Observation.ObservationIgnored` 单独占一行 + +- **时间段**:2026-11-12,分支 `feature/observable-nested-expansion`(worktree `.worktrees/MachOSwiftSection-ObservableNestedExpansion`,基于 `next` 2837d2e0),两次在本地合进 `next` 供用户查看,当天正式落地。提案 [0095-observable-nested-expansion](../Evolutions/0095-observable-nested-expansion.md)(轻量档),接着第 132 节的 0093。 +- **动机**:0093 的分块展开,把 accessor 块与存储直接算作展开 `@Observable` 的结果。Swift 源码里 `ObservableMacro` 只给每个被跟踪属性加 `@ObservationTracked`,accessor 块与存储是 `ObservationTrackedMacro` 写的,Xcode 也分两次展开,RuntimeViewer 要照这个分层显示。同一轮里,用户在 RuntimeViewer 里看 SwiftUI 时发现,折叠形态的 `@Observation.ObservationIgnored` 与很长的类型挤在一行,行行折行。 +- **关键决策**: + - 分块分两层。第一层每个被跟踪属性一块 `@Observation.ObservationTracked`(`.trackedPropertyAttribute`,放在折叠声明上方),带一个 `NestedExpansion`:属性在块里的 UTF-8 范围、宏,以及展开它的分块,也就是原来的 `.trackedProperty`,内容不变。两层的 `anchorKind` 都是同一个折叠声明的区域,`anchorKind` 改为存储属性。 + - 属性写成带模块名的 `@Observation.ObservationTracked`(用户选定;宏源码写的是 `@ObservationTracked`),经类型打印器印出,module selector 照样生效。 + - 被导出过滤排除的属性两层都不出;属性块里不放标记区域,范围由 `attributeUTF8Range` 给出。整块展开 `printMacroExpansion` 不变,仍是两层合起来的样子。 + - `@Observation.ObservationIgnored` 单独占一行,放在声明上方;被忽略的 wrapped property,wrapper 属性也单独占一行(用户选定),`lazy` 留在声明行,别处的 wrapper 属性照旧与声明同行。公开的 `printThrowingVariable` 签名不变,转调一个内部重载。 +- **落地**: + - SwiftInspection:`ObservableMacroRecognition.observationTrackedAttributeNameNode`。SwiftDeclaration:`SwiftAttachedMacro.observationTracked`。 + - SwiftPrinting:`MacroExpansionPart`(`.trackedPropertyAttribute`、`NestedExpansion`、存储的 `anchorKind`)、`printMacroExpansionParts`、`observationIgnoredAttribute(level:)`、`printThrowingVariable` 的内部重载、`printThrowingSynthesizedWrappedProperty(_:level:placesAttributeOnItsOwnLine:)`。 + - 测试:`ObservableMacroInterfaceTests` 的两层分块、属性写法与属性换行(成员与合成两条路径)。 + - 文档:提案、`Modules/SwiftInterface.md`、`AGENTS.md`、`AgentPlugins/swift-section` 的 skill。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上跑。最终全量 2909 个测试,只红两条:`FileMappingTests`,基线上同样失败;`BoundedConcurrentMapTests` 的时限超时,是既有偶发,失败在新测试开始之前。分块 API 不影响 interface 与 dump 的输出;折叠形态只改了换行,而渲染 A/B 的候选侧带 `--expand-macros`,比较不到折叠形态,所以没跑渲染 A/B。 +- **后续**:RuntimeViewer 照这一版的分块显示两层展开,它的锁文件要钉到推送后的 origin/next。 +- **对应版本**:0.25.0。 + +## 135. 首次代码库体检,修掉它确认与待确认的九条严重 bug + +- **时间段**:2026-11-16,分支 `fix/codebase-audit-2026-11-16`(worktree `.worktrees/MachOSwiftSection-AuditFixes`,基于 `next` 1ba927ad)。在 JHs-Mac-Studio 上体检与修复,转到 JHs-Mac-Studio-Ultra 验证并当天落地。 +- **动机**:第一次用 `audit-codebase` 给整个 `next` 做体检,审的是近 30 天的改动(443 个文件,约 2.6 万新增行),报告与账本见 [Reviews/CodebaseAudits/](Reviews/CodebaseAudits/README.md)。确认 7 条严重 bug、2 条待确认,用户批准修掉 7 条,第 8 条(待确认)随第 2 条一起修;前八条验证完后,第 9 条(待确认)也批准修掉。 +- **关键决策**: + - 每条先写复现测试,确认修复前失败(两条是子进程 SIGTRAP,其余是错误输出),测试永久保留;崩溃类的用 exit test,避免拖垮整个测试进程。 + - 参数个数守卫收成 `ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`,类成员与协议要求两条路径共用,不再各写一份。 + - 第 8 条不改读取器的表示,在 `ObjCProtocolRecord.make` 里核对扩展编码与方法表编码是否同一签名,对不上就整组不用:不论错位从哪来都挡得住。 + - 第 4 条修的时候发现同类问题:文件里给别的镜像的 Swift 类写的 category 指向类元数据符号 `_$s…CN`,interface 把扩展印成 `extension __C._$s…`。由新的 `NodeTypeNaming.swiftClassNode(fromRuntimeName:)` 统一认 `_TtC`、`$s`、`_$s` 三种写法,dump 那份私有实现也改用它。 + - 三条建议不修的登记为已裁决清单的 A83–A85。 +- **落地**: + - CrossReferenceAnalysis:`CrossReferenceAnalyzer.ClassArgumentReturn`(`objc_opt_class` 与原样返回的两个分开),`ImageFunctionTable.isObjectiveCClassMethod(at:)`;`RenamedReexportIndex` 不再把超出表尾的终端大小与游标相加。 + - SwiftObjCInterop:`ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`、`ObjCEncodedType.characterString(isConst:)` 与 `withoutExtendedNames`、`ObjCProtocolRecord.make` 的签名核对、`SwiftClassWithoutClassObjectIndex` 的同名处理、`ObjCRuntimeNames` 改用共享的类名识别;`ObjCImportedTypes` 照 ClangImporter 导入 C 数组(超过 4,096 个元素不导入、指针指向它时是 `OpaquePointer`,单元素数组是元素本身,嵌套展开超过 65,536 个元素同样不导入)。 + - SwiftInspection:`NodeTypeNaming.swiftClassNode(fromRuntimeName:)`。SwiftThunkAnalysis:`ObjCProtocolWitnesses` 对别的镜像的 Swift 类按运行时名取表,`ObjCMembers.table(forObjCClassNamed:)` 的所属名取 Swift 名。SwiftDeclaration:`ObservableMacroExpansionRecovery.isGeneratedFunction(name:node:)`。SwiftDump:category 行的类名。 + - 测试:新增 `MalformedExportTrieTests`、`ClassOfReceiverSendTests`,以及 `ObjCProtocolRequirementBuilderTests`、`ObjCImportedMemberBuilderTests`、`ObjCProtocolDefinitionIndexingTests`、`SwiftClassWithoutClassObjectIndexTests`、`ObservableMacroInterfaceTests`、`ObservableMacroExpansionRecoveryTests` 里的用例;三个现场编译的 fixture 各加了对应的形态。 + - 文档:体检报告与账本、`ReviewAdjudications.md`(A83–A85)、`Modules/CrossReferenceAnalysis.md`、`Modules/SwiftObjCInterop.md`、`Modules/SwiftDeclaration.md`、文档索引,`AGENTS.md` 的 SwiftObjCInterop 一段补了 `_$s…CN` 类名这个陷阱。`AgentPlugins/swift-section` 的 skill 不用改:它说的「不印 `access(keyPath:)` 这几个方法」指宏生成的那几个,修复后依然成立。没有新术语。 +- **验证**:在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6,本地兄弟依赖)上跑全量:2,916 个测试、554 个套件,红 3 条;第 9 条修完后在最终代码上又跑一次全量,2,917 个测试只红其中 2 条(`FileMappingTests`、`BoundedConcurrentMapTests` 的时限)——`FileMappingTests.readersOfOneCacheFileShareOneMapping`、`SharedCacheTests.differentKeysParallelViaAsyncLet`、`BoundedConcurrentMapTests.cancellationStopsSubmittingPendingElements` 的时限,都是满负载下的既有偶发,三个套件单独重跑全过;28 核上并行全量没有卡死。此前在 JHs-Mac-Studio(10 核)上,受影响的 22 个套件 118 个测试全过,并行全量两次卡死在 `DemanglingWave`(体检报告第 10 条,与本批改动无关)。没跑渲染 A/B:改动只影响几种具体形态的输出,不是大重构。 +- **后续**: + - 体检报告里复核为 PLAUSIBLE、未达门槛的 8 条线索没动。 +- **对应版本**:0.25.0。 +- **补记(同日,体检报告第 10 条)**:验证修复时发现的卡死已查明并修掉,分支 `fix/demangling-wave-hang`。 + - 复现:在子进程里同时起「核数 × 2」个任务,各自在协作线程上同步读一个新建 storage 的 demangled index(`SymbolIndexDemangledIndexTests.firstReadersOnEveryCooperativeThreadAllFinish`),28 核的 Ultra 上也稳定卡住。 + - 根因:协作线程全部同步阻塞时,它们仍占着同一 QoS 的并发额度,交给 `DispatchQueue.global()` 的那批 demangle 分不到线程,建索引的线程同步等它,整个进程停住。只用 GCD 的探针也一样:全局队列和私有并发队列都饿死,私有串行队列(挂在 overcommit 根队列上)0.07 秒就执行。 + - 修法:`DemanglingWave` 改从私有串行队列起头,`concurrentPerform` 照常用满所有核。`AGENTS.md` 的异步一节加了这条规则,`Modules/MachOSymbols.md` 写明原因,回归测试所在的套件加进了 CI 名单。 + - 验证:修复前回归测试两次都卡满看门狗,修复后单跑 15 秒通过。JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6,本地兄弟依赖)上全量 2,918 个测试只红 `FileMappingTests` 一条,是负载相关的既有问题。回归测试在全量里连排队一共 360 秒,所以子进程的看门狗定为 300 秒,真回归时子进程永远卡住,照样变红。 + +## 136. Swift 实现的类,导入声明以 Swift 一侧为准 + +- **时间段**:2026-11-17 至 11-18,三个仓库同名的分支 `feature/swift-first-imported-declarations`(本库 worktree `.worktrees/MachOSwiftSection-SwiftFirstImportedDeclarations`)。在 JHs-Mac-Studio 上写,在 JHs-MacBook-Pro 上构建与测试:JHs-Mac-Studio-Ultra 当天连不上 GitHub。用户看过效果后追加的注释位置与分段在 JHs-Mac-Studio-Ultra 上做。 +- **动机**:RuntimeViewer 的 Generated Interface 显示 macOS 27.2 SceneHosting 的 `SHScenePresentation`(`@objc @implementation` 类)时,只有 5 个成员用上 Swift 声明,其余按 selector 推导(`isHostingSceneLayer(_: Any!)`)。系统框架剥掉 thunk 符号、`-O` 把函数体内联进 thunk,0048 的前两档配不上,按名字的第三档只算 override。用户要求 Swift 实现的类以 Swift 一侧为准,并让 ObjC 头文件标出 `NS_REFINED_FOR_SWIFT`。提案 [0096-swift-first-imported-declarations](../Evolutions/0096-swift-first-imported-declarations.md),三个库共用。 +- **关键决策**: + - `@objc @implementation` 类改成桥接 Swift 类那样的形状:类体是实现的 Swift 一侧,纯 Swift 成员也在,没有 Swift 成员回答的 ObjC 方法放最后;category 与 ObjC 实现的类仍逐个成员替换。 + - 按名字配对在打印时做(`ObjCImplementingSwiftMembers`),不改 0048 在索引期记下的事实;认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀并优先于同名的纯 Swift 成员;类型明显对不上的不配(`ObjCSwiftTypeCompatibility`);两边都只有对方一个候选时才配。 + - 「改名成员」两种:配上 `__` 成员的有凭据;同名 Swift 属性类型对不上的 ObjC 属性是推断,只用于属性。推断的那种在导入声明里打成结构化注释(`refinedForSwiftMember` 种类),挂在占了它原名的 Swift 属性正上方,声明里的属性名与类型各成一段(`.name`、`.type`),供宿主分色——这两点是用户在 RuntimeViewer 里看过效果后追加的;交给宿主的查询是 `objcMembersRefinedForSwift(in:)`,用本库自己的类型——本库按版本依赖 MachOObjCSection,它的新接口(`ObjCSwiftImportNotes`)只在它的 `next` 上。 + - `@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性,Swift 一侧的 interface 同样生效;只剩 ivar 的存储属性在导入声明里打成同名 ObjC 属性的导入形式。 +- **落地**: + - SwiftObjCInterop:`ObjCSwiftTypeCompatibility`、`ObjCMemberShape.removingRefinedForSwiftPrefix`、`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)` 与 `Property` 的特性判断、`ObjCImportedMember.objcPropertyName`。 + - SwiftDeclaration:`ObjCImportedMemberDefinition.objcPropertyName`。SwiftIndexing:`objcClassRuntimeNamesExtendedInSwift`。 + - SwiftPrinting:`ObjCImplementingSwiftMembers`(从打印器文件里移出、改按位置配对)、`ObjCRefinedForSwiftMember`、`objcMembersRefinedForSwift(in:)`、`@implementation` 类的 Swift 优先打印、`printExtensionBodyContents`(扩展体与导入声明共用)、存储属性的 `var` / `weak`。SwiftDeclarationRendering:`StructuredComment.refinedForSwiftMember(declaration:)` 与注释种类 `refinedForSwiftMember`。 + - 测试:夹具加 `ScenePresentationWidget`(仿 `SHScenePresentation`);`ObjCImportedDefinitionTests` 四个新用例、`ObjCMemberRecoveryTests` 一个、新的 `ObjCSwiftTypeCompatibilityTests`、`StructuredCommentTests` 一条期望;识别测试的类集合加上新类。 + - 文档:`ObjCCommandLine.md`「The Swift view」、插件 skill 的 `references/objc.md`、`Modules/SwiftObjCInterop.md`、`Modules/SwiftDeclaration.md`、术语表(新词「改名成员」)。 +- **验证**:JHs-MacBook-Pro(macOS 27.2,Xcode 27.2,本地兄弟依赖只配了 swift-demangling `next`)。新测试改动前失败(夹具编过后 11 处),改动后相关套件全过;全量(`--skip IntegrationTests`)有 167 个失败点,与同机同夹具跑不含改动的 `next` 完全相同——SymbolTests 夹具的 ABI 基线按 Xcode 26.6 录,这台只有 27.2,另有 `SymbolicDemanglerTests` 要的模拟器 SwiftUI 不在。追加的两处在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2,本地兄弟依赖)上验证:两个新用例改动前失败、改动后通过,相关的 9 个套件 73 个测试全过。 +- **对应版本**:0.25.0。 + +## 137. 离线交叉引用与地址符号化 + +- **时间段**:2026-11-18 至 11-19,本库分支 `feature/offline-cross-references-and-symbolication`(worktree `.worktrees/MachOSwiftSection-OfflineCrossReferences`),RuntimeViewer 同名分支(worktree `.worktrees/RuntimeViewer-OfflineCrossReferences`)。在 JHs-Mac-Studio-Ultra 上写、构建与测试。 +- **动机**:交叉引用只能在活的进程里读;归档的 cache、别的设备的 cache、磁盘上的 app 都要开 IDA。愿景《不依赖 IDA 的逆向》的第一步:同一套分析从文件读,加上地址符号化,并给命令行与 MCP 入口。 +- **关键决策**: + - 分两步:本提案在本库内把交叉引用拆成核心 / ObjC / Swift 三层模块,用源码扫描守住 import 边界;把核心与 ObjC 层迁去 MachOKitExtensions 与 MachOObjCSection 另写提案。 + - 两种模式唯一的本质差别(槽里的值怎么得到)收进读取协议 `CrossReferenceMemory`;文件模式整 cache 建表 2.58 秒,与进程内 2.48 秒相当。 + - 桩与槽的解析抽成 `CodeAddressResolution`,`SwiftThunkAnalysis` 与交叉引用共用。 + - 引用多了路线、ivar、字符串与经槽读到的导入符号;JSON 的地址一律是十六进制字符串。 +- **落地**:`CrossReferenceCore`、`CrossReferenceObjC`、`CodeAddressResolution` 三个新模块;`CrossReferenceAnalysis` 成为门面并加文件模式与 `symbolication(of:)`;SwiftSectionKit 的 `ReferencesRequest` / `SymbolicateRequest` 与 `swift-section refs` / `symbolicate`;RuntimeViewer 的两个引擎命令、CLI 四个子命令(协议版本 3)与四个 MCP 工具。 +- **顺带修掉**:`ARM64Trampoline` 把「读槽后不经该寄存器跳转」的指令序列误认成 GOT 桩;`SlotResolver` 在可执行文件上把 rebase 目标当成文件偏移;收集器共用调用方的键集合,并发扫描时引用计数争抢让整 cache 查 `init` 的调用者从 2 秒变成 150 秒(`next` 上的同一写法 RuntimeViewer 也会踩到)。 +- **文档**:提案 [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md);`Modules/CrossReferenceAnalysis.md`、`CrossReferenceCore.md`、`CodeAddressResolution.md`、`SwiftSectionKit.md`;README 与插件 skill 的 `references/cross-references.md`;术语表新增「地址符号化」「识别器」「引用路线」「stub island」。 +- **验证**:JHs-Mac-Studio-Ultra(macOS 27.2)。全量测试(跳过 IntegrationTests)2,993 个零失败;系统框架渲染 A/B 三条读取路径 84 对逐字节一致;RuntimeViewer 一侧在沙盒里编过 Core、CLI 与 MCP,新测试全过。用户验收用功能分支的 release 版 CLI(Xcode 27.2,本地兄弟依赖)跑了 selector 调用者、归档 27.0 与 27.2 cache 的类引用、桩与槽的符号化和一个胖文件。 +- **对应版本**:0.25.0。 + +## 138. MachO 层迁入 MachOKitExtensions 2.0.0,废弃的读取写法删除 + +- **时间段**:2026-11-11 至 2026-11-19,本库与 MachOKitExtensions 各两条分支:`feature/move-reading-and-resolving-modules`,以及从它切出的 `feature/move-macho-infrastructure-modules`。只推送,不合进常驻检出,与第 139 节同日落地。 +- **动机**:不看 Swift 元数据的包(MachOKitUI 关掉 Swift 支持时、swift-decompiler)只要读取层与符号表,却得依赖整个本库;愿景《不依赖 IDA 的逆向》第 6 条也要求与语言无关的代码归 MachOKitExtensions。 +- **关键决策**: + - 由 MachOKitExtensions 维护两份唯一提案:[0002 move-reading-and-resolving-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) 与 [0003 move-macho-infrastructure-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md)。本库的提案索引各加一行 cross-repository。 + - `MachOReading`、`MachOResolving`、`MachOPointers`、`MachOCaches`、`MachODependencies`、`MachOBase`、`MachOFoundation` 原名迁入,各带同名 product。 + - `MachOSymbols` 拆成两半。与语言无关的符号表、采集(`SymbolSweep`)与只收 C/C++/ObjC 名字的新 `SymbolIndexStore` 进 MachOKitExtensions。Swift 那一半留在本库,模块改名 `SwiftSymbols`,store 改名 `SwiftSymbolIndexStore`,经 `SymbolTableRouting` 钩子接上。 + - MachOKitExtensions 为此发大版本 2.0.0,防止旧版本库自带的同名模块与新版本包被一起解析。 + - 0057 的废弃读取写法不进 MachOKitExtensions,与搬迁同版删除:344 个转发、`AsyncResolvable` 与 `implementationAddress(in: machO)` 旧名;覆盖率登记表去掉 15 个键。删除前,swift-decompiler 与 MachOKitUI 都已改用 `ReadingContext`。 +- **落地**: + - 本库删掉迁走的 target、`ConcurrentFileMappingTests.swift` 与 `DeprecatedReadingFormsTests`,依赖改为 MachOKitExtensions `from: "2.0.0"`。 + - 符号索引的目录、类型与 import 改名,`ContinuousIntegrationTestFilterTests` 与 `AllFixtureSuites.swift` 跟着改。 + - 实现说明搬到 MachOKitExtensions:`ReadingContextAbstraction.md`(本库保留调用侧那份)、`SymbolIndex.md`、`SharedCache.md`、`DependencyResolution.md`。 +- **验证**: + - 两份提案各自的全量测试与渲染 A/B 记在它们的决策日志。 + - 2026-11-19 合入 `origin/next` 之后的重新验证,由第 139 节的候选一并补上:debug 全量 2,901 个测试通过,84 对渲染 A/B 逐字节一致。 + - 落地当天又跑了两侧的 release 测试,结果见第 139 节。 +- **对应版本**:0.25.0(MachOKitExtensions 2.0.0)。 + +## 139. 交叉引用的核心层与 ObjC 层迁出本库 + +- **时间段**:2026-11-19 起,三个仓库同名的分支 `feature/move-cross-reference-layers`(本库与 MachOKitExtensions 从各自的 `feature/move-macho-infrastructure-modules` 切出,MachOObjCSection 从 `next` 切出)。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上构建与测试。 +- **动机**:愿景《不依赖 IDA 的逆向》第 6 条要求与语言无关的部分归 MachOKitExtensions、ObjC 专属的归 MachOObjCSection。0097 已在本库拆好、量过;MachOKitExtensions 2.0.0 与本库 0.25.0 本来就是大版本与破坏性版本,同日搬只走一轮三个仓库的发版。 +- **关键决策**: + - 下层只开 `@_spi(Internals)` 给本库,对外的分析器与公开模型留在本库,RuntimeViewer 不改代码;搬走的 `package` 一律改成 SPI(共约 370 处),不按「跨包才改」逐个挑。 + - `CrossReferenceCore` → `MachOCodeReferences`、`CodeAddressResolution` → `MachOAddressResolution`、`ARM64InstructionDecoding` 名字不变,都进 MachOKitExtensions;`CrossReferenceObjC` → MachOObjCSection 的新 target `ObjCCodeReferences`。 + - 进程内部分用 `#if canImport(Darwin)` 包住,文件模式在 Linux 上也能编(未验证);删掉从来只写 `.none` 的 `IndirectCallEvidence.table`,`refs --json` 的 `table` 键一起删。 + - 测试跟代码走,但几乎都经门面建分析器,所以只搬直接测下层的几组与源码扫描;Capstone 对照的解码器测试留在本库。 + - 落地顺序:MachOKitExtensions 2.0.0 → MachOObjCSection 0.8.207(MachOKitExtensions 下限抬到 2.0.0)→ 本库 0.25.0 → RuntimeViewer 抬钉。 +- **落地**:先把 `next` 合进基础设施搬迁分支(冲突七处,两边改动都保留);三个模块与 ObjC 层的源码、测试、实现说明分别进 MachOKitExtensions 与 MachOObjCSection;本库删掉四个模块与 `CodeAddressResolutionTests`,门面、`SwiftThunkAnalysis`、`SwiftDeclarationRendering` 与测试改用 SPI import。 +- **文档**:提案 [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md);`Modules/CrossReferenceAnalysis.md`(仍是三层的总说明)、`Modules/README.md`、`SwiftThunkAnalysis.md`、`AccessorThunkResolutionExplained.md`、`ProjectMap.md`、术语表与 `AGENTS.md`;MachOKitExtensions 的 `MachOCodeReferences.md`、`MachOAddressResolution.md`、`ARM64InstructionDecoding.md`,MachOObjCSection 的 `ObjCCodeReferences.md`;本库的三份旧模块文档删除。 +- **验证**: + - 都在 JHs-Mac-Studio-Ultra 上跑,Xcode 26.6;明细记在提案的决策日志。 + - 测试:MachOKitExtensions 161 个、MachOObjCSection 343 个、本库 debug 全量 2,901 个,都通过。 + - 对照:AppKit、SwiftUICore、Foundation 三个镜像的整表 A/B 一致;84 对渲染 A/B 逐字节一致;吞吐比 `next` 快 1% 到 11%。 + - RuntimeViewer 的 Core、CLI、MCP 不改源码就能编过。 + - 落地当天加跑 release 测试。MachOKitExtensions 161 个全过。本库 2,901 个测试里红 6 条:`SpecializedRuntimeTypeNameTests` 的 5 条是已知的 release 必红,release 优化把测试里没用到的私有类型删掉了,CI 的名单也不含这个套件;`LargeStackTaskExecutionTests.demanglerEntriesInsideTheBodyDoNotHop` 是满载下的偶发,单独连跑三次都过。 +- **对应版本**:0.25.0(MachOKitExtensions 2.0.0、MachOObjCSection 0.8.207)。 + +## 140. 0.25.0 发版 + +- **时间段**:2026-11-19。 +- **动机**:用户批准发 0.25.0,并把等它的三份搬迁同日合入(第 138、139 节)。0.24.0 以来 `next` 另有第 108–137 节,以及两节还没编号的 SwiftDeclaration 整理里已经合进来的部分(它们的提案还在进行)。 +- **关键决策**: + - **① 发版顺序**:swift-demangling 0.7.4 → MachOKitExtensions 2.0.0 → MachOObjCSection 0.8.207 → 本库 0.25.0。每一步依赖前一步的 tag,前一步发出后下一步才能只走远端依赖编过。 + - **② swift-demangling 发 0.7.4**:0092 用到它 `next` 上的 `DemangleOptions.useExistentialAny`,一直没发版。`next` 上另有 0019(`Demangler` / `Remangler` 改为 `~Copyable`,都是 internal),两者都不破坏兼容,按它的惯例发补丁版;本库要求抬到 `"0.7.4"..<"0.8.0"`。发版前在 Ultra 上用 Xcode 26.6 跑过它的全部测试,651 个通过。 + - **③ 0057 的废弃读取写法按期删除**:期限两次顺延后定在 0.25.0,条件是 MachOKitUI 与 swift-decompiler 先改用 `ReadingContext`,两者都已改。删除随第 138 节的搬迁分支进来,Changelog 的 Breaking 写明。 + - **④ Changelog 约 5,400 字符**,超出大版本 4,000 字符的预算:Breaking 有 13 条,每条都要调用方改代码(模块搬家、符号索引改名、旧读取写法删除、快照格式 13、默认写 `any`、几个新 case 与类型变化、依赖下限)。 + - **⑤ 版本号**:`Version.swift` 与两个 `plugin.json` 改为 0.25.0;插件 skill 里「after 0.24.0」的标注改为「from 0.25.0」。README 的安装示例与 product 表已由搬迁分支改好。 + - **⑥ 下游**: + - MachOKitUI 要求 MachOKitExtensions `from: "1.3.0"`,与 0.25.0 要的 2.0.0 冲突,所以会继续解析到 0.24.x,不会突然编不过;它改用 2.0.0 是它自己的后续提案。 + - swift-decompiler 跟本库的 `next`,只用 `SwiftInterface`、`SwiftDump`、`SwiftDeclarationRendering`、`SwiftLayout` 四个 product。 + - RuntimeViewer 跟 `next`,要同日把 `MachODependencies` 改从 MachOKitExtensions 取。 +- **落地模块**:`Sources/Executables/swift-section/Version.swift`、`AgentPlugins/swift-section/`(两个 `plugin.json`、skill)、`Changelogs/0.25.0.md`、`Package.swift`(MachOObjCSection 与 swift-demangling 的下限)、本账本(第 108–139 节的对应版本、本节)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 26.6。 + - 发版提交,`git archive` 导出的干净副本,只走远端依赖(MachOKitExtensions 2.0.0、MachOObjCSection 0.8.207、swift-demangling 0.7.4),scratch 是新的。 + - 照 release 配置编 `swift-section` 通过,`--version` 输出 0.25.0。 + - 有 3 条 warning:`SwiftDeclarationPrinter+ObjCImportedDefinitions.swift` 里 `try await MemberList` 下没有会抛错的调用。这段代码本分支没动过,`next` 上原样就有。 + - 两侧 release 测试的结果见第 139 节。 + - `claude-isolated plugin validate` 对插件目录与 marketplace(`--strict`)都通过;本机没有 Codex 的 `validate_plugin.py`,这一项没做,这次两个 `plugin.json` 只改了版本号。 +- **关联文档**:[Changelogs/0.25.0.md](../../Changelogs/0.25.0.md)。 +- **对应版本**:0.25.0。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ProjectMap.md b/Documentations/Internal/ProjectMap.md new file mode 100644 index 000000000..0ad4844e8 --- /dev/null +++ b/Documentations/Internal/ProjectMap.md @@ -0,0 +1,145 @@ +# MachOSwiftSection 项目地图 + +- **核对基准**: `1dcc0c08`(`next`,提交于 2026-10-31)——下面每个说法都对照过这个 commit,之后的改动从这里讲起。Mach-O 基础模块迁往 MachOKitExtensions(2026-11)之后,模块名、`Sources/` 路径与符号索引的行号已按迁移后的代码同步,其余行号仍以这个 commit 为准 +- **怎么用**: 这一页只讲项目现在长什么样、东西在哪。细节顺着链接去 [模块参考](Modules/README.md)、[术语表](../Glossary.md)、[提案](../Evolutions/README.md);给 agent 的约定与陷阱在仓库根的 [`AGENTS.md`](../../AGENTS.md)。 + +## 这是什么 + +一个 Swift 库加一个命令行工具 `swift-section`:不把二进制加载进进程,直接从 Mach-O 文件或 dyld shared cache 里读出 Swift 和 Objective-C 的类型、协议、遵循、字段布局,再还原成 dump、`.swiftinterface`,或者在两个、多个版本之间做 ABI diff 与 evolution。它自带 demangler(包括 symbolic reference),读取逻辑照着 Swift runtime 自己的实现移植。规模:`Sources/` 972 个文件、约 11.3 万行 Swift;`Tests/` 约 8 万行。 + +## 产物与进程 + +| 产物 | 入口 | 是什么 | +|---|---|---| +| 21 个库 product | `Package.swift:1344` | 每层一个,下游按需挑;`SwiftSectionKit` 是「CLI 能做的全部事情」那一个 | +| `swift-section` | `Sources/Executables/swift-section/SwiftSectionCommand.swift:3` | CLI 包装层:只做 flag 映射、错误措辞、输出流路由和退出码,逻辑都在 `SwiftSectionKit` 的 request 里 | +| `baseline-generator`、`regen-baselines` | `Sources/Executables/baseline-generator/BaselineGeneratorMain.swift:5`、`Plugins/RegenerateBaselinesPlugin/RegenerateBaselinesPlugin.swift` | 重新生成 fixture 的 ABI 基线 | +| SymbolTests fixture 工程 | `Tests/Projects/SymbolTests/SymbolTests.xcodeproj` | 编出测试读的 `SymbolTestsCore`;产物不进 git,每台机器自己编 | +| agent 插件 | `AgentPlugins/swift-section/` | 装进 Claude Code 和 Codex,教 agent 用这个 CLI | +| `swift-section-mcp` | `MCP/Sources/swift-section-mcp/` | 独立子包;2026-06-10 之后没动过,现在还能不能编过未核对 | + +谁调谁: + +```text +swift-section CLI ──► SwiftSectionKit requests ──┐ + ├──► library ──► MachOFile ──► Mach-O file / dyld shared cache file on disk +RuntimeViewer · MachOKitUI · swift-decompiler ───┘ └──► MachOImage ──► image already loaded in the host process +``` + +- 两种 reader 共用一套模型:`Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift:14` 和 `Sources/ABI/MachOSwiftSection/MachOImage+Swift.swift:14` 给出同一个 `machO.swift` 入口。 +- 只有 `MachOImage` 能调运行时,所以有些事实分两条路得到:字段布局注释在进程内读 live metadata,离线由 SwiftLayout 算(`Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift:117`)。 +- 上游是同组织的兄弟仓库:MachOKit(fork)、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string、swift-capstone。兄弟目录存在且设了 `USING_LOCAL_DEPENDENCIES=1` 才用本地副本,否则静默用远端版本(`Package.swift:42`)。 + +## 模块分层 + +子节点是父节点的依赖: + +```text +swift-section CLI wrapper +└─ SwiftSectionKit one request per subcommand (+ MachOObjCSection's ObjC* products for `objc`) + ├─ SwiftDump the `dump` output + ├─ TypeIndexing `__C` type → module attribution (macOS only) + └─ SwiftInterface orchestrator: single version / diff / evolution + ├─ SwiftIndexing image → declaration model + ├─ SwiftPrinting declaration model → Swift source (a peer of SwiftIndexing) + ├─ SwiftSpecialization generic specialization + └─ SwiftDiffing ABI comparison, no Mach-O access +SwiftDeclaration the shared declaration model all of the above read and write +└─ SwiftDeclarationRendering comment engine shared by dump and interface + ├─ SwiftLayout static field offsets and layouts + └─ SwiftThunkAnalysis accessor-thunk evaluation, ObjC member tables +SwiftObjCInterop the Objective-C side of Swift types (MachOObjCSection enters here) +└─ SwiftInspection runtime-metadata analysis, symbol attribution + ├─ SwiftSymbols the Swift symbol index (SwiftSymbolIndexStore) + └─ MachOSwiftSection ABI model: the `__swift5_*` sections and their descriptors + └─ MachOBase reading / resolving / pointers (external, MachOKitExtensions) +MachOFoundation = MachOBase + MachOSymbols + MachODependencies (all external, MachOKitExtensions) +``` + +- `MachOBase`、`MachOFoundation`、`MachOSymbols`(与语言无关的符号表、采集与 C/C++ 符号索引)、`MachODependencies`、`MachOCaches`、`MachOPointers`、`MachOReading`、`MachOResolving` 都是 MachOKitExtensions 2.0.0 的 product,不在本仓库;`Utilities` 仍在本仓库,由 `MachOSwiftSection` 再导出。 + +- 每个 target 的完整依赖在 `Package.swift`(`:336` 起);每个模块一句话的说明在 `AGENTS.md`。 +- `Sources/` 按职责分 9 组目录,新 target 要在 `Package.swift` 里写 `path:`([提案 0055](../Evolutions/0055-group-sources-by-layer.md))。分组不等于依赖层次:`Sources/Output/SwiftDeclarationRendering` 反而被 `Sources/Declaration/SwiftDeclaration` 依赖。 +- ABI 层自包含:`MachOSwiftSection` 只依赖 `MachOBase`,不碰符号索引和 demangler(`Package.swift:464`),符号归属在 `SwiftInspection` 里做。 +- dump 和 interface 是两条独立的打印路径:dump 按 descriptor 逐个打印、不建声明模型,interface 先建模型再打印;两者共用 `SwiftDeclarationRendering` 的注释引擎。 + +## 关键流程 + +### `swift-section dump ` + +1. `DumpCommand.run()` 把 flag 映射成 `DumpRequest` — `Sources/Executables/swift-section/Commands/DumpCommand.swift:84`(映射在 `:63`) +2. `DumpRequest.run` 装上 thunk reader,加载二进制 — `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:140` +3. `MachOSource.load()` 打开文件,或从 dyld shared cache 里取出那个 image,得到 `MachOFile` — `Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift:59` +4. 不建声明模型;只有 `--emit-private-source-files` 才另建一个索引器 — `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:190` +5. 按段走:类型、协议、Swift 声明的 `@objc` 协议、遵循、关联类型、`@objc @implementation` 类 — `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:231` +6. 类型列表直接读 `__swift5_types` — `Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift:18` +7. 每个类型交给对应的 dumper,比如 class 交给 `ClassDumper` — `Sources/Output/SwiftDump/Dumpable/Class+Dumpable.swift:10`、`Sources/Output/SwiftDump/Dumper/ClassDumper.swift:13` +8. 结果写进 `SwiftSectionOutput`;CLI 的实现把产品送 stdout、诊断送 stderr — `Sources/Commands/SwiftSectionKit/Output/SwiftSectionOutput.swift:14`、`Sources/Executables/swift-section/Output/StandardStreamOutput.swift:19` + +### `swift-section interface ` + +1. `InterfaceCommand.run()` 把 flag 映射成 `InterfaceRequest` — `Sources/Executables/swift-section/Commands/InterfaceCommand.swift:103`(映射在 `:78`) +2. 建 `SwiftInterfaceBuilder` — `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:180` +3. `prepare()` 交给索引器 — `Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift:105`、`:125` +4. 索引器在 large-stack executor 上依次建类型、协议、遵循、extension 的定义;类型的字段和成员这时还不填 — `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:273`(四个阶段在 `:502`、`:642`、`:722`、`:897`) +5. `printRoot()` 先算出导出过滤的范围,再按块打印 — `Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift:141`、`:152` +6. 打印一个类型之前才 `index(in:)`:字段、成员、要跨几种符号才推得出的事实在这一步填上,每个定义只跑一次 — `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:275`、`Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift:16` +7. 打印器渲染成 `SemanticString`(带语义标注的字符串,宿主据此着色) — `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:262` +8. 交给输出 — `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:207` + +### `swift-section evolution …` + +1. `EvolutionCommand.run()` 把 flag 映射成 `ABIEvolutionRequest` — `Sources/Executables/swift-section/Commands/EvolutionCommand.swift:107`(映射在 `:59`) +2. 默认按 CPU 核数并发处理各个输入 — `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:78`、`:88` +3. 输入是 JSON 快照就直接解码,格式版本对不上就报错 — `Sources/Commands/SwiftSectionKit/Swift/ABISnapshotLoading.swift:27`、`Sources/Output/SwiftDiffing/ABISnapshotDocument.swift:94` +4. 输入是二进制就走和 interface 同一个索引器,再把每个定义都 `index(in:)` 一遍、冻结成 `ABISnapshot` — `Sources/Commands/SwiftSectionKit/Swift/ABISnapshotLoading.swift:44`、`Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift:58`、`:107` +5. `ABIEvolutionBuilder` 把 N 份快照对齐,每个声明一条 lineage — `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:105`、`Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift:9` +6. `ABIEvolutionReporter` 写出报告 — `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:113`、`Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift:30` +7. 带 `--interface` 时改走另一条:合并成一份带演进注释的 interface — `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:79` + +## 地标 + +- `Package.swift` — 29 个库 target 的声明与依赖(`:336` 起)、product 清单(`:1344`);最近三个月改了 80 次,是改得最勤的文件 +- `Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift:15` — Swift 符号索引:在 MachOKitExtensions 的 `SymbolSweep` 采集上 demangle、按成员种类分桶 +- `Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift:14` — ABI 模型的入口 `machO.swift` +- `Sources/Analysis/SwiftInspection/SymbolicDemangler.swift:31` — 带 symbolic reference 的名字怎么还原成完整的名字 +- `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:45` — 从一个 image 建出声明模型 +- `Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift:16` — 一个类型在声明模型里的样子 +- `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:19` — 把声明模型打印成 Swift 源码 +- `Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift:19` — interface 的编排:prepare、导出过滤、按块打印 +- `Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift:15` — 所有 request 共用的唯一加载器 +- `Sources/Output/SwiftDiffing/ABISnapshotDocument.swift:77` — 快照格式版本(现在是 10);改了 key 的写法就要升,旧快照随之读不进 + +## 术语 + +完整的项目术语见 [术语表](../Glossary.md),这里只列读代码前必须知道的十个。 + +- **image**:一个 Mach-O 二进制单位——一个框架、一个可执行文件,或 dyld shared cache 里的一员。 +- **`MachOFile` / `MachOImage`**:两种 reader。前者离线读磁盘上的文件或 cache 文件,后者读当前进程已加载的 image,能调运行时。 +- **descriptor**:`__swift5_*` 段里描述类型、协议、遵循的记录,彼此用相对指针相连;`MachOSwiftSection` 就是它们的 Swift 封装。 +- **symbolic reference**:mangled name 里直接指向某个 descriptor 的相对指针;普通 demangler 解不开,由 `SymbolicDemangler` 负责。 +- **`Node` / `NodeReference`**:demangle 出来的语法树;`NodeReference` 是共享存储里的节点引用,它自带的相等性按所在 store 算,跨 store 比较要用 `StructuralNodeReferenceKey`。 +- **materialize**:从 descriptor 读出完整的 wrapper。一次操作最多一次,用局部变量传下去,不缓存回定义上。 +- **export status**:一个声明的符号在不在导出表里,`--exported-only` 和 `// not exported` 注释都看它;四种「下不了结论」的情况一律不算未导出。 +- **snapshot / lineage**:snapshot 是一个版本冻结下来的 ABI,可以存成 JSON 基线;lineage 是一个声明跨 N 个版本的在场情况与事件。 +- **marking mode**:全量打印一遍,把受选项控制的内容标上可见条件,由宿主按当前选项投影;RuntimeViewer 的 Find 用它建语料。 +- **stand-in member symbol**:真正的实现符号没了时,用 image 里剩下的别的入口(method descriptor、`@objc` thunk、initializing entry point)造的替身。 + +## 在做的事 + +- 0.24.0(2026-10-26)之后合进 `next` 的都还没发版:[提案 0076–0084](../Evolutions/README.md) 和几个修复。下一版按计划删掉废弃的读取接口([提案 0057](../Evolutions/0057-reading-context-migration.md)),MachOKitUI 和 swift-decompiler 要先迁移(2026-10-26 时还在用,之后未复核)。 +- 等批准:[静态布局引擎读取 accessor thunk 背后的字段类型](../Evolutions/draft-static-layout-through-accessor-thunks.md)(2026-09-16 起草,没开始实现)。 +- 跨仓库进行中:嵌套坐标字段的精确访问大小,由 swift-decompiler 维护唯一的提案(链接见 [提案索引](../Evolutions/README.md))。 +- 开着的 issue:#137(两个问题都已修在 `next`,等发版)、#139(interface 把手写的 `_x` 字段当成 property wrapper 的 backing storage)、#140(dump 给被删实现的 class 方法印出 `class func static`)、#99(vtable 里的 class 方法印成 `static`)、#83(个别框架生成 interface 失败)。 +- 已知没做:image group 演进还没接命令行([提案 0082](../Evolutions/0082-image-group-evolution.md) 的后续项);只带上下文 `where` 子句的方法,函数头会多印一个泛型参数表([演进账本](ProjectEvolutionLog.md)第 118 节记录,未核对)。 +- 兄弟仓库待发版:MachOObjCSection 的 `next` 上有重复成员按来源取舍、只打导出声明、ObjC 一侧的注释结构标记;swift-demangling 的 `next` 上有两处修复。 +- 文档缺口:[模块参考](Modules/README.md) 还有 13 个模块没写。 +- 审查积压:仓库根 `Roadmaps/` 下按日期存着各轮 review 的发现清单。 + +## 复杂度热点 + +- **符号索引的几套成员索引**(`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift:296`–`:302`):实现符号、method descriptor、protocol witness、`@objc` thunk 四套成员索引并列,同一个成员可能同时出现在几套里。名字键去掉了 private discriminator,同名的私有类型共用一个桶,所以按单个类型查要用带 node 的重载(`:1284`)。难在哪一套回答哪一种问题,只能从注释和提案里拼出来。 +- **`TypeDefinition` 索引的步骤顺序是承重的**(`Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift:22`):`final` 的还原要读 `applyThunkAttributes` 挂上的 `@objc` 证据,又必须早于 `orderedMembers` 拷贝成员值;wrapped property 的还原要等字段和成员变量都齐。换了顺序照样编译通过,输出却静默变错。 +- **dyld shared cache 里的四种偏移口径**(MachOKitExtensions 的 `Sources/MachOAddressResolution/ImageAddressSpace.swift:43`):本库的 offset 是「未滑动的虚拟地址减 shared region 起点」;另外三种(subcache 文件偏移、`MachOFile.fileOffset(of:)`、`FullDyldCache.address(of:)`)看着能用却不对,而且算错时给出的是一个落在邻近 image 里、看起来合理的地址,不报错。 +- **泛型参数的层号**(`Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift:30`):一层只算真正声明了参数的上下文,不能数祖先链;opaque type 还要把声明它的函数(debug 构建里还有属性)算进去。八个读取点曾各自数错,现在统一从这里取。 +- **ObjC 成员的三档证据**(`Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift:9`):IMP 处的 `To` 符号、符号被剥后反汇编 thunk、只按名字推断。第三档只记录、用不用由使用方决定,而且不能写进 `attributes`——紧接着的 `final` 还原会把它当成 `@objc dynamic` 的证据。 diff --git a/Documentations/Internal/ReadingContextAbstraction.md b/Documentations/Internal/ReadingContextAbstraction.md index 299519182..1d0a7db55 100644 --- a/Documentations/Internal/ReadingContextAbstraction.md +++ b/Documentations/Internal/ReadingContextAbstraction.md @@ -1,8 +1,10 @@ # ReadingContext Abstraction +> 读取层本身——`ReadingContext`、`MachOContext`、`InProcessContext`、`Resolvable`、`SymbolOrElement`、`MachOFile` 怎么读、缓存范围的设计、读取层这一侧怎么看穿包装类型——自 0.25.0 起是 MachOKitExtensions 包的 MachOReading / MachOResolving 模块(2.0.0 起,模块名不变),实现说明在那个包的 `Documentations/Internal/ReadingContextAbstraction.md`,迁移的来历见它的提案「把 MachOReading 与 MachOResolving 迁入本包」。本文留下的是本库这一侧:ABI 层的读取接口怎样统一到 `ReadingContext`、指针协议怎样接入、上层怎样按缓存范围缓存,以及看穿包装类型在本库各处的规则。 + ## Overview -This document describes the design and implementation of the `ReadingContext` protocol abstraction, which unifies memory reading operations across different data sources (MachO files and in-process memory). +This document describes how this package reads through the `ReadingContext` protocol abstraction, which unifies memory reading operations across different data sources (MachO files and in-process memory). The abstraction itself lives in MachOKitExtensions; see the note above. ## Problem Statement @@ -60,91 +62,10 @@ This duplication leads to: └───────────────────────────────┘ └─────────────────────────────────┘ ``` -### RuntimeProtocol Extension - -The existing `RuntimeProtocol` is extended to support pointer type aliases: - -```swift -public protocol RuntimeProtocol { - associatedtype StoredPointer: FixedWidthInteger & UnsignedInteger - associatedtype StoredSignedPointer: FixedWidthInteger - associatedtype StoredSize: FixedWidthInteger & UnsignedInteger - associatedtype StoredPointerDifference: FixedWidthInteger & SignedInteger - - static var pointerSize: Int { get } -} - -// New: InProcess runtime for direct memory access -public enum InProcess: RuntimeProtocol { - public typealias StoredPointer = UInt - public typealias StoredSignedPointer = Int - public typealias StoredSize = UInt - public typealias StoredPointerDifference = Int - - public static var pointerSize: Int { MemoryLayout.size } -} -``` - -### Key Components - -#### 1. ReadingContext Protocol - -The core abstraction that unifies different memory reading modes: - -```swift -public protocol ReadingContext: Sendable { - associatedtype Runtime: RuntimeProtocol - associatedtype Address - - func readElement(at address: Address) throws -> T - func readWrapperElement(at address: Address) throws -> T - func readString(at address: Address) throws -> String - func advanceAddress(_ address: Address, by offset: Int32) -> Address -} -``` - -#### 2. MachOContext - -Wraps a MachO file/image for external reading: - -```swift -public struct MachOContext: ReadingContext { - public typealias Runtime = RuntimeTarget64 - public typealias Address = Int - - public let machO: MachO - - // Delegates to MachO.readElement, MachO.readString, etc. -} -``` - -#### 3. InProcessContext - -Provides direct memory access for in-process reading: - -```swift -public struct InProcessContext: ReadingContext { - public typealias Runtime = InProcess - public typealias Address = UnsafeRawPointer - - // Direct memory load via UnsafeRawPointer -} -``` +`RuntimeProtocol` and its `InProcess` runtime, the `ReadingContext` requirements, `MachOContext`, `InProcessContext` and `Resolvable` are described in MachOKitExtensions' implementation note, where they now live. ### Integration with Existing APIs -#### Resolvable Protocol Extension - -```swift -extension Resolvable { - // New unified API - public static func resolve( - at address: Context.Address, - in context: Context - ) throws -> Self -} -``` - #### RelativePointerProtocol Extension ```swift @@ -159,7 +80,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.25.0. +Since the single-implementation pass (below, 2026-09-30) the `ReadingContext` form is the only one there is. The Mach-O form (`in: machO`) and the pointer form (no reader argument) were deprecated forwarders from 0.22.0 and are deleted in 0.25.0. ```swift // A Mach-O file or image: pass its context. @@ -193,66 +114,7 @@ let desc1 = try readProtocolDescriptor(at: offset, in: machO.context) let desc2 = try readProtocolDescriptor(at: ptr, in: InProcessContext.shared) ``` -## Comparison with Swift Runtime - -This design is inspired by the Swift runtime's `MemoryReader` abstraction: - -| Swift Runtime (C++) | This Project (Swift) | -|---------------------|----------------------| -| `MemoryReader` | `ReadingContext` | -| `InProcessMemoryReader` | `InProcessContext` | -| `CMemoryReader` | `MachOContext` | -| `RemoteAddress` | `Context.Address` | -| `RuntimeTarget<8>` / `InProcess` | `RuntimeTarget64` / `InProcess` | - -### Swift Runtime Reference - -From `swift/include/swift/ABI/TargetLayout.h`: - -```cpp -// InProcess: Pointer = T* (real pointer) -struct InProcess { - template - using Pointer = T*; -}; - -// External: Pointer = StoredPointer (just a number) -template -struct External { - template - using Pointer = StoredPointer; -}; -``` - -From `swift/include/swift/Remote/MemoryReader.h`: - -```cpp -class MemoryReader { -public: - virtual bool readBytes(RemoteAddress address, uint8_t *dest, uint64_t size) = 0; - virtual bool readString(RemoteAddress address, std::string &dest) = 0; - // ... -}; -``` - -## File Structure - -``` -Sources/ -├── MachOReading/ -│ └── Reading/ -│ ├── ReadingContext.swift # Core protocol -│ ├── MachOContext.swift # MachO implementation -│ └── InProcessContext.swift # InProcess implementation -├── MachOResolving/ -│ └── Resolvable+ReadingContext.swift # Resolvable extension -├── MachOPointers/ -│ └── Protocol/ -│ └── RelativePointerProtocol+ReadingContext.swift # Pointer extension -└── MachOSwiftSection/ - └── Protocols/ - └── RuntimeProtocol.swift # Extended with InProcess -``` +The comparison with the Swift runtime's `MemoryReader` the design follows, and where each part of the reading layer lives, are in MachOKitExtensions' implementation note. ## Migration Strategy @@ -261,7 +123,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.25.0, postponed twice 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; forwarders deleted 2026-11-11 for 0.25.0, see below | ## Benefits @@ -319,7 +181,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.25.0 删除(原定 0.23.0,下游未迁完而两次推迟)。下面是代码里看不出来、下次维护会踩的几点。 +每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份在 0.22.0 改成一行转发(`machO.context` / `InProcessContext.shared`)并标 `@available(*, deprecated)`,0.25.0 删除(原定 0.23.0,下游未迁完而两次推迟;2026-11-11 在 MachOReading / MachOResolving 迁入 MachOKitExtensions 的同一版删去)。下面几点是当年做转发时的取舍,转发虽已删除,以后给读取接口加重载时同样会遇到。 ### 转发必须原地保留 @@ -331,7 +193,7 @@ Two deliberate decisions worth keeping in mind: ### 约束扩展里的空指针 guard -在 `where Pointee: OptionalProtocol` 这类约束扩展里,按名字调用一个同时是协议 requirement 的方法,绑定的是 requirement,也就是无约束的 witness,而不是旁边那个约束重载。所以转发如果写成 `try resolve(at: offset, in: machO.context)`,就会跳过空指针 guard,去读空指针自己所在位置的字节。guard 因此放在一个私有 helper 里,由 `ReadingContext` 入口和各个转发共同调用(`RelativeDirectPointerProtocol` 等四个协议,以及 `PointerProtocol`、`SymbolOrElementPointer`)。 +在 `where Pointee: OptionalProtocol` 这类约束扩展里,按名字调用一个同时是协议 requirement 的方法,绑定的是 requirement,也就是无约束的 witness,而不是旁边那个约束重载。所以转发如果写成 `try resolve(at: offset, in: machO.context)`,就会跳过空指针 guard,去读空指针自己所在位置的字节。guard 因此放在一个私有 helper 里,由约束扩展里的 `ReadingContext` 入口调用,转发删除之前也由各个转发调用(`RelativeDirectPointerProtocol` 等四个协议,以及 `PointerProtocol`、`SymbolOrElementPointer`)。 ### 收成一份时修掉的分歧 @@ -345,16 +207,14 @@ Two deliberate decisions worth keeping in mind: ### 性能 -`InProcessContext` 的 tag 掩码在进程里只算一次;`UnsafeRawPointer.stripPointerTags()` 每次调用都要找当前镜像、遍历一遍 load command。`advanceAddress` 也会剥 tag,与旧指针版的 `resolveDirectOffset(from:)` 一致。`MachOContext.addressFromVirtualAddress` 不再在 `resolveOffset(at:)` 之前多剥一次,因为 `MachOFile.fileOffset(of:)` 与 `MachOImage.resolveOffset(at:)` 自己会剥;它与 `addressFromOffset`、`offsetFromAddress` 一起声明成不抛错。 +本进程地址的 tag 掩码、`MachOContext` 的地址换算、`MachOFile` 只对 dyld cache 里的镜像问 cache 文件、读取直接用 MachOKit 打开文件时做的映射(演进提案 `machofile-performance`),这些取舍随读取层搬到了 MachOKitExtensions,写在它的实现说明里。本库留下两个经本库样本或元数据验证的回归测试:`StandaloneFileReadingTests`(打开 fixture 的副本后把它的路径换成 dyld cache 的头部,读取仍须读到原文件的内容),以及 `FileMappingTests` 里在 256 个描述符的上限内读完 400 个 Swift 镜像的那一个;只测映射本身的另外三个随模块搬走了。 ### 缓存范围:上层只读接口也收成一份 上层有一批接口只读数据,却因为要按镜像缓存而离不开 `machO`:`SymbolicDemangler` 的 `demangleType` / `demangleContext`、SwiftDeclaration 的 `typeName` / `protocolName`、`GenericContext+Dump` 等。`ReadingContext` 原先说不出自己读的是哪个镜像,所以 `SymbolicDemangler` 的 context 入口干脆不走缓存。现在 `ReadingContext` 多了一条带默认值的 requirement `cacheScope`:`MachOContext` 答 `.image(identifier:)`,`InProcessContext` 答 `.process`,其余一律 `.uncached`。反混淆 memo 与节点驻留池按它选层,这批接口因此也收成了只收 context 的一份。 - **同一个镜像只有一个键**:`.image` 带的就是 reader 的 `MachOTargetIdentifier`,两个缓存用现成的 `SharedCacheKey(identifier:)` 建键,与 `SharedCacheKey(machO)` 得到的是同一个键。经 reader 和经 context 存进去的条目是同一条,`SymbolicDemangler.removeCache(for:)` 与驱逐注册表照常认领、清理。 -- **身份不装箱**:每次 memo 查找都要问一次 `cacheScope`。文件的 identifier 是路径加 UUID,放不进 existential 的 24 字节内联缓冲,包成 `AnyHashable` 每次都要堆分配,而 `SharedCacheKey` 当初就是为了去掉这次分配才写成现在的样子(见 [Modules/MachOCaches.md](Modules/MachOCaches.md)「键」一节)。所以 `.image` 的载荷是具体类型 `MachOTargetIdentifier`,不是 `AnyHashable`。代价是 identifier 不是这个类型的读者经 context 读时不缓存(`MachOContext` 答 `.uncached`),只慢不错;今天的读者(`MachOFile`、`MachOImage`、MachOKitUI 的包装类型)全都是这个类型。 -- **默认不缓存是安全边界,不是省事**:全进程那层按偏移做键,只有地址是绝对地址时两个镜像才不会撞。一个以文件偏移为地址的第三方 context 如果落进去,会把 A 镜像的解析结果当成 B 镜像的返回。 -- **只暴露缓存身份,不暴露 Mach-O**:`.image` 带的是 reader 的 `identifier`,不是 reader 本身,调用方拿它做不了符号查询或 `as? MachOFile`,延续提案 0018「`ReadingContext` 只管读」的定位。`SymbolicDemangler` 查符号仍走它私有的 `SymbolLookupContext` 转型。 +- `cacheScope` 本身的设计取舍(身份为什么不装箱、默认不缓存为什么是安全边界、为什么只暴露缓存身份而不暴露 Mach-O)随读取层搬到了 MachOKitExtensions 的实现说明。本库这边要守的一条:`SymbolicDemangler` 查符号仍走它私有的 `SymbolLookupContext` 转型,不靠 `cacheScope` 拿读取器(提案 0018「`ReadingContext` 只管读」)。 ### 这次没动的已知缺口 @@ -368,7 +228,7 @@ Two deliberate decisions worth keeping in mind: 现在的规则: - **读取器种类只问三个取法**(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 的内部协议,外面的包装类型遵循不了。 +- **能力协议先问自己、再问底下的读取器**:`MachOContext.bindRebaseResolver` 先看包装类型自己是否遵循 `MachOBindRebaseResolving`,没有就用 `underlyingReader` 的;建 ObjC 索引用的 `objcImplementationClassReader` 直接取 `underlyingReader`,因为 `ObjCImplementationClassReading` 是 SwiftObjCInterop 的内部协议,外面的包装类型遵循不了。 - **按类型在编译期选策略的协议给包装类型默认实现**:`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`。 @@ -376,16 +236,5 @@ Two deliberate decisions worth keeping in mind: 没动的:按类型静态约束的 API(`GenericSpecializer where MachO == MachOImage`、`ImageUniverse.dependencyClosure(root:)`、`DependencyClosure` 的两个约束扩展)不是运行时判断,持有包装类型的宿主自己传 `base`。 -## Future Considerations - -1. **Async Support**: Add `AsyncReadingContext` for async reading operations -2. **Caching**: Add optional caching layer to `ReadingContext` -3. **Remote Reading**: Add `RemoteProcessContext` for reading from other processes -4. **32-bit Support**: `MachOContext` could dynamically select `RuntimeTarget32` based on MachO header - -## References - -- Swift Runtime: `swift/include/swift/ABI/TargetLayout.h` -- Memory Reader: `swift/include/swift/Remote/MemoryReader.h` -- Metadata Reader: `swift/include/swift/Remote/MetadataReader.h` +本库的 `ReaderKindCastScanTests` 只扫本库自己的 `Sources/`;搬到 MachOKitExtensions 的 MachOReading / MachOResolving 由那个包里的同名扫描守着。 - Reflection Context: `swift/include/swift/RemoteInspection/ReflectionContext.h` diff --git a/Documentations/Internal/References/SwiftGenericsDeclarations.md b/Documentations/Internal/References/SwiftGenericsDeclarations.md index e96ea53d6..c807282ee 100644 --- a/Documentations/Internal/References/SwiftGenericsDeclarations.md +++ b/Documentations/Internal/References/SwiftGenericsDeclarations.md @@ -828,7 +828,7 @@ Subscript 用 `subscript` 关键字引入。它们只能作为 nominal type 和 每条 storage declaration 都有一组 **accessor declaration**,它们是一种特殊的 function declaration。在 declaration context 的层级里,accessor declaration 是 storage declaration 的兄弟节点。Accessor 的 interface type 取决于 accessor 的种类。例如 getter 返回值,setter 则把新值作为参数接收。变量的 accessor 不接收任何其它参数;subscript 的 accessor 还会接收 subscript 的 index 参数。本书不再需要关于 accessor 和 storage declaration 的更多细节。 -> 译注:这组 accessor declaration 在二进制里表现为一族独立的符号(`g`/`s`/`m` 等后缀),本库的 `DefinitionBuilder` 要把它们按所属成员重新分组,才能还原出「一个 computed property」而不是散落的若干函数;stored `var` 的 accessor 组一度在按字段名去重时被丢弃,以及 lazy 字段应当打印调用方可见的 getter 类型而非 `Optional` 存储类型这两件事,见 [FinalKeywordAndLazyAccessorTypeRecovery.md](../FinalKeywordAndLazyAccessorTypeRecovery.md)。 +> 译注:这组 accessor declaration 在二进制里表现为一族独立的符号(`g`/`s`/`m` 等后缀),本库的 `MemberDefinitionBuilder` 要把它们按所属成员重新分组,才能还原出「一个 computed property」而不是散落的若干函数;stored `var` 的 accessor 组一度在按字段名去重时被丢弃,以及 lazy 字段应当打印调用方可见的 getter 类型而非 `Optional` 存储类型这两件事,见 [FinalKeywordAndLazyAccessorTypeRecovery.md](../FinalKeywordAndLazyAccessorTypeRecovery.md)。 ## Source Code Reference diff --git a/Documentations/Internal/References/SwiftGenericsIntroduction.md b/Documentations/Internal/References/SwiftGenericsIntroduction.md index edcd968ed..ff8d0a3d0 100644 --- a/Documentations/Internal/References/SwiftGenericsIntroduction.md +++ b/Documentations/Internal/References/SwiftGenericsIntroduction.md @@ -99,7 +99,7 @@ Generic signature 连同解析好的参数类型与返回类型,被打包成 <τ_0_0> (τ_0_0) -> τ_0_0 ``` -> 译注:「名字不重要、depth 与 index 才是身份」这条事实,在二进制里表现得最直白——mangled name 只编码 depth 与 index,generic parameter 的源码名字根本没有落盘。本库的 demangler 把符号解回 `Node` 树时拿到的就是这套坐标,随后按位置重新取名 `A`、`B`……见 [Modules/MachOSymbols.md](../Modules/MachOSymbols.md)。 +> 译注:「名字不重要、depth 与 index 才是身份」这条事实,在二进制里表现得最直白——mangled name 只编码 depth 与 index,generic parameter 的源码名字根本没有落盘。本库的 demangler 把符号解回 `Node` 树时拿到的就是这套坐标,随后按位置重新取名 `A`、`B`……见 [Modules/SwiftSymbols.md](../Modules/SwiftSymbols.md)。 **Interface type** 完整描述了「引用一个声明」这件事在类型检查中的行为。算出函数的 interface type 之后,type checker 转向函数体。`return` 语句里表达式的类型必须与函数声明的返回类型匹配。类型检查 `return` 后面的表达式 `x` 时,我们用 name lookup 找到参数声明 `_ x: T`。这条参数声明的 interface type 是 generic parameter type `T`,它要相对于函数的 generic signature 来理解。但赋给这个表达式的类型,是 `T` 所对应的 **archetype**,记作 `⟦T⟧`。我们后面会学到,archetype 是 type parameter 的一种自描述形式,它的行为像一个具体类型。 diff --git a/Documentations/Internal/References/SwiftGenericsTypeResolution.md b/Documentations/Internal/References/SwiftGenericsTypeResolution.md index 9a56a0736..b3b7e4c32 100644 --- a/Documentations/Internal/References/SwiftGenericsTypeResolution.md +++ b/Documentations/Internal/References/SwiftGenericsTypeResolution.md @@ -69,7 +69,7 @@ Structural resolution stage 虽然跳过了一部分语义检查,却仍然可 **identifier type representation** 是单个 identifier,它命名了某个外层 scope 里的一个 type declaration。我们从该 type representation 的 source location 出发,用 unqualified lookup 找到 **resolved type declaration**(见 `compilation-model.tex`(中译 [SwiftGenericsCompilationModel.md](SwiftGenericsCompilationModel.md))(中译 [SwiftGenericsCompilationModel.md](SwiftGenericsCompilationModel.md))的 Name Lookup 一节)。然后构造 resolved type:随 type declaration 的种类不同,它会是 nominal type、type alias type、generic parameter type 或 dependent member type。下面先看几个例子,再讲一般原理。 -> 译注:本库也有一套「按名字找类型」的机制,只不过找的是 Mach-O 镜像里的 type descriptor:先在根镜像的 `__swift5_types` 里找,miss 了再按依赖闭包的广度优先顺序逐个镜像折进来。规则见 [MachODependencies.md](../Modules/MachODependencies.md) 与 [StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md)。 +> 译注:本库也有一套「按名字找类型」的机制,只不过找的是 Mach-O 镜像里的 type descriptor:先在根镜像的 `__swift5_types` 里找,miss 了再按依赖闭包的广度优先顺序逐个镜像折进来。规则见 MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) 与 [StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md)。 ### Nominal types. diff --git a/Documentations/Internal/References/SwiftGenericsTypes.md b/Documentations/Internal/References/SwiftGenericsTypes.md index a9eddee73..5d65edb28 100644 --- a/Documentations/Internal/References/SwiftGenericsTypes.md +++ b/Documentations/Internal/References/SwiftGenericsTypes.md @@ -115,7 +115,7 @@ var x: Element 更一般地,可以这样变换一个类型:按 kind 把它拆开,递归地变换每个 structural component,再由新的 component 组出一个同 kind 的新类型。先预告一下 `substitution-maps.tex`(中译 [SwiftGenericsSubstitutionMaps.md](SwiftGenericsSubstitutionMaps.md)):若 `Element` 是一个 generic parameter type,那么把 `Array` 里的 `Element` 换成 `Int` 就得到 `Array`,这叫 **type substitution**。编译器提供了各种工具来简化「按 type kind 做递归遍历与变换」的实现,type substitution 就是这类变换的一个例子。 -> 译注:本库拿到的是这棵类型树被 mangler 序列化之后再 demangle 回来的形态——一棵 `Node` 树。结构完全同构:`Node.Kind` 对应本章的 type kind,子节点对应 structural component,「不可变、整棵替换」这条纪律在本库里同样成立(`NodeReference` 走 intern 后共享,任何改写都是重建)。索引与共享机制见 [MachOSymbols.md](../Modules/MachOSymbols.md) 与 [SharedNodeStoreMigration.md](../SharedNodeStoreMigration.md)。 +> 译注:本库拿到的是这棵类型树被 mangler 序列化之后再 demangle 回来的形态——一棵 `Node` 树。结构完全同构:`Node.Kind` 对应本章的 type kind,子节点对应 structural component,「不可变、整棵替换」这条纪律在本库里同样成立(`NodeReference` 走 intern 后共享,任何改写都是重建)。索引与共享机制见 [SwiftSymbols.md](../Modules/SwiftSymbols.md) 与 [SharedNodeStoreMigration.md](../SharedNodeStoreMigration.md)。 ### Canonical types diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 7bd3950b8..4220fbbf6 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -172,6 +172,7 @@ - **与 main 基线对比**:标注是 PR #111 新增,无基线可比。 - **既往修复**:无。 - **复审条件**:出现「实现符号保留而 `To` thunk 被选择性剥除」的真实输入(自定义 strip 脚本 / 非常规链接产物)。届时 dump 侧已有的 `containsSymbol(named: name + "To")` 口径可以直接搬到 interface 侧作第二道豁免。 +- **2026-10-27 复核**:论证 ② 的前提「未剥离时实现符号与 `To` thunk 同在」不成立。整模块优化的 app 会把 internal `@objc` 成员的函数体内联进 thunk、删掉实现符号,只留 thunk(issue #137,Xcode 27.2 的 `Xcode Service` 里 22 个)。这种成员原先根本不进模型,没有行可标;现在由 thunk 造的替身建出(提案 `thunk-only-objc-members`),`applyThunkAttributes` 照常打 `@objc`,豁免照常生效。裁决不变,也不是上面的复审条件。 --- @@ -685,6 +686,7 @@ - **二、离线特化把 `.metadata` 实参当指针用,文件里读出的 `Metadata` 会成野指针**:不成立。离线 `specialize` 的文档(`GenericSpecializer+StaticSpecialization.swift` 开头)与 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md) 都写明 `.metatype` / `.metadata` / `.specialized` 是宿主进程自己的类型;`.specialized` 的 `metadata()` 先从内存读 kind,只可能是已经解引用过的进程内地址。在线路径对 `.metadata` 一直有同样的前提,误用时同样会崩,不是本 PR 引入的新风险。 - **三、特化后的泛型 enum 跳过解析不出的 payload,会算出错误的 Enum Layout**:不成立。`RuntimeFieldLayoutBackend` 在打印布局前用 value witness table 的 size 交叉校验(`impliedTotalSize` 与 `typeLayout.size` 不等就不出注释),这条校验是 `12232bee` 专门为这类缺口加的,对特化的泛型 enum 同样生效;跳过 payload 只会让注释消失,不会印出错的布局。非泛型 enum 在基线上就这样跳过。 - **四、`GenericParameterDepthLayout` 跳过匿名上下文,让泛型方法的 opaque 描述符层号算错、thunk 名字跟着错**:不成立。层结构确实把方法的参数与 opaque 参数并成一层,但 kind-9 thunk 的实参缓冲只按命名声明的签名绑定(编译器 `AbstractMetadataAccessor::emit` 取 `O->getGenericSignature()`),不含 opaque 参数;两种层结构只在第三个字及以后不同,那里放的是 witness table,从不被命名。基线用 `AccessorThunkOwnerLayout(genericContext:)` 算出的是同一个结构,PR 只是把计算挪了位置。 +- **四的复审(2026-10-31)**:结论不变,前提的描述过时了。opaque 描述符的层布局已改由 `GenericParameterDepthLayout.make(forOpaqueType:genericContext:in:)` 计算([ProjectEvolutionLog](ProjectEvolutionLog.md) 第 118 节):匿名上下文增加参数也开一层,方法的参数与 opaque 参数各占一层,不再「并成一层」。就这一条说的泛型方法而言,thunk 实参的命名不受影响:实参缓冲仍只含命名声明的参数,它们在两种结构下的坐标相同。但「跳过匿名上下文无害」只在泛型方法上成立:Debug 构建里属性的 opaque 类型挂在一个带着类型泛型签名、父级却是类型父级的匿名上下文下,跳过它就找不到类型,provider 给约束定的层号与 opaque 改写给实参的分层都会算错,RuntimeViewer 的 Debug 构建因此 trap,这次一并修掉。 - **既往修复**:无。 - **复审条件**:上面任何一条的前提被改动——打印器或 RuntimeViewer 改了追加扩展的条件;离线特化开始接受文件里读出的 `Metadata`;enum 布局的 size 交叉校验被拿掉;thunk 的实参缓冲开始带 opaque 参数。 @@ -769,6 +771,7 @@ - **为什么暂缓**:修法简单(`.direct` 的目标按运行时地址解析;槽位解析为 `.unrecognized` 时退回名字),但仓库规则要求修复带修复前失败的测试,本机没有 26.x 的进程可扫。 - **既往修复**:无。第一批(`0c0ebce3`)在 macOS 27.2 上写成,那时缓存已无桩。 - **复审条件**:有 macOS 26 或 iOS 26 的环境可跑测试(另一台机器、或用户批准的 Simulator)——那时先写测试再修,同时让 RuntimeViewer 的调用者键带上改名再导出的别名(只有按名字报的调用需要它)。 +- **复核(2026-10-27,macOS 26.6)**:在 26.6 的机器上看过,仍复现不了。AppKit、Foundation、SwiftUI、libswiftCore 的 `__auth_stubs` 全是经槽位的四条指令(`adrp x17` / `add x17` / `ldr x16, [x17]` / `braa`,各 4,815、2,832、6,588、224 个),没有 `.direct` 形态,所以上面「macOS 26 及更早的缓存里有」的说法至少对 26.6 不成立。继续暂缓,复审条件改为能拿到 iOS 26 真机或更早 macOS 的缓存。同一轮另有一种桩 MachOKit 也读不出槽位:ld64 改写过的 `nop` / `ldr x16, <槽>` / `br x16`,已由 `ARM64Trampoline` 补读(第二轮审查第 1 条的横向排查,见 [2026-10-27 审查记录](../../Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md))。 --- @@ -901,3 +904,127 @@ - **为什么不修**:diff / evolution 的 `associatedtype` 行按名字逐行比较、不带约束,约束挪过去就丢了。显式传值正是为了防这件事,提案 [0073-protocol-requirement-placement](../Evolutions/0073-protocol-requirement-placement.md) 的决策日志记了这个选择。 - **既往修复**:无。 - **复审条件**:diff 开始比较每个关联类型的约束(那时 `associatedtype` 行要带上约束,协议头才能按配置走)。 + +--- + +## A76 — 目标算得出来的寄存器调用仍记成没有目标的 `.indirect`(交叉引用第二轮审查 3) + +- **裁决**:不修(2026-10-27,数据裁决)。 +- **发现**:`ReferenceScanner.indirectReference(through:at:in:kind:)` 只记载入的偏移与指针认证常量,不看寄存器里有没有已知的地址或槽位。`adrp` / `add` 算出函数地址、或从 GOT 槽载入后再 `blr` 的调用,目标算得出来,仍报成 `.indirect`。 +- **复现 / 是否误报**:属实。macOS 26.6 的 AppKit 有 15,034 处 `blr`,目标算得出来的约 100 处,其中 97 处是从全局变量载入的函数指针,多是软链接的函数指针,变量里放的是运行时才写入的值。抽查的一个第三方 App 有 314 处,312 处调的是 `___chkstk_darwin`,即编译器为大栈帧插入的栈探测。 +- **与 main 基线对比**:模块在 0.24.0 新写,0.23.0 没有。 +- **为什么不修**:算得出目标的不到 1%。其中多数是变量里的运行时状态,按扫描「只记确定的事」的规矩不该当成目标;剩下的栈探测函数没有查询价值。 +- **既往修复**:无。 +- **复审条件**:某类常见代码让这种调用的占比明显变大,比如某个编译器版本改为经寄存器调用跨库函数。 + +--- + +## A77 — `swiftTypeIdentity(ofDescriptorAt:)` 每次都把镜像里的类线性走一遍(交叉引用第二轮审查 10) + +- **裁决**:暂不修(2026-10-27)。 +- **发现**:`ObjectiveCClassIndex.swiftClassObject(describedBy:)` 为找描述符对应的 Swift 类,逐个检查镜像里的全部类;`swiftTypeIdentity(ofDescriptorAt:)` 对结构体、枚举的描述符也照样走一遍。RuntimeViewer 在 `CrossReferenceQuery.swift` 里为每条 Swift 类型结果调一次。 +- **复现 / 是否误报**:写法属实。估算每次几十微秒;没有实测,在用的 10 核 Mac Studio 不适合做性能测量。 +- **与 main 基线对比**:0.24.0 新写。 +- **为什么不修**:一次查询的结果通常几十到几百条,合计在毫秒级。修法便宜:先看描述符的种类是不是类,或者为类索引建一张「描述符 → 类」的表。等有实际需要再做。 +- **既往修复**:无。 +- **复审条件**:RuntimeViewer 的大结果列表出现可感知的卡顿,或在更强的机器上测得单次超过 100 微秒。 + +--- + +## A78 — 没有 `…Mn` 符号的类型算 key 时,demangle 的结果留在按镜像的缓存里(交叉引用第二轮审查 5,**有意设计**) + +- **裁决**:不修(2026-10-27)。 +- **发现**:`SwiftTypeIndex.key(ofDescriptorAt:)` 与 `ImageFallbackNames` 给类型起名时,没有符号就调 `SymbolicDemangler.demangleContext`,结果记在按镜像的 `SharedCache` 里;分析器的 `releaseImageData(exceptForImagesAt:)` 不碰这份缓存。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:0.24.0 新写。 +- **为什么不修**:有意设计。上一轮审查的 B2(`6d3b80ed`)把类型查询里不受控的 demangle 改成用完即弃,同时写明保留这份按镜像的记忆。它和库里其它按镜像的缓存一样归 `SharedCacheRegistry` 管,宿主调 `evictImagesWithoutLiveOwners()` 就能回收,这是库统一的释放方式,理由仍成立。模块文档原先说它「随镜像淘汰」,容易读成 `releaseImageData` 会放掉它,这次改写成由宿主经注册表回收。 +- **既往修复**:B2(`6d3b80ed`)处理过同一片代码,这一处是当时有意留下的。 +- **复审条件**:分析器要求一次放干净它碰过的所有按镜像状态;或实测这份缓存在 RuntimeViewer 里占用可观。 + +--- + +## A79 — `isMapped` 一类函数线性查找映射区间(交叉引用第二轮审查 7) + +- **裁决**:不修(2026-10-27,数据裁决)。 +- **发现**:`isExecutable(runtimeAddress:length:)`、`isMapped(runtimeAddress:length:)`、`mappedLength(fromRuntimeAddress:)` 对区间数组线性查找;数组是缓存的每个映射加上缓存外镜像的每个段,几百项。审查认为每次发送都要查,全缓存「上千万次」。 +- **复现 / 是否误报**:写法属实,量级不成立。这几个函数只在解析调用目标(每个目标由扫描器记住,只解析一次)、读槽位、读 selector 字符串和 mangled 名字时用到。macOS 26.6 的 AppKit 里 148,494 处发送经 selector 桩,不查;要查的只有传统发送 174 处与 super 发送 7,859 处,约占发送的 5%。 +- **与 main 基线对比**:0.24.0 新写。 +- **为什么不修**:次数不大,每次也只是几百次比较,扫描时间不花在这里。同类的性能发现 A66 也是看过数据后判的不修。 +- **既往修复**:无。 +- **复审条件**:profiling 显示这几个函数占扫描时间可观。修法现成:区间排序后二分查找。 + +--- + +## A80 — 懒绑定的槽位可能指向 `__stub_helper`(交叉引用第二轮审查 4,**误报**) + +- **裁决**:误报(2026-10-27)。 +- **发现**:审查认为不用 chained fixups 的懒绑定二进制,槽位在第一次调用前指向镜像自己的 `__stub_helper`,扫描直接读槽会把调用解析到那里。 +- **复现 / 是否误报**:造不出。dyld 在加载时就绑定每个槽位,懒指针也一样。`LazyBindingTests` 现编一个部署目标 macOS 11、`-no_fixup_chains` 的 dylib,以 `RTLD_LAZY` 加载,断言函数第一次被调用之前槽里已经是 `puts`;macOS 27.2 上通过,2026-10-27 在 macOS 26.6 上也通过。 +- **与 main 基线对比**:—。 +- **为什么判误报**:这个测试就是为该场景设的哨兵,模块文档「缓存外镜像的 GOT 槽」一节写着依据。 +- **既往修复**:无。当初有意这样设计,并留了哨兵。 +- **复审条件**:`LazyBindingTests` 变红。那时让解析失败的桩退回导入名,修法与 A64 的后半相同。 + +--- + +## A81 — MachOKit 的 `StubDecoder` 读不出 ld64 改写过的桩的槽位(交叉引用第二轮审查第 1 条的横向排查,上游缺口) + +- **裁决**:不报上游,也不在 fork 里修(2026-10-27,用户决定暂不处理)。 +- **发现**:ld64 按 linker optimization hint 把桩改写成 `nop` / `ldr x16, <槽>` / `br x16` 之后,MachOKit(0.54.101)的 `StubDecoder` 不认这种形态,`Stub.branch` 给 `.unknown`,读不出槽位。`StubDecoder` 是上游作者写的,上游的 MachOKit 同样如此。 +- **复现 / 是否误报**:属实。Asset Catalog Viewer(macOS 12 SDK)的 212 个桩全是这种形态;`LinkerOptimizationHintTests` 里改写过的桩,本库补读之前只认出 `.importedSymbol("_puts")`。 +- **与 main 基线对比**:缺口在依赖里,一直都有;本库从 0.24.0 的交叉引用分析起用 MachOKit 解桩。 +- **为什么不修**:用户决定暂不向上游报,也不在 fork 里改。本库已经不靠它:`ImageFunctionTable` 在 MachOKit 给不出 `.viaSlot` 时,用 `ARM64Trampoline` 读桩自己的字节取槽位;SwiftThunkAnalysis 认桩本来就从文件读出字节交给 `ARM64Trampoline`,不经 `StubDecoder`。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Analysis/CrossReferenceAnalysis/Scanning/ImageFunctionTable.swift` 的 `trampoline(in:)` 回退。 +- **复审条件**:本库有新代码直接拿 MachOKit 的 `Stub.branch` 取槽位、不经 `ARM64Trampoline`;或上游自己修了 `StubDecoder`,那时这个回退成了多余,可以删。 + +--- + +## A82 — 单字母的泛型参数(交叉引用第二轮审查第 12 条的同类) + +- **裁决**:暂不清理(2026-10-27,用户决定暂不安排)。 +- **发现**:第 12 条把 `pc`、`lhs` / `rhs` 这些缩写的名字改成了完整的名字;同类的单字母泛型参数(``、`` 一类)没有一起改。审查时数过,`Sources` 约 167 处、`Tests` 约 126 处,其中一部分在字符串里。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:main 上同样有,分布在各模块,不是这次的改动引入的;这次的修复批次一处也没有新加。 +- **为什么不修**:用户决定暂不安排清理。改名不改行为,但公开泛型类型的参数名可能被下游的 extension 按名字用到,真要清理时那部分要连同下游一起改。`AbbreviatedIdentifierScanTests` 只扫 `pc`、`lhs`、`rhs`,不管泛型参数。 +- **既往修复**:没有专门清理过。提案 [0044-opaque-parameters-for-single-use-generics](../Evolutions/0044-opaque-parameters-for-single-use-generics.md)(`7d429938`)把只用一次的泛型参数改写成 `some P`,为的是去掉多余的泛型参数列表,剩下的没有改名;`4e8f4a7f`(2026-10-08)只改了特化器新代码里的缩写。 +- **复审条件**:用户安排清理时。这条只覆盖已有的这些;改动里新加的单字母泛型参数照常算发现。 + +--- + +## A83 — `@Observable` 的折叠特例叠在共享的字段渲染上(2026-11-16 代码库体检,结构类,**有意设计**) + +- **裁决**:不修(2026-11-16,用户确认)。 +- **发现**:`SwiftDeclarationPrinter+Headers.swift` 的 `renderedModelFieldDeclarations` 为 `@Observable` 分了 `ModelMembersSelection` 三种模式(`.typeBody`、`.observableMacroExpansion`、`.observableMacroComputedProperties`),`.typeBody` 下还有几个分支各自组合可见性,成员循环里另外穿着 `folding` 与 `marksObservationIgnored`。下一个要折叠的宏还得在同一个函数里加模式和分支。 +- **复现 / 是否误报**:结构属实,没有错误输出。 +- **与 main 基线对比**:`f0fd4447`(2026-11-11)引入,main 上没有。 +- **为什么不修**:提案 [0093-observable-macro-folding](../Evolutions/0093-observable-macro-folding.md) 有意把折叠接进字段块与成员块,为的是展开形态与折叠形态用同一套打印代码,两种形态的注释逐字节一致。拆成「各个宏的折叠规则先产出字段列表、字段渲染只消费列表」要动这套共用,眼下只有一个宏,收益不抵风险。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` 的 `renderedModelFieldDeclarations`;体检报告 [CodebaseAudit20261116](Reviews/CodebaseAudits/CodebaseAudit20261116.md)。 +- **复审条件**:出现第二个要折叠的宏时。 + +--- + +## A84 — 交叉引用索引里同一条指令上几条引用的先后每个进程不同(2026-11-16 代码库体检,**不修**) + +- **裁决**:不修(2026-11-16,用户确认)。 +- **发现**:`CodeReferenceIndex` 查询结果先按指令排,同一条指令上的引用再按分组号排,而分组的顺序取自 `keyedTargets` 字典的遍历(`Models/CodeReferenceIndex.swift:117`、`:291`),Swift 的 `Hasher` 每个进程随机播种。一次查 `{.selector("alloc"), .selector("init")}` 两个键时,`objc_alloc_init` 那条指令上的两条发送谁先谁后每个进程都可能不同;扫描路径 `references(to:inImageAt:)` 固定 `alloc` 在前。类型文档说两条路径的答案一致。 +- **复现 / 是否误报**:属实,只差顺序,内容一致。 +- **与 main 基线对比**:`3ca49d4d`(2026-10-18)的索引在 main 上也有;同一条指令上出现两条引用要等 `e64b1085`(2026-10-27,入口点发送)之后,那部分 main 上没有。 +- **为什么不修**:宿主只拿结果显示调用者,不逐数组比较两条路径;现有测试也不比这种组合。要修只是在分组时按键排序,代价很小,但眼下没有消费者受影响。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift`;体检报告 [CodebaseAudit20261116](Reviews/CodebaseAudits/CodebaseAudit20261116.md)。 +- **复审条件**:有宿主或测试开始逐数组比较索引与扫描两条路径的结果,或类型文档要继续承诺「答案完全一致」时。 + +--- + +## A85 — `reader-benchmark` 用 `print` 输出测量结果(2026-11-16 代码库体检,规则类,**有意如此**) + +- **裁决**:不修(2026-11-16,用户确认)。 +- **发现**:全局指令「编码风格」要求打日志不用 `print`;`Sources/Executables/reader-benchmark/ReaderBenchmark.swift:221-232` 用 `print` 输出测量结果。 +- **复现 / 是否误报**:写法属实,但输出的是基准的结果,不是日志。 +- **与 main 基线对比**:`b28d8887`(2026-11-06)引入,main 上没有。 +- **为什么不修**:基准可执行文件的标准输出就是它的产品;`swift-section` 经 `StandardStreamOutput` 的规定只管那个 CLI,`reader-benchmark` 不随库发布。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Executables/reader-benchmark/ReaderBenchmark.swift`;体检报告 [CodebaseAudit20261116](Reviews/CodebaseAudits/CodebaseAudit20261116.md)。 +- **复审条件**:它被并进 `swift-section`,或开始输出诊断与进度信息。 diff --git a/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261116.md b/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261116.md new file mode 100644 index 000000000..e8a7d7837 --- /dev/null +++ b/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261116.md @@ -0,0 +1,281 @@ +# 代码库体检 2026-11-16 + +- **分支与提交**: `next` @ `1ba927ad`(工作树干净) +- **范围**: 首次体检。改动集取近 30 天:`42cbf5d4`(2026-10-17)到 HEAD,`Sources/` 下 443 个文件、+25,658 −3,228 行,分四块派 finder 深审严重 bug,另各派一个 finder 看结构与冗余。改动集的量已经达到一轮的深审上限、覆盖了大半模块,本轮不轮转。全仓机械扫描照常跑。 +- **降级**: 本机没有 `jscpd` / `pmd`,重复代码全靠人工判断;仓库没有 `.swiftlint.yml`,没跑 lint;`Tests/` 不在审查范围(见账本「不审」)。 +- **对照已裁决清单**: 跳过 4 条(A62 交叉引用的手写锁、A82 存量单字母泛型参数,以及复核时引用的两条有文档的有意设计:`OSLogEventHandler` 的 `os.Logger` 豁免、`ImageReference` 读失败当空表)。没有推翻任何已裁决条目。 +- **子 agent**: 6 个 finder + 2 个复核;补漏在主线程做。 + +## 总评 + +近 30 天新增的代码以 ObjC 互操作(`SwiftObjCInterop`,把 ObjC 类、category、协议按 ClangImporter 的规则导入成 Swift 声明)和交叉引用分析为主,严重 bug 也集中在这两块:确认 7 条、待确认 2 条,没有丢数据或安全问题,崩溃类的都要畸形或少见的输入才触发。最该先处理的是两条常见路径上的错误输出:`[self class]` 之后的类方法发送被交叉引用记到实例上,以及所有 `const char *` 成员被印成可变指针。`@BitField` 迁移(125 个 ABI 文件)逐条核过位置与宽度,没有问题。结构上的主要代价是 ObjC 互操作这批新代码里有四处成对的重复,和三份同构的 dyld cache 共享登记表。 + +## 严重 bug + +### 1. 交叉引用把 `[self class]` 之后的类方法发送记成发给实例 + +- **位置**: `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift:211-215`、`Sources/Analysis/CrossReferenceAnalysis/Scanning/ReferenceScanner.swift:142-143`、`:358` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `ClassOfReceiverSendTests`。 +- **失败场景**: ObjC 实例方法里写 `[[self class] baz]`,编出来是 `objc_opt_class(self)` 再 `objc_msgSend`。扫描把 `objc_opt_class` 当成「原样返回参数」,调用后 `x0` 仍记作 `.methodReceiver`(实例),`receiverHint` 于是把对 `+baz` 的发送记成发给方法自己的接收者。宿主按接收者区分实例方法与类方法时,`+[Foo baz]` 的真实调用者被漏掉或算到 `-baz` 头上。`objc_opt_class` 只对类字面量是原样返回,对实例返回的是它的类。 +- **能复现吗**: 能。任何 `[self class]`、`[[self class] alloc]` 的写法都会触发,ObjC 代码里很常见。 +- **新的还是旧的**: `59631757`(2026-10-17,report Objective-C class references)把 `objc_opt_class` 归进「返回传入的类」,和 `0c0ebce3`(2026-10-16)起就有的方法接收者跟踪叠在一起出错;`e64b1085`(2026-10-27)最后改过这段。首次体检,`main` 上也有。 +- **值不值得修**: 静默错误输出,RuntimeViewer 的「谁调用了这个方法」直接受影响。建议修:`objc_opt_class` 只在 `x0` 持有类字面量时保留状态,持有方法接收者时改记为「接收者的类」或清空。 +- **以前修过吗**: 没有。模块文档 `Modules/CrossReferenceAnalysis.md` 与提案 0072、0076 只讨论了类字面量接收者,当初的设计没考虑方法接收者经过 `objc_opt_class` 的情况,那个前提对这种情况不成立。 +- **同类实例**: 无。同一处并列的 `objc_opt_self` 与 `swift_getInitializedObjCClass` 对参数确实原样返回。 + +### 2. ObjC 协议要求:编码里的参数比 selector 的冒号少时数组越界崩溃 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCProtocolRequirements.swift:184-186` → `Sources/Analysis/SwiftObjCInterop/ObjCImporterNaming.swift:174` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `ObjCProtocolRequirementBuilderTests.anEncodingThatDoesNotFitTheSelectorIsNotImported`。 +- **失败场景**: `methodRequirement` 不核对编码的参数个数与 selector 的冒号数是否一致,就交给 `ObjCImporterNaming.importedName`;后者按冒号数建 `parameterIndices`,再用 `parameterTypes[$0]` 取类型。协议方法 `takeOne:andAnother:` 配上只有一个参数的编码(`v24@0:8@16`)就越界 trap。`dump` 与 `interface` 都走得到。 +- **能复现吗**: 机制确认。编译器正常产出的记录不会不一致,触发要靠第 8 条(待确认)的编码错位,或畸形二进制。 +- **新的还是旧的**: `e56ad3ff` / `ae6b78f0`(2026-10-28,@objc 协议要求的导入与命名),窗口内新出现,`main` 上没有。 +- **值不值得修**: 崩溃,修法便宜。建议修:在 `importedName` 入口统一校验参数个数,两条调用路径一起受益。 +- **以前修过吗**: 同类问题只修了一半。`b44b3391`(2026-11-10,never pair a selector with a short encoding)给类成员路径加了 `argumentMatchedMethodType`(`ObjCImportedMemberBuilder.swift:225-240`),提交说明写的正是 "trapped on the missing argument";协议要求这条路径没跟着改。 +- **同类实例**: `ObjCImporterNaming.swift:432` 的 `parameterTypes[0]`,在有冒号而编码没有参数时同样越界(未复核)。 + +### 3. `const char *` 成员被印成 `UnsafeMutablePointer` + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift:181`、`Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift:76` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `ObjCImportedMemberBuilderTests.aConstantCStringImportsAsAnImmutablePointer`。 +- **失败场景**: 解析器读到 `r` 时记下了 `isConst`,但 `case "*"` 直接返回 `.characterString`,把 const 丢了;导入映射对 `.characterString` 一律给 `UnsafeMutablePointer`。`- (const char *)UTF8String`(编码 `r*16@0:8`)于是印成可变指针,ClangImporter 给的是 `UnsafePointer`。 +- **能复现吗**: 能,所有 `const char *` 的属性、参数和返回值都会这样。 +- **新的还是旧的**: 解析在 `ae6b78f0`(2026-10-28),映射在 `9dca5805`(2026-11-10),窗口内新出现,`main` 上没有。 +- **值不值得修**: interface 里的类型错误,很常见。建议修:让 `.characterString` 带上 const,映射成 `UnsafePointer`。 +- **以前修过吗**: 没有。 +- **同类实例**: 无。其它指针的 const 在 `ObjCTypeEncoding.swift:188` 保留了,只有 `r*` 丢。 + +### 4. 另一模块的 Swift 类经 category 遵循本镜像的 `@objc` 协议时,witness 全部找不到 + +- **位置**: `Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCProtocolWitnesses.swift:96-101` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `ObjCProtocolDefinitionIndexingTests`(文件、进程内、strip 三个读法);修的时候发现文件里的同类问题,见文末「修复」。 +- **失败场景**: `memberTable` 对任何 `_TtC` 名字都先按 Swift 类查表,查不到直接 `return nil`,不回退 `table(forObjCClassNamed:)`;而按 Swift 名查表只认本镜像 classlist 里的类。本镜像写 `extension OtherModule.Foo: MyObjCProtocol`(`Foo` 是另一模块的 `NSObject` 子类)时,这个 conformance 的 witness 一律丢失。这与 `:92-95` 的注释(另一镜像的类按 runtime name 查)相反。 +- **能复现吗**: 能,条件是跨模块的 category 遵循,常见于 app 给框架类加协议。 +- **新的还是旧的**: `bf1e6d0a`(2026-10-28,tie stripped conformers and keep imported protocol names),窗口内新出现,`main` 上没有。 +- **值不值得修**: 静默丢失 witness 与成员归属。建议修:按 Swift 名查不到时回退按 runtime name 查。 +- **以前修过吗**: 没有。 +- **同类实例**: `Sources/Output/SwiftDump/Dumpable/ObjCCategoryProtocolAdoption+Dumpable.swift:56` 同样按 `_Tt` 前缀分流(见「规则」一节)。 + +### 5. 同名的 private 泛型类:第二个被去重丢掉,第一个的 ObjC 成员表套到两个定义上 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/SwiftClassWithoutClassObjectIndex.swift:168`(名字的生成在 `:345-346`) +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `SwiftClassWithoutClassObjectIndexTests.sameNamedPrivateGenericClassesAreBothListed`。 +- **失败场景**: 两个文件各有一个 `private class Foo: NSObject`,它们的 `name` 都是不带私有鉴别符的 `Mod.Foo`,`Storage` 按 `name` 去重时丢掉第二个,`namesBySwiftQualifiedName["Mod.Foo"]` 只剩一项。`ObjCMembers.table(forSwiftClassQualifiedName:)`(`ObjCMembers.swift:57-59`)本该在多于一项时拒绝猜,现在会把第一个类的成员表(`override`、selector 判定)同时安到两个 Swift 定义上。`:163-164` 的注释说多条目表示同名 private 类,对泛型类不成立。 +- **能复现吗**: 能,需要同模块里两个同名的 private 泛型 `NSObject` 子类,少见。 +- **新的还是旧的**: `c11e3a06`(2026-10-27,read the ObjC class data of Swift classes without a class object),窗口内新出现,`main` 上没有。 +- **值不值得修**: 少见,但结果是错的 `override` 与 `@objc(selector)`,不是漏印。建议修:去重键带上私有鉴别符或描述符偏移。 +- **以前修过吗**: 没有。同名私有类型的成员归属问题以前在 issue #115(`PrivateTypeMemberAttribution.md`)修过,那次修的是成员索引,不是这张表。 + +### 6. `@Observable` 类里手写的同名方法被当成宏生成的而藏掉 + +- **位置**: `Sources/Declaration/SwiftDeclaration/Indexing/Building/ObservableMacroExpansionRecovery.swift:161-174` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `ObservableMacroInterfaceTests.methodsNamedLikeTheGeneratedOnesArePrinted`、`ObservableMacroExpansionRecoveryTests.theGeneratedMethodsAreToldByTheirShape`。 +- **失败场景**: `isGeneratedFunction` 只比方法名与参数标签,不比参数类型;无参函数没有标签列表,`argumentLabels.isEmpty` 也算命中。用户在 `@Observable` 类里手写 `func shouldNotifyObservers()`,或写一个 `access(keyPath: String)` 重载,都会被计入 `generatedFunctions`(`TypeDefinition+ObservableMacro.swift:66-73`),interface 默认的折叠形态不印它。 +- **能复现吗**: 能,需要手写与宏生成成员同名的方法,少见。 +- **新的还是旧的**: `f423e26c`(2026-11-11,recover what the @Observable macro generated),窗口内新出现,`main` 上没有。 +- **值不值得修**: 静默丢成员。建议修:连参数类型一起比。 +- **以前修过吗**: 没有。提案 0093 只说宏生成的不印,没讨论手写同名的情况。 + +### 7. 畸形 export trie 让 `cursor + Int.max` 溢出,崩掉宿主进程 + +- **位置**: `Sources/Analysis/CrossReferenceAnalysis/Scanning/RenamedReexportIndex.swift:91` +- **判定**: CONFIRMED +- **状态**: 已修(同日),回归测试 `MalformedExportTrieTests`。 +- **失败场景**: `readULEB128` 能读出 0 到 2^64−1 的任意值。export trie 里终端大小 ≥ 2^63 时,`Int(clamping:)` 得 `Int.max`,`cursor + …` 溢出 trap。第一次跨镜像查调用者、或宿主调 `preparePrefilters()` 时走到。 +- **能复现吗**: 机制确认,只有畸形或人为构造的缓存外 dylib 会触发,编译器产出的不会。 +- **新的还是旧的**: `0bb8f963`(2026-10-17,look for the names other images re-export a function under),`main` 上也有。 +- **值不值得修**: 罕见,但崩的是宿主进程(RuntimeViewer 注入时是被查看的 App),修法一行。建议修:越界或溢出时把这个节点当畸形跳过。 +- **以前修过吗**: 没有。`:82-83` 的注释声明要容忍畸形 trie,这一处漏了。 +- **同类实例**: 无,全仓只有这一处 `Int(clamping:)` 后接加法。 + +### 8. 待确认:协议的某个方法列表读不出时,extended 类型编码整体错位 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCProtocolRecord.swift:149`(`MachOImage` 版在 `:189`),对齐逻辑在 `:82-88` +- **判定**: PLAUSIBLE +- **状态**: 已修(同日,随第 2 条),回归测试 `ObjCProtocolRequirementBuilderTests.extendedTypesThatDoNotFitTheirMethodsAreNotPaired`。 +- **失败场景**: 某个方法列表读不出或是 list-of-lists 时按 `[]` 处理,但 extended method types 仍按剩余方法的总数逐槽对齐,后面每个方法拿到的是别的方法的编码:协议要求静默印错参数与返回类型;参数个数对不上时,接着触发第 2 条的崩溃。`:108-111` 的注释防了「数组读一半」,没防「列表缺失」。 +- **能复现吗**: 缺证据:要找到一个 `methods(in:)` 对 `protocol_t` 的某个列表返回 nil 的真实二进制。`protocol_t` 正常不会是 list-of-lists。 +- **新的还是旧的**: `02b3d5f5`(2026-10-28,find the @objc protocols an image declares in Swift),`main` 上没有。 +- **值不值得修**: 待确认;建议和第 2 条一起修,读不出的列表按原位置占位,不压缩。 +- **以前修过吗**: 没有。 + +### 9. 待确认:编码里超大的 C 数组让导入卡死或耗尽内存 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift:97-100` +- **判定**: PLAUSIBLE +- **状态**: 已修(同日,用户看过报告后批准),回归测试 `ObjCImportedMemberBuilderTests.aCArrayImportsAsClangImporterImportsIt`。 +- **失败场景**: C 数组按编码里的元素个数建等长 tuple,个数没有上限,`readNumber` 能读到接近 `Int.max`。编码 `^[999999999c]` 会让 `map` 分配十亿个节点。正常的方法与属性编码里 C 数组会退化成指针,只有指向数组的指针或畸形编码能走到这里。 +- **能复现吗**: 缺证据:要一个真实二进制里出现大数组的 `^[N…]` 编码,或人为构造。 +- **新的还是旧的**: `9dca5805`(2026-11-10),`main` 上没有。 +- **值不值得修**: 待确认,低优先;加一个上限(超过就印成 `OpaquePointer`)即可。 +- **以前修过吗**: 没有。 + +## 修复验证时发现的严重问题 + +### 10. 并行建 demangled index 时整个进程卡死 + +- **位置**: `Sources/MachO/MachOSymbols/SymbolIndexStore.swift:2019-2040`(`DemanglingWave.start` / `waitUntilDemangled`),调用处 `:1018-1022`,加锁处 `:297-303` +- **判定**: CONFIRMED(本机两次复现) +- **状态**: 已修(同日,用户看过报告后批准「先缩小复现再修」),回归测试 `SymbolIndexDemangledIndexTests.firstReadersOnEveryCooperativeThreadAllFinish`。 +- **失败场景**: 建 demangled index 的线程持着构建锁,把下一批名字交给 `DispatchQueue.global()` 去还原,再同步等这批做完(`group.wait()`)。同时别的读者在协作线程上调 `demangledIndex`,经 `withLargeStack` 同步阻塞,等大栈线程,而大栈线程要么持锁等这一批、要么等这把锁。协作线程池被占满后,那批任务一直没有被调度起来,整个测试进程停住,CPU 为 0。 +- **能复现吗**: 能。在公司那台 10 核 Mac Studio(macOS 27.2,Xcode 26.6)上,修复分支的并行全量测试两次都卡死,一次在约 9 分钟处,一次在约 2 分钟处。`sample` 显示 10 个协作线程全在 `demangledIndex(reportingProgressTo:)` → `StackSafeExecutor.runOnLargeStack` 的信号量上;几个大栈线程在 `DemanglingWave.waitUntilDemangled()`,其余在构建锁上;没有一个线程在执行 `DemanglingWave.start` 交出去的那批任务。卡住时在跑的是 `DumpAndInterfaceRequestTests`、`ConstructedThunkOracleTests`、`SymbolIndexDemangledIndexTests.concurrentFirstReadersShareOneBuild` 等与本次修复无关的套件。还缺一条单独就能变红的命令:在 `LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`(单线程协作池)下单跑 `SymbolIndexDemangledIndexTests` 不卡,4 个测试 2 秒跑完;28 核的 Ultra 上并行全量也不卡。之后缩小成了一条命令:在子进程里同时起「核数 × 2」个任务,各自在协作线程上同步读一个新建 storage 的 demangled index,28 核的 Ultra 上也稳定卡住(两次都卡满 60 秒看门狗),采样形态与 10 核那台一致。 +- **根因**: 协作线程全部同步阻塞时,它们仍占着同一 QoS 的并发额度,交给 `DispatchQueue.global()` 的任务分不到线程。只用 GCD 的探针证实了这一点:把协作线程全部阻塞后,全局队列和私有并发队列的任务 5 秒内都没执行,私有串行队列(挂在 overcommit 根队列上)0.07 秒就执行了。建索引的线程同步等这一批,于是整个进程停住。 +- **修法**: `DemanglingWave` 改从私有串行队列起头,里面的 `concurrentPerform` 照常用满所有核(探针实测 28 个线程),没有别的线程加入时由调用线程自己做完。`AGENTS.md` 的异步一节加了「同步等待的工作只交给私有串行队列」这条规则;回归测试所在的套件加进了 CI 的名单。 +- **新的还是旧的**: `b4f80bf9`(2026-11-06,demangle a symbol table's names on several threads ahead of the interning sweep,提案 0088 第 5 项)引入,`main` 上没有。11-12 两批的全量测试在 28 核的 Ultra 上跑过,协作线程池有 28 个线程,没有撞上。体检时第 D 单元的 finder 判断「靠大栈线程池的溢出放行不会死锁」,但那个放行只管大栈线程,管不到 GCD 全局队列给不给线程。 +- **值不值得修**: 卡死。宿主在 Swift 并发里同时给几个镜像建索引(RuntimeViewer、多版本 evolution),核数少的机器上就可能撞上。建议修:那批任务改交给不和协作线程池共用额度的地方执行(私有串行队列,或自己起线程;私有并发队列不行,见下文根因),并把回归测试所在的套件加进 CI。 +- **以前修过吗**: 同一类问题出过:项目 `CLAUDE.md` 写着「不要在协作线程上无时限地等一个需要线程池线程的任务,比如 `DispatchQueue.global()` 的 block」,2026-09-29 有三个测试因此在 3 核的 CI 上冻住整个进程,CI 为此加了 `LIBDISPATCH_COOPERATIVE_POOL_STRICT=1` 的步骤。这次是同一类等待出现在库代码里,而且等待的一方在大栈线程上,那一步的套件名单没收它。 + +## 规则 + +### 新增违规(窗口内,2026-10-17 起) + +| 规则 | 位置 | 说明 | +|------|------|------| +| 项目 `CLAUDE.md` SwiftObjCInterop 一段:"every name-keyed ObjC-side lookup of a Swift class falls back to it [`SwiftClassObjectIndex`] on a miss" | `Sources/Output/SwiftDump/Dumpable/ObjCCategoryProtocolAdoption+Dumpable.swift:54-60` | 私有 `classNode()` 自己 demangle `_Tt` / `$s` 名字,没用会回退查索引的 `ObjCRuntimeNames.classNode(forRuntimeName:in:)`;interface 那条路(`ObjCCategoryConformance.swift:35`)用的是后者。可能的后果是同一镜像里改过运行时名的类,它的 category 在 dump 里印成 `__C.Name`、interface 里印成 Swift 名,但同镜像的 category 一般已被链接器合并进类里,这个后果没有证实。引入于 `07c6153f`(2026-10-28)。可能的原因:这里只拿得到 `ReadingContext`,共享函数要 `machO`。 | +| 全局指令「编码风格」:"更不要用 print" | `Sources/Executables/reader-benchmark/ReaderBenchmark.swift:221-232` | 基准可执行文件用 `print` 输出测量结果,是产品输出而不是日志;`swift-section` 的 `StandardStreamOutput` 规定不管它。建议不修,见文末。引入于 `b28d8887`(2026-11-06)。 | + +窗口内新增的其余命中都不是违规:`InitAccessorFixture.swift:80-81` 的 `var b` / `var a` 是写在字符串里、测试时现场编译的 fixture 源码;`SwiftPrinting` 新增的 `var x: T` 在文档注释里;新增的 `NSLock`(`MachODependencies` 三份登记表、`SwiftLayout/LazilyBuiltIndex.swift`)是按文件或按 cache 的打开登记、以及 `SharedCache` 条目内部的槽位,不是按镜像的缓存;`GenericArgumentEnvironment.swift:215` 的 `"Swift.AnyObject"` 只用作查找 key。 + +### 存量计数 + +首次体检,没有上轮。只列计数不为 0 的规则;检查式见账本。 + +| 规则 | 模块分布 | 本轮 | 上轮 | 变化 | +|------|---------|------|------|------| +| 不用 `print` | SwiftInspection 12(`SpareBitAnalyzer.printAnalysis`,在 `PrintFailureEventTests` 允许名单里)、MachOTestingSupport 4、MachOFixtureSupport 4、reader-benchmark 4、SwiftDeclarationRendering 2 与 MachOReading 1(都是文档注释) | 27 | — | — | +| 不直接用 `os.Logger` | SwiftIndexing 1(`OSLogEventHandler`,`PrintFailureEventTests` 登记的豁免) | 1 | — | — | +| 不用 `FileHandle.standard*.write` | RegenerateBaselinesPlugin 2、SwiftIndexing 1(注释) | 3 | — | — | +| 节点工厂调用(信号) | SwiftThunkAnalysis 10、SwiftLayout 8、SwiftSpecialization 6、SwiftPrinting 4、SwiftDeclarationRendering 4、MachOSymbols 2、SwiftDeclaration 1、SwiftDump 1(全是 `Node.create`,只对无子节点的叶子做驻留) | 36 | — | — | +| 裸 `NodeReference(interning:)`(信号) | MachOSymbols 5、SwiftInspection 1、SwiftPrinting 1 | 7 | — | — | +| 单字母泛型参数(存量,A82) | MachOPointers 21、MachOReading 17、MachOTestingSupport 16、MachOSwiftSection 7、MachOFixtureSupport 6、Utilities 5、SwiftDeclaration 3、MachOResolving 3、SwiftLayout 2、SwiftSpecialization 2、其余四个模块各 1 | 86 | — | — | +| 单字母局部变量 | SwiftInspection 14、SwiftPrinting 7(5 处在文档注释)、SwiftLayout 2、SwiftDeclaration 2、MachOTestingSupport 2、SwiftInterface 1、MachOFixtureSupport 1 | 29 | — | — | +| 裸 `_mangledTypeName` | SwiftDeclarationRendering 1(`RuntimeTypeNameDemangling` 自己,合规) | 1 | — | — | +| `first(of: .privateDeclName)`(信号) | SwiftPrinting 2(`FunctionNodePrinter.swift:58`、`VariableNodePrinter.swift:56`,作用在 `children` 数组上只查直接子节点,合规) | 2 | — | — | +| `NodeReference` 作键(信号) | SwiftIndexing 1(`SwiftDeclarationIndexer.swift:1091`) | 1 | — | — | +| `Task {}` | MachOSymbols 1(文档注释) | 1 | — | — | +| 手写锁(信号) | MachODependencies 10、CrossReferenceAnalysis 7(A62)、SwiftDeclarationRendering 5、SwiftThunkAnalysis 5、MachOTestingSupport 4、SwiftObjCInterop 3、MachOSymbols 2、MachOCaches 2、其余五个模块各 1 | 43 | — | — | +| 废弃转发器 | MachOSwiftSection 252、MachOPointers 45、MachOResolving 29、SwiftInspection 15、SwiftDeclaration 8、SwiftDump 3、SwiftInterface 2、其余三个模块各 1 | 356 | — | — | +| 模块限定名字符串(信号) | SwiftLayout 34、SwiftInterface 31、SwiftInspection 18 | 83 | — | — | + +## 代码异味与层次 + +### 成员排序逻辑有三份 + +- **位置**: `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObservableMacro.swift:418-426`,对照 `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:800`、`:842-852` +- **问题与代价**: `.byOffset` / `.byCategory`(`vtableOrdered`、按类别、滤掉 `minVTableOffset == nil`)的排序在 `@Observable` 展开里抄了第三份;排序规则改一处,展开里的成员顺序就和类型体不一致。finder 担心的「漏了 property wrapper 合成成员的过滤」复核后不影响输出(这份只留宏生成的函数)。 +- **更简单的形状**: 抽一个 `orderedMembersForPrinting(of:)` 给三处共用。 +- **四问**: 确认存在;`f0fd4447`(2026-11-11)引入,`main` 上没有;代价中等、收益明确,建议修;没修过。 + +### `SwiftDeclarationIndexer` 的几个阶段函数过长 + +- **位置**: `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:913-1249`(`indexExtensions`,约 337 行)、`:723-860`(`indexConformances`,约 138 行)、`:503-634`(`indexTypes`,约 130 行)、`:281-400`(`prepareIndexes`,约 120 行) +- **问题与代价**: 每个新识别能力(这一窗口的「其它镜像类型的成员」、`@Observable`、ObjC 协议)都往这几个函数里加步骤,全文 1,606 行,近 30 天又涨了 240 行。 +- **更简单的形状**: 每个阶段拆成具名步骤,`indexExtensions` 先拆。 +- **四问**: 确认存在;起源于 `e2759bb6`(2025-11-18,Split SwiftInterfaceBuilder Class)之后逐步加长,`main` 上也有;建议在下次动这些函数时顺手拆,不单独排期;没处理过。 + +### `SymbolIndexStore` 一个文件管太多事 + +- **位置**: `Sources/MachO/MachOSymbols/SymbolIndexStore.swift`(2,046 行) +- **问题与代价**: 符号表行、`ExportFacts`、`_symbolic` 表、晚到名字的 side store、`DemangledIndex` 的懒构建与锁、按 owner 分组都在一个类型下。内部已按嵌套类型分块,代价主要是一个文件过大、锁与栈的不变量要在大文件里推理(裁决 A61 的「持锁时 demangle」就出在这里)。 +- **更简单的形状**: 把 `DemangledIndex` 的构建与 owner 分组搬到各自的文件或类型。 +- **四问**: 确认存在;始于 `406d2187`(2025-06-26),逐步长大,`main` 上也有;收益中等,可排低优先;没处理过。 + +### `SwiftDeclaredObjCProtocolIndex` 同一映射一半存、一半现算 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/SwiftDeclaredObjCProtocolIndex.swift:94-97`、`:135-137` +- **问题与代价**: `Storage` 存了 `qualifiedNamesByRuntimeName`,查找时先拿它判断有没有,再对 `protocols` 线性 `first`。建字典时同名的后者覆盖前者,`first` 取的却是前者,同一镜像两个协议用同一运行时名时两边会分叉(现实中几乎不会)。 +- **更简单的形状**: 直接存 `[String: SwiftDeclaredObjCProtocol]`。 +- **四问**: 确认存在;`02b3d5f5` 与 `e56ad3ff`(2026-10-28),`main` 上没有;代价小,顺手修;没修过。 + +## 重复代码 + +### `MachODependencies` 里三份同构的共享登记表 + +- **位置**: `Sources/MachO/MachODependencies/SharedDyldCacheOpenings.swift:33`、`SharedMachOFileOpenings.swift:68`、`DyldCacheImageDirectory.swift:136` +- **重复了什么**: 外层锁加 `[Key: Slot]`、每个 slot 自带 `NSLock` 先查后建,各约 30 行;`SharedDyldCacheOpenings.swift:36-38` 自己注明照抄了 `DyldCacheImageDirectory`。两个弱引用版本的 slot 从不从字典删除,条目数随进程里见过的文件数增长,每条约两三百字节,量级可以忽略。 +- **该合并到哪里**: `MachODependencies`(或 `MachOCaches`)里一个泛型 slot 登记表,参数化强 / 弱持有与建好后的预热。 +- **四问**: 确认;`ab0fc5cd`(2026-11-03)、`accdec47` 与 `6fe12bf7`(2026-11-06),`main` 上没有;并发策略改一处要改三处,建议合并;没处理过。 + +### ObjC 属性的 getter / setter selector 推导写了两份 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberBuilder.swift:177-185` 与 `Sources/Analysis/SwiftObjCInterop/ObjCProtocolRequirements.swift:155-163`(`PropertyAccessors` 与 `propertyAccessors(of:)`);attribute string 的手工 `split` 另有三处(`ObjCProtocolRequirements.swift:157`、`ObjCImportedMemberBuilder.swift:179,205`、`ObjCImporterNaming.swift:218`) +- **该合并到哪里**: 一个只要求 `name` 与 `attributes` 的小协议加共享实现,放在 `ObjCImporterNaming` 旁边。 +- **四问**: 确认逐字相同、合并后行为不变;`e56ad3ff`(2026-10-28)与副本 `97741012`(2026-11-10),`main` 上没有;改 selector 推导时两条路径会不一致,建议合并;提案 0090 决策日志说过协议要求复用已有 builder,类成员这边却另抄了一份。 + +### ObjC 协议要求的打印写了两份 + +- **位置**: `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift:231-237` 与 `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift:126-132`;`printingKind(of: ObjCProtocolRequirementDefinition)` 在两文件 `:294-300` 与 `:177-183` 逐字相同 +- **重复了什么**: 两个函数只差 `@objc` 是总写还是只在显式 selector 时写。 +- **该合并到哪里**: 合成一个函数,用参数控制 `@objc` 的写法。 +- **四问**: 确认;`bfecf4bf`(2026-10-28)与副本 `ed72c915`(2026-11-10),`main` 上没有;建议合并;没处理过。 + +### 「已 realize 的类先经 `class_rw_t` 再取 `class_ro_t`」写了四份 + +- **位置**: `Sources/Analysis/SwiftLayout/ObjCClassIndex.swift:124`、`Sources/Analysis/CrossReferenceAnalysis/Scanning/ObjectiveCClassIndex.swift:155`、`Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassIndex.swift:609`、`Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift:236` +- **重复了什么**: 同一段 runtime 规则(ro → rw.ro → rw.ext.ro),四份写法等价,还没有分叉。 +- **该合并到哪里**: 下沉到四个模块共同依赖的一层(`SwiftObjCInterop`,或上游 `MachOObjCSection` 的 `ObjCClass64` 扩展)。 +- **四问**: 确认;`5a9971d6`(2026-06-22)、`584f1ff7`(2026-09-20)、`1292cda2`(2026-10-11)、`59631757`(2026-10-17),前两份 `main` 上也有;每份不到 20 行,收益中等,可排低优先;没处理过。 + +## 死代码 + +| 位置 | 判定依据 | 引入 | 建议 | +|------|---------|------|------| +| `Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift:105` `isReturnOptional`(internal) | `rg isReturnOptional` 在 `Sources`、`Tests`、`Plugins` 与上游 swift-demangling 都只有声明;不是协议要求 | `9fdb1a5a`(2025-09-28),`main` 上也有 | 删 | +| `Sources/Analysis/SwiftLayout/ImageReference.swift:200` `protocolClassConstraint(forQualifiedTypeName:)`(internal) | 唯一使用方直接读底层字典(`ImageUniverse.swift:250`),测试也读字典 | `a5fe6743`(2026-06-21),`main` 上也有 | 删 | +| `Sources/ABI/MachOSwiftSection/Models/Mangling/MangledName.swift:116` `isContentsEqual(to:)`(package) | `package` 在包外不可见,`Sources`、`Tests` 都没有引用 | `f67b11cc`(2025-10-13),`main` 上也有 | 删 | +| `Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift:68` `TypeLayout.dumpDebugDescription`(fileprivate) | 本文件内无使用,fileprivate 不可能被动态引用 | `560b683c`(2025-12-24),`main` 上也有 | 删 | + +都不涉及动态引用(selector、类名字符串、KVC、插件注册)。 + +## 复核为 PLAUSIBLE、未达门槛的线索 + +后果不是崩溃、丢数据或安全问题,按门槛不列为发现;记在这里,供以后有证据时重新判断。 + +| 位置 | 机制 | 什么能证实它 | +|------|------|-------------| +| `Sources/Support/ARM64InstructionDecoding/ARM64Trampoline.swift:64-67` | GOT 桩识别一见 `ldr` 就判为桩,不核对后面的 `br` / `braa`;`SwiftThunkAnalysis` 的 `resolveCallee`(`MachOThunkEnvironment.swift:278`)对未认出的被调函数都先试它 | 一个以 `adrp; ldr` 开头的普通函数被 thunk 调用,thunk 读取器把它跟到 GOT 槽 | +| `Sources/Analysis/SwiftObjCInterop/SwiftDeclaredObjCProtocolIndex.swift:226` | 字段描述符的名字用 `.symbolString` 拼成文本再 demangle,没走 `SymbolicDemangler`;名字里有 symbolic reference 时该 `@objc` 协议整个消失 | 编一个 `struct Outer { @objc protocol P {} }`(SE-0404 嵌套协议),看名字里有没有 symbolic reference | +| `Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift:30`、`ObjCInterfaceIndexerClassHierarchyProvider.swift:118` | 父类读不出时空名被转成 `nil`,宿主 provider 路径判定祖先链完整,可能下出错误的 `@objc(selector)`;库自己的路径判为不完整 | `superclassTypeMangledName` 或 demangle 抛错的真实镜像,走 RuntimeViewer 的 provider 路径 | +| `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:973`、`:1091` | 两个成员批次合并后用裸 `NodeReference` 键分组,违反只在单批次内用裸键的规则 | 在 SwiftUI / SwiftUICore 的 interface 里找重复的 `extension … where` 头 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:1250-1253` | 废弃转发 `opaqueType(forNode:index:usesModuleSelectors:)` 不带 `useExistentialAny`,仍调它的宿主拿到不带 `any` 的拼写 | 下游(RuntimeViewer、MachOKitUI)是否还调这个废弃接口 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:554` | 折叠形态无条件藏起 `Observable` conformance extension;类型自身打印失败时这个 conformance 彻底消失(失败本身已有 `definitionPrintFailed` 事件) | 一个打印会抛错的 `@Observable` 类 | +| `Sources/Analysis/SwiftLayout/ImageReference.swift:51-52` | 依赖镜像的 `ImageReference`(强引用 `MachOFile` 与七个索引)进进程级 `SharedCache`,没有 owner 认领,CLI 从不调 `evictImagesWithoutLiveOwners()`,多版本运行时可能随版本数增长 | 确认 `evolution` 是否经 `ImageUniverse` 带依赖闭包;若是,对几个归档 cache 跑它,看 `lsof` 计数和 footprint | +| `Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:234-238` | `objc evolution --interface` 先把所有版本的 `MachOFile` 装进数组,映射整个运行期都开着(先全部加载是为了推断平台) | 几十个 dyld cache 跑一次,量文件描述符与 footprint | + +## 建议不修(用户确认后登记进已裁决清单) + +用户已确认,三条依次登记为 [ReviewAdjudications](../../ReviewAdjudications.md) 的 A83、A84、A85。 + +| 发现 | 理由 | 重新判断的条件 | +|------|------|---------------| +| `@Observable` 的折叠特例叠在共享的字段渲染上(`SwiftDeclarationPrinter+Headers.swift:523-560`,`ModelMembersSelection` 三种模式) | 提案 0093 有意把折叠接进字段块与成员块,为的是展开形态与折叠形态用同一套打印代码,注释逐字节一致;理由仍成立 | 出现第二个要折叠的宏时,再考虑改成由各个宏的折叠规则产出字段列表 | +| `CodeReferenceIndex` 查询结果里同一条指令上多条引用的顺序每个进程不同(`Models/CodeReferenceIndex.swift:117`、`:291`),与扫描路径的顺序不一致 | 内容一致,只差同一指令上 `alloc` / `init` 这类并列引用的先后;现有测试不比这种组合。可以只把类型文档里「答案完全一致」改成「集合一致」 | 宿主或测试开始逐数组比较两条路径的结果 | +| `reader-benchmark` 用 `print` 输出测量结果 | 基准可执行文件,输出是产品结果不是日志,不随库发布 | 它被并进 `swift-section` 或开始输出诊断信息 | + +## 修复(2026-11-16 同日) + +体检报告写完后,用户批准修第 1–7 条,第 8 条随第 2 条一起修;前八条验证完之后又批准修第 9 条;三条「建议不修」登记为已裁决清单的 A83–A85。分支 `fix/codebase-audit-2026-11-16`,每条都先写复现测试、确认它在修复前失败(第 2、7 条是子进程 SIGTRAP,其余是错误输出),修复后转绿。 + +- **第 1 条**:`CrossReferenceAnalyzer.ClassArgumentReturn` 把 `objc_opt_class`(返回参数的类)与 `objc_opt_self`、`swift_getInitializedObjCClass`(原样返回参数)分开;`objc_opt_class` 之后,`x0` 只在类方法里或不是方法接收者时保留。函数表新增 `isObjectiveCClassMethod(at:)`。 +- **第 2 条**:参数个数守卫收成 `ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`,类成员(`ObjCImportedMemberBuilder`)与协议要求(`ObjCProtocolRequirements`)共用;协议要求也照类成员的做法,扩展编码不合时退回方法表的编码,再不合就不导入。顺带修了原来扩展编码解析失败、退回方法表编码时 `typeEncoding` 仍记扩展编码的不一致。 +- **第 3 条**:`ObjCEncodedType.characterString` 带上 `isConst`,`r*` 导入成 `UnsafePointer`。 +- **第 4 条**:`ObjCProtocolWitnesses` 对本镜像之外的 Swift 类按运行时名取 category 的成员表;`ObjCMembers.table(forObjCClassNamed:)` 的所属名对 Swift 类取 Swift 限定名,strip 过的镜像里 thunk 代码那一档才认得这些成员。**同类问题**:修的时候发现,从文件读时这种 category 指向的是类元数据符号 `_$s…CN` 而不是 `_TtC…`,`ObjCRuntimeNames` 不认,interface 把扩展印成 `extension __C._$s36…`,dump 那份自己的实现只认 `$s` 不认 `_$s`。改为由新的 `NodeTypeNaming.swiftClassNode(fromRuntimeName:)` 统一认 `_TtC`、`$s`、`_$s` 三种写法,`ObjCRuntimeNames`、dump 的 category 行、`swiftClassQualifiedName(fromRuntimeName:)` 都经它。 +- **第 5 条**:`SwiftClassWithoutClassObjectIndex.Storage` 把同名的类都登记进限定名表,按名字查遇到同名时返回空。 +- **第 6 条**:`ObservableMacroExpansionRecovery.isGeneratedFunction(name:node:)` 连形状一起比:`access`、`withMutation` 要求泛型、第一个参数是 `KeyPath`,`shouldNotifyObservers` 要求泛型、两个参数。 +- **第 7 条**:终端大小超出表尾时不再与游标相加,按「没有子节点」处理。 +- **第 8 条**:`ObjCProtocolRecord.make` 逐个核对扩展编码与方法表编码是否同一签名(擦掉类名、协议名与 block 签名后比较),有一个对不上就整组不用。 +- **第 9 条**(在 Ultra 上验证完前八条之后,用户批准一并修):C 数组照 ClangImporter 的 `VisitConstantArrayType` 导入——超过 4,096 个元素的不导入(指针指向它时导入成 `OpaquePointer`),只有一个元素的导入成元素本身;嵌套数组展开后超过 65,536 个元素的同样当作导入不了,免得构造出来的编码让构建与打印没有尽头。顺带修了单元素数组印成一元元组的偏差。 +- **fixture 的扩充**:`SwiftDeclaredObjCProtocolsFixture` 的 kit 加 `KitWidget`、客户端加 `KitWidgetAdopted` 与对它的 extension;`ClassesWithoutClassObjectsFixture` 的客户端加第二个源文件与两个同名 private 泛型类;`ObservableMacroFixture` 加 `HandwrittenNamesModel`。列举协议、category 与被识别类的既有断言随之补上新成员。 +- **验证**:JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6,本地兄弟依赖)上全量 2,916 个测试只红 3 条,都是满负载下的既有偶发(`FileMappingTests`、`SharedCacheTests` 的重叠测试、`BoundedConcurrentMapTests` 的时限),单独重跑全过。JHs-Mac-Studio(10 核)上受影响的 22 个套件 118 个测试全过,并行全量两次卡死在第 10 条。没跑渲染 A/B:改动只影响上面几种具体形态的输出,不是大重构。 + +## 下一轮 + +- **轮转候选**(从未深审、按行数与近期改动排):`SwiftInspection`(6,316)、`SwiftSpecialization`(4,883)、`SwiftLayout`(4,704)、`TypeIndexing`(1,311)、`MachOCaches`(675)、`MachOPointers`(809),合计约 1.9 万行;`MachOSwiftSection`(10,453)这轮只看了 `@BitField` 迁移,留给再下一轮。 +- **本轮没覆盖到的**:单元 C 的 finder 没读 `StructuredComment*`、`DeclarationRenderConfiguration`、`InterfaceVersionRendering`、`EvolutionMarking`、`SwiftDeclaredObjCProtocolDumper` 等文件;单元 B 的 `ObjCImporterNaming.swift`(1,030 行)只读了约四分之三;单元 D 没读 `ObjCInterfaceRequest`。下一轮的改动集若碰到它们,优先读。 +- 补漏(主线程)重看了 `ObjCImporterNaming` 的下标运算、ObjC interface 会话、符号表并行 demangle 的等待、窗口内新增的布尔配置默认值,没有新发现。 diff --git a/Documentations/Internal/Reviews/CodebaseAudits/README.md b/Documentations/Internal/Reviews/CodebaseAudits/README.md new file mode 100644 index 000000000..196eea4f2 --- /dev/null +++ b/Documentations/Internal/Reviews/CodebaseAudits/README.md @@ -0,0 +1,88 @@ +# 代码库体检账本 + +由 `audit-codebase` 维护。每轮体检先读它决定范围,跑完再更新。各轮报告与本文件同目录(`CodebaseAudit.md`),由下面的「运行记录」索引。 + +## 模块表 + +「最近深审」写「从未(改动集审过 …)」的模块,只审过那一轮改动集里的改动与所在函数,没有整模块深审过;轮转时按「从未」对待。 + +| 模块 | 路径 | 源码行数 | 最近深审 | 深审时的提交 | 未结的严重问题 | +|------|------|---------|---------|-------------|---------------| +| CrossReferenceAnalysis | `Sources/Analysis/CrossReferenceAnalysis/` | 4,483 | 2026-11-16 | `1ba927ad` | 0 | +| ARM64InstructionDecoding | `Sources/Support/ARM64InstructionDecoding/` | 279 | 2026-11-16 | `1ba927ad` | 0 | +| SwiftObjCInterop | `Sources/Analysis/SwiftObjCInterop/` | 7,073 | 2026-11-16 | `1ba927ad` | 0 | +| SwiftThunkAnalysis | `Sources/Analysis/SwiftThunkAnalysis/` | 3,629 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftInspection | `Sources/Analysis/SwiftInspection/` | 6,316 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftLayout | `Sources/Analysis/SwiftLayout/` | 4,704 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftDeclaration | `Sources/Declaration/SwiftDeclaration/` | 6,631 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftIndexing | `Sources/Declaration/SwiftIndexing/` | 2,509 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftSpecialization | `Sources/Declaration/SwiftSpecialization/` | 4,883 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftPrivateDiscriminators | `Sources/Declaration/SwiftPrivateDiscriminators/` | 828(不含生成文件) | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftAttributeInference | `Sources/Declaration/SwiftAttributeInference/` | 191 | 从未 | — | — | +| TypeIndexing | `Sources/Declaration/TypeIndexing/` | 1,311 | 从未 | — | — | +| SwiftPrinting | `Sources/Output/SwiftPrinting/` | 7,543 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftDeclarationRendering | `Sources/Output/SwiftDeclarationRendering/` | 6,580 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftDump | `Sources/Output/SwiftDump/` | 3,323 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftInterface | `Sources/Output/SwiftInterface/` | 4,065 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftDiffing | `Sources/Output/SwiftDiffing/` | 3,698 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftOutputTransformer | `Sources/Output/SwiftOutputTransformer/` | 1,527 | 从未 | — | — | +| SwiftSectionKit | `Sources/Commands/SwiftSectionKit/` | 3,155 | 从未(改动集审过 2026-11-16) | — | 0 | +| swift-section | `Sources/Executables/swift-section/` | 2,242 | 从未(改动集审过 2026-11-16) | — | 0 | +| reader-benchmark | `Sources/Executables/reader-benchmark/` | 285 | 从未(改动集审过 2026-11-16) | — | 0 | +| baseline-generator | `Sources/Executables/baseline-generator/` | 33 | 从未 | — | — | +| MachOSwiftSection | `Sources/ABI/MachOSwiftSection/` | 10,453 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOSwiftSectionC | `Sources/ABI/MachOSwiftSectionC/` | 588 | 从未 | — | — | +| MachOSymbols | `Sources/MachO/MachOSymbols/` | 3,207 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachODependencies | `Sources/MachO/MachODependencies/` | 1,156 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOReading | `Sources/MachO/MachOReading/` | 1,416 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOResolving | `Sources/MachO/MachOResolving/` | 431 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOPointers | `Sources/MachO/MachOPointers/` | 809 | 从未 | — | — | +| MachOCaches | `Sources/MachO/MachOCaches/` | 675 | 从未 | — | — | +| MachOBase、MachOFoundation | `Sources/MachO/MachOBase/`、`Sources/MachO/MachOFoundation/` | 13 | 从未 | — | — | +| Utilities | `Sources/Support/Utilities/` | 507 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOMacros | `Sources/Support/MachOMacros/` | 452 | 从未(改动集审过 2026-11-16) | — | 0 | +| MachOFixtureSupport | `Sources/TestSupport/MachOFixtureSupport/` | 17,324 | 从未 | — | — | +| MachOTestingSupport | `Sources/TestSupport/MachOTestingSupport/` | 5,829 | 从未(改动集只做过结构与冗余审查 2026-11-16) | — | — | +| MachOTestingSupportC | `Sources/TestSupport/MachOTestingSupportC/` | 18 | 从未 | — | — | +| RegenerateBaselinesPlugin | `Plugins/RegenerateBaselinesPlugin/` | 81 | 从未 | — | — | + +**不审**: + +- `Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`Scripts/GenerateKnownSwiftSourceFileNames.sh` 生成,2,027 行)。 +- `Tests/`(25 个测试目标,约 8.3 万行;含 `Tests/Projects/` 下的 fixture 源码,它们为了制造特定的二进制形态而刻意写得古怪):只作为核对发现时的证据读,不轮转深审。要纳入轮转,在这里改写并给它们加行。 +- `Scripts/`(A/B 验证用的 Python 脚本,不是构建目标)、`AgentPlugins/`(agent 插件的文档)、`Documentations/`。 + +## 规则检查式 + +在仓库根目录运行;全部带 `-g '*.swift' Sources Plugins`,并排除 `PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`| grep -v KnownFileNames | wc -l`)。计数包含注释与字符串里的命中,只用来看趋势;每条命中算不算违规由各轮报告判断。 + +| 规则 | 来源 | 检查式(`rg -nP`) | 2026-11-16 | +|------|------|--------|-----------| +| 不用 `print` 打日志 | 全局指令「编码风格」;项目 `CLAUDE.md`「writing a log statement」 | `'(?)'` | 86 | +| 不用单字母局部变量 | 全局指令「编码风格」 | `'\b(let\|var)\s+[a-z]\s*[=:]\|\bfor\s+(case\s+let\s+)?[a-z]\s+in\b'` | 29 | +| 不用 `FullDyldCache.host` | 项目 `CLAUDE.md`「MachODependencies」一段 | `'FullDyldCache\.host(?!\w)'` | 0 | +| 运行时 metatype 不裸用 `_mangledTypeName` | 项目 `CLAUDE.md`「touching the demangler…」 | `'_mangledTypeName\('` | 1 | +| 不用 `first(of: .privateDeclName)` 读鉴别符(信号) | 同上 | `'first\(of: \.privateDeclName\)'` | 2 | +| `NodeReference` 作键要用 `StructuralNodeReferenceKey`(信号) | 同上 | `'\[\s*NodeReference\s*:\|Set\|Dictionary **0.25.0 更新**:本文涉及的 Mach-O 基础模块——`MachOBase`、`MachOFoundation`、`MachOPointers`、`MachODependencies`,以及 `MachOSymbols` 与语言无关的那一半——已迁到 MachOKitExtensions 2.0.0,模块名不变。`MachOBase` 不再再导出 `Utilities`(`Utilities` 留在本仓库,改由 `MachOSwiftSection` 自己 `@_exported import`);`MachOSymbols` 的 Swift 部分留在本仓库,改名 `SwiftSymbols`,`SymbolIndexStore` 改名 `SwiftSymbolIndexStore`。ABI 层的边界本身没有变:`MachOSwiftSection` 仍只依赖 `MachOBase`,够不到任何符号索引与 demangler。下表「之后」一列与「下游迁移」按迁移后的模块名写。 + ## 改了什么 | 之前 | 之后 | |---|---| -| `MachOSwiftSection` 依赖 `MachOFoundation` 伞模块(含 `MachOSymbols`、`MachODependencies`)和 `Demangling`,并把伞模块整个再导出 | 只依赖新的底层伞模块 `MachOBase`(`MachOKitExtensions` + `MachOReading` + `MachOResolving` + `MachOPointers` + `Utilities`)并再导出它;`Package.swift` 上看不到符号索引与 demangler | +| `MachOSwiftSection` 依赖 `MachOFoundation` 伞模块(含 `MachOSymbols`、`MachODependencies`)和 `Demangling`,并把伞模块整个再导出 | 只依赖新的底层伞模块 `MachOBase`(`MachOKitExtensions` + `MachOReading` + `MachOResolving` + `MachOPointers`,0.25.0 起在 MachOKitExtensions)并再导出它,另外自己再导出 `Utilities`;`Package.swift` 上看不到符号索引与 demangler | | 五个描述符的 Layout 字段是 `RelativeDirectPointer`,访问器 `implementationSymbols(in:)` 一调就建整镜像符号索引 | 字段是 `RelativeDirectRawPointer`,访问器 `implementationOffset: Int?`(纯指针算术)与 `implementationAddress(in context:)`;`ProtocolRequirement` 用 `defaultImplementation…` 前缀 | | `implementationSymbols(in:)` 家族在 ABI 层 | 同名扩展在 `SwiftInspection`(`Extensions/Descriptor+ImplementationSymbols.swift`),实现是拿偏移问 `machO.symbols(offset:)`;只有 MachO 一条腿 | -| `Symbol` / `Symbols` / `SymbolOrElement` 在 `MachOSymbols`,`Symbols` 是 `AsyncResolvable` | 三个纯值类型在 `MachOResolving`;`Symbols` 不再是 `Resolvable`;`Symbol` 走索引库的 `resolve(from:in:)` 与 `resolvesSymbolUsingIndexStore` 作为扩展留在 `MachOSymbols` | +| `Symbol` / `Symbols` / `SymbolOrElement` 在 `MachOSymbols`,`Symbols` 是 `AsyncResolvable` | 三个纯值类型在 `MachOResolving`;`Symbols` 不再是 `Resolvable`;`Symbol` 走索引库的 `resolve(from:in:)` 与 `resolvesSymbolUsingIndexStore` 作为扩展留在符号索引模块(今 `SwiftSymbols`) | | `SymbolOrElementPointer` 独占一个 `MachOSymbolPointers` target | 并入 `MachOPointers`,target 删除 | | `String.isSwiftSymbol` / `stripManglePrefix`、`cModule` / `objcModule` 来自 `Demangling` | 本模块自有 `hasSwiftManglingPrefix` / `strippingSwiftManglingPrefix`(`Extensions/String+.swift`)与 `CImportedModuleNames`(`Models/Mangling/`),`ManglingPrefixTests` 钉住与 demangler 一致 | -分层由编译器守:`MachOSwiftSection` 的依赖列表里没有 `MachOSymbols` 与 `Demangling`,回归就是编译错误。 +分层由编译器守:`MachOSwiftSection` 的依赖列表里没有 `SwiftSymbols`、`MachOSymbols` 与 `Demangling`,回归就是编译错误。 ## 从签名看不出来的决策 @@ -35,7 +37,7 @@ ### `Symbol.resolve(from:in:)` 为什么还在 -`MetadataReader` 的 `MachOContext.lookupSymbol` 与 `SwiftDeclarationRendering` 的 `OpaqueType+` 仍用它,且它承载 `resolvesSymbolUsingIndexStore` 开关(MachOKitUI 会置 false)。它现在是 `MachOSymbols` 里 `Symbol` 的静态扩展方法,不再是 `Resolvable` 要求:语义是「查」不是「读」。 +`MetadataReader` 的 `MachOContext.lookupSymbol` 与 `SwiftDeclarationRendering` 的 `OpaqueType+` 仍用它,且它承载 `resolvesSymbolUsingIndexStore` 开关(MachOKitUI 会置 false)。它现在是 `SwiftSymbols`(当时的 `MachOSymbols`)里 `Symbol` 的静态扩展方法,不再是 `Resolvable` 要求:语义是「查」不是「读」。 ### `ResilientWitness.implementationAddress(in:)` 的两个形态 @@ -51,10 +53,10 @@ |---|---| | `try d.implementationSymbols(in: machO)` | 去掉 `try`,文件补 `import SwiftInspection` | | `d.implementationSymbols(in: context)` | 删除;要位置用 `try d.implementationAddress(in: context)` | -| `try Symbols.resolve(from: offset, in: machO)` | `machO.symbols(offset: offset)`(`MachOSymbols`) | +| `try Symbols.resolve(from: offset, in: machO)` | `machO.symbols(offset: offset)`(`SwiftSymbols`) | | `MachOSymbols.Symbol` 限定名 | 不限定,或 `MachOResolving.Symbol` | | `import MachOSymbolPointers` | 删除(并入 `MachOPointers`) | -| 经 `import MachOSwiftSection` 间接用 `SymbolIndexStore` 等 | 补 `import MachOFoundation` | +| 经 `import MachOSwiftSection` 间接用 `SymbolIndexStore`(今 `SwiftSymbolIndexStore`)等 | 补 `import SwiftSymbols`;用 `DependencyClosure` 等补 `import MachODependencies`(MachOKitExtensions) | | `ResilientWitness.implementationOffset` | 现在是 `Int?` | ## 验证 diff --git a/Documentations/Internal/StaticFieldOffsetComputation.md b/Documentations/Internal/StaticFieldOffsetComputation.md index a460b490a..ce8b4a4eb 100644 --- a/Documentations/Internal/StaticFieldOffsetComputation.md +++ b/Documentations/Internal/StaticFieldOffsetComputation.md @@ -104,7 +104,7 @@ resilient 的本质是「编译当前二进制时不知道字段布局,但运 ### 已有基础设施 - **按依赖名解析镜像**:上游包 `MachOKitExtensions` 的 `DyldCache+.swift` 的 `machOFile(by mode:)` —— 按 install name / image name 从 dyld shared cache 捞 `MachOFile`。系统 Swift 库、Foundation、SwiftUI 等都在 cache 里,这条路已通。 -- **符号索引**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` —— 按 name/offset 建索引。 +- **符号索引**:`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift` —— 按 name/offset 建索引。 - **ReadingContext 抽象**:`MachOContext` 已把「从哪个镜像读」参数化,扩展成多镜像顺理成章。 ### 需新建三块 @@ -122,7 +122,7 @@ resilient 的本质是「编译当前二进制时不知道字段布局,但运 ## 5. ObjC 祖先 class -本项目**已依赖 MachOObjCSection**(`Package.swift:122`,`useCustomObjCSection=true`),已用于 `SwiftInspection/ClassHierarchyDumper.swift`、`TypeIndexing/ObjCInterfaceIndexer.swift`。它提供 `ObjCIvarListProtocol`(ivar list)、`ClassROData`(class_ro_t),能静态读 ObjC class 的 **instanceStart / instanceSize / ivars**。 +本项目**已依赖 MachOObjCSection**(`Package.swift:122`,`useCustomObjCSection=true`),已用于 `SwiftObjCInterop/ClassHierarchyDumper.swift`、`TypeIndexing/ObjCInterfaceIndexer.swift`。它提供 `ObjCIvarListProtocol`(ivar list)、`ClassROData`(class_ro_t),能静态读 ObjC class 的 **instanceStart / instanceSize / ivars**。 对应运行时算法:`initClassFieldOffsetVector`(`Metadata.cpp:3771-3776`)对 ObjC 父类**从 `rodata->InstanceStart` 起算、对齐 `0xF`**。解法: @@ -143,7 +143,7 @@ resilient 的本质是「编译当前二进制时不知道字段布局,但运 - 名字解析:`MetadataReader` + `ReadingContext` 抽象(静态/运行期通吃)。 - 静态分流信号:`MetadataInitialization` kind、`singleton/foreignMetadataInitialization` 模型。 - 现成 vector 读取:`StructMetadata.fieldOffsets(...)` / `FinalClassMetadata.fieldOffsets(...)`(含 MachOFile overload)。 -- dyld cache 取镜像:`DyldCache+.swift` 的 `machOFile(by:)`;符号索引 `SymbolIndexStore`。 +- dyld cache 取镜像:`DyldCache+.swift` 的 `machOFile(by:)`;符号索引 `SwiftSymbolIndexStore`。 - ObjC ivar:MachOObjCSection 的 `ObjCIvarListProtocol` / `ClassROData`。 **缺口(需新建):** @@ -238,7 +238,7 @@ fixed-layout 非泛型(单镜像) 直接读 vector,几乎零成本 | MetadataInitialization 分流信号 | `Models/Type/TypeContextDescriptorFlags.swift`、`Models/Metadata/MetadataInitialization/` | | enum 静态布局算法 | `Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift`、`SpareBitAnalyzer.swift`、`BitMask.swift` | | 现有 field rendering(runtime 依赖点) | `Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift`(`:98-110` fieldOffsets、`:189-203` substitution、`:388-420` 节点替换骨架、`:497` deref runtime metadata vector)、`FieldLayoutRenderer+Enum.swift:113-148`(payloadSize/XI 全靠 runtime VWT) | -| dyld cache 取镜像 / 符号索引 | 上游包 `MachOKitExtensions` 的 `DyldCache+.swift`(`machOFile(by:)`)、`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` | +| dyld cache 取镜像 / 符号索引 | 上游包 `MachOKitExtensions` 的 `DyldCache+.swift`(`machOFile(by:)`)、`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift` | | InProcess-only runtime 桥 | `Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift` | | 泛型 specialization(runtime 编排,可作 ground truth/fallback) | `Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift`、`ConformanceProvider.swift`(已静态、可复用) | -| ObjC ivar / class_ro_t | MachOObjCSection `ObjCIvarListProtocol`、`ClassROData`;本项目用例 `Sources/Analysis/SwiftInspection/ClassHierarchyDumper.swift`、`Sources/Declaration/TypeIndexing/ObjCInterfaceIndexer.swift` | +| ObjC ivar / class_ro_t | MachOObjCSection `ObjCIvarListProtocol`、`ClassROData`;本项目用例 `Sources/Analysis/SwiftObjCInterop/ClassHierarchyDumper.swift`、`Sources/Declaration/TypeIndexing/ObjCInterfaceIndexer.swift` | diff --git a/Documentations/Internal/StaticLayoutDependencyClosure.md b/Documentations/Internal/StaticLayoutDependencyClosure.md index b370544c2..85baada7f 100644 --- a/Documentations/Internal/StaticLayoutDependencyClosure.md +++ b/Documentations/Internal/StaticLayoutDependencyClosure.md @@ -4,7 +4,7 @@ > > **状态:已落地。** 下文设计/步骤为原始计划,末尾「落地实测」记录与计划的差异;与实现冲突处以「落地实测」为准。 > -> **2026-09-02 更新**:本文描述的定位器(`MachOFileDependencyLocator`)、BFS 遍历与 `LayoutDependencySearchPath` 已下沉为共享模块 `MachODependencies`(提案 [0017](../Evolutions/0017-macho-dependencies-module.md));`ImageUniverse.dependencyClosure(root:…)` 工厂现在是 `DependencyClosure` 的薄包装,cache 的 bare name 匹配也从「枚举顺序首写者胜」改为「install path 精确优先、排序兜底」。现行契约以 [Modules/MachODependencies.md](Modules/MachODependencies.md) 为准,本文保留为阶段 3 的设计与实测记录。 +> **2026-09-02 更新**:本文描述的定位器(`MachOFileDependencyLocator`)、BFS 遍历与 `LayoutDependencySearchPath` 已下沉为共享模块 `MachODependencies`(提案 [0017](../Evolutions/0017-macho-dependencies-module.md));`ImageUniverse.dependencyClosure(root:…)` 工厂现在是 `DependencyClosure` 的薄包装,cache 的 bare name 匹配也从「枚举顺序首写者胜」改为「install path 精确优先、排序兜底」。现行契约以 MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) 为准(`MachODependencies` 自 0.25.0 起由 MachOKitExtensions 2.0.0 提供),本文保留为阶段 3 的设计与实测记录。 ## 背景与目标 @@ -97,7 +97,7 @@ extension ImageUniverse { 1. **`ImageReference` 索引可复用化**:把「从一个 machO 建 type/protocol 索引」抽成可被多镜像聚合调用的形式(当前 `init` 已是单镜像版,加一个把多个 `ImageReference` 合并的入口)。 2. **`ImageUniverse` 多镜像化**:`rootImage` + `dependencyImages`,全局表合并,`resolveType` / `resolveProtocolClassConstraint` 改查全局表(root 优先)。加 `dependencyClosure(root:dependencyImages:)` 底层工厂。单测:手工塞两个镜像,验证跨镜像解析。 3. **`MachOImage` 便利工厂**:`dependencyClosure(root: MachOImage)` 经 `MachOImage(name:)` 递归 + 防环。用 fixture(`machOImage`)验证 `DistributedActorTest` 经 vector 完全解析、`ResilientChild` 字段偏移可算。 -4. **`MachOFile` 便利工厂**:`dependencyClosure(root: MachOFile, searchPaths:)` 经 `FullDyldCache.cachedHost` + 显式路径。2026-10-08 起,从 dyld cache 里读出来的 root 先在自己所在的 cache 里找依赖,再查这些路径([Modules/MachODependencies.md](Modules/MachODependencies.md) §3)。 +4. **`MachOFile` 便利工厂**:`dependencyClosure(root: MachOFile, searchPaths:)` 经 `FullDyldCache.cachedHost` + 显式路径。2026-10-08 起,从 dyld cache 里读出来的 root 先在自己所在的 cache 里找依赖,再查这些路径(MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) §3)。 5. **resilient 验证扩展**(见下)。 6. **文档**:更新 `StaticLayoutEngine.md`(移除阶段 3 残留项)、本文「实测」回填、`Documentations/README.md`。 diff --git a/Documentations/Internal/StaticLayoutEngine.md b/Documentations/Internal/StaticLayoutEngine.md index e06beb4fe..34a4168cf 100644 --- a/Documentations/Internal/StaticLayoutEngine.md +++ b/Documentations/Internal/StaticLayoutEngine.md @@ -78,12 +78,12 @@ Tests/SwiftLayoutTests/ - **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 字节。 - **`DependentMemberTypeBridge`(关联类型,阶段 7)**:泛型类型的字段用关联类型(`struct AssociatedTypeStorage { var index: C.Index }`,字段串 `A.Swift.Collection.Index`)时,实例化替换只能把 base 的 `dependentGenericParamType` 换成具体类型,节点仍是 `dependentMemberType(具体base, Protocol.Assoc)`。此桥从节点取出 (base 限定名, 协议限定名, 关联类型名) 三元组,查 `__swift5_assocty` 的 witness——`ImageReference` 新建「`conforming|protocol|assoc` → `AssociatedTypeRecord`」索引,`ImageUniverse` 新增第四个解析 seam `resolveAssociatedTypeWitness`(与前三个共用惰性折入)。取到 witness 的 `substitutedTypeName` 后**在声明该 conformance 的镜像里** demangle(其符号引用相对该镜像),再用 base 自身的 bound-generic 环境二次替换(`Array` 的 `Element` witness 是 `Array` 的参数 (0,0) → `Int16`),最后照常 `layout(forTypeNode:)`。base 仍未替换(裸 `A` / depth>0)则降级。 -- **受约束 / 扩展 existential(阶段 7)**:`any Boxed`(带 primary associated type 约束或 same-type 约束的 existential)经 `symbolicExtendedExistentialType` 节点编码——`symbolicExtendedExistentialType → (unique|nonUnique)…ShapeSymbolicReference → constrainedExistential → Type → ProtocolList`。**约束不改变容器大小**(`any Boxed` 与 `any Boxed` 布局相同:opaque buffer + metadata + 每协议 1 witness),故 `extendedExistentialLayout` 取出内层 `ConstrainedExistential` 的 existential 类型节点,路由回既有 `existentialLayout`(自动处理 class-bound / opaque 区分),requirement list 忽略。 +- **受约束 / 扩展 existential(阶段 7)**:`any Boxed`(带 primary associated type 约束或 same-type 约束的 existential)在字段记录里是一个 `symbolicExtendedExistentialType`:extended existential shape 的符号引用(shape 在自己的 generalization signature 上写成 `any Boxed<τ_0_0>`)加上实参列表 `[Int]`。2026-11-11 起(提案 [0092-existential-any](../Evolutions/0092-existential-any.md))`SymbolicDemangler` 解出类型时就把实参代回 shape(`ExtendedExistentialTypeResolution`),交给引擎的是与 getter 符号同形的 `constrainedExistential`。**约束不改变容器大小**(`any Boxed` 与 `any Boxed` 布局相同:opaque buffer + metadata + 每协议 1 witness),故 `existentialLayout` 遇到 `constrainedExistential` 时按它的协议列表算,requirement list 忽略;`any Boxed.Type` 是 `existentialMetatype(constrainedExistential)`,走元类型路径(一个 metadata 字加 witness table——原先从 shape 里往下找时这条分支走不到,被当成了值容器)。`extendedExistentialLayout` 只留给没经过 `SymbolicDemangler` 的树,复用同一个解析函数。 - **嵌套于特化泛型父类的类型命名(阶段 7)**:`Outer.Inner` 作字段时,字段节点是 `Enum/Structure(boundGenericStructure(Outer), Identifier('Inner'))`——父上下文是 `boundGeneric*`。原 `NodeTypeNaming.contextQualifiedName` 的 switch 未处理 `boundGeneric*`(落到 `default: node.text` 返回 nil),导致父链被丢、限定名退化成裸 `Inner` 而 miss 索引(实测 SwiftUI `@Environment.Content` 等 279 例)。修复:`contextQualifiedName` 对 `boundGeneric*` 解包到底层 nominal 再递归、对 `.type` 包裹解包。 - **父链实参环境(阶段 8)**:阶段 7 修好了嵌套类型的**命名**,但字段**使用父参数**的嵌套类型(`Environment` 唯一字段 `content: Content`,`Content` 的 payload 引用 `Value`)仍降级——`Content` 自身不带 `typeList`,实参挂在父链的 `boundGeneric*` 节点上,旧 `make(forBoundGenericNode:)` 只认节点顶层的 `typeList`,建出空环境。修复:`make(forInstantiatedTypeNode:)` 沿 nominal 父链**逐层收集**各 `boundGeneric*` 的 direct `typeList`(demangler 恰好只给声明参数的层套 `boundGeneric*` 壳),最外层 = depth 0——`Environment.Content` 绑定 `{(0,0)→Bool}`,多级 `Outer.Inner` 绑定 `{(0,0)→Int8, (1,0)→Int64}`(顺带修正了旧实现对多级实例化把最内层 typeList 误绑 depth 0 的潜在错位,此前被降级掩盖)。`structureLayout`/`enumLayout` 的 builtin 查表改为**在环境为空时**才做(此前按 `node.kind` 判非泛型;`Enum(BoundGeneric…, Content)` 的 kind 是裸 `.enum`,需以环境判定实例化)。实测这是系统框架剩余 198 例 `genericParameterUnsubstituted` 的全部根因(SwiftUI 的 `Environment<…>` 字段族)。2026-10-01 补上一处遗漏:父链遍历原先在 extension 节点处停下,约束 extension 里声明的类型(`Outer.ConstrainedInner`,外层实参挂在 `Extension(, Outer, )` 的被扩展类型上)只收到最内层实参,把 `String` 绑到 depth 0;现在走进被扩展类型继续收集。遍历本身移到 SwiftInspection 的 `GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode:)`,与离线泛型特化共用([OfflineGenericSpecialization.md](OfflineGenericSpecialization.md))。 -- **class-bound 泛型参数不特化解析(阶段 9)**:阶段 5–8 都在解**具体实例化**(`Foo` 有实参)。阶段 9 转向**未特化**的泛型类型本身:一个 `T: AnyObject` / `T: SomeClass` / `T: SomeClassBoundProtocol` 约束的参数,其存储在运行期**必然是单个对象引用**(8 字节、8 对齐、bitwise-takable、XI = `swift_getHeapObjectExtraInhabitantCount` = 0x7FFF_FFFF(64 位 Darwin 饱和),与具体 class field 完全一致),且**每个 class 实例化布局都相同**——故 `T` 字段本身及其后所有字段无需任何实参即可精确算出。`ClassBoundGenericParameterAnalysis` 读 descriptor 的**累积规范需求签名**(`genericContext.requirements`;需求的 subject 携带绝对 `(depth,index)`,与字段记录同坐标系,嵌套上下文无需额外簿记),demangle 每条需求的**裸参数** subject(约束在依赖成员 `T.Element` 上的不 pin `T`,跳过),再按需求 kind + resolved content 判 class-bound:`layout(.class)`(`T: AnyObject`)、`baseClass`(`T: SomeClass`)、或 class-bound `protocol`(`.objc` 恒真;`.swift` 看 descriptor 的 `classConstraint`;跨镜像 symbol 引用经 `resolveProtocolClassConstraint` + `isObjCProtocolDeclared` seam 按名回收)。结果经 `augmentedWithClassBoundParameterKeys` 注入 `GenericArgumentEnvironment.classBoundParameterKeys`,在每个读字段入口应用(`StaticLayoutCalculator.fieldLayout(ofStruct:/ofClass:)` 与求解器 `computeStructLayout` / `computeClassLayout` 收口点——故泛型超类 `class Sub: Base` 与 ObjC 祖先泛型子类同样受益)。替换阶段:未被具体实参替换、且命中 class-bound 集的 `dependentGenericParamType` 经**同一套 top-down 替换**(故能钻进 `Element?`/`(Element, Int)`/`[Element]`/闭包等复合类型)改写成占位 `.class` 节点,求解器按既有 `.class → .pointerSized` 分派(占位节点名字惰性——class 节点从不被读名/递归)。**具体实参始终优先**于 class-bound 兜底(class-bound 参数的具体实例化用其真实实参);class-bound 泛型 **multi-payload enum**(`ClassBoundContent`)布局固定但 class-bound archetype 不贡献 spare bits(可能装 ObjC tagged pointer,GenEnum.cpp ~7205),其 mpenum 记录 `usesPayloadSpareBits = false`,两条分支算出同样的附加 tag 字节数字。剩余不可静态定:无约束或非 class-bound 参数(`T`、`T: Equatable`、value/pack 参数)——不特化即缺实参,保持逐字段降级。 +- **class-bound 泛型参数不特化解析(阶段 9)**:阶段 5–8 都在解**具体实例化**(`Foo` 有实参)。阶段 9 转向**未特化**的泛型类型本身:一个 `T: AnyObject` / `T: SomeClass` / `T: SomeClassBoundProtocol` 约束的参数,其存储在运行期**必然是单个对象引用**(8 字节、8 对齐、bitwise-takable、XI = `swift_getHeapObjectExtraInhabitantCount` = 0x7FFF_FFFF(64 位 Darwin 饱和),与具体 class field 完全一致),且**每个 class 实例化布局都相同**——故 `T` 字段本身及其后所有字段无需任何实参即可精确算出。`ClassBoundGenericParameterAnalysis` 读 descriptor 的**累积规范需求签名**(`genericContext.requirements`;需求的 subject 携带绝对 `(depth,index)`,与字段记录同坐标系,嵌套上下文无需额外簿记),demangle 每条需求的**裸参数** subject(约束在依赖成员 `T.Element` 上的不 pin `T`,跳过),再按需求 kind + resolved content 判 class-bound:`layout(.class)`(`T: AnyObject`)、`baseClass`(`T: SomeClass`)、或 class-bound `protocol`(`.objc` 恒真;`.swift` 看 descriptor 的 `classConstraint`;跨镜像 symbol 引用经协议 seam `resolveProtocol` 按名回收,Swift 描述符与 ObjC 记录哪个先折进来就认哪个)。结果经 `augmentedWithClassBoundParameterKeys` 注入 `GenericArgumentEnvironment.classBoundParameterKeys`,在每个读字段入口应用(`StaticLayoutCalculator.fieldLayout(ofStruct:/ofClass:)` 与求解器 `computeStructLayout` / `computeClassLayout` 收口点——故泛型超类 `class Sub: Base` 与 ObjC 祖先泛型子类同样受益)。替换阶段:未被具体实参替换、且命中 class-bound 集的 `dependentGenericParamType` 经**同一套 top-down 替换**(故能钻进 `Element?`/`(Element, Int)`/`[Element]`/闭包等复合类型)改写成占位 `.class` 节点,求解器按既有 `.class → .pointerSized` 分派(占位节点名字惰性——class 节点从不被读名/递归)。**具体实参始终优先**于 class-bound 兜底(class-bound 参数的具体实例化用其真实实参);class-bound 泛型 **multi-payload enum**(`ClassBoundContent`)布局固定但 class-bound archetype 不贡献 spare bits(可能装 ObjC tagged pointer,GenEnum.cpp ~7205),其 mpenum 记录 `usesPayloadSpareBits = false`,两条分支算出同样的附加 tag 字节数字。剩余不可静态定:无约束或非 class-bound 参数(`T`、`T: Equatable`、value/pack 参数)——不特化即缺实参,保持逐字段降级。 - **具体 sameType 钉住(阶段 9 补全)**:同一趟需求扫描里,除 class-bound 外还提取 `sameType` 钉住。`extension Foo where Value == Date { struct Bar { var x: Value } }` 这类**约束扩展**里嵌套的类型,其 descriptor 的泛型签名继承了外层 `Value` 参数**加上** `Value == Date` 需求,故字段 `x: Value` 不特化即解析为 `Date`。`ClassBoundGenericParameterAnalysis.layoutFacts` 现返回 `RequirementSignatureLayoutFacts { classBoundParameterKeys, concreteSameTypeSubstitutions }`:对 kind==`.sameType` 且 LHS 为**裸参数**的需求,取 RHS(`resolvedContent` 的 `.type(MangledName)`)demangle、**仅当其完全具体**(不含 `dependentGenericParamType`/`dependentMemberType`——引用别的参数则无法独立替换)时,把 unwrapped RHS 节点作为**真正的 substitution**(不是占位 class)注入 `GenericArgumentEnvironment.substitutions`(`augmented(withRequirementFacts:)`,仅填实例化节点未覆盖的参数——真实例化实参恒优先,且与钉住不矛盾)。钉住到具体类型的参数被编译器从 accessor 的 key 实参里**丢弃**(已被完全确定),故这类嵌套类型的 runtime 布局用**无参** accessor 取得。RHS 可为标量(`Int64`,单镜像即解析)或 bound-generic 具体类型(`Range`,经依赖闭包解析 stdlib descriptor)。实测**收益很小**(5 框架 579 条 sameType 里仅约 23 条是「裸参数 == 具体类型」——75% 是依赖成员 subject 归 assocty bridge、21% 是抽象参数对参数),但它是需求签名能不特化推断的**正确补全**:class-bound + 具体 sameType 合起来 = 需求签名不带实参所能确定的全部。**同值钉住(value generic)同样打通**:`extension ValueGenericBuffer where count == 5` 的需求即 kind==`sameType` 加 `isValueRequirement` 标志(GenMeta.cpp:7460——编译器复用 sameType 而非新增 SameValue kind),RHS mangle 为整数字面量(demangle 出 `.integer` 节点)——`.integer` 天然通过「完全具体」检查、环境按阶段 6 的 value 实参规则绑定,**零代码改动即解析**(fixture `ValuePinnedInner` 的 `InlineArray` 字段 10 字节,双 reader 对 runtime 逐字段相等;值钉住参数同样被丢出 accessor key 实参,无参 accessor 即真值)。顺带修复 SwiftPrinting 接口打印**丢 SE-0452 整数节点**的缺陷(`NodePrintable.printNameInBase` 补 `.integer`/`.negativeInteger`——此前 `ValueGenericBuffer<>`、`InlineArray<, Swift.Bool>`、`where A == ` 渲染为空且已固化进旧接口快照;SwiftDump 路径走 Demangling `NodePrinter` 一直正确)。 -- **Swift 声明 `@objc` 协议的 existential(阶段 8)**:`PlatformAccessibilityElementProtocol & NSObject` 形态。Swift 声明的 `@objc` 协议**不 emit Swift protocol descriptor**(不进 `__swift5_protos`),唯一 runtime 痕迹是 ObjC protocol record(`__objc_protolist`,旧式 `_TtP_` 名)。`ExistentialLayoutBridge` 在 class 约束查找 miss 后回退查第五个 seam `isObjCProtocolDeclared`(`ObjCProtocolIndex` 把 `_TtP…_` 解析回限定名建索引;原生 ObjC 协议的裸名不解析——它们 demangle 成 `__C` 引用、在更早的分支处理):命中即视同 imported ObjC 协议——强制 class-bound、不计 witness table。实测这是系统框架剩余 13 例 `typeDescriptorNotFound` 的全部根因。 +- **Swift 声明 `@objc` 协议的 existential(阶段 8)**:`PlatformAccessibilityElementProtocol & NSObject` 形态。Swift 声明的 `@objc` 协议**不 emit Swift protocol descriptor**(不进 `__swift5_protos`),唯一 runtime 痕迹是 ObjC protocol record(`__objc_protolist`,旧式 `_TtP_` 名)。`ExistentialLayoutBridge` 经协议 seam `resolveProtocol` 同时查 Swift 描述符与 ObjC 协议记录(`ObjCProtocolIndex` 把 `_TtP…_` 解析回限定名建索引;原生 ObjC 协议的裸名不解析——它们 demangle 成 `__C` 引用、在更早的分支处理):落在 ObjC 记录上即视同 imported ObjC 协议——强制 class-bound、不计 witness table。(2026-11-06 前是先查 class 约束、miss 后才回退查第五个 seam `isObjCProtocolDeclared`,每个这种协议都先把整个依赖闭包折一遍。)实测这是系统框架剩余 13 例 `typeDescriptorNotFound` 的全部根因。 - **`ExistentialLayoutBridge`**:从 runtime `ExistentialTypeInfoBuilder`(`TypeLowering.cpp`)移植。opaque `any P` / 协议组合 = 3-word inline buffer + 1 metadata word + 每协议 1 witness word(`32 + 8N`);class-bound(`AnyObject` / class 约束协议 / 显式 superclass)= 1 object word + N witness(`8·(1+N)`);`any Error` = 1 boxed word(8);existential metatype = 1 metadata word + N witness(`8·(1+N)`,与 class-bound 无关)。是否 class-bound 由各协议 descriptor 的 class 约束决定(`protocolListWithAnyObject`/`WithClass` 结构上即 class-bound)。**marker 协议(`Sendable` 等)已被编译器从 mangled field 名剥离**,故每个列出的协议都计 1 个 witness,无需自行过滤 marker。跨模块协议的 class 约束现经依赖闭包解析(见下)。**imported ObjC 协议**(`any NSCopying` 等,由 `NodeTypeNaming.objCProtocolBareName` 识别 `__C.` 的 `.protocol` 节点)无 Swift descriptor:它**恒为 class-bound 且不贡献 Swift witness table**(`id

` 即单个 class 引用),故强制 existential class-bound 且不计入 witness 数——纯 ObjC existential = 8 字节,混合组合 = 1 object word + N(Swift 协议) witness。 - **ObjC 祖先起点(阶段 4)**:`superclassStartLayout` 中,超类 demangle 出的若是 `__C.`(ObjC 类,由 `NodeTypeNaming.objCClassBareName` 识别),则该类自身字段从 ObjC 父类的 `instanceSize` 起算(`NSObject` = 8,仅 isa),经第三个 seam `resolveObjCClassInstanceSize(byBareName:)` 取得;**先于** Swift 侧 `resolveType` 判断(ObjC 名在 Swift 类型索引里必然 miss,若先走 `resolveType` 会无谓地把整条依赖闭包索引一遍)。读法用 `ObjCClassIndex`:从 `__objc_classlist` 取 instance `class_ro_t`(in-process 的 realized 类经 `class_rw_t` 回退)的 `instanceSize`——与 `ObjCClass.info(in:).instanceSize` 同值但不解析 methods/ivars;**取 `instanceSize` 而非 `instanceStart`**(后者是 ObjC 类自身首 ivar 起点,cache 上常为 0)。alignmentMask 取 7(指针对齐)。ObjC 类无 Swift descriptor,故只能这样起算;其上的 Swift 字段照常累加。 - **`ImageUniverse` 依赖闭包(阶段 3)**:`singleImage` 之外新增 `dependencyClosure`。求解器始终只经 `resolveType` / `resolveProtocolClassConstraint` / `resolveObjCClassInstanceSize` 三个 seam 查类型,故闭包**不动求解器一行**。root 立即索引,依赖按 BFS 顺序**惰性索引**——仅当某次 resolve 在已索引镜像里全部 miss 时,才推进索引下一个依赖、命中即停(一次 OS 全闭包可达数百镜像,eager demangle 每个会耗数秒;真实查询只命中前几个 Swift 依赖)。便利工厂:`MachOImage` 经活动 dyld(`MachOImage(name: bareName)`)解析,`MachOFile` 经显式 on-disk 路径 + dyld shared cache(cache 一次性按 bare-name 建索引)。详见 [StaticLayoutDependencyClosure.md](StaticLayoutDependencyClosure.md)。 diff --git a/Documentations/Internal/SwiftDeclaredObjCProtocols.md b/Documentations/Internal/SwiftDeclaredObjCProtocols.md new file mode 100644 index 000000000..7548528e7 --- /dev/null +++ b/Documentations/Internal/SwiftDeclaredObjCProtocols.md @@ -0,0 +1,101 @@ +# Swift 声明的 `@objc` 协议与类对 ObjC 协议的遵循 + +提案 [`swift-declared-objc-protocols`](../Evolutions/0079-swift-declared-objc-protocols.md) 的实现说明。 + +## 一句话 + +Swift 源码声明的 `@objc` 协议没有 protocol descriptor,类对任何 ObjC 协议的遵循也没有 conformance record,所以 `dump` 与 `interface` 原本两样都不输出。现在本库从 `__swift5_fieldmd` 认出本镜像声明的这种协议(`SwiftDeclaredObjCProtocolIndex`),从它的 ObjC 协议记录读出要求,每条要求的 Swift 写法取自实现它的类、没有实现者时按 ClangImporter 的规则从 selector 推出并用 `@objc(selector)` 钉住;类的遵循从 `class_ro_t` 与 category 的协议表读出(`ObjCProtocolAdoptionIndex`),打在类头部与 `extension X: P {}` 上。 + +## 编译器给这种协议留下了什么 + +- **没有 protocol descriptor**:`GenMeta.cpp` 的 `emitProtocolDecl` 在 `isObjC()` 分支直接返回,`__swift5_protos` 里没有它,本库所有从 protocol descriptor 出发的路径都看不见它。 +- **一条 field descriptor**:`emitFieldDescriptor` 在那个分支之前调用,所以本模块声明的每个 `@objc` 协议都有一条 kind 为 `ObjCProtocol` 的 field descriptor,名字是协议的 Swift mangling(`$s13DVTFoundation17DVTTeamCredentialP`)。这是「本镜像声明了它」的唯一可靠证据。 +- **一条 ObjC 协议记录**(`protocol_t`,登记在 `__objc_protolist`):运行时名默认是旧式 mangling `_TtP<模块><名字>_`,嵌套在类型里的是 `_TtPC…`,源码写了 `@objc(Name)` 就是那个名字。记录里有四张方法表、属性表与带类名的扩展类型编码(`@"NSString"32@0:8@"NSString"16^@24`)。 +- **要求没有任何 Swift 符号**:探针确认,无论 public 还是 internal、开不开 library evolution,都没有。和协议有关的 Swift 符号只有 protocol extension 成员、field descriptor、typeref,以及引用属性时的 key path getter(local,`strip -x` 后就没了)。 + +## 认出本镜像的协议(`SwiftDeclaredObjCProtocolIndex`) + +- **以 field descriptor 为准,不看 `protocol_t.flags` 的 IsSwift 位**:引用别的模块的 Swift `@objc` 协议时,Swift 也会生成一份带这一位的弱定义副本;ObjC 代码经 `-Swift.h` 引用 Swift 协议时,clang 生成的副本这一位是 0。两种记录的符号名不同(`_PROTOCOL_<名字>` 与 `_OBJC_PROTOCOL_$_<名字>`),链接时不合并,同一镜像里可能有两份同名记录。所以配对只看名字,同名两份时取这一位为 1 的那份。 +- **配对**:没改名的按运行时名 `_TtP…_` 解出的限定名配;改过名的按「ObjC 名等于 Swift 名的最后一段」配(`@objc(X) protocol X`,苹果的常见写法)。ObjC 名与 Swift 名不同的配不上:声明照样打出,注明找不到记录。 +- **没有反射元数据时**退回:运行时名是 `_TtP…` 且模块是本镜像的 Swift 模块之一的,算本镜像声明的。改过名的认不出来。 +- **没认领的记录**:Swift 生成、却没有声明认领的记录(`unclaimedSwiftEmittedRecords`),只剩改过名的那些:别的模块改过名、被本镜像引用的,以及本镜像里改成别的名字的。下文的跨镜像查找只对这些名字做。 +- `ABI` 层为此加了 `__swift5_fieldmd` 的整段遍历(`fieldDescriptors`)与 `FieldDescriptor.actualSize`:本库原本只顺着类型描述符的指针读 field descriptor,而协议没有类型描述符指向它。 + +## 要求怎么写 + +### 取自实现者 + +`ObjCProtocolWitnesses`(SwiftThunkAnalysis)对每条要求,在采纳了这个协议(或它在本镜像里的子协议)的类里找实现它的成员: + +- 采纳者来自 `ObjCProtocolAdoptionIndex` 的反查,类按 class-list 顺序、再到 category 的目标类,所有要求都找到就停。 +- 成员来自类的 ObjC 成员表([ObjCMemberRecovery.md](ObjCMemberRecovery.md)),只认 `To` 符号与 thunk 代码两档证据,不认只按名字的第三档。**Swift 类的表必须按 Swift 全名取(`table(forSwiftClassQualifiedName:)`)**:按运行时名取的表是给 ObjC 类用的,它要求 thunk 代码引用的成员属于 `__C.<运行时名>`,Swift 类的成员因此在 strip 过的镜像里一个都联结不上——只有 `To` 符号那一档不查归属,没 strip 时看不出来。 +- 声明照抄那个成员的符号,去掉 `@objc` thunk 标记,initializing entry point 读成 allocating 的,**上下文换成协议**:模型与 dump 里这条要求读作协议自己的(`SameNameRenamed.ping()`),不是实现者的。 +- **是否写 `@objc(selector)`**:成员表对 witness 一律不给显式 selector 的判定,因为 witness 的 selector 继承自协议;而协议声明里这条要求本身就是声明处,没有继承可言,所以按 `ObjCMemberShape.isDefaultSelector` 移植的编译器推导判断——推出来的与实际的不同才写,推不出来时照写。 +- 来源的类名是 `TypeName`,经 resolver 打印,模块选择器才能生效。 + +### 只有 selector + +`ObjCProtocolRequirementBuilder`(SwiftObjCInterop)按记录顺序构造声明的 node,形状与 demangle 成员符号得到的一样(`Global > Function`、`Global > Static > Getter > Variable`、`Global > Allocator`、`Global > Getter > Subscript`),打印器照打成员的方式打它: + +- **名字**:`ObjCImporterNaming` 移植 importer 的 `omitNeedlessWords`(`lib/Basic/StringExtras.cpp`)与 `ImportName.cpp` 的相关部分:在第一段的最后一个介词处拆出基名与第一个标签、按参数与返回值的类型名删词、初始化器去掉 `With`、`…error:` 与 `…AndReturnError:` 还原成 `throws`、subscript 访问器。再加本库自己的一步:第一个标签以 `with` 开头、后面还有词时去掉 `with`,这是 Swift 插入 `With` 那条规则的逆运算。completion handler 保持 closure,不改写成 `async`。 +- **类型**:`ObjCTypeEncodingParser` 读扩展类型编码,照 importer 的桥接写成 Swift 类型(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`、`id

` → 协议存在类型、block → closure),可空性未知写 `!`(`Swift.ImplicitlyUnwrappedOptional`,interface 的打印器写成 `T!` 与 `init!`)。MachOObjCSection 的 `extendedMethodTypes(in:)` 只返回表里第一条,本库按下标读整张表。 +- 属性的 getter 与 setter 归到属性,`objectAtIndexedSubscript:` 这类归到 subscript,类方法打 `static`,optional 的打 `optional`。 +- 所有这种要求都打 `@objc(selector)`,协议体开头一行注释说明 Swift 名是推出来的。命名规则的测试以真实 ClangImporter 对同一批 selector 与类型的输出为准(`ObjCImporterNamingTests`)。 + +## 类对 ObjC 协议的遵循(`ObjCProtocolAdoptionIndex`) + +- **数据从哪来**:编译器把一个声明写的 ObjC 协议遵循记进它那份类数据的协议表(`GenClass.cpp` 的 `visitConformances`)。**同一模块里的 extension 并进类自己的数据**,它写的遵循也记在类的 `class_ro_t` 里,探针里这种镜像根本没有 `__objc_catlist`。只有 extension 别的模块的类(ObjC 类,或别的模块的 Swift 类),并且有 `@objc` 成员时,才生成 category。索引读本镜像每个 Swift 类的 `class_ro_t`(没有 class object 的类经 [ClassesWithoutClassObjects.md](ClassesWithoutClassObjects.md) 的索引)与每个 category 的协议表。 +- **隐含的协议**:类遵循一个继承了 ObjC 协议的 Swift 协议时,编译器把那个 ObjC 协议也记进表里(`getObjCProtocols` 的递归)。索引走一遍本镜像的遵循记录:协议是本镜像的 Swift 协议、它的 requirement signature 里 `Self` 的协议要求(递归经本镜像的其它 Swift 协议)出现了 ObjC 协议,这些 ObjC 协议就记作这个类隐含的。类按描述符的限定名对,category 的目标若是 ObjC 类,按遵循记录里的 ObjC 类名(`directObjCClassName`、`indirectObjCClass` 的 `_OBJC_CLASS_$_` 符号)对。先判协议有没有这种祖先、再给类型起名,绝大多数遵循在第一步就跳过了。 +- **为什么是新索引**:找实现者要「谁采纳了协议 P」,打印要「类 X 采纳了哪些」,两种查法在一次构建里建好;`ObjCClassMethodIndex` 与 RuntimeViewer 用的 provider 接缝不动,下游不用跟着改。 + +## ObjC 协议名换成 Swift 名(`ObjCRuntimeNames`) + +- `_TtP…_` 按旧式 mangling 解出。 +- 本镜像改过名的查上面的索引。 +- **别的模块改过名的**:运行时名不带模块。只有本镜像里「没认领的记录」的名字才去找(clang 生成的记录名字的就是 ObjC 协议),到 ObjC 祖先链用的同一个依赖闭包里找。只查带 `__swift5_fieldmd` 的镜像(改过名的协议只能经 field descriptor 认出),系统缓存里 clang 写的框架一个都不读;第一个命中为准,按名字缓存在解析器上。**建索引要 demangle,所以在解析器的锁外建,锁内只做不存在才插入**(项目规则:持锁时不许发生 demangle 跳转)。改成别的名字的协议在它自己的镜像里也配不上,找不到,按 ObjC 名写。 +- **导入的协议在 `__C` 里保留 ObjC 名**(`__C.NSObject`),与编译器的 mangling(`So8NSObject_p`)和现有输出一致;`NSObjectProtocol` 这种 Swift 名由打印时的 type database 按 APINotes 给出。自己加 `Protocol` 后缀会让 type database 按 C 名查不到。 + +## 模型与输出 + +| | 模型 | interface | dump | +|---|---|---|---| +| 协议 | `ObjCProtocolDefinition`(indexer 的 `objcProtocolDefinitions` / `allObjCProtocolDefinitions`),要求是 `ObjCProtocolRequirementDefinition`,在 `index(in:)` 里读;protocol extension 挂成它的 `defaultImplementationExtensions` | `@objc protocol X: P`(改过名加 `@objc(Name)`),排在 Swift 协议之后;嵌套在类型里的打进 `extension 父类型 { … }`;默认实现跟在后面 | `protocols` 段,两种排序都有:每条要求一行 Swift 声明,行尾注释写 selector、required / optional、类型编码、实现者与联结依据;段末一行列出没认领的记录,找到 Swift 名的写在箭头后面 | +| 类的协议 | `TypeDefinition.objcProtocolNames`,在类的 `index(in:)` 里读 | 类头部、父类之后 | 类头部下一行 `// ObjC protocols: …`,隐含的标注 `(implied by a Swift conformance)` | +| category 的协议 | indexer 的 `objcCategoryConformances`(`ObjCCategoryConformance`),`prepare()` 时收集 | 每个 category 一个 `extension X: P {}`,排在所有 extension 之后 | `protocolConformances` 段,`extension X: P {} // ObjC category at 0x…` | + +- **导出状态**:这种协议自己没有符号,新增无结论 case `ExportStatus.declarationHasNoSymbol`,`--exported-only` 下照样保留。下游四个仓库(RuntimeViewer、MachOKitUI、swift-decompiler、MachOViewer)都没有穷举 `ExportStatus` 的 `switch`。 +- **私有协议的名字**:interface 的声明头,以及 dump 在不带父名时声明的名字,都只打裸名(`@objc protocol P {`),不带私有鉴别器,与 Swift 协议的声明头一致。Swift 协议只在 ABI diff 里显示鉴别器,用来区分只差鉴别器的两次构建,而这种协议不进 diff 与 evolution,用不着它。dump 带父名时经 resolver 打印全名,显不显示鉴别器跟 demangle 选项走,这一点也与 Swift 协议相同。 +- **diff 与 evolution 不收录**:类头部的协议只由单版本 interface 的 `printTypeDefinition` 传给头部渲染器(`objcProtocolNames:` 参数),diff 渲染器的 `printTypeHeader` 不传;category 的遵循不进 `conformanceExtensionDefinitions`,只由 `SwiftInterfaceBuilder` 打印。ABI 快照不记这两样,两边一致,快照与二进制对比时不会出现假差异。 +- **SwiftLayout**:`ObjCProtocolIndex` 认存在类型里的 Swift 声明 `@objc` 协议,原本只读 `_TtP<模块><名字>_` 两段式的记录名,改过名的与嵌套在类型里的都认不出,那个存在类型的布局就算不出来。现在并上 `SwiftDeclaredObjCProtocolIndex` 给出的本镜像协议;原读法保留,别的模块协议在本镜像的副本、没有反射元数据的镜像仍靠它。 + +## 已知限制 + +- ObjC 名与 Swift 名不同的改名协议(`@objc(PRBDifferentlyNamed) protocol DifferentlyNamed`)配不上记录,要求列不出来,类头部里它按 ObjC 名写(`__C.PRBDifferentlyNamed`)。 +- 只有 selector 的要求,Swift 名是 importer 规则推出来的,可能与源码不同(探针里照苹果写法显式写 selector 的 10 条对上 5 条);ObjC 层面的含义由 `@objc(selector)` 保住。 +- 隐含的协议只认本镜像的 Swift 协议:遵循的是别的镜像的 Swift 协议时,它继承的 ObjC 协议照样打出来。 +- 同一模块里 extension 写的遵循与类声明写的分不出来,都在类头部;链接器做 category merging 时 category 里的也一样。 +- 别的模块的 Swift 类在本镜像里的 category,目标类名取运行时名;改过名的别的模块的 Swift 类按 ObjC 名写成 `__C.<名字>`。 +- 实现者只在本镜像里找,不到别的镜像里找。 + +## 验证 + +- `SwiftDeclaredObjCProtocolsFixture`(SwiftSectionTestingSupport)测试时现编两个镜像。kit 声明三个 `@objc` 协议(没改名、改成自身名字、改成别的名字);客户端声明六种形状的协议(编译器推导 selector、改成自身名字、改成别的名字、继承另一个、internal、嵌套在类型里)、在类声明与同模块 extension 里采纳它们的类、采纳 kit 协议的类、遵循继承 `NSCopying` 的 Swift 协议的类、extension `DateFormatter` 采纳协议(category),以及装着改名协议与嵌套协议存在类型的结构体;`.full`、关掉反射元数据、`strip -x` 三个变体。 +- `SwiftDeclaredObjCProtocolIndexTests`、`ObjCImporterNamingTests`、`ObjCProtocolRequirementBuilderTests`(SwiftObjCInteropTests):配对、退回路径、没认领的记录;命名规则对照真实 ClangImporter 的输出(含 DVTFoundation 的 selector);要求的种类、访问器、类成员与 optional。 +- `ObjCProtocolDefinitionIndexingTests`(SwiftIndexingTests):文件、进程内、strip 后的文件三条路径的模型——要求的来源(selector 或实现者)、strip 后经 thunk 代码联结、继承的协议、默认实现、类与 category 的协议、跨镜像找回的改名协议、隐含协议的剔除。 +- `SwiftDeclaredObjCProtocolInterfaceTests`(SwiftInterfaceTests)、`SwiftDeclaredObjCProtocolDumpTests`(SwiftDumpTests)、`SwiftDeclaredObjCProtocolRequestTests`(SwiftSectionKitTests):两种输出、两种 dump 排序、进程内与文件的 interface 一致。 +- `SwiftDeclaredObjCProtocolExistentialLayoutTests`(SwiftLayoutTests):存在类型的静态布局对照运行时的字段偏移,进程内与文件两条路径。 +- SymbolTestsCore 的快照:interface 多了三个 `@objc` 协议的声明(`ObjCProto` 嵌在 enum 里,打进 `extension`),`ObjCBridgeWithProto` 的头部带上 `ObjCProto`;dump 里这个类多一行 `// ObjC protocols:`。 +- 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Xcode 26.6,远端依赖):510 个套件、2648 个测试全部通过。已有测试里只动了两处:SymbolTestsCore 的两份快照(重录,见上一条),以及 `ExportStatusTests` 里对 `ExportStatus` 的穷举 `switch` 补上新 case。 +- 渲染 A/B(2026-10-28,JHs-Mac-Studio-Ultra,基线是 `next` 5f09ca46 的 `git archive`,两侧同一份 `Package.resolved`、Xcode 26.6):96 对里 32 对一致(Combine 与 SwiftData 的各条腿),64 对不同(SwiftUI、SwiftUICore、WidgetKit、ActivityKit 的各条腿)。逐行归类,没有一行说不清: + - 删掉的行只有两种:769 处类头部,每处都换成只多了 ObjC 协议的新头部(`class FetchController: __C.NSObject, __C.NSFetchedResultsControllerDelegate where …`,泛型的 `NSHostingView` 也带上了 `SwiftUI.XcodeViewDebugDataProvider`);35 行挪了位置,全是 Swift 声明的 `@objc` 协议的 protocol extension(`extension WidgetKit.WidgetExtensionSession`、iOS 15.5 模拟器的 `extension SwiftUI.PlatformAccessibilityElement`),连同成员与地址注释挪到了协议声明后面。没有任何已有的声明或成员被删掉或改动。 + - 新增的 1979 行都属于预期的几类:协议声明及其要求、三种说明注释、dump 的 `// ObjC protocols:` 行与协议段的事实注释、category 的 `extension`(SwiftUICore 的 `extension __C.NSObject: SwiftUI.PlatformAccessibilityElementProtocol {}`,它的要求因此取自 `__C.NSObject`)。 + - SwiftUI 本身不声明 `XcodeViewDebugDataProvider` 与 `PlatformAccessibilityElementProtocol`:两者是 SwiftUICore 声明的(ABI 模块名同为 `SwiftUI`),SwiftUI 里只有引用它们时生成的副本,声明出现在 SwiftUICore 的输出里。 + - 两侧渲染耗时持平:72 次 CLI 渲染总计 1196 秒对 1236 秒(8 路并发下的总和),cache-26.6 的 SwiftUI interface 都是 20 秒。 +- DVTFoundation(Xcode 26.6)手工核对:11 个协议都打出来,两个改过名的带 `@objc(Name)`;`DVTIconReference` 的头部是 `__C.NSObject, DVTFoundation.DVTResourceReference, __C.NSCopying`;只是被引用的 `NFAImageDownloadObserver`(DVTNFASupport)不打成声明。`BackendCredentialsProvider` 重复列出父协议的两个属性,它自己的记录里就有,源码重新声明过。 + +## 延伸阅读 + +- 提案 [`swift-declared-objc-protocols`](../Evolutions/0079-swift-declared-objc-protocols.md),决策日志记着每处偏离方案的地方。 +- [ObjCMemberRecovery.md](ObjCMemberRecovery.md):ObjC 成员表,实现者的签名从这里取。 +- [ClassesWithoutClassObjects.md](ClassesWithoutClassObjects.md):没有 class object 的类的 `class_ro_t`。 +- [Modules/SwiftLayout.md](Modules/SwiftLayout.md):存在类型的布局。 diff --git a/Documentations/Internal/SymbolIndexStoreMemoryOptimization.md b/Documentations/Internal/SymbolIndexStoreMemoryOptimization.md index 48d17c083..ceac8db2c 100644 --- a/Documentations/Internal/SymbolIndexStoreMemoryOptimization.md +++ b/Documentations/Internal/SymbolIndexStoreMemoryOptimization.md @@ -2,6 +2,8 @@ 日期:2026-08-09(覆盖 2026-07 至 2026-08 的三波优化);最后更新:2026-08-28(8 月中回填了 0002/0003 落地、262 MB 曲线与 opaque 索引的结构键形态;本日做表述层重写,技术内容不变) +> **0.25.0 起的名字**:本文写于模块拆分之前,文中的 `SymbolIndexStore` 即今天的 `SwiftSymbolIndexStore`(模块 `SwiftSymbols`,见 [Modules/SwiftSymbols.md](Modules/SwiftSymbols.md));`SymbolTable`、`SymbolRowBucket` 与采集已迁到 MachOKitExtensions 的 `MachOSymbols`。MachOKitExtensions 里另有一个只收 C/C++/ObjC 名字的 `SymbolIndexStore`,与本文无关。 + ## 导读 这篇文档回答一个问题:`SymbolIndexStore`——RuntimeViewer 浏览二进制时的符号查询底座——的内存占用是怎么从 842 MB 降到 262 MB 的。答案分三波优化:第一波把 demangle 结果从堆上的 class 对象树换成紧凑的连续缓冲存储;第二波把散落各处的小缓存合并、清退;第三波把几十万个驻留的符号名字符串换成「指向原始数据的引用 + 用时再取」。每一波各解决一类浪费,本文逐波讲清它解决什么、付出了什么约束,最后给出实测数字和当前的存储模型全貌。 diff --git a/Documentations/Internal/SymbolicManglingSymbols.md b/Documentations/Internal/SymbolicManglingSymbols.md index bdd884feb..f16ec922d 100644 --- a/Documentations/Internal/SymbolicManglingSymbols.md +++ b/Documentations/Internal/SymbolicManglingSymbols.md @@ -7,8 +7,8 @@ mangled name 里的 symbolic reference 只是 5 个字节(控制字节 + 相对偏移),说得出被引用的东西在哪,说不出它叫什么。 编译器另给每条带引用的 mangled name 生成一个供链接器去重的符号,名字里按引用顺序写出每个被引用者的完整 mangling, -模块、外层类型、private 鉴别符一个不缺,而 dyld shared cache 保留着它们。`SymbolIndexStore` 在已有的符号表扫描里把这类 -符号收进一张独立的表;SwiftInspection 的 `SymbolicManglingIndex` 把每个引用和它的被引用者配对,按被引用的位置建索引。 +模块、外层类型、private 鉴别符一个不缺,而 dyld shared cache 保留着它们。`SwiftSymbolIndexStore` 在已有的符号表扫描里把这类 +符号收进一张独立的表(采集由 MachOKitExtensions 的 `SymbolSweep` 按 `SwiftSymbolTableRouting` 分表);SwiftInspection 的 `SymbolicManglingIndex` 把每个引用和它的被引用者配对,按被引用的位置建索引。 匿名上下文里的类型取名(`AnonymousContextNameIndex`:private 类型的鉴别符,函数体里声明的局部类型的完整名字)是第一个消费者,`SymbolicDemangler` 的对照测试是第二个。 ## 这些符号长什么样 @@ -48,24 +48,24 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference | 层 | 文件 | 做什么 | |---|---|---| -| MachOSymbols | `SymbolicManglingSymbols.swift` | `SymbolicManglingSymbols`:按行、零拷贝的集合(`MachOImage` 的名字留在映射的字符串表里);`SymbolicManglingSymbolName`:拆出角色、带占位的 mangled name、被引用者;字节级前缀判断 `nameBytesHaveSymbolicManglingSymbolPrefix` | -| MachOSymbols | `SymbolIndexStore.swift` | 两条采集腿各多一个前缀分支,收进 `Storage.symbolicManglingSymbolTable`(沿用 `SymbolTable`);查询 `symbolicManglingSymbols(in:)` | +| SwiftSymbols | `SymbolicManglingSymbols.swift` | `SymbolicManglingSymbols`:按行、零拷贝的集合(`MachOImage` 的名字留在映射的字符串表里);`SymbolicManglingSymbolName`:拆出角色、带占位的 mangled name、被引用者;字节级前缀判断 `nameBytesHaveSymbolicManglingSymbolPrefix` | +| SwiftSymbols | `SwiftSymbolIndexStore.swift`、`SwiftSymbolTableRouting.swift` | routing 把这类名字分进采集的 `.symbolicMangling` 表(`.nameOnly`),存为 `Storage.symbolicManglingSymbolTable`(沿用 MachOKitExtensions 的 `SymbolTable`);查询 `symbolicManglingSymbols(in:)` | | SwiftInspection | `SymbolicManglingIndex.swift` | `SymbolicManglingReference`(种类、引用位置、被引用位置、符号位置、第几个被引用者,24 字节);按镜像的 `SharedCache`:读每个符号标的 mangled name、按顺序配对、按被引用位置排一份下标;查询 `references(in:)` / `references(to:in:)` / `referentNode(of:in:)` / `referentNode(forContextDescriptorAt:in:)` / `referentNodes(ofSymbolAt:in:)` / `unpairedSymbolCount(in:)` | | SwiftInspection | `AnonymousContextNameIndex.swift` | 不再自己扫符号表:遍历 `0x01` 引用,每个描述符只读一次父级,父级是匿名上下文就从解好的被引用者节点里取名字——private 类型取鉴别符,局部类型(名字是 `localDeclName`)把整个名字存成 type mangling,用时再解;某个引用解不出来就接着试下一个指向同一描述符的引用。原名 `AnonymousContextPrivateDiscriminatorIndex`,提案 [0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md) 改名 | -| SwiftIndexing | `SwiftDeclarationIndexer.deinit` | 符号库那一支(`claims.symbolStore`)一起驱逐 `SymbolicManglingIndex` | +| SwiftIndexing | `SwiftDeclarationIndexer.deinit` | 符号库那一支(驱逐组 `.swiftSymbolStore`,`.symbolicMangling` 跟随它)一起驱逐 `SymbolicManglingIndex` | ## 为什么这样落 - **独立的一张表**:不进 `symbolRowsByOffset`,所以 `symbols(for:in:)` / `Symbol.resolve` 的结果不变——它们的调用方默认拿到的 都是能 demangle 的 Swift 符号;也不进 demangle 扫描、不进导出事实。`containsSymbol(named:)` 同样看不到它们。 -- **收集在 MachOSymbols、解码在 SwiftInspection**:解码要读 mangled name 的字节,现成的解析是 ABI 模型里的 - `MangledName.resolve(from:in:)`,`MachOSymbols` 的依赖够不到 ABI 模型;提案 0018 也已把符号归属放在 SwiftInspection。 +- **收集在 SwiftSymbols、解码在 SwiftInspection**:解码要读 mangled name 的字节,现成的解析是 ABI 模型里的 + `MangledName.resolve(from:in:)`,`SwiftSymbols` 的依赖够不到 ABI 模型;提案 0018 也已把符号归属放在 SwiftInspection。 - **不驻留 `String` / `Node`**:引用只记位置与下标,被引用者在查询时连同前面的被引用者一起 transient demangle。 -- **驱逐**:索引的存储握着符号库那张表,符号库被回收时它若留着,就钉住那张表,所以放在 `claims.symbolStore` 那一支。 +- **驱逐**:索引的存储握着符号库那张表,符号库被回收时它若留着,就钉住那张表,所以跟随 `.swiftSymbolStore` 那一支。 匿名上下文名字索引只存字符串(鉴别符、局部类型的 mangling),不握任何表,仍跟着 demangle memo 走。 -- **代价**:离线路径(`MachOContext`)找符号本来就经 `SymbolIndexStore`,收集在同一趟扫描里,不多扫一遍。进程内路径 +- **代价**:离线路径(`MachOContext`)找符号本来就经 `SwiftSymbolIndexStore`,收集在同一趟扫描里,不多扫一遍。进程内路径 (`InProcessContext`)找符号走 MachOKit,不建符号库;私有鉴别符改为经本索引之后,进程内第一次遇到没有名字的匿名上下文, - 要先为该镜像建 `SymbolIndexStore`(原先只扫一遍符号表)。RuntimeViewer 这类宿主通常早已为正在看的镜像建好;这笔一次性 + 要先为该镜像建 `SwiftSymbolIndexStore`(原先只扫一遍符号表)。RuntimeViewer 这类宿主通常早已为正在看的镜像建好;这笔一次性 代价没有单独测量。 ## 边界 @@ -103,7 +103,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference - 提案:[0050-symbolic-mangling-symbol-index](../Evolutions/0050-symbolic-mangling-symbol-index.md);上游 [0018](../Evolutions/0018-self-contained-abi-layer.md)(符号归属在 SwiftInspection)、[0001](../Evolutions/0001-symbol-name-offsetization.md) / [0003](../Evolutions/0003-symbol-row-bucket-flattening.md)(符号表的行与名字来源)。 -- [Modules/MachOSymbols.md](Modules/MachOSymbols.md)「子系统 5」。 +- [Modules/SwiftSymbols.md](Modules/SwiftSymbols.md)「子系统 5」。 - [SpecializedInterfaceBoundRenderingRestoration.md](SpecializedInterfaceBoundRenderingRestoration.md)「私有鉴别符(2026-09-24)」:私有鉴别符修复本身。 -- 测试:`Tests/MachOSymbolsTests/SymbolicManglingSymbolCollectionTests.swift`、`Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift`、 +- 测试:`Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift`、`Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift`、 `Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift`、`Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift`。 diff --git a/Documentations/Internal/SystemFrameworkRenderingVerification.md b/Documentations/Internal/SystemFrameworkRenderingVerification.md index 58e6b29c7..198c53726 100644 --- a/Documentations/Internal/SystemFrameworkRenderingVerification.md +++ b/Documentations/Internal/SystemFrameworkRenderingVerification.md @@ -8,7 +8,9 @@ Scripts/run-rendering-ab-verification.py <基线检出> <重构检出> \ [--output-root 目录] [--frameworks A,B,...] [--scenarios cache-15.5,sim-iOS-18.5,...] \ [--baseline-scratch 目录] [--candidate-scratch 目录] [--skip-image-part] \ - [--jobs N] [--baseline-cache 目录 | --no-baseline-cache] [--skip-build] + [--jobs N] [--baseline-cache 目录 | --no-baseline-cache] [--skip-build] \ + [--candidate-dump-arguments 参数] [--candidate-interface-arguments 参数] \ + [--candidate-image-options 选项] ``` 脚本默认自己构建两侧的 release CLI(带 `--skip-build` 时什么都不构建,只用预先构建好的产物,见「关键调用细节」),跑完三部分、输出逐对 IDENTICAL/DIFFERS 表格;有任何差异以非零码退出。 @@ -55,6 +57,17 @@ SwiftUI、SwiftUICore、SwiftData、Combine、ActivityKit、WidgetKit——**输 三样都不碰 `compare_all_pairs` 与 `.skip` 标记的写法,harness 自己的单元测试(`Scripts/test-run-rendering-ab-verification.py`)在改动后重跑为绿。 +## 默认写法变了时怎么比(2026-11-11 起) + +一次改动把新写法设成默认(`any` 关键字,提案 [0092-existential-any](../Evolutions/0092-existential-any.md)),候选与基线在它碰到的每一行上都不同,逐字节比对就说明不了「别的都没变」。办法是只在候选一侧把新默认关掉,再与改动前的基线比: + +- `--candidate-dump-arguments '…'`、`--candidate-interface-arguments '…'`:按 shell 规则拆开,追加到候选一侧 dump / interface 的命令行(如 `--disable-existential-any`、`--no-existential-any`)。基线侧的 CLI 可能不认识这些开关,所以它的命令行与渲染缓存都不受影响。 +- `--candidate-image-options a,b`:追加到候选一侧 MachOImage 部分的 `RV_OPTS`(如 `bareExistentials`,`RenderingVerificationTests` 据此关掉 `any`)。 + +关掉新默认之后仍然不同的行,就是这次改动在新写法之外带来的变化,逐条核对。再打开它跑一遍,抽查差异只在新写法上。 + +interface 默认折叠 `@Observable` 展开之后(提案 [0093-observable-macro-folding](../Evolutions/0093-observable-macro-folding.md)),候选一侧用 `--candidate-interface-arguments=--expand-macros` 与 `--candidate-image-options expandsMacros` 回到折叠之前的写法。dump 没有对应的开关:它的差异只能是 `@Observable` 类的类头行多出 `@Observation.Observable `,去掉这个前缀后应与基线逐字节相同。 + ## 验收标准与差异排查 - 验收:**所有配对逐字节一致**(`cmp`)。 diff --git a/Documentations/Internal/ThunkOnlyObjCMembers.md b/Documentations/Internal/ThunkOnlyObjCMembers.md new file mode 100644 index 000000000..fa02e046b --- /dev/null +++ b/Documentations/Internal/ThunkOnlyObjCMembers.md @@ -0,0 +1,73 @@ +# 只剩 `@objc` thunk 或 initializing entry point 的成员 + +> 提案 [0077-thunk-only-objc-members](../Evolutions/0077-thunk-only-objc-members.md) 的实现说明。读者:维护者。为什么要做、范围怎么定的在提案里,本文讲落地后的形状、几个看代码看不出来的决定,以及边界。 + +## 一句话 + +成员模型从实现符号建成员。优化构建会把实现符号删掉,只留下同一个成员的另一个入口:`@objc` 成员的函数体被内联进它的 Objective-C thunk(`$s…To`),Swift entry point 随后被删掉;class 的 initializer 的 allocating entry point(`…fC`)被内联进调用方后删掉,只剩 initializing entry point(`…fc`)。现在符号索引把每个 `To` thunk 也按它进入的成员登记一份;`indexMembers` 和 extension 索引在真实符号与提案 0054 的 `Tq` 替身之后,再用这两种入口造替身,补上缺的成员;dump 在类的成员列表后面加 `[ObjC Thunk]` 一节。 + +## 规模 + +- Xcode 27.2 的 `Xcode Service` 可执行文件(Release 构建,整模块优化):36 个 `To` thunk 里有 28 个旁边没有 Swift entry point。其中 6 个是 ivar destroyer(`…fETo`),不是成员;其余 22 个成员分布在 7 个类里,比如 `MenuBarPanelWindow` 的 `canBecomeKey`、`XcodeServiceAppDelegate` 的 `applicationShouldOpenUntitledFile(_:)`。另有 9 个 class initializer 只剩 `fc`。改动前 dump 与 interface 一个都不打。 +- 只有 internal 成员会这样:整模块优化看得到它的每一处使用,所有使用都内联完了,entry point 才能删。public 与 open 成员的 entry point 要留给模块外的调用方,删不掉。所以这是 app 和 app 内嵌组件的形状;系统框架的公开 API 基本不受影响。 + +## 落地形状 + +| 层 | 文件 | 做什么 | +|---|---|---| +| SwiftSymbols | `SwiftSymbolIndexStore.swift` | 扫描时,以 `objCAttribute` 开头的符号照旧进 thunk 属性的标记表,此外经 `processMemberSymbol` 按它进入的成员归类,存进第四个成员索引 `objcThunkMemberSymbolRowsByKind`。它与实现符号、`Tq`、protocol witness 三个索引并列,键同样是「成员类别 → 类型名 → 类型节点」,存的是 thunk 自己的行。查询是 `objcThunkMemberSymbols(of:for:in:)`、两个带 node 的重载和 `objcThunkMemberSymbols(of:excluding:in:)`。 | +| SwiftDeclaration | `Indexing/Building/StandInMemberSymbolBuilder.swift` | 造替身与去重:`memberStandIn(forObjCThunkSymbol:in:)`、`allocatorStandIn(forInitializerSymbol:in:)`、`supplementing(_:with:)`、`declaredEntityKey(of:)`(从 `ClassDispatchLookups` 挪过来,0054 的 `Tq` 替身也用它),以及造之前按名字预筛的 `imageKeepsTheMemberSymbol(replacedBy:symbolIndexStore:in:)`。`TypeMembers` 是一个类型自己成员的替身表,`supplementingExtensionMembers(_:symbolIndexStore:in:)` 补 extension 成员。 | +| SwiftDeclaration | `TypeDefinition+MemberIndexing.swift` | 七类成员的 builder 输入都按「真实符号 → `Tq` 替身 → 这两种替身」的顺序拼起来。 | +| SwiftIndexing | `SwiftDeclarationIndexer.indexExtensions()` | 按类型分组之前先补替身;成员全是替身的类型也会得到 extension。 | +| SwiftDump | `ClassDumper` | 成员符号各节之后,按成员类别列出只剩 thunk 的成员(`/* [ObjC Thunk] Function */` 等),行尾照常挂 ObjC 方法表的注释。 | +| SwiftDiffing | `ABISnapshotDocument.currentFormatVersion` | 加一:旧基线会把新建出来的成员全报成新增。 | + +## 替身为什么长这样 + +与 0054 同一个思路:替身照它顶替的实现符号的样子造,mangled 名和成员树都与实现符号相同,偏移用镜像里留下的那个入口。 + +- **名字**:thunk 的名字就是成员的 mangled 名后面接 `To`,去掉后缀就是实现名;initializer 的两个入口只差最后的 `fc` / `fC`。下游按名字推导的几处——导出判定往名字后面拼 `Tj` / `Tq`,ObjC 方法表按「名字 + `To`」联结(initializer 按 allocator 名换成 `…fcTo`),`applyThunkAttributes` 按成员名打 `@objc`——都不用改。 +- **树**:thunk 的树是 `global(objCAttribute, )`,去掉标记节点得到 `global()`,与实现符号 demangle 出来的形状一样,所以 vtable 的 `Tq` 按节点联结照常命中。`handleTick(_:)` 这种实现指针为 null 的槽也能联结上,成员于是按槽号排序。initializing entry point 的 entity 是 `constructor`,要改写成 `allocator`:builder 只认 allocator,vtable 槽、ObjC 方法表与 ABI 身份也都按 allocator 记。 +- **偏移**:thunk 是 `@objc` 成员唯一的代码,initializing entry point 是 initializer 唯一的代码,地址注释就指向它们。注意 thunk 用的是 Objective-C 的调用约定(`x0` 是 `self`,`x1` 是 `_cmd`),不是 Swift 的。 +- **一个 initializer 两个入口都剩下**(`XcodeServiceAppDelegate.init()` 有 `fc` 与 `fcTo`,没有 `fC`):initializing entry point 的替身排在 thunk 的替身前面,先到者胜,地址落在 Swift 的入口上。 + +## 什么时候不补 + +- **真实符号或 0054 的 `Tq` 替身已经声明了这个成员**:按成员实体节点结构相等判断(`declaredEntityKey(of:)`,merged function 先跳过它开头的标记节点)。造替身之前还会先按名字查实现符号在不在,在就不造:没有被优化掉的镜像里,几乎每个 `@objc` 成员和 initializer 都是这种情况,这一步省掉了逐个物化、intern 再丢弃的开销。 +- **`…ToTm`**:几个 thunk 合并后共用的函数体。`Xcode Service` 里 `canBecomeKey` 等三个 thunk 都是 `mov w2, #imm; b` 跳进同一个 `…ToTm`。它不是成员,扫描时第一个子节点是 `mergedFunction`,根本进不了新索引。 +- **`__ivar_destroyer`**(`…fETo`):`processMemberSymbol` 不认它,同样不进新索引。 + +## 顺带修的 `@objc` 误标 + +`applyThunkAttributes` 按成员名给成员打 `@objc`,但 initializer 的 thunk 记不下 initializer 的名字(`ThunkAttributeMember.memberName` 取的是树里遇到的第一个 identifier,也就是类型名),于是只要一个 initializer 有 thunk,这个类的**所有** initializer 都被打上 `@objc`。`Xcode Service` 的 0.24.0 输出里 `MenuBarLabelHostingView` 的 `@objc override init(rootView:)` 就是这样来的:`init(rootView:)` 是 `NSHostingView` 的泛型初始化方法,不可能是 `@objc`,真正有 thunk 的是 `init?(coder:)`。这次补回的 initializer 让问题更显眼——`MenuBarPanelPresenter.init(statusItem:content:)` 的参数是 `SwiftUI.AnyView`,也被打成了 `@objc`。 + +现在按 mangled 名找 initializer:thunk 进入的是 initializing entry point,它的名字是 allocator 名把 `fC` 换成 `fc`,再接上 thunk 种类的后缀(`To` / `TO` / `TE`),镜像里有这个符号才打。渲染 A/B 里看到,`@nonobjc` 的 `TO` thunk 也会挂在 allocating entry point 上(iOS 15.5 模拟器的 SwiftUI 里有 16 个 `…fCTO`、25 个 `…fcTO`,ObjC 的 `To` 则是 187 个 `…fcTo`、0 个 `…fCTo`)。这 16 个全是 SwiftUI 调用的导入 ObjC initializer 的桥接 thunk(`NSFileHandle.__allocating_init(forReadingFrom:)` 一类),镜像里没有它们的实现,interface 从不打印,所以只查 `fc` 不会漏掉任何打印出来的成员。基线把 SwiftUI 自己写在这些类 extension 里的 initializer 也盖上 `@nonobjc`,正是被这些 thunk 带出来的。`ThunkOnlyMemberFixture` 的 `ThunkOnlyWidget.init(tags:)` 钉住这一点。 + +方法有同一类问题:标记表里只有成员名,重载共用一个名字,`@objc func handleTick(_:)` 旁边的 Swift-only `handleTick(count:)` 也被打成 `@objc`。现在方法同样按自己的符号名加后缀查 thunk(merged function 先去掉 `Tm`)。属性仍按名字匹配:一个类型里不会有两个同名属性。fixture 里的 `handleTick(count:)` 钉住这一点。 + +## Swift 6.4:initializer 只剩签名特化副本 + +Swift 6.4 的 `-O -wmo` 对 internal 类的 initializer 又多做一步:allocating entry point 照旧内联进调用方删掉,initializing entry point 也换成它的函数签名特化副本(function signature specialization,`…fcTf4gn_n`:编译器改了参数的传递方式,比如把 owned 改成 guaranteed,再让所有调用方改调副本)后删掉。镜像里这个 initializer 只剩副本,`fc` 与 `fC` 都没有,上面两种替身都造不出来,interface 里它整个缺席。Xcode 27.2(Swift 6.4.2)编出的夹具就是这样,`ThunkOnlyObjCMemberTests` 因此红了 4 处。 + +- **索引**:副本的树是 `global(functionSignatureSpecialization, constructor)`。扫描时以 `functionSignatureSpecialization` 开头、后面是 `constructor` 的符号,按它特化的 initializer 归进第五个索引 `specializedInitializerSymbolRowsByKind`(键与另外四个相同,存副本自己的行);别的特化不归档,免得给每个特化过的函数都多存一份。查询是 `specializedInitializerSymbols(of:for:in:)`、带 node 的重载和 `specializedInitializerSymbols(of:excluding:in:)`。 +- **替身**:`allocatorStandIn(forSpecializedInitializerSymbol:in:)`。副本的名字就是 initializing entry point 的名字接上 `Tf…` 后缀,所以从后往前找 `Tf`,取第一个使前缀以 `fc` 结尾的位置,前缀就是 initializing entry point 的名字(`specializedInitializerName(of:)`);特化的特化(`…fcTf4gn_nTf4n_g`)也读得回去。之后与 initializing entry point 的替身完全一样:`constructor` 改写成 `allocator`、`fc` 换成 `fC`,偏移是副本的偏移。 +- **什么时候用**:只在镜像里 `fc` 与 `fC` 都没有时(`imageKeepsTheMemberSymbol(replacedBy:symbolIndexStore:in:)` 对副本查这两个名字)。顺序排在 initializing entry point 的替身之后、thunk 的替身之前,所以还有 `fc` 时地址落在 `fc` 上。 +- **地址**:注释指向副本。副本的参数约定与原函数不同(`Tf` 后面的编码写着改了什么),反汇编时要照副本的约定读。 +- **ABI 快照格式升到 11**:旧基线会把这些 initializer 报成新增。 + +## 边界 + +- **泛型类与经 `__objc_stublist` 登记的类没有静态的 class object**。本提案落地时读不到它们的 ObjC 方法表,替身成员只有 thunk 给的 `@objc`。2026-10-27 起方法表从 Swift 元数据读(提案 `objc-classes-without-class-objects`,[ClassesWithoutClassObjects.md](ClassesWithoutClassObjects.md)),`override` 照常给出;只有父类是另一个镜像里的 Swift 类时,链断在那里,仍然只有 `@objc`。 +- **`class` 与 `static`**:没有 vtable 槽的类型级成员照旧打成 `static`,与有实现符号时一样(见 [ClassMemberKeywordRecovery.md](ClassMemberKeywordRecovery.md))。 +- **interface 里替身成员与普通成员看起来一样**,替身从哪来只在 dump 里写明。从 initializing entry point 建出的 initializer,dump 本来就列在 `/* Constructor */` 下,没有改。 +- **0054 的「ABI 墓碑不补」照旧**:墓碑槽本身不造替身。槽对应的成员若还剩 initializing entry point 或 `@objc` thunk,由那一边的替身补上,槽号经节点联结照常挂上。 + +## 验证 + +- `ThunkOnlyMemberFixture`(SwiftSectionTestingSupport)把同一份源码编两次:`-Onone` 保留每个入口,是独立的事实;`-O -wmo` 复现 app 的 Release 构建。内部类的 ObjC 覆写(`description`、`isEqual(_:)`、`init()`)、`@objc` 方法与 `@objc class func`、同模块 extension 里的 `@objc` 方法、`NSObject` extension 里的 `@objc` 方法、泛型类的覆写与它合成的 `init()`,以及只剩 `fc` 的 `init(values:)`。 +- `ThunkOnlyObjCMemberTests`(SwiftInterfaceTests):先钉住前提(优化版里 `isEqual(_:)` 只有 thunk、`init(values:)` 只有 `fc`,否则后面的断言会在不再删 entry point 的编译器上空过);两份构建打印出的各声明块成员集合相同;`@objc` / `override` 按 ObjC 方法表给出,泛型类只有 `@objc`;替身的地址是 thunk 或 `fc` 的地址;进程内 `MachOImage` 与文件打印相同。 +- `ThunkOnlyObjCMemberDumpTests`(SwiftDumpTests):优化版的 dump 有 `[ObjC Thunk]` 各节和方法表注释,未优化版没有这一节,泛型类的 thunk 行不带 ObjC 注释。 +- 修复前先跑(JHs-Mac-Studio-Ultra,Xcode 26.6,远端依赖):只有测试的提交上,7 个暴露问题的测试全部失败(24 处),3 个只核对前提的测试通过;`@objc` 误标的两条测试在各自的修复之前,两种构建都失败,印出的正是 `@objc init(tags: [Swift.String])` 与 `@objc func handleTick(count: Swift.Int) -> Swift.Int`。 +- 修复后:新增的两个套件 11 个测试全部通过;全量 `swift test --skip IntegrationTests` 2599 个测试 / 499 个套件,唯一的变化是 SymbolTestsCore 的 interface 快照里三个参数为泛型 `A` 的 initializer 不再带 `@objc`(快照随之更新,单独重跑通过)。 +- `Xcode Service`:本分支与 `next` 基线各编 release CLI 对比,dump 只有新增(70 行,各类的 `[ObjC Thunk]` 一节),interface 只删掉两行,是 `MenuBarLabelHostingView` 两个被误标的 `@objc override init(rootView:)` / `init?(coder:rootView:)`;22 个只剩 thunk 的成员与 9 个只剩 `fc` 的 initializer 都打出来了,地址分别是 thunk 与 `fc` 的地址。 +- 渲染 A/B(2026-10-27,Ultra,基线 `next` b4d76a3b,两侧同一份 `Package.resolved`):96 对里 61 对逐字节一致,35 对不同,全部人工归了类。dump 的差异全是新增;interface 删掉的行,除下面几处,都能在候选侧找到去掉 `@objc` 的同一行,即两处 `@objc` 误标的修正。其余几处:`hitTest(_:cacheKey:)`、`attributes(location:effectiveRange:rangeLimit:)`、`_update(environment:)` 这类参数里有 `UInt32?`、`_NSRange?` 或 `inout` Swift 结构体、不可能是 `@objc` 的方法,去掉 `@objc` 后没有 vtable 槽的随之判成 `final`;SwiftUICore 的 `TextAnimator.configuration` 从「由 backing storage 合成、类型只知道是 `Any?`」变成从 thunk 的 getter 与 setter 建出、类型 `[Swift.String : Any]?`;一个 `accessibilityIdentifier` 因 getter 有了替身而联结上 ObjC 方法表,多出 `override`。新增的大头在 SwiftUI:它保留了 local 符号,内部类的 `@objc` 覆写常常只剩 thunk。 diff --git a/Documentations/ObjCCommandLine.md b/Documentations/ObjCCommandLine.md index 975d5be57..fd5222b51 100644 --- a/Documentations/ObjCCommandLine.md +++ b/Documentations/ObjCCommandLine.md @@ -30,6 +30,9 @@ swift-section objc dump # One class, protocol, category, struct or union swift-section objc interface +# The same class, protocol or category as Swift imports it +swift-section objc interface --swift + # Freeze a binary's Objective-C API as a baseline snapshot (JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -38,6 +41,9 @@ swift-section objc diff # Follow every declaration across N ≥ 2 versions swift-section objc evolution --labels 17.0,18.0,26.0 + +# The same versions merged into one header, each declaration annotated with its lifecycle +swift-section objc evolution --labels 17.0,18.0,26.0 --interface -o evolution.h ``` `dump` is the default, so `swift-section objc ` is `swift-section objc dump `. @@ -74,6 +80,47 @@ reads other images yet (see the first item under [Things you must know](#things- Without it the first match wins, in the order classes → protocols → categories → structs → unions. +## The Swift view (`interface --swift`) + +`interface --swift` prints a class, category or protocol the way Swift imports it, the +declaration Xcode shows as its Generated Interface, instead of as an Objective-C header: + +```text +$ swift-section objc interface NSColor --uses-system-dyld-shared-cache -n AppKit --swift +class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __C.NSCopying, … { + // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them. + @objc(encodeWithCoder:) func encode(with: __C.NSCoder!) + init!(coder: __C.NSCoder!) + … +``` + +- **The names are inferred.** They are the ClangImporter's naming rules applied to what the + binary records. On macOS 27.2's AppKit about 81 % of the public members get the name the SDK + gives them. The rest need what only the SDK has: API notes and `NS_SWIFT_NAME` renames, enum + and option-set type names, collection element types, nullability. Where the printed name would + not lead the compiler back to the selector, `@objc(selector)` pins it. +- **The types are what the binary records.** An object whose nullability is unknown prints as + `T!`, as Swift imports a header without nullability annotations; an enum or option-set + argument prints as its integer type; imported types keep their Objective-C names under `__C`. +- **What Swift implements prints as Swift declares it.** A Swift class prints as the Swift class. + An `@objc @implementation` class prints as its Swift side: the implementation's body under the + class's own declaration, its Swift-only members included, then the Objective-C methods no Swift + member answers to. A member of a Swift extension prints as that Swift member. An OS framework + strips the thunks and inlines the bodies into them, so a member the symbols do not tie is paired + with the Swift member the importer's rules name after its selector, when that is the only one + and its type fits. A property the header marks `NS_REFINED_FOR_SWIFT` is implemented under a + `__` name; when that implementation left no symbol, the property shows as a comment, + `// NS_REFINED_FOR_SWIFT: var __settings: …`, right above the Swift property that took its plain + name. A stored property whose type the binary does not + record prints as the Objective-C property synthesized on it. The binary's Swift declarations are + indexed first for this, so `--swift` takes longer than the header: about 16 seconds for AppKit. +- **A class shows its own members.** The linker merges a binary's categories on its own classes + into the classes, so they print as members of the class; in a dyld shared cache, the categories + the cache attached to a class ahead of time are left out. Only a category on a class of + another binary is a category; name it by its unique name, such as `CIColor(NSAppKitAdditions)`. +- A Swift class goes by its runtime name (`_TtC6AppKit11SliderModel`), as for the header. Structs + and unions have no Swift view. + ## Ten generation switches All of them default to off: with none given, the output is the metadata as it stands, nothing @@ -134,16 +181,38 @@ swift-section objc evolution CoreLocation-*.json --summary-only | Option (`diff` and `evolution`) | Meaning | |---|---| | `--summary-only` | Only the verdict (`diff`: the breaking line; `evolution`: the transition summary) | -| `--json` | Structured JSON instead of the text report (not together with `--summary-only`) | +| `--json` | Structured JSON instead of the text report (not together with `--summary-only` or `--interface`) | | `--fail-on-breaking` | Exit nonzero when there is an API-breaking change, for CI gating | | `-o, --output-path ` | Write to a file instead of stdout (progress and logs always go to stderr) | | `--labels a,b,c` | `evolution` only: the version axis, one label per input; defaults to each snapshot's stored label or the file name | +| `--interface` | `evolution` only: one header merging every version, each declaration annotated with its lifecycle (see below); every input must be a binary or a cache | +| `--emit-available` | With `--interface`: also spell each lifecycle one availability macro expresses (`API_AVAILABLE` / `API_OBSOLETED`) | +| `--platform ` | With `--emit-available`: the macros' platform name, instead of the one inferred from `LC_BUILD_VERSION` | The input options (`--dyld-shared-cache` / `-n` / `-p` / `-a`) are the same as `dump`'s; for `diff` and `evolution` they mean "every input is a cache, extract the same image from each". `snapshot` rejects `--uses-system-dyld-shared-cache`: the running system's cache has no stable path to record in the baseline. +### The annotated header (`evolution --interface`) + +`--interface` replaces the lineage report with one header that merges every version. Each declaration is rendered the way `objc dump` renders it, and the ones that changed carry their lifecycle at the end of the line — `// [○●●] added in 18.0`, `removed in …`, or `modified in …: old → new` — where the bitmap has one position per version and the header's second line says which. A removed declaration stays where it last was. A class, protocol or category that was added or removed is annotated on its `@interface` / `@protocol` line alone, not member by member, and a changed superclass or protocol adoption is a comment line above it. The annotations are the lineages the text and JSON reports print, read from the same snapshots. + +`--emit-available` also spells each lifecycle one availability macro can express: `API_AVAILABLE(macos(13.0))` for a declaration added inside the axis, and `API_OBSOLETED("Removed", macos(12.0, 13.0, 13.0))` for one added and later removed. The versions are axis points, not necessarily the releases that really introduced or removed a declaration. A declaration present from the first version and removed later gets no macro, because `API_OBSOLETED` needs the version that introduced it; neither does one that disappeared and came back, one that was only modified, or one whose labels are not version numbers. The platform comes from every input's `LC_BUILD_VERSION`, a simulator counting as its device. When the inputs name none or different ones, name it with `--platform` in the macros' own spelling: `macos`, `ios`, `tvos`, `watchos`, `visionos`, `macCatalyst` or `driverkit`. + +```bash +swift-section objc evolution \ + 15.5/dyld_shared_cache_arm64e \ + 26.5/dyld_shared_cache_arm64e \ + 27.0/dyld_shared_cache_arm64e \ + --dyld-shared-cache -n AppKit \ + --labels 15.5,26.5,27.0 \ + --interface --emit-available \ + -o AppKit-evolution.h +``` + +Every input must be a binary or a cache: a snapshot does not carry rendered declarations, so a snapshot input is a usage error. Pass `--labels` when the inputs are caches, since each label otherwise defaults to the file name, which is `dyld_shared_cache_arm64e` for all of them. The versions are indexed one at a time and only what was rendered is kept: in a release build, AppKit across 52 macOS caches (11.0.1 to 27.2) takes about three minutes and peaks at 2 GB. + ## Things you must know Each of these lets a normal-looking output lead to a wrong conclusion, and none of them shows @@ -212,3 +281,17 @@ complain about four kinds nobody asked for. **Keeping exit code 0 is deliberate**: these are diagnostics, not failures, and no existing script or CI job should turn red over them. For gating, use `diff --fail-on-breaking`. + +### 5. Swift classes without a class object are read from Swift metadata + +`__objc_classlist` holds a class object for every Swift class whose metadata the compiler can emit complete. Three kinds of class have none. They are listed from their Swift metadata instead, each under a comment line naming the kind: + +| Comment | Class | Listed as | +|---|---|---| +| `// Generic Swift class, instantiated at runtime` | A generic class. Its `class_ro_t` is the template its generic metadata pattern carries, and every instantiation gets a copy with a name of its own | Its Swift name with its generic parameters: `Module.Panel` | +| `// Swift class with resilient ancestry, registered through __objc_stublist` | A class whose superclass is in another module built with library evolution, such as SwiftUI | Its runtime name: `_TtC6Module5Label` | +| `// Swift class with generic ancestry, registered through __objc_stublist` | A class whose superclass is a generic class of the same module | Its runtime name | + +The last two kinds are listed only when an Objective-C class is among their ancestors, since only then does the compiler register them in `__objc_stublist`. A superclass that is a Swift class of another binary keeps its Swift spelling (`SwiftUI.NSHostingView`), and `--strip-overrides` cannot see past it. + +A `snapshot` written by `swift-section` 0.24.0 or earlier does not contain these classes, so a `diff` against it reports each of them as added. Regenerate the baseline with the current tool before you compare. diff --git a/Documentations/ObjCCommandLine_zh.md b/Documentations/ObjCCommandLine_zh.md index b53d0b5ce..2780ba95a 100644 --- a/Documentations/ObjCCommandLine_zh.md +++ b/Documentations/ObjCCommandLine_zh.md @@ -27,6 +27,9 @@ swift-section objc dump # 只导出一个类 / 协议 / 分类 / struct / union swift-section objc interface +# 同一个类 / 协议 / 分类,打印成 Swift 导入它的样子 +swift-section objc interface --swift + # 把二进制的 Objective-C API 冻结成基线快照(JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -35,6 +38,9 @@ swift-section objc diff # 跨 N ≥ 2 个版本追踪每个声明的生命线 swift-section objc evolution --labels 17.0,18.0,26.0 + +# 把这几个版本合并成一份头文件,每个声明标出自己的生命周期 +swift-section objc evolution --labels 17.0,18.0,26.0 --interface -o evolution.h ``` `dump` 是默认子命令,所以 `swift-section objc ` 等于 `swift-section objc dump `。 @@ -68,6 +74,35 @@ Objective-C 这边目前不读取别的镜像(见「必须知道的四件事 `interface` 还有一个 `--kind`,用来区分一个既是类名又是 struct 名的名字。不给的话按 类 → 协议 → 分类 → struct → union 的顺序取第一个找到的。 +## Swift 视图(`interface --swift`) + +`interface --swift` 把一个类、分类或协议打印成 Swift 导入它之后的样子,也就是 Xcode 里 +Generated Interface 显示的声明,而不是 Objective-C 头文件: + +```text +$ swift-section objc interface NSColor --uses-system-dyld-shared-cache -n AppKit --swift +class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __C.NSCopying, … { + // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them. + @objc(encodeWithCoder:) func encode(with: __C.NSCoder!) + init!(coder: __C.NSCoder!) + … +``` + +- **名字是推出来的**:把 ClangImporter 的命名规则用在二进制记录的信息上。macOS 27.2 的 + AppKit 里,公开成员约有 81 % 与 SDK 给的名字一致;其余的要 SDK 才有的信息:API notes 与 + `NS_SWIFT_NAME` 的改名、枚举与选项集的类型名、集合的元素类型、可空性。打印出的名字推不回 + 原 selector 时,用 `@objc(selector)` 钉住。 +- **类型是二进制记录的类型**:不知道可空性的对象打成 `T!`,与 Swift 导入没有可空性标注的 + 头文件一样;枚举与选项集参数打成它的整数类型;导入的类型保持 `__C` 下的 Objective-C 名。 +- **Swift 实现的部分照 Swift 的声明打印**:Swift 类打成那个 Swift 类,`@objc @implementation` + 类与 Swift extension 的成员打成那个 Swift 成员。为此要先索引二进制里的 Swift 声明,所以 + `--swift` 比头文件慢,AppKit 约 16 秒。 +- **类只显示自己的成员**:链接器会把二进制给自己的类写的分类并进类里,所以它们打成类的成员; + dyld shared cache 里,cache 预先附加到类上的分类不算。只有给别的二进制的类写的分类才是分类, + 按它的唯一名字指定,例如 `CIColor(NSAppKitAdditions)`。 +- Swift 类按运行时名指定(`_TtC6AppKit11SliderModel`),与头文件一样。struct 与 union 没有 + Swift 视图。 + ## 十个生成开关 全部默认关闭:一个开关都不加时,输出就是元数据的原样,不删任何东西,也不加任何注释。 @@ -124,16 +159,38 @@ swift-section objc evolution CoreLocation-*.json --summary-only | 选项(`diff` 和 `evolution` 都有) | 作用 | |---|---| | `--summary-only` | 只打印结论(`diff`:是否破坏兼容的那一行;`evolution`:各次版本变化的摘要) | -| `--json` | 输出结构化 JSON,而不是文本报告(不能和 `--summary-only` 一起用) | +| `--json` | 输出结构化 JSON,而不是文本报告(不能和 `--summary-only` 或 `--interface` 一起用) | | `--fail-on-breaking` | 有破坏 API 兼容的变化时以非零退出码结束,给 CI 把关用 | | `-o, --output-path ` | 写进文件,而不是 stdout(进度和日志一律走 stderr) | | `--labels a,b,c` | 只有 `evolution` 有:版本轴的标签,每个输入一个;不给时取快照里存的标签或文件名 | +| `--interface` | 只有 `evolution` 有:把所有版本合并成一份头文件,每个声明标出自己的生命周期(见下文);每个输入都必须是二进制或 cache | +| `--emit-available` | 配合 `--interface`:一个可用性宏能表达的生命周期,再写成这个宏(`API_AVAILABLE` / `API_OBSOLETED`) | +| `--platform ` | 配合 `--emit-available`:宏里的平台名,不用从 `LC_BUILD_VERSION` 推断的那个 | 输入选项(`--dyld-shared-cache` / `-n` / `-p` / `-a`)和 `dump` 一样;在 `diff` 和 `evolution` 里的 意思是「每个输入都是 cache,从每一份里取同一个镜像」。`snapshot` 不接受 `--uses-system-dyld-shared-cache`:当前系统的 cache 没有一个稳定的路径可以记进基线。 -## 必须知道的四件事 +### 带标注的头文件(`evolution --interface`) + +`--interface` 不出逐条的报告,而是把所有版本合并成一份头文件。每个声明都按 `objc dump` 的方式渲染;有变化的声明在行尾写出生命周期:`// [○●●] added in 18.0`、`removed in …`,或者 `modified in …: 旧 → 新`。位图每一位对应一个版本,对应关系写在文件头的第二行。删掉的声明留在它最后出现的位置。加入或删掉的类、协议、分类只在 `@interface` / `@protocol` 那一行标注,成员不再逐个标;父类或协议遵循变了,写成它上方的一行注释。这些标注就是文本报告和 JSON 里的那些 lineage,取自同样的快照。 + +`--emit-available` 再把一个可用性宏能表达的生命周期写成宏:在版本轴中途加入的写 `API_AVAILABLE(macos(13.0))`,加入后又删掉的写 `API_OBSOLETED("Removed", macos(12.0, 13.0, 13.0))`。宏里的版本是版本轴上的点,不一定是真正引入或删除这个声明的那个版本。从第一个版本就在、后来删掉的声明不写宏,因为 `API_OBSOLETED` 必须带引入版本;删了又加回的、只被修改过的、标签不是版本号的,也都不写。平台取自每个输入的 `LC_BUILD_VERSION`,模拟器算作它对应的设备平台。输入里没有平台、或者平台各不相同时,用 `--platform` 按宏自己的写法指定:`macos`、`ios`、`tvos`、`watchos`、`visionos`、`macCatalyst` 或 `driverkit`。 + +```bash +swift-section objc evolution \ + 15.5/dyld_shared_cache_arm64e \ + 26.5/dyld_shared_cache_arm64e \ + 27.0/dyld_shared_cache_arm64e \ + --dyld-shared-cache -n AppKit \ + --labels 15.5,26.5,27.0 \ + --interface --emit-available \ + -o AppKit-evolution.h +``` + +每个输入都必须是二进制或 cache:快照里没有渲染好的声明,传入快照会报用法错误。输入是 cache 时要传 `--labels`,否则每个标签都取文件名,而这些文件都叫 `dyld_shared_cache_arm64e`。各版本逐个索引,只留下渲染好的内容:release 构建下,AppKit 跨 52 个 macOS cache(11.0.1 到 27.2)约三分钟,内存峰值约 2 GB。 + +## 必须知道的五件事 下面每一条,都会让一份看起来正常的输出把你引向错误的结论,而且签名和 `--help` 里都看不出来。 @@ -189,3 +246,17 @@ dump 一个纯 Swift 二进制,都会为你根本没问过的四类刷屏。 **退出码保持 0 是有意的**:这些是诊断信息,不是失败,不应该让任何现有的脚本或 CI 因此变红。 需要把关时,用 `diff --fail-on-breaking`。 + +### 五、没有 class object 的 Swift 类,从 Swift 元数据读出来 + +编译器能把元数据整个静态生成的 Swift 类,在 `__objc_classlist` 里都有一个 class object。有三种类没有,它们改为从 Swift 元数据读出来列出,每个前面有一行注释说明是哪一种: + +| 注释 | 哪种类 | 列出时用的名字 | +|---|---|---| +| `// Generic Swift class, instantiated at runtime` | 泛型类。它的 `class_ro_t` 是 generic metadata pattern 里的模板,每次实例化都拷一份、各自取名 | Swift 名字加上泛型参数:`Module.Panel` | +| `// Swift class with resilient ancestry, registered through __objc_stublist` | 父类在另一个开了 library evolution 的模块里的类,比如 SwiftUI 的类 | 运行时名:`_TtC6Module5Label` | +| `// Swift class with generic ancestry, registered through __objc_stublist` | 父类是本模块泛型类的类 | 运行时名 | + +后两种只在祖先里有 Objective-C 类时才列出,因为只有这时编译器才把它们登记进 `__objc_stublist`。父类是另一个二进制里的 Swift 类时,父类名保持 Swift 写法(`SwiftUI.NSHostingView`),`--strip-overrides` 也越不过它。 + +`swift-section` 0.24.0 及更早版本写的 `snapshot` 里没有这些类,拿它做 `diff` 会把它们一个个报成新增。比较之前先用当前版本重新生成基线。 diff --git a/Documentations/README.md b/Documentations/README.md index 4e89fe70d..be8fecfe5 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -1,5 +1,7 @@ # Documentation +**Start here: [Internal/ProjectMap.md](Internal/ProjectMap.md)** — 项目地图:项目现在长什么样(产物、模块分层、`dump` / `interface` / `evolution` 三条关键流程、地标、术语、在做的事、复杂度热点),头部记着核对时的 commit,之后的改动从那里讲起。 + Documentation is split by audience. > **Project kind: library (source distribution).** SPM library product consumed from source — @@ -12,6 +14,16 @@ Documentation is split by audience. > Proposals [0006](Evolutions/0006-final-keyword-and-lazy-accessor-type-recovery.md)–[0008](Evolutions/0008-interface-header-and-export-status-annotations.md) are the issue #106 interface-fidelity batches (`final` keyword + lazy accessor type, extension container dedup, interface header + export-status annotations). > Project-specific terminology lives in [`Glossary.md`](Glossary.md) (Chinese; register new terms in the same batch that introduces them — cross-project terms stay in the global glossary). +## 愿景(Visions) + +方向层面的边界与取舍,位于提案之上,统辖若干提案;属于某个愿景的提案在头部用「所属愿景」字段指回它。 + +- **[不依赖 IDA 的逆向](Visions/ReverseEngineeringWithoutIDA.md)**(Active)—— 让 agent 默认读带注解的汇编、 + IDA 退为后备:地址符号化、跨镜像交叉引用、注解反汇编、数据解码、控制流与常量追踪、构建间逐函数比对、按需持久化, + 横跨 MachOKitExtensions、本库、swift-capstone 与 RuntimeViewer;定下手写解码器与 capstone 的分工、不建完整 + 中间表示、先现算后落盘、分层归属与正确性的标准答案。第一步是提案 + [0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md)。 + ## External — for library users / other developers Public, reference-style documentation. Bilingual (English + 中文). @@ -70,15 +82,19 @@ selects names using each access's offset and width. |---|---| | [Modules/](Internal/Modules/README.md) | **按模块组织的参考文档系列**:每个库模块一篇权威入口(定位 / 子系统分工 / 跨文件契约 / 细节文档指路);该目录 README 是覆盖状态表。 | | [Modules/SwiftSectionKit.md](Internal/Modules/SwiftSectionKit.md) | SwiftSectionKit 模块参考(兼 `swift-section` 包装层):一个子命令一个请求类型、输出端三路与换行语义、诊断 = 级别 + 命令行原文、环境注入、`MachOSource` 唯一加载器;包装层只剩 flag 映射 / 错误翻译 / 流路由 / 退出码;与拆分前的两类有意偏差;测试锚点与「加一个 flag」的步骤。 | -| [Modules/MachODependencies.md](Internal/Modules/MachODependencies.md) | MachODependencies 模块参考:所有功能共用的依赖解析——搜索路径、load name 归一(与 `MachOImage(name:)` 的契约)、两种定位器(进程内 / 文件:install path 精确优先、bare name 排序兜底、cache 一次性索引)、direct / transitive 遍历与顺序契约、未解析清单;SwiftLayout 与 SwiftInterface 两处薄包装的语义边界与测试锚点。 | -| [Modules/MachOCaches.md](Internal/Modules/MachOCaches.md) | MachOCaches 模块参考:不是 dyld cache 的支持层,是按镜像缓存的原语——`SharedCache` 的 get-or-build 三段式与「构建闭包在调用点」、`SharedCacheKey` 只哈希 UUID、`SharedCacheRegistry` 的认领与最后持有者驱逐、eviction group 与 follows 对照表、宿主接内存压力的入口、新加一个 cache 的三步。 | +| [DependencyResolution.md(MachOKitExtensions)](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md) | `MachODependencies` 自 0.25.0 起由 MachOKitExtensions 2.0.0 提供,实现说明在该仓库:所有功能共用的依赖解析——搜索路径、load name 归一、两种定位器、direct / transitive 遍历与顺序契约、未解析清单。本库 SwiftLayout 与 SwiftInterface 两处薄包装的语义边界见 [Modules/SwiftLayout.md](Internal/Modules/SwiftLayout.md) 与 [Modules/SwiftInterface.md](Internal/Modules/SwiftInterface.md)。 | +| [SharedCache.md(MachOKitExtensions)](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md) | `MachOCaches` 自 0.25.0 起由 MachOKitExtensions 2.0.0 提供,实现说明在该仓库:按镜像缓存的原语(不是 dyld cache 的支持层)——`SharedCache` 的 get-or-build 与「构建闭包在调用点」、`SharedCacheKey`、`SharedCacheRegistry` 的认领与最后持有者驱逐、eviction group 与 follows、宿主接内存压力的入口。本库各模块的驱逐组声明在各自的 `SharedCacheEvictionGroup+.swift`。 | | [Modules/SwiftInterface.md](Internal/Modules/SwiftInterface.md) | SwiftInterface 模块参考:编排层定位与三种输出产品(单版本 interface / 两侧 diff / N 路 evolution),五个子系统(核心 builder、opaque 解析、共享 union 走查、diff 渲染、evolution 渲染)的分工、契约与测试锚点,消费入口速查。 | | [Modules/SwiftDeclaration.md](Internal/Modules/SwiftDeclaration.md) | SwiftDeclaration 模块参考:共享声明模型的定位与七个子系统,四条关键契约(持描述符引用而非胖 wrapper 的 materialization 纪律、名字按结构相等且 `kind` 不参与、四态 `ExportStatus` 的两种「无结论」作用域、库代码不写进程流与事件兜底)。 | -| [Modules/MachOSymbols.md](Internal/Modules/MachOSymbols.md) | MachOSymbols 模块参考:符号索引层的定位与四个子系统(索引本体与非单射的名字键、查询出口与 detach 规则、跨 store 对账为什么必须用 `StructuralNodeReferenceKey`、大栈执行器),以及改结构布局要先 clean 等契约。 | +| [Modules/SwiftSymbols.md](Internal/Modules/SwiftSymbols.md) | SwiftSymbols 模块参考(原 `MachOSymbols` 的 Swift 部分):Swift 符号索引 `SwiftSymbolIndexStore` 的定位与五个子系统(经 `SymbolSweep` + `SwiftSymbolTableRouting` 采集后的两段式索引与非单射的名字键、查询出口与 detach 规则、跨 store 对账为什么必须用 `StructuralNodeReferenceKey`、大栈执行器、`_symbolic` 符号表),以及不写裸 `SymbolIndexStore`、改结构布局要先 clean 等契约。与语言无关的符号表、采集与 C/C++ 符号索引见 MachOKitExtensions 的 [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md)。 | | [Modules/SwiftLayout.md](Internal/Modules/SwiftLayout.md) | SwiftLayout 模块参考:静态布局引擎的能力边界与八个子系统(入口与递归求解、基础累加、已知布局表与 builtin 交叉校验、三个桥接、无实参也能算的那部分、ObjC 互操作、镜像查找面),四条关键契约(降级是产品的一部分、实参永远赢过推断、官方离线实现不是标准答案、跨模块偏移按具体部署算)。 | +| [Modules/SwiftObjCInterop.md](Internal/Modules/SwiftObjCInterop.md) | SwiftObjCInterop 模块参考:Swift 类型在 Objective-C 一侧留下的东西(从 SwiftInspection 拆出,提案 0089-swift-objc-interop-module)——五个子系统(Swift 类的 class object 与改过的运行时名、`@objc @implementation` 类、Swift 声明的 `@objc` 协议与 ObjC 协议遵循、方法表与祖先链与成员表、ClangImporter 命名规则与类型编码),它与 SwiftInspection 的单向依赖、MachOObjCSection 从这一层进入,五条关键契约与测试锚点,各子系统的专题文档导读。 | | [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 桩、读任何目标前先确认可读、寄存器只记确定的事、尾调用与跳转表的区分、运行时辅助调用名单、分析器的生命周期与吞吐。 | +| [Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md) | CrossReferenceAnalysis 模块参考,也是交叉引用三层的总说明(下层在 MachOKitExtensions 与 MachOObjCSection):从 arm64 机器码读出函数表与每个函数的引用——地址口径(`CodeLocation`、MachOKit `FunctionStart.offset` 其实是绝对地址)、macOS 27 / iOS 27 起全缓存共用的 selector 桩与 GOT 桩、读任何目标前先确认可读、寄存器只记确定的事、尾调用与跳转表的区分、运行时辅助调用名单、分析器的生命周期与吞吐。 | +| MachOKitExtensions 的 [MachOAddressResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOAddressResolution.md) | 原 CodeAddressResolution 模块参考,提案 0098 搬去 MachOKitExtensions:离线地址解析(`ImageAddressSpace`、`StubChainResolver`、`SlotResolver`、`CacheImageLocator`),线程读取与交叉引用文件模式共用 | +| MachOKitExtensions 的 [MachOCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md)、[ARM64InstructionDecoding.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/ARM64InstructionDecoding.md) | 原 CrossReferenceCore 与 ARM64InstructionDecoding 模块参考,已搬去 MachOKitExtensions:交叉引用与语言无关的核心层、手写的 A64 解码;接口只开 `@_spi(Internals)` 给本库 | +| MachOObjCSection 的 [ObjCCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/main/Documentations/Internal/ObjCCodeReferences.md) | 原 CrossReferenceObjC 模块参考,已搬去 MachOObjCSection:交叉引用的 ObjC 层 | | [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. | @@ -88,7 +104,7 @@ selects names using each access's offset and width. | [NestedFieldOffsetCycleGuard.md](Internal/NestedFieldOffsetCycleGuard.md) | 嵌套字段偏移展开在**有环**类型图上的指数级路径枚举(`DVTIconKit` "死循环")与两道守卫:`indirect` case 是堆 box 指针故报告但不下钻(值类型字段图唯一的成环途径,实际消除爆炸的那道),以及**路径作用域**的已打开类型集合(运行时按 metatype 指针、静态按打印类型名)作为解析误判造成假环的纵深防御。含"为什么深度上限约束不了路径数"、按路径而非全局的取舍、运行时/静态两条实现各自的回归套件,以及 2026-05-16 打印路径 DAG 爆炸修复的教训为何没能横移过来的查证。 | | [StaticFieldOffsetComputation.md](Internal/StaticFieldOffsetComputation.md) | Research + implementation guide for computing stored-property field offsets statically (offline, no runtime): fixed-layout vs resilient, the `performBasicLayout` algorithm, `MetadataInitialization` triage, the dependency-closure type resolver, ObjC ancestors via MachOObjCSection, and a generics difficulty assessment. | | [StaticLayoutEngine.md](Internal/StaticLayoutEngine.md) | The shipped `SwiftLayout` module: what was actually built for static field-offset computation (recompute via `performBasicLayout` rather than reading the vector), the file structure, the runtime-accessor-vs-static validation suite, empirical findings that diverged from the research, and the known per-field degradations. Existentials (opaque / class-bound / error / metatype), the default-actor storage builtin, cross-module field/superclass/protocol types (via the dependency closure), ObjC-ancestor classes (Phase 4 — a Swift class deriving from `NSObject` et al. starts its fields at the ObjC ancestor's `instanceSize`, read via `MachOObjCSection`), multi-payload enums + imported C value types (via `__swift5_builtin` whole-type layouts), imported-ObjC-protocol existentials (`any NSCopying`), C-function-pointer / ObjC-block fields, and concrete bound-generic instantiations as fields (Phase 5 — purely syntactic `dependentGenericParamType` substitution via `GenericArgumentEnvironment`, depth-0 type parameters) are resolved; only a top-level generic type's own unsubstituted parameters, value/pack arguments, and depth>0 nested-context parameters remain degraded. | -| [StaticLayoutDependencyClosure.md](Internal/StaticLayoutDependencyClosure.md) | Phase-3 (**shipped**): extends `SwiftLayout` from single-image to a dependency closure (`LC_LOAD_DYLIB` + dyld shared cache) so cross-module field/superclass/protocol types resolve, with zero resolver changes. Covers the homogeneous-per-root typing decision, the `ImageUniverse.dependencyClosure` factory, the resilient-class static-computability boundary (and why their runtime field-offset vector is empty), and the validation strategy — plus a "落地实测" section recording where the implementation diverged from the plan (lazy per-image indexing over a 551-image closure, bare-name matching, missing-section tolerance, one-shot cache indexing, literal pinning for resilient classes that emit no `…Wvd` global). ObjC ancestors were resolved by Phase 4 (`ObjCClassIndex` + a third `resolveObjCClassInstanceSize` seam; see StaticLayoutEngine.md). **2026-09-02 起**定位器与遍历已下沉为共享模块 `MachODependencies`(见 [Modules/MachODependencies.md](Internal/Modules/MachODependencies.md)),本文保留为阶段 3 的设计与实测记录。 | +| [StaticLayoutDependencyClosure.md](Internal/StaticLayoutDependencyClosure.md) | Phase-3 (**shipped**): extends `SwiftLayout` from single-image to a dependency closure (`LC_LOAD_DYLIB` + dyld shared cache) so cross-module field/superclass/protocol types resolve, with zero resolver changes. Covers the homogeneous-per-root typing decision, the `ImageUniverse.dependencyClosure` factory, the resilient-class static-computability boundary (and why their runtime field-offset vector is empty), and the validation strategy — plus a "落地实测" section recording where the implementation diverged from the plan (lazy per-image indexing over a 551-image closure, bare-name matching, missing-section tolerance, one-shot cache indexing, literal pinning for resilient classes that emit no `…Wvd` global). ObjC ancestors were resolved by Phase 4 (`ObjCClassIndex` + a third `resolveObjCClassInstanceSize` seam; see StaticLayoutEngine.md). **2026-09-02 起**定位器与遍历已下沉为共享模块 `MachODependencies`(0.25.0 起由 MachOKitExtensions 提供,见该仓库的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)),本文保留为阶段 3 的设计与实测记录。 | | [LeafMigrationPlan.md](Internal/LeafMigrationPlan.md) | Plan for making `SwiftDump` a leaf module. | | [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md) | 离线泛型特化的实现说明(提案 offline-generic-specialization):`GenericSpecializer` 在 `MachOFile` 上不经 runtime 特化——实参变成类型节点,非 key 参数由 same-type 约束补齐,按层分组成 `GenericArgumentBinding`,按运行时 `_buildDemanglingForContext` 的规则拼实例化类型名;约束检查分「确定违反报错 / 证明不了警告」两档;打印器与静态布局引擎按 binding 出绑定头部、代换并投影关联类型的字段类型、全部布局注释,与在线模式逐字节对照。另记参数层号只数声明了参数的上下文(`GenericParameterDepthLayout`)及其整类修复的五处、在线模式给特化泛型 enum 补 Enum Layout、两条路径按设计不同的三处。 | | [SpecializedInterfaceBoundRenderingRestoration.md](Internal/SpecializedInterfaceBoundRenderingRestoration.md) | 修复 leaf 迁移引入的回归:interface 路径重新对特化定义做绑定渲染——头部打印 `Box`(跳过泛型签名子句)、字段经特化 metadata 替换;机制经 `SpecializedMetadataNodeSubstitution` + 下移的 `BoundDumpedTypeNameRenderer` 落在 `SwiftDeclarationRendering`,dump 路径零变化。2026-09-23 补一节:运行时名字把私有类型的 anonymous context 写成描述符地址,打出 `struct .WindowPortal<…>`、丢模块与外层类型;五处运行时名字来源统一经 `RuntimeTypeNameDemangling` 去掉它;同日第二批:interface 打印器把 extension context 打印成被扩展的类型(离线同样受益,`Invalidations.Tuple` → `NSView.Invalidations.Tuple`)。2026-10-01 补一节:离线特化的定义带 binding 而不是 metadata,头部改由 `boundTypeNode(of:)` 统一给出。 | @@ -102,7 +118,7 @@ selects names using each access's offset and width. | [OpaquePrimaryAssociatedTypeAttribution.md](Internal/OpaquePrimaryAssociatedTypeAttribution.md) | 提案 0011 的实现说明:opaque 返回类型的 primary associated type 按 anchor 协议逐条归属(anchor 直接命中 → refine 闭包 → 名字兜底,兜底要求 anchor 在组合外——塌缩与未 pin 在 descriptor 里逐字节同形);三层解析链在实现里被 `resolvedContent` 塌成「descriptor 可达性」两问;内置 stdlib 表是 primary 名单/顺序的唯一来源(SE-0346 无运行时痕迹);两种 reader 输出深度差异是接受的设计。 | | [DiffableInterfacePlan.md](Internal/DiffableInterfacePlan.md) | Implementation plan for the diffable (ABI-diff) interface. | | [ABIDiffDesignAndLimitations.md](Internal/ABIDiffDesignAndLimitations.md) | The `SwiftDiffing` ABI-diff engine: identity/payload keys, three-way match, extension-bucket merging, and the known limitations (notably: `@frozen` is unrecoverable from the binary, so the compatibility verdict treats every type as resilient). | -| [ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) | N ≥ 2 版本的 ABI 演化追踪(`ABIEvolution` lineage 模型 + N 路矩阵算法 + timeline reporter)与作为其地基的 snapshot 持久化(`ABISnapshotDocument` 版本头、`ABIProvenance`、CLI `snapshot` / `evolution` 命令、diff 的快照输入与 `--json`)。 | +| [ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) | N ≥ 2 版本的 ABI 演化追踪(`ABIEvolution` lineage 模型 + N 路矩阵算法 + timeline reporter)与作为其地基的 snapshot 持久化(`ABISnapshotDocument` 版本头、`ABIProvenance`、CLI `snapshot` / `evolution` 命令、diff 的快照输入与 `--json`);第六批记录「看不见的版本」:没有 local Swift 符号的镜像里非导出成员的缺席不算删除,按两侧推断(`◍` / `◌`、`… between A and B`),diff 共用同一套规则。 | | [PerConformanceAttribution.md](Internal/PerConformanceAttribution.md) | extension 变更的 per-conformance / per-`where`-block 归属:容器按 (target, protocol, where 指纹, retroactive) 拆分、索引期冻结的归属字段与 witness 投影(`assocwitness:`)、key scheme v3、键碰撞源的结构性消解、diffable renderer 的 `: Protocol` 头。 | | [ProtocolRequirementProjection.md](Internal/ProtocolRequirementProjection.md) | stripped protocol requirement(PWT slot)投影(`pwtslot:` 命名空间、flags 指纹 payload、中段插入的诚实级联、符号化状态不对称局限)+ remangle 回退键自识别(`unmangled:` 前缀)与 `remangleFallbacks()` 审计通道;key scheme v4。 | | [DefaultImplementationAwareCompatibility.md](Internal/DefaultImplementationAwareCompatibility.md) | 默认实现感知的兼容性判定:`ProtocolDefinition.defaultedRequirementPWTOffsets`(描述符相对指针,不经符号表,stripped 侧同样精确)、`MemberRecord.hasDefaultImplementation`(仅 verdict 元数据,经 PWT offset 关联已解析成员)、`MemberChange` / `LineageEvent` 的 `compatibilityOverride`(defaultless requirement 追加判 breaking,stripped slot 获得默认实现判 additive);formatVersion 5。 | @@ -111,13 +127,16 @@ selects names using each access's offset and width. | [EnumLayoutAuditFixes.md](Internal/EnumLayoutAuditFixes.md) | 对照 Swift 官方源码(`EnumImpl.h` / `Enum.cpp` / `GenEnum.cpp` / `TypeLowering.cpp`)的枚举布局全面审计与五项修复:indirect 单 payload 的 heap-pointer XI(曾被误判为 overflow 布局)、枚举自身 VWT 的 size 交叉校验与 payloadXI 精确反推、spare-bits payload case 的位级 `fixedBitMasks`(不再整字节过度声明)、empty case 判别区完整记录(tagged 零扩展 + spare-bits 全位固定)、no-payload XI 封顶;runtime 对拍测试增量与 RuntimeViewerCore token 同步。 | | [OutputTransformerMigration.md](Internal/OutputTransformerMigration.md) | `Transformer` 模板机制的 Swift 侧(注释 token 模板 + 预设)从 RuntimeViewerCore 迁入库侧的新 `OutputTransformer` 模块(ObjC 侧 CType/ivarOffset 暂留 RV):架构(模块清单、宽容 Codable 持久化契约、SwiftInspection 桥接、闭包工厂 + `applyTransformers` 接线)、RV 兼容语义(auto-append、partial-mask 安全回退)、RV 侧收编为 `@_exported` shim + 一行接线。 | | [CLITransformerTemplateInterface.md](Internal/CLITransformerTemplateInterface.md) | `swift-section` 的注释模板命令行入口:三层配置(`--transformer-config` JSON 文件 / `--enum-layout-style` 整模块预设 / 逐模块模板选项)与其优先级、"内置模板名 vs 字面模板" 的解析规则(未知名字报错而非退化)、"启用的模块自动打开对应注释开关" 规则、`transformer tokens/templates/config` 发现性子命令,以及 `interface` 补齐 `--emit-type-layout` / `--emit-enum-layout`。 | -| [ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) | The `ReadingContext` reading-abstraction design, the 2026-05 model-coverage completion pass, and the 2026-09-30 single-implementation pass(提案 0057 的实现说明):旧形式为什么原地保留成转发、哪两个协议保留了已废弃的 requirement、约束扩展里空指针 guard 的绑定陷阱、收成一份时修掉的分歧与性能处理。 | +| [ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) | 本库这一侧怎么用 `ReadingContext`(读取层本身 0.25.0 起在 MachOKitExtensions,实现说明也在那边):2026-05 的模型覆盖补全、2026-09-30 的单一实现(提案 0057 的实现说明)——旧形式当年为什么原地保留成转发(0.25.0 已删除)、约束扩展里空指针 guard 的绑定陷阱、收成一份时修掉的分歧、上层按缓存范围缓存,以及看穿包装类型在本库各处的规则。 | | [FixtureTestingAndContinuousIntegration.md](Internal/FixtureTestingAndContinuousIntegration.md) | **Fixture 测试体系与 CI 的设计来历**(整合自已删除的 `docs/superpowers/` 四份 spec + CI 落地记录):为什么 fixture 只用 SymbolTestsCore、`#filePath` 路径锚定陷阱、命名空间约定与边界规则、ABI 覆盖四支柱与 sentinel 信任危机(88/157 suite 失真)的收紧、CI 白名单 regex 与首轮五坑。现行操作规程仍以 AGENTS.md 为准。 | | [ClassMemberKeywordRecovery.md](Internal/ClassMemberKeywordRecovery.md) | `class` / `static` 成员关键字的还原:mangling 层面两者不可区分,判据是「类型级成员有 vtable method descriptor ⇒ 源码是 `class`」(`static` 隐式 final、不进 vtable);模型侧 `isClassMember` 计算属性 + 三个 node printer 接线 + dump vtable 段落关键字,顺带消灭非法的 `override static` 输出;`final class func` 等四类 ABI 上与 `static` 完全一致,保守输出语义等价的 `static`。 | -| [ObjCImplementationClassRecognition.md](Internal/ObjCImplementationClassRecognition.md) | `@objc @implementation` 类的识别(提案 `objc-implementation-class-recognition` 的实现说明):`SwiftInspection.ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表建每镜像索引,前置条件是本镜像定义的纯 ObjC class object,证据分 definitive(导出的 accessor / `Wvd` 字段偏移全局变量)与 inferred(`?` / 空 ivar encoding)两档;ivar 与 `Wvd` 按偏移值 join;interface 打 `@objc @implementation` 并还原存储属性,dump 新增 `objcImplementationClasses` 段;方法表只对命中的类读、IMP 处符号只作佐证;顺带让 extension 成员也拿到 thunk 推断的 `@objc`。 | +| [ObjCImplementationClassRecognition.md](Internal/ObjCImplementationClassRecognition.md) | `@objc @implementation` 类的识别(提案 `objc-implementation-class-recognition` 的实现说明):`SwiftObjCInterop.ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表建每镜像索引,前置条件是本镜像定义的纯 ObjC class object,证据分 definitive(导出的 accessor / `Wvd` 字段偏移全局变量)与 inferred(`?` / 空 ivar encoding)两档;ivar 与 `Wvd` 按偏移值 join;interface 打 `@objc @implementation` 并还原存储属性,dump 新增 `objcImplementationClasses` 段;方法表只对命中的类读、IMP 处符号只作佐证;顺带让 extension 成员也拿到 thunk 推断的 `@objc`。 | | [ObjCMemberRecovery.md](Internal/ObjCMemberRecovery.md) | 从 ObjC 方法表还原 Swift 成员的 ObjC 事实(提案 `objc-ancestor-override-recovery` 与 `objc-member-selector-recovery`)的实现说明:per-class 的 ObjC 成员表怎么建(类 / 元类 / category 的方法表,祖先链,采纳协议的 selector),三档证据(IMP 处的 `To` 符号 / 反汇编 thunk 找它引用的成员实现 / 只按 selector 名字,默认关)在代码里的位置,编译器默认 selector 推导的移植,provider 接缝与库读取器,三个 join 的键,祖先链怎么经依赖闭包走过独立文件的 bind(解析器、注册表、平台守卫、memo 的解析器身份),边界(泛型类、无处可解析的 bind、strip 后的显式 selector、仅 ARM64)。 | | [DescriptorOnlyVTableMembers.md](Internal/DescriptorOnlyVTableMembers.md) | interface 里只剩 method descriptor 符号的 class 成员(提案 `0054-interface-descriptor-only-vtable-members` 的实现说明):规模为什么要按符号表而不是导出表算(macOS cache 里只有 AppKit 被剥光、少 53 个成员,SwiftUI / SwiftUICore / Foundation 保留 local 符号),`classDispatchLookups` 造的替身成员符号为什么用实现函数的 mangled 名和实现偏移(async 再跳一次),真实符号优先的去重键,class 的 vtable 成员在打印时按槽号排在前面,哪些槽不补(ABI 墓碑、modify / read、叫不出名字的槽、override 槽),边界(拿不到 `@objc` / ObjC 覆写、合成 Codable 成员的去重、多版本渲染不改排序、snapshot 格式 6)与验证。 | -| [CustomObjCClassNames.md](Internal/CustomObjCClassNames.md) | 改过 ObjC 运行时名的 Swift 类(提案 `0052-objc-custom-class-name` 的实现说明):`SwiftInspection.SwiftClassObjectIndex` 顺着类元数据的描述符指针(按字段位置解 rebase,不能走 `descriptor(in:)`)或 resilient 父类的 metadata pattern,把 `HasCustomObjCName` 与 `class_ro_t` 名配到描述符上;`@objc(Name)` 与 `@_objcRuntimeName(Name)` 按对象模型区分(`@objc` actor 例外);成员恢复与布局引擎按名字查不到时回退到它,为什么只在查不到时回退;编译器给 ObjC 类的子类排字段从 8 起算、运行时整体滑动;边界与 macOS 27 AppKit 实测(74 个类)。 | +| [ThunkOnlyObjCMembers.md](Internal/ThunkOnlyObjCMembers.md) | 只剩 `@objc` thunk 或 initializing entry point 的成员(提案 `0077-thunk-only-objc-members` 的实现说明):整模块优化把 internal 成员的实现符号删掉、只留另一个入口时(`Xcode Service` 里 22 个 `@objc` 成员、9 个 initializer),符号索引的第四个成员索引 `objcThunkMemberSymbols` 怎么登记 `To` thunk,`StandInMemberSymbols` 造的替身为什么用实现名、实现的成员树和留下的那个入口的地址(initializer 改写成 allocator),什么时候不补(真实符号已声明、`…ToTm`、ivar destroyer),dump 的 `[ObjC Thunk]` 一节,边界(2026-10-27 起泛型类与 stub-list 类的方法表另由 `ClassesWithoutClassObjects.md` 读出)与验证。 | +| [ClassesWithoutClassObjects.md](Internal/ClassesWithoutClassObjects.md) | 没有 class object 的 Swift 类(提案 `objc-classes-without-class-objects` 的实现说明):泛型类、父类在别的 resilience domain 的类、父类是本模块泛型类的类各自的 `class_ro_t`、元类的 `class_ro_t` 与 stub 在 Swift 元数据的哪里(对照编译器的元数据策略与运行时的 `initializeClassMetadataFromPattern`),名字与父类怎么定,交给本库方法表与 MachOObjCSection 的各是哪些,已知限制(别的镜像里的 Swift 父类断链、读不到挂在 stub 上的 category)与验证。 | +| [SwiftDeclaredObjCProtocols.md](Internal/SwiftDeclaredObjCProtocols.md) | Swift 声明的 `@objc` 协议与类对 ObjC 协议的遵循(提案 `swift-declared-objc-protocols` 的实现说明):编译器给这种协议只留 field descriptor 与 ObjC 协议记录、要求没有 Swift 符号,本库怎么认出本镜像声明的(以 field descriptor 为准、按名字配对、IsSwift 位为什么不算证据),要求的两种写法(取自实现者——Swift 类的成员表要按 Swift 全名取;按 ClangImporter 规则从 selector 推出、用 `@objc(selector)` 钉住),类的协议从 `class_ro_t`(同模块 extension 并在里面)与 category 读出、隐含协议怎么剔除,别的模块改过名的协议到依赖闭包里找,导入协议保留 ObjC 名,interface / dump / 模型 / SwiftLayout 各自的落点,已知限制与验证。 | +| [CustomObjCClassNames.md](Internal/CustomObjCClassNames.md) | 改过 ObjC 运行时名的 Swift 类(提案 `0052-objc-custom-class-name` 的实现说明):`SwiftObjCInterop.SwiftClassObjectIndex` 顺着类元数据的描述符指针(按字段位置解 rebase,不能走 `descriptor(in:)`)或 resilient 父类的 metadata pattern,把 `HasCustomObjCName` 与 `class_ro_t` 名配到描述符上;`@objc(Name)` 与 `@_objcRuntimeName(Name)` 按对象模型区分(`@objc` actor 例外);成员恢复与布局引擎按名字查不到时回退到它,为什么只在查不到时回退;编译器给 ObjC 类的子类排字段从 8 起算、运行时整体滑动;边界与 macOS 27 AppKit 实测(74 个类)。 | | [SelfContainedABILayer.md](Internal/SelfContainedABILayer.md) | ABI 层自包含(提案 `self-contained-abi-layer` 的实现说明):`MachOSwiftSection` 只依赖新伞模块 `MachOBase`,描述符只暴露 `implementationOffset` / `implementationAddress(in:)`,符号归属上移 `SwiftInspection`,值类型下沉 `MachOResolving`;记录为什么多一个伞模块、为什么 `ReadingContext` 腿没有符号形态(旧腿在读机器码)、为什么不留 typealias、为什么 async 重载只能删;附下游迁移表。 | | [LargeStackTaskExecutorAdoption.md](Internal/LargeStackTaskExecutorAdoption.md) | 大栈任务执行器接入与跨版本并行(提案 `large-stack-executor-and-cross-version-parallelism` 的实现说明):为什么打印路径每个符号付一次线程往返、为什么执行器按剩余栈探测就能让整个 task 内联、`LargeStackTaskExecution.run` 包了哪些入口与嵌套为何免费、macOS 15 以下的静默回退、跨版本并行为什么安全而版本内并行为什么不做(MachOKit 共享 FileHandle)、`--jobs` 与 `concurrentMap(maximumConcurrency:)` 的语义;附 0.6.0 / 0.6.3 / 执行器开关的计时表与渲染 A/B 结论。 | | [ExtensionContainerUnification.md](Internal/ExtensionContainerUnification.md) | Extension 容器统一(提案 0007 的实现说明):双产线重复(协议尾随 descriptor 副本 + 符号扫描桶副本)的「附着 + 打印抑制」消解——桶是 ABI 快照的直接输入故不可移除,附着对象留桶打标、顶层打印跳过;descriptor 合成降级为 fallback(ICF 地址上丢成员);桶内同身份合并、空 requirement 签名桶折叠、`updateConfiguration` no-op 修复、嵌套协议扩展块死循环修复;裸头 typealias 块并存为 P1-9 残余(格式冻结约束下不合并)。 | @@ -175,12 +194,33 @@ selects names using each access's offset and width. | [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。 | +| [Evolutions/0076-objc-runtime-send-entry-points.md](Evolutions/0076-objc-runtime-send-entry-points.md) | **提案 0076(Implemented)**:clang 把 `[[Foo alloc] init]`、`isKindOfClass:`、`respondsToSelector:`、`new`、`class`、`self`、`alloc` 编成对 libobjc 专用入口的调用,交叉引用原先只把 `objc_msgSend` 当发送,按 selector 查调用者会漏掉它们(macOS 26.6 的 AppKit 查 `init` 漏掉约 78%)。这些调用改记成它们代表的发送(`objc_alloc_init` 记 `alloc` 与 `init` 两条),selector 预筛也留下导入这些入口的镜像;不认 `objc_retain` 一类。 | +| [Evolutions/0077-thunk-only-objc-members.md](Evolutions/0077-thunk-only-objc-members.md) | **提案 0077(Implemented)**:只剩 `@objc` thunk 或 initializing entry point 的成员照样建出来——整模块优化的 app 里,`@objc` 成员的函数体常被内联进它的 ObjC thunk、Swift entry point 被删掉,class 的 initializer 只剩 initializing entry point(`…fc`),成员模型只认实现符号,dump 与 interface 因此整个丢掉这些成员(issue #137、#138)。符号索引给 `To` thunk 加第四个成员索引,模型照提案 0054 的办法从剩下的入口造替身,dump 加 `[ObjC Thunk]` 一节;ABI snapshot 格式版本加一。 | +| [Evolutions/0078-objc-classes-without-class-objects.md](Evolutions/0078-objc-classes-without-class-objects.md) | **提案 0078(Implemented)**:没有 class object 的 Swift 类——泛型类、父类在别的 resilience domain 的类、父类是本模块泛型类的类——不在 `__objc_classlist` 里,`swift-section objc` 列不出它们,本库的 ObjC 方法表也读不到,`override` 因此不判(issue #137 的 ObjC 侧)。新的 `SwiftClassWithoutClassObjectIndex` 从 Swift 元数据找出它们的 `class_ro_t`,方法表据此给出证据,`ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)` 交给 MachOObjCSection 0.8.201 的索引器。 | +| [Evolutions/0079-swift-declared-objc-protocols.md](Evolutions/0079-swift-declared-objc-protocols.md) | **提案 0079(Implemented)**:Swift 源码定义的 `@objc` 协议在 dump 与 interface 里都不出现——编译器只给它生成 ObjC 的 `protocol_t`,不生成 Swift protocol descriptor;ObjC 协议也没有 witness table 与遵循记录,所以 Swift 类对任何 ObjC 协议的遵循(`NSCopying` 这类导入的也算)在 interface 里全部丢失。本镜像定义了哪些协议以 `__swift5_fieldmd` 的 ObjCProtocol 记录为准;要求的签名取自本镜像的 Swift 实现者,没有实现者的照 ClangImporter 的规则从 selector 推出 Swift 名,再用 `@objc(selector)` 钉住;类的遵循读 `class_ro_t` 与 category 的协议表。 | +| [Evolutions/0080-objc-evolution-interface.md](Evolutions/0080-objc-evolution-interface.md) | **提案 0080(Implemented)**:`objc evolution --interface`——把 N 个版本的 ObjC 头文件按声明合并成一份,外观沿用 `objc dump` 的渲染,在类、协议、分类及其方法、属性、ivar 上标出加入、删除、修改的版本(照 Swift `evolution --interface` 的位图注释),`--emit-available` 再补 `API_AVAILABLE` / `API_OBSOLETED`。合并与标注的渲染在 MachOObjCSection,本库做 CLI、SwiftSectionKit 请求与集成测试。 | +| [Evolutions/0081-evolution-unobservable-presence.md](Evolutions/0081-evolution-unobservable-presence.md) | **提案 0081(Implemented)**: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 符号、每个成员是否导出(格式版本 9),被剥版本里本来就看不见的声明记为看不见;一段看不见的版本两侧状态相同时按两侧推断并在位图里画 `◍`,两侧不同时记成区间事件(`removed between 12.7 and 15.0`)。规则放在 SwiftDiffing,diff 的判定一并适用,`diff --interface` 的渲染不动。 | +| [Evolutions/0082-image-group-evolution.md](Evolutions/0082-image-group-evolution.md) | **提案 0082(Implemented)**:一个版本由一组 image 组成的演进——Apple 拆框架时声明在 image 之间搬家(AppKit → UIFoundation / CollectionViewCore / CoreAutoLayout,SwiftUI → SwiftUICore),单 image 的演进把它们报成删除与新增。image 组把组里的声明合成一个 API 面比较,组内搬家单独记成 `moved`,lineage 报告、JSON 与联合接口都支持;顺带修掉 SwiftUI 给 SwiftUICore 类型加的、没有 extension 上下文的成员在单 image 索引里整个消失的缺口。ObjC 侧由 MachOObjCSection 实现,本库接集成测试。 | +| [Evolutions/0083-exported-only-marking-mode.md](Evolutions/0083-exported-only-marking-mode.md) | **提案 0083(Implemented)**:导出过滤进入标记模式——RuntimeViewer 要过滤未导出的类型与成员,Find 的语料用标记模式打印,而导出过滤原本不在标记模式里,开着选项也搜得到未导出的成员;改为标记模式下照常输出、包进「这个开关关着才可见」的区域。同批把 C 导入类型的 `exportStatus` 改为不给结论:它的描述符是每个用到它的模块各自的副本、从不导出,判成未导出会连带删掉本镜像给它写的公开扩展。 | +| [Evolutions/0084-comment-structure.md](Evolutions/0084-comment-structure.md) | **提案 0084(Implemented)**:注释结构标记——RuntimeViewer 要在 SourceEditor 面板把注释画成标签、字段偏移树与枚举布局可折叠,且不解析注释文本。新开关 `marksCommentStructure` 下,打印器把每条注释包进 swift-semantic-string 0.6.0 新增的 `AnnotationRegion`,标出种类(本库扩展的 `AnnotationRegion.Kind`)和每段的角色,字段偏移树与枚举布局用区域嵌套表达层级;关着时输出逐原子不变,打开后分离出的冻结串与关着时完全相同。含 interface 路径全部注释输出点的种类与段映射。 | +| [Evolutions/0086-shared-dependency-openings.md](Evolutions/0086-shared-dependency-openings.md) | **提案 0086(Implemented)**:依赖定位器共享同一路径的打开——定位器按根建,每个都把搜索路径上点名的 dyld cache 与显式 Mach-O 文件各开一份,RuntimeViewer 离线读一个 bundle 时描述符随根数成倍增长。改为按文件身份在进程里只打开一份、弱引用共用,FullDyldCache 不加锁的懒状态在交出前先读好;独立文件的共享以 MachOKit 0.55.101 去掉 `cache` 探测为前提。公开接口不变。 | +| [Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md](Evolutions/0087-resolvable-locatable-layout-wrapper-macro.md) | **提案 0087(Implemented)**:ABI 层的样板宏 `@LocatableLayoutWrapping` 改名为 `@ResolvableLocatableLayoutWrapper`,并由宏补上遵循。提案 0027 的宏只生成 `layout` / `offset` / `init(layout:offset:)`,遵循要在声明处另写,而用它的 98 个 struct 全都是 `ResolvableLocatableLayoutWrapper`;现在宏加了 extension 角色,补上类型还缺的协议,宏声明搬进 MachOSwiftSection。`conformances:` 写出整条协议链(只靠隐含遵循时,静态成员引用编不编得过取决于编译顺序),用宏的文件必须 `import MachOKit`。生成的存储成员与改前逐字相同。 | +| [Evolutions/0088-machofile-performance.md](Evolutions/0088-machofile-performance.md) | **提案 0088(Implemented)**:离线(`MachOFile`)读取追平进程内。符号索引分两段,只为别的镜像而读的依赖镜像不再 demangle 整个镜像;依赖镜像的各张表用到才建、按镜像共享;读取直接取 MachOKit 打开文件时的映射(fork 的 `fileBytes`);MachOObjCSection 在 cache 里按地址找镜像改为查表;符号名多线程还原、按原顺序驻留;import 列表在节点池里只遍历一次;另修两处热点。上游配套发版 MachOKit fork 0.55.102(含懒缓存的并发首读竞态修复)、MachOObjCSection 0.8.206、swift-demangling 0.7.3(`Demangler` 不再整份复制自身)。本机 cache 里的 SwiftUI 打开全部布局注释生成 interface,离线打印 304 G → 86 G 条指令(进程内 61 G),输出逐字节不变、公开 API 不变;开发用基准程序 `reader-benchmark` 在同一进程里比较两种读取器。 | +| [Evolutions/0089-swift-objc-interop-module.md](Evolutions/0089-swift-objc-interop-module.md) | **提案 0089(Implemented)**:把 SwiftInspection 的 ObjC 部分拆成新模块 `SwiftObjCInterop`——39 个源文件里有 19 个(约 6100 行)讲 Swift 类型在 ObjC 一侧的样子(class object、`@objc @implementation` 类、Swift 声明的 `@objc` 协议、ObjC 方法表与祖先链、ClangImporter 命名规则),是几份 ObjC 功能提案就近累积进来的。整块搬到 SwiftInspection 之上、SwiftLayout 与 SwiftThunkAnalysis 之下,类型名与访问级别不变,SwiftInspection 从此不依赖 MachOObjCSection;公开类型换模块是源码破坏,留不了过渡别名(循环依赖),RuntimeViewer 的两处同批加 import,随 0.25.0 发布。 | +| [Evolutions/0090-objc-imported-declarations.md](Evolutions/0090-objc-imported-declarations.md) | **提案 0090(Implemented)**:ObjC 类、category 与协议按 Swift 导入它们的样子建成声明,供 RuntimeViewer 做 Xcode 式的 Generated Interface。把 0079 为协议要求移植的 ClangImporter 命名规则与类型桥接推广到类与 category(属性、方法、工厂初始化器、error 约定、subscript),新增三种声明模型由 `SwiftDeclarationIndexer` 按名字现建、`SwiftDeclarationPrinter` 打印;Swift 实现的部分(桥接出去的 Swift 类、`@objc @implementation` 类、Swift extension 的成员)按 selector 配到 Swift 成员,照抄真实声明。类只读自己的表;链接器已把同镜像的 category 并进类。`swift-section objc interface --swift` 打印这种声明。AppKit 实测只凭运行时元数据有 80.8 % 的成员与 SDK 真名一致。 | +| [Evolutions/0091-export-verdict-without-local-symbols.md](Evolutions/0091-export-verdict-without-local-symbols.md) | **提案 0091(Implemented)**:没有本地符号的镜像里(macOS 27.2 共享缓存的 AppKit),名字经过扩展上下文的未导出类型判不出导出结论(重整名一腿遇到扩展一律放弃),Swift 声明的 `@objc` 协议也从不判定,RuntimeViewer 排除未导出后仍列出私有类型。改为只在带约束的扩展上放弃;第一、二条腿判不了时,私有或局部声明(看名字或描述符外层的匿名上下文)判为未导出;私有 `@objc` 协议判为未导出,`--exported-only` 时连同只遵循它的 ObjC 类别一起去掉。测试用现编夹具的三个变体(未剥离、只留 `_symbolic`、`strip -x`)先红后绿。 | +| [Evolutions/0092-existential-any.md](Evolutions/0092-existential-any.md) | **提案 0092(Implemented)**:interface 与 dump 照编译器写 `.swiftinterface` 的规则给 existential 写上 `any`——默认打开的开关(interface 的 `usesExistentialAny` / `--no-existential-any`,dump 的 swift-demangling 新选项 `useExistentialAny` / `--disable-existential-any`),`(any P)?`、`any P.Type`、`(any P).Type`、`any Any.Type` 都照编译器;`Any` 与 `AnyObject` 不写。顺带修好 constrained existential 字段(`any Boxed` 在 interface 里印成 `Swift.Int`):在 `SymbolicDemangler` 把实参代回 extended existential 的 shape,ABI 快照格式随之升到 12。 | +| [Evolutions/0093-observable-macro-folding.md](Evolutions/0093-observable-macro-folding.md) | **提案 0093(Implemented)**:识别 `@Observable` 宏——构造时只读字段记录就认得出(`TypeDefinition.attachedMacros`,剥过符号照样认),索引期按证据(init accessor、成员的 setter 或 `_modify`、初始值表达式、存储字段名)分出被跟踪属性的存储。interface 默认折叠成源码的样子(`@Observation.Observable` 加普通的 `var x: T`,宏生成的成员与 conformance 不印),`expandsMacros` / `--expand-macros` 照二进制原样印;宿主做内联展开用 `printMacroExpansion` 整块或 `printMacroExpansionParts` 分块,`marksAttachedMacros` 标出锚点。dump 只在类头加属性。 | +| [Evolutions/0094-init-accessor-recovery.md](Evolutions/0094-init-accessor-recovery.md) | **提案 0094(Implemented)**:还原 SE-0400 的 init accessor——它的符号(后缀 `vi`)作为所属属性的一个 accessor 建进模型(`AccessorKind.initAccessor`),dump 列出它,ABI diff 把它算进 accessor 集合(快照格式 13),interface 在 accessor 块里印 `init`。二进制不记录 `@storageRestrictions`:名单只按「同名的 `_x`、类型与属性相同」推断(`VariableDefinition.initializedFieldNames`,类型取 init accessor 自己的符号,比较撇开 `sending`),推得出印 `@storageRestrictions(initializes: _x) init`,推不出只印 `init` 并在声明上一行注明。 | +| [Evolutions/0095-observable-nested-expansion.md](Evolutions/0095-observable-nested-expansion.md) | **提案 0095(Implemented)**:`@Observable` 的分块展开照 Swift 源码分两层——展开 `@Observable` 只给每个被跟踪属性出一个 `@ObservationTracked`,再展开它才是 accessor 块与存储 `_x`;第一层分块带嵌套展开(属性在内容里的 UTF-8 范围与展开它的分块)。 | +| [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | +| [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | +| [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | | [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 的数量与内存实测。 | +| [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | +| [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | | [DeclarationModelMemoryFootprint.md](Internal/DeclarationModelMemoryFootprint.md) | NodeStore 迁移后的声明模型内存足迹量测:`TypeDefinition` 1272 字节的逐属性构成(两份 `TypeContextWrapper` 占 74%)、`TypeContextWrapper` 按最大 case `Class` 定尺的原因、`parentContext` 是被当成永久字段的临时值、mini-store 增殖与 `MetadataReaderCache` 仍持 `Node` 树;含四项可回收估算(合计 ~8–10%)与「当前不建议实施、应先剖析其余 90%」的结论。 | | [NodeStoreMigrationOpenIssues.md](Internal/NodeStoreMigrationOpenIssues.md) | NodeStore 迁移的遗留问题台账:每条问题记录成因、影响面、修复位置与当前状态(已修 / 裁决不修 / 仍打开),闭环的条目保留成因备回溯。大部分条目已闭环或已终审;与 `Reviews/` 下两份审查记录冲突时以后者为准。 | | [SystemFrameworkRenderingVerification.md](Internal/SystemFrameworkRenderingVerification.md) | 系统框架渲染 A/B 验证流程(大重构必跑):两个检出对同一批真实输入(归档 dyld cache → 无则当前系统 cache、模拟器 runtime → 无则现有 runtime、当前系统 MachOImage)逐字节比对 dump+interface;入口脚本 `Scripts/run-rendering-ab-verification.py`,含回退规则、踩坑清单(`-p` 消歧、fat 二进制 `-a`、同 boot 会话、scratch 隔离)与 2026-08-03 基线运行记录。 | @@ -191,3 +231,4 @@ selects names using each access's offset and width. | [ObjCChanges/](Internal/ObjCChanges/README.md) | **ObjC 侧的外部变化跟踪**:本仓库之外(Swift Evolution、clang / LLVM、objc4、Apple 系统二进制)会改变二进制里 ObjC 事实的变化,每篇记上游状态与核对日期、二进制里的新形态、对 ObjC 成员恢复 / `@implementation` 识别 / `swift-section objc` 的影响分级,以及将来支持时的约束;该目录 README 是状态总表。目前一篇:direct method 的新 ABI(LLVM 23 已合入)与 Swift `@objcDirect`(pitch 阶段),这类方法不在 method list 里,成员恢复会静默漏掉。 | | [TaskReports/](Internal/TaskReports/) | Dated per-task fix / investigation reports. | | [Reviews/](Internal/Reviews/) | Dated code-review records — one file per review event: findings, measurements taken at the time, and the resulting to-do list. Distinct from the topic-organised issue ledgers (e.g. `NodeStoreMigrationOpenIssues.md`), which they cross-reference. | +| [Reviews/CodebaseAudits/](Internal/Reviews/CodebaseAudits/README.md) | **代码库体检账本**:定期对整个分支(不是某次 diff)做的体检——模块表(每个模块最近一次深审的日期与提交、未结的严重问题)、规则检查式与各轮计数、运行记录;各轮报告(`CodebaseAudit.md`)与它同目录,由它索引。每轮体检先读它决定审哪些模块。 | diff --git a/Documentations/SwiftSectionKit.md b/Documentations/SwiftSectionKit.md index 329de42c4..b12aef191 100644 --- a/Documentations/SwiftSectionKit.md +++ b/Documentations/SwiftSectionKit.md @@ -59,10 +59,12 @@ if outcome.hasBreakingChange == true { | `ObjCDumpRequest` | `swift-section objc dump` | `ObjCDumpRequest.Outcome` (what was found) | | `ObjCInterfaceRequest` | `swift-section objc interface` | — | | `ObjCAPISnapshotRequest`, `ObjCAPIDiffRequest`, `ObjCAPIEvolutionRequest` | `swift-section objc snapshot / diff / evolution` | the document / an outcome | +| `ReferencesRequest` | `swift-section refs` | `ReferencesResult` (the references, how many images were scanned, whether `limit` cut them short) | +| `SymbolicateRequest` | `swift-section symbolicate` | `[AddressSymbolication]`, one an address, in order | Options that exclude each other are one enum rather than several flags: an `ABIDiffRequest.Report` is a change list, a summary, JSON or an annotated interface, never two at once. Where the command line has a flag that implies another (`--emit-expanded-field-offsets` implies field offsets), the request has one value covering both (`FieldOffsetComments.expanded`). -A binary is named by a `MachOSource` — a thin or fat file, an image inside a dyld shared cache file, or an image of the running system's cache. `snapshot`, `diff` and `evolution` take `SnapshotSource.path`, which may name a binary or a snapshot document; the file's first non-whitespace byte tells them apart, as on the command line. +A binary is named by a `MachOSource` — a thin or fat file, an image inside a dyld shared cache file, or an image of the running system's cache. `refs` and `symbolicate` read machine code across many images, so they take a `CrossReferenceInput` instead: a set of files read together, a whole cache file, or the whole running system's cache, read from its files. Their results carry `CrossReferenceAnalysis` types (`CodeReference`, `AddressSymbolication`); import that module to inspect them. `snapshot`, `diff` and `evolution` take `SnapshotSource.path`, which may name a binary or a snapshot document; the file's first non-whitespace byte tells them apart, as on the command line. ## The output contract @@ -83,7 +85,7 @@ Where the command line prints a diagnostic is the command line's business: it wr ## Errors -Thrown errors are worded without naming command-line options: `MachOSourceError` (a fat binary without an architecture, a missing slice, a cache image that is not there), `SnapshotSourceError.binaryRequired(path:)` (a snapshot document handed to an annotated interface), `AvailabilityPlatformInferenceError` (an annotated evolution asked to infer its `@available` platform, when an input's platform has no `@available` name or the inputs' platforms differ), `ObjCDeclarationLookupError`. Errors from the layers below — a missing file, a snapshot document of an unsupported format version, `ABIEvolutionError.labelCountMismatch` — pass through unchanged. +Thrown errors are worded without naming command-line options: `MachOSourceError` (a fat binary without an architecture, a missing slice, a cache image that is not there), `SnapshotSourceError.binaryRequired(path:)` (a snapshot document handed to an annotated interface), `AvailabilityPlatformInferenceError` (an annotated evolution asked to infer its `@available` platform, when an input's platform has no `@available` name or the inputs' platforms differ), `ObjCDeclarationLookupError`, `CrossReferenceRequestError` (an image, a symbol, a class or a function the analyzed images do not have, an address two files both hold, a file with no arm64 code). Errors from the layers below — a missing file, a snapshot document of an unsupported format version, `ABIEvolutionError.labelCountMismatch` — pass through unchanged. `swift-section` translates the first group back into the wording it has always printed, and reports a usage mistake as a validation error (exit code 64). A host that wants its own wording does the same. diff --git a/Documentations/Visions/ReverseEngineeringWithoutIDA.md b/Documentations/Visions/ReverseEngineeringWithoutIDA.md new file mode 100644 index 000000000..3593fa4bc --- /dev/null +++ b/Documentations/Visions/ReverseEngineeringWithoutIDA.md @@ -0,0 +1,207 @@ +# 愿景:不依赖 IDA 的逆向 + +- **状态**: Active +- **最后更新**: 2026-11-19 +- **相关提案**: [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) + +愿景**不做具体决定**,它划定一个方向的边界与取舍原则,让后续每个提案不必重新论证一遍。 +具体怎么做写在各自的提案里。 + +## 这是什么领域 + +从 Mach-O 的字节出发,产出 agent 读懂一段代码在做什么所需的全部材料,覆盖 Apple 平台的 arm64 / arm64e +二进制:dyld shared cache 里的系统镜像(包括 `/Volumes/DyldSharedCaches` 下归档的各个版本)、独立 app 与它 +内嵌的框架、Xcode 的私有框架。具体包括: + +- **函数边界与命名**:每个函数从哪开始、到哪结束、叫什么,包括没有符号的函数、block、`.cold` 片段。 +- **地址符号化**:任意一个地址是什么——哪个镜像的哪个函数加多少偏移、哪个桩最终跳到哪、哪个槽里装着谁。 +- **交叉引用**:谁调用了某个函数、谁发送了某个 selector、谁读了某个类对象、某个 ivar、某个字符串,跨镜像、 + 跨整个 cache。 +- **带注解的反汇编**:每个调用、地址生成、槽读取都标上真实名字或字符串内容的汇编。 +- **控制流与局部数据流**:跳转表恢复、基本块划分、函数内的寄存器常量追踪(selector、调用的常量参数)。 +- **数据常量解码**:CFString、ObjC 字面量、KeyPath、Swift 字符串、相对指针、fixup 指针。 +- **两个构建之间逐函数比较**。 +- **分析结果的持久化**(如果实测证明需要)。 +- **查询入口**:`swift-section` 的子命令、RuntimeViewer 的 CLI 与 MCP,以及全局 `reverse-engineering` + skill 规定的逆向流程。 + +涉及的仓库:MachOKit(fork)、MachOKitExtensions、MachOObjCSection、本库(`CrossReferenceAnalysis`、 +`SwiftThunkAnalysis`、`swift-section`)、swift-capstone、RuntimeViewer。 + +**不算在内的**,见文末「不在此愿景内」:伪代码、运行时检查与跟踪、交互式标注、x86_64。 + +## 为什么值得系统性投入 + +今天逆向的第三阶段完全交给 IDA:全局 `reverse-engineering` skill 规定「先类型定义,再成员地址,最后 +反编译」,第三步经 idalib MCP 调 IDA。2026-11-18 统计本机全部 Claude Code 对话记录,agent 对 IDA 的调用 +(调用量前 30 的工具合计)约 4.76 万次,其中 `decompile` 27,447 次(约 58%)、`disasm` 9,454 次、 +`xrefs_to` 2,304 次、`xref_query` 441 次,其余是开关库与读字节。 + +但 agent 真正离不开 IDA 的,是**给地址起名**和**查引用**,伪代码反而是可替代的那一块(见「现状与代价」)。 +要替代的这几块——地址符号化、交叉引用、注解反汇编、控制流、数据解码、持久化——每一块都要面对同一组问题: +扫描用哪个解码器、地址按哪种约定换算、符号化放在哪一层、输出给 agent 的契约长什么样、要不要落盘。不先定 +方向,每份提案都会把这组取舍重新吵一遍。 + +## 现状与代价 + +以下都可在所引的记忆、笔记或文档里核实(`~/.claude/agent-memory/reverse-explorer*/`、各项目的 agent 记忆、 +全局 `reverse-engineering` skill 的 `references/ipsw-cache-recipes.md`)。 + +- **跨镜像查「谁用了它」没有工具**。约 15 条逆向笔记靠手工两跳:先按字节扫 `__objc_selrefs` 或 GOT 槽 + (低 4 字节是 `VA - 0x180000000`),再反汇编 stub island 找 `adrp x1` + `add x1`,最后 `ipsw dyld a2s` + 起名(`reverse-explorer/cross-cache-caller-search.md`)。 + - `ipsw dyld xref` 不跟进 stub island,结果为空什么也证明不了;`dyld_info -imports` 静默漏掉大部分 bind。 + - 2026-10-29 有一次把「某个类没人实例化」判错:漏查了经 GOT 读**本镜像自己**类对象的两处调用。 + - 列出导入某个类的镜像,只能对 4,115 个镜像各跑一次 `ipsw dyld macho --symbols`,28 核 2 分 40 秒。 +- **cache 里的调用目标常常没名字或名字是错的**。 + - `dyld_info -disassemble` 把 macOS 26.7 SwiftUICore 的 2,195 个 `__auth_stubs` 桩标成同一个错名, + 15.3 万条 `bl` 的目标名字错(RuntimeViewer 记忆 `dyld-info-mislabels-cache-stubs.md`)。 + - 27.0 起 `objc_msgSend$…` 桩合并到 cache 级区域,`ipsw dyld a2s` 对它只回 `?`。 + - IDA 单镜像库里的导入桩被叫成 `j___<该镜像第一个局部符号>_N`。 + - 整个 cache 1,308 万个函数起点里 37.8% 没有符号(macOS 26.7)。 +- **IDA 本身在拖后腿**。 + - 23 个会话在 `idb_open` 时报 `Remote end closed connection`(1.6–2.5 GB 的库,60 秒工具超时)。 + - `idb_close(save: false)` 照样回写 `.i64`,之后再开常报 `internal error 1228`。 + - `xrefs_to` / `disasm` 只回 10 行却报 `done: true`。 + - 一个库只装得下几个镜像,跨镜像的引用在库里看不到;漏一个镜像就得重建,几分钟起步。 +- **伪代码有系统性错误**。约 16 条笔记记着 Hex-Rays 的误判:丢掉 `@try` / `@catch`、返回多个 `double` + 的函数只剩 `d0`、7 个参数的签名被截成 5 个、带 label 的分支里祖先 `if` 的条件不再成立。skill 早就规定 + 「汇编与伪代码冲突时信汇编」。 +- **手工解码与比对的成本**。32 个会话手写过 `struct.unpack`;SourceEditor 为逐函数比对原版与重建版的汇编, + 写了 30 个 Python 脚本和一份 981 行的规整规则(`SourceEditor/Documentations/Internal/AssemblyComparison.md`)。 + +基础其实已经有一半:本库的 `CrossReferenceAnalysis`(提案 0072)在进程内 1.6–3.0 秒扫完整个 cache、 +认得 27 的 cache 共用桩和 stub island;`SwiftThunkAnalysis` 里已有一套离线的桩链与槽解析;swift-capstone +7 已经把 AArch64 的指令、操作数、别名都包成 Swift 类型。缺的是把它们接到磁盘文件、接到命令行,并补齐其余几块。 + +## 根本的设计取舍 + +1. **agent 的主读物:汇编还是伪代码。** 伪代码短、结构一目了然,但有上面那类系统性错误,而且离不开 IDA; + 汇编是地面真值,但裸汇编里的 `bl 0x19…` 没有名字,长函数很长。 +2. **扫描用哪个解码器:手写子集还是 capstone。** 手写的 `ARM64InstructionDecoding` 只认交叉引用用得到的 + 指令形态,单线程比 capstone 快 25–50 倍;capstone 覆盖全部指令和完整的操作数语义,有上游背书。两套并存 + 就得保证它们对同一条指令的理解一致。 +3. **要不要像 Binary Ninja 那样建完整的中间表示。** Binary Ninja 把代码提升成多层 IL 并在 SSA 上做常量传播, + 引用识别的上限高,但这是一个反编译器级别的工程;只做函数内的轻量寄存器追踪,能覆盖 `adrp` + `add`、 + `adrp` + `ldr` 槽、`mov x1` 这些常见模式,跨基本块的复杂数据流会漏。 +4. **按需现算还是落盘索引。** 现算没有失效问题,重复查询却要重扫;落盘快,但要管 cache 版本、格式演进和磁盘 + 占用。 +5. **统一地址空间还是按镜像建模。** Binary Ninja 把整个 cache 放进一个地址空间,跨镜像的引用就是普通地址; + 本库的 `CodeLocation` 是「镜像下标 + 未滑动地址」,RuntimeViewer 已经按它建了一层查询。 +6. **新能力放在哪一层。** MachOKit 是 p-x9 上游的 fork,fork 已落后上游 33 个提交,越加越难合; + MachOKitExtensions 是自有的通用层,正在接收本库的读取层(MachOKitExtensions 草案 + `move-reading-and-resolving-modules`,之后又接收了整个 Mach-O 层,见下文「我们选的方向」第 6 条); + 本库的 Analysis 层离使用方最近,但通用的东西放这里,别的仓库 + (MachOKitUI、swift-decompiler)拿不到。 +7. **正确性的标准答案用谁。** 反汇编有 `otool -tV` / `llvm-objdump`;fixup 有 `dyld_info -fixups`(只读本机 + cache);交叉引用没有天然的地面真值,IDA 自己就会漏,Binary Ninja 更全但只能在它的界面里跑。 + +## 我们选的方向 + +1. **agent 默认读带注解的汇编,IDA 是后备。** + - **IDA**:负责本方向工具还覆盖不到的交叉引用、控制流特别复杂的超长函数,以及 swift-decompiler 的研究 + (它以 IDA 的 microcode 为输入)。 + - **Binary Ninja**:只在用户手动使用时作参照,不进 agent 的默认流程。 + - 2026-11-18 用户曾选定「Binary Ninja 负责交叉引用、IDA 负责复杂函数」的分工,前提是 Binary Ninja 的 + 交叉引用更强;同日的实测(见下)推翻了这个前提,用户改定 IDA 为主。dyld cache 里跨镜像的引用两家都受 + 「一个库或一个视图只装得下部分镜像」所限,交给第 1 阶段的新工具。 + - 改 skill 的默认流程之前,先量一次:挑几十个函数,比较注解汇编和 Hex-Rays 伪代码的 token 数与正确率, + 结果写进本愿景。 + - **放弃**:伪代码作为默认读物;Hex-Rays 的类型恢复带来的那部分可读性。 + + Binary Ninja 6(6.0.10601)起自带 MCP 服务器,以下是评估时查到与实测到的情况: + - GUI 内的 HTTP 版随所有 GUI 版本提供,包括用户的 Personal 版:设置里开 `ui.mcp.enabled`、重启、 + `Plugins > MCP > Start Server`,默认 `http://127.0.0.1:24642/mcp`。无界面的 `binaryninja_mcp` 只随 + Commercial / Ultimate。 + - 2026-11-18 在本机实测连通(服务名 `binaryninja_ui_mcp` 0.1.0,未设令牌):共 75 个工具,读的有 + `bn_function_callers` / `bn_function_callees`、`bn_function_xrefs_to` / `_from`、`bn_data_xrefs_to` / + `_from`、`bn_type_xrefs_to` / `_from`、`bn_function_disassembly`、`bn_function_il`、 + `bn_function_decompile`、`bn_function_basic_blocks`、`bn_memory_read`;写的有改名、注释、定义类型与 + 数据变量。 + - 限制:必须开着界面;当前视图跟随界面,多个 agent 同时用会互相抢;工具清单里**没有**从 dyld shared + cache 加载某个镜像的工具,cache 里的镜像要在界面里加载;函数相似度比对(含 BinDiff)只有 Ultimate 版有。 + - **实测(2026-11-18):在独立二进制上,经 MCP 查交叉引用,Binary Ninja 不如 IDA。** + - 样本:Finder 26.5.2(ObjC 为主)与 ControlCenter 26.7(Swift 为主),arm64e,120 个目标、527 条代码 + 引用、49 条数据引用。标准答案由 `otool -tV` 加独立的 `adrp` 寄存器跟踪、`dyld_info -fixups`、相对方法 + 列表与 `__swift5_types` 解码生成,不依赖任何一方。 + - 代码引用召回:IDA 一次查询 97.0%、两跳 99.4%,裁决后没有真误报;Binary Ninja 经 MCP 一次查询 67.6%, + 另有 22 条 `adrp` 页地址误报。Binary Ninja 的分析里其实有 97.7%(按函数粒度算,偏宽),差距出在 MCP + 接口:`bn_data_xrefs_to` 只报「数据 → 数据」,没有「代码 → 数据地址」的反查,所以类引用、字符串、ivar + 三类经 MCP 都是 0%;`bn_function_callers` 不认 objc stub 调用,要再调 `bn_function_xrefs_to`;方法列表 + 的 IMP 字段只找到 8/16。 + - 双方各自的盲点:IDA 漏掉恰好页对齐的类对象(`adrp; add #0`),按类符号查询只给一跳;Binary Ninja 漏掉 + Swift 大字符串的 `adrp; add; sub #0x20` 写法(13 处只中 2 处),也没给 `retab` 之后的异常清理代码建函数。 + - 耗时:Binary Ninja 从打开到分析完成,Finder 224 秒、ControlCenter 81 秒;IDA 打开现成 `.i64` 约 3 秒 + (建库时间未计)。 + - 没测到的:dyld shared cache 里的跨镜像引用。IDA 的弱点主要在这里(一个库只装得下几个镜像),而 + Binary Ninja 的 MCP 又没法加载 cache 镜像,这一场景要用户在界面里手动加载后才能比。 +2. **两个解码器分工。** 扫描整个 cache 的热路径用手写的 `ARM64InstructionDecoding`;给人和 agent 读的反汇编 + 文本、需要完整操作数语义的地方(跳转表、寄存器追踪)用 swift-capstone。两者之间用对拍测试保持一致: + 同一批函数两边解码,结果逐条比。swift-capstone 因此要加大维护——拿 `otool -tV` 整镜像对拍正确性(重点是 + arm64e 的 PAC 指令、LSE 原子指令和 Apple 专有指令),并提供把地址操作数换成名字的符号化接口。 + - **放弃**:只维护一套解码器的简单。 +3. **不建完整的中间表示,只做函数内的轻量常量追踪。** 在 `RegisterFile` 的基础上扩展:基本块内向前追踪 + `adrp` / `add` / `ldr` / `mov` 产生的常量,遇到调用清掉调用者保存的寄存器;跨基本块只在单前驱、或多个 + 前驱的值一致时传递。这是 Binary Ninja SSA 常量值的一个子集,覆盖它做 ObjC selector 识别时用到的那部分。 + - **放弃**:跨函数数据流、类型传播。Swift 的字段级引用(谁读写了某个结构体字段)依赖类型传播,等常量追踪 + 落地后再评估。 +4. **先现算,量过再落盘。** 0072 与 RuntimeViewer 0056 都定过「不做存盘索引」;离线模式的吞吐要实测,冷启动 + 读几个 GB 的 cache 若明显拖慢重复查询,持久化再作为独立阶段提出。 +5. **保留按镜像的 `CodeLocation`,另给一张全 cache 的地址符号化表。** 统一地址空间里最有价值的是「任何地址 + 都能说出它是什么」,这一点用符号化器单独提供,不推翻已有的模型和 RuntimeViewer 的查询层。 +6. **分层:与语言无关的部分归 MachOKitExtensions,ObjC 专属的归 MachOObjCSection,Swift 专属的与命令入口留在本库。** 与语言无关的包括读取、地址换算、桩与槽的解析,也包括分析本身的核心——指令扫描、函数表、字符串、符号化;ObjC 专属的是消息发送、类引用、ivar、方法列表这类识别。核心经扩展点接纳各语言层的识别,不认识任何一种语言,对新语言封闭、对扩展开放。自 MachOKitExtensions 2.0.0 起,本库原来的整个 Mach-O 层(读取、指针、按镜像的缓存、依赖闭包、符号表与采集,外加一个 C/C++ 符号索引)都在那里,本库的 `Sources/MachO/` 分组已经没有了(MachOKitExtensions 草案 `move-macho-infrastructure-modules`);不依赖 Swift 元数据的新通用代码直接写进 MachOKitExtensions。交叉引用是先在本库按这几层写成独立模块、用源码扫描守住每层能 import 什么、量过之后再整体搬过去的(0097 拆层,提案 [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md) 搬家);本库里的模块名刻意不同于落脚处的名字,免得与已发布版本的同名模块冲突。除了修 bug,不往 MachOKit fork 里加新能力。 +7. **标准答案**:反汇编对 `otool -tV`;fixup 对本机 cache 的 `dyld_info -fixups`;交叉引用以 IDA(查到两跳) + 为主要参照,Binary Ninja 为辅——第 1 条的实测里,IDA 两跳的召回是 99.4%,Binary Ninja 经 MCP 是 67.6%。 + 最可靠的仍是 `otool -tV` 加独立寄存器跟踪生成的标准答案,那次实测就是这样做的。 + +## 分阶段设想 + +只给轮廓,实际提案可以调整顺序或合并拆分。 + +1. **交叉引用与地址符号化扩展到磁盘文件和归档 cache**——本库已有的进程内分析器支持文件,补几类引用,新增 + 符号化器,`swift-section refs` / `symbolicate` 两个子命令,RuntimeViewer 的 CLI 与 MCP 接上交叉引用。 + 提案 [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md)。 +2. **函数清单与带注解的反汇编**——边界来自 `LC_FUNCTION_STARTS`、符号表、ObjC 方法表的 IMP 与 unwind 信息, + 包括 block 和 `.cold`;用 swift-capstone 出文本,每个调用、地址生成、槽读取都经第 1 步的符号化器标名。 + swift-capstone 的对拍与符号化接口在这一步做。 +3. **数据解码与数据引用**——`read --as cfstring | objc-literal | keypath | swift-string | relative-pointer | + fixup-pointer`;方法表条目指向 IMP、CFString 指向字符串这类「数据 → 地址」的引用进交叉引用。 +4. **控制流与常量追踪**——跳转表恢复、基本块、跨块常量传递;顺带做调用点常量参数普查(例如 + `dyld_program_sdk_at_least` 每个调用点传的版本集合)。 +5. **两个构建逐函数比汇编**——按符号或 selector 配对,规整重定位与 ARC 差异,每个函数判成「完全一致 / + 只有重定位差异 / 有实质变化」三档;SourceEditor 的比对脚本收编进来。 +6. **分析结果落盘**——只在前几步实测证明重复查询的代价不可接受时提出。 +7. **切换默认流程**——完成「我们选的方向」第 1 条里的测量后,`reverse-engineering` skill 的第三阶段改成 + 「读注解汇编」,IDA 降为后备。 + +## 不在此愿景内 + +- **伪代码与反编译器**:swift-decompiler 自己的路线,目前以 IDA 的 microcode 为输入。 +- **运行时检查与跟踪**:读活对象的 ivar、列存活实例、selector 调用跟踪,属于 RuntimeViewer 自己的方向。 +- **交互式标注库**:改名、注释、手工类型存回数据库,这是 IDA / Binary Ninja 的产品形态,不做。 +- **x86_64 与其他架构**:只有 Apple Silicon 机器,系统二进制都有 arm64e 切片。 +- **把 Binary Ninja 当 agent 的主力后端**:Personal 许可没有无界面 API,无界面的 `binaryninja_mcp` 也只随 + Commercial / Ultimate 提供;它的 GUI MCP 只能在用户开着界面时用。 +- **改进 IDA 后备路径**(例如 idax 建库时写入我们的桩名和 Swift 函数名):IDA 降为后备后按需另提,不是本 + 愿景的目标。 + +## 待确认 + +- **注解汇编与伪代码的实测结果**(「我们选的方向」第 1 条的测量)。 +- **dyld shared cache 跨镜像引用上 IDA 与 Binary Ninja 的差距**:实测只覆盖了独立二进制;后备已定为 IDA, + 这一项只在将来重新评估后备时才需要补测。 + +## 相关提案 + +| 提案 | 状态 | 它推进了愿景的哪一部分 | +|------|------|------------------------| +| [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) | Implemented | 第 1 阶段:交叉引用与地址符号化扩展到磁盘文件和归档 cache,并接到 `swift-section` 与 RuntimeViewer 的 CLI / MCP;顺带把交叉引用按「我们选的方向」第 6 条拆成核心、ObjC、Swift 三层(真正迁出本库另写提案) | +| [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md) | Accepted | 「我们选的方向」第 6 条:把 0097 拆出的核心层与地址解析、ARM64 解码搬进 MachOKitExtensions,ObjC 层搬进 MachOObjCSection,随本库 0.25.0 落地 | + +--- + +> **愿景是活文档**,随认识加深可以修订,修订时更新「最后更新」。 +> 这一点与提案不同 —— 提案是决策快照,落地后保持原貌不改。 +> +> 方向被推翻时,状态改为 `Superseded`(并指向取代它的愿景)或 `Abandoned`(并写明为什么放弃), +> **文档保留不删** —— 它是「当初为什么往那个方向走」的唯一记录。 diff --git a/Package.swift b/Package.swift index d18ff9dbe..cefcb9c25 100644 --- a/Package.swift +++ b/Package.swift @@ -96,8 +96,7 @@ var dependencies: [Package.Dependency] = [ .package(url: "https://github.com/apple/swift-collections", from: "1.2.0"), .package(url: "https://github.com/p-x9/AssociatedObject", from: "0.13.0"), - .package(url: "https://github.com/p-x9/swift-fileio.git", from: "0.9.0"), - .package(url: "https://github.com/Mx-Iris/FrameworkToolbox", from: "0.4.0"), + .package(url: "https://github.com/Mx-Iris/FrameworkToolbox", from: "0.17.0"), .package(url: "https://github.com/gohanlon/swift-memberwise-init-macro", from: "0.6.0"), @@ -133,8 +132,16 @@ extension Package.Dependency { // 0.53.0 through 0.54.100 trapped there, and the ObjC ancestor // lookup reads the exports of every image it walks, the iOS 15.5 // simulator's UIKit among them. MachOObjCSection and - // MachOKitExtensions require it as well. - from: "0.54.101", + // MachOKitExtensions require it as well. 0.55.101 gives a file not + // read out of a dyld cache no cache instead of opening its path as + // one on every `cache` access: offline reading of a standalone file + // spent two thirds of its time reopening the file. 0.55.102 hands + // over the bytes it mapped a file into (`fileBytes`), which every + // `MachOFile` read now goes through, and remembers a dyld cache's + // mapping tables and its main, full and symbol caches safely when + // several threads first read one image at once: two indexes built + // on one image crashed in `mappingInfo(for:)`. + from: "0.55.102", ), ) @@ -151,13 +158,21 @@ extension Package.Dependency { // its cache too (`dyldCacheImage`), which `SharedCacheKey` hashes. // 1.1.1 builds each dyld sub-cache once instead of on every read // that crosses into another cache file, and hands back the same - // instance each time, which `DyldCache.fileIO` keys its mapping on. + // instance each time. // 1.1.2 adds `FullDyldCache.cachedHost`, the system cache opened // once per process rather than once per dependency locator. // 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", + // sees through a host's wrapper type. 1.3.1 grows the memos of + // `resolveRebase(fileOffset:)` / `resolveBind(fileOffset:)` in + // place, where each new entry used to copy the whole dictionary. + // 1.3.2 stores a file's `identifier` and its bind index once: + // threads reading a new file for the first time each stored their + // own, freeing the value another thread was still reading, and + // `SharedCacheKey` reads the identifier on every lookup. + // 2.0.0 carries MachOReading and MachOResolving, which used to be + // targets of this package; earlier releases do not have them. + from: "2.0.0", ), ) @@ -181,8 +196,28 @@ extension Package.Dependency { // instance property and adopted protocol of a class other images // extend, such as NSView. 0.8.200 merges upstream 0.8.2 and reads // every list an image attaches to a class, not just its first: - // `_UTCoreType` lost the methods of its second list. - "0.8.200" ..< "0.9.0", + // `_UTCoreType` lost the methods of its second list. 0.8.201 + // takes the classes without a class object a host supplies + // (`ObjCSuppliedClass`): generic Swift classes and the ones + // `__objc_stublist` registers, read from Swift metadata here. + // 0.8.202 reads the method names of a macOS 11 dyld cache, whose + // relative method lists count a selector from the name field + // itself: the selector base it used to add only exists from + // macOS 12, so every class and category method of an 11.x cache + // read as garbage. 0.8.204 adds `ObjCEvolutionInterfaceBuilder`, + // the merged and annotated header `objc evolution --interface` + // prints; 0.8.203 carried it too, but crashes the Swift 6.3 + // compiler of Xcode 26. 0.8.205 compares a version made up of a + // group of images (`evolution(ofImageGroups:versions:)`, + // `addVersion(images:version:)`), which the integration tests + // drive over AppKit with the frameworks Apple moved its classes + // into. 0.8.206 finds the image of a dyld cache an address or a + // header index lies in through tables built once per cache file, + // where reading a protocol list walked every image of the cache + // for each pointer. + // 0.8.207 holds `ObjCCodeReferences`, the Objective-C layer of the + // cross-reference analysis, and takes MachOKitExtensions 2.0.0. + "0.8.207" ..< "0.9.0", ), ) } @@ -200,8 +235,15 @@ extension Package.Dependency { // 0.7.2 adds `DemangleOptions.useModuleSelectors`, which // `--module-selectors` prints with, and answers kind queries on a // `NodeReference` without retaining its store, which parallel - // printing contended on. - "0.7.2" ..< "0.8.0", + // printing contended on. 0.7.3 demangles without copying the + // whole demangler on each `require(pop())` and remangles without + // visiting every slot of its hash cache on the way out: building + // a symbol index on several threads spent 2.3 times its + // single-threaded CPU time on those copies. + // 0.7.4 spells existentials with `any` on request + // (`DemangleOptions.useExistentialAny`), which `interface` and + // `dump` print with by default. + "0.7.4" ..< "0.8.0", ), ) @@ -212,9 +254,10 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/swift-semantic-string", - // 0.5.0 adds definition regions, which `marksNestedDefinitions` - // wraps each nested definition in. - from: "0.5.0", + // 0.6.0 adds the annotation regions `marksCommentStructure` marks + // every comment with; 0.5.0 added the definition regions + // `marksNestedDefinitions` wraps each nested definition in. + from: "0.6.0", ), ) @@ -253,10 +296,65 @@ extension Target.Dependency { name: "MachOObjCSection", package: "MachOObjCSection", ) + static let ObjCCodeReferences = Target.Dependency.product( + name: "ObjCCodeReferences", + package: "MachOObjCSection", + ) static let MachOKitExtensions = Target.Dependency.product( name: "MachOKitExtensions", package: "MachOKitExtensions", ) + // The reading layer: targets of this package until MachOKitExtensions + // 2.0.0 took them over under the same names. + static let MachOReading = Target.Dependency.product( + name: "MachOReading", + package: "MachOKitExtensions", + ) + static let MachOResolving = Target.Dependency.product( + name: "MachOResolving", + package: "MachOKitExtensions", + ) + // The rest of the Mach-O layer, which MachOKitExtensions 2.0.0 took over + // under the same names. `MachOSymbols` there is the language-neutral + // half of what was this package's `MachOSymbols`: the symbol table, the + // sweep and the C, C++ and Objective-C symbol index; the Swift half is + // `SwiftSymbols` below. + static let MachOPointers = Target.Dependency.product( + name: "MachOPointers", + package: "MachOKitExtensions", + ) + static let MachOCaches = Target.Dependency.product( + name: "MachOCaches", + package: "MachOKitExtensions", + ) + static let MachODependencies = Target.Dependency.product( + name: "MachODependencies", + package: "MachOKitExtensions", + ) + static let MachOSymbols = Target.Dependency.product( + name: "MachOSymbols", + package: "MachOKitExtensions", + ) + static let ARM64InstructionDecoding = Target.Dependency.product( + name: "ARM64InstructionDecoding", + package: "MachOKitExtensions", + ) + static let MachOAddressResolution = Target.Dependency.product( + name: "MachOAddressResolution", + package: "MachOKitExtensions", + ) + static let MachOCodeReferences = Target.Dependency.product( + name: "MachOCodeReferences", + package: "MachOKitExtensions", + ) + static let MachOBase = Target.Dependency.product( + name: "MachOBase", + package: "MachOKitExtensions", + ) + static let MachOFoundation = Target.Dependency.product( + name: "MachOFoundation", + package: "MachOKitExtensions", + ) static let MachOKitMain = Target.Dependency.product( name: "MachOKit", package: "MachOKit", @@ -320,7 +418,7 @@ extension Target { static let Utilities = Target.target( name: "Utilities", dependencies: [ - .target(.MachOMacros), + .target(.SwiftSectionMacros), .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .product(name: "AssociatedObject", package: "AssociatedObject"), .product(name: "MemberwiseInit", package: "swift-memberwise-init-macro"), @@ -331,110 +429,22 @@ 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: [ - .product(.MachOKit), - .product(.MachOKitExtensions), - .target(.Utilities), - ], - path: "Sources/MachO/MachOCaches", - ) - - /// Dependency resolution shared by every feature that needs a binary's - /// linked images (evolution proposal macho-dependencies-module): - /// search paths, the in-process / on-disk locators, and the direct or - /// transitive `DependencyClosure` walk over `LC_LOAD_DYLIB`. Knows nothing - /// about Swift metadata, so it sits with the other MachO* leaf targets and - /// is re-exported by `MachOFoundation`. - static let MachODependencies = Target.target( - name: "MachODependencies", - dependencies: [ - .product(.MachOKit), - .product(.MachOKitExtensions), - ], - path: "Sources/MachO/MachODependencies", - ) - - static let MachOReading = Target.target( - name: "MachOReading", + /// The Swift symbol index: every Swift name of an image demangled and + /// classified (members, types, witnesses, thunks), on top of + /// MachOKitExtensions' `MachOSymbols`, whose sweep collects the names. + static let SwiftSymbols = Target.target( + name: "SwiftSymbols", dependencies: [ .product(.MachOKit), .product(.MachOKitExtensions), - .target(.Utilities), - .product(name: "FileIO", package: "swift-fileio"), - ], - path: "Sources/MachO/MachOReading", - ) - - static let MachOResolving = Target.target( - name: "MachOResolving", - dependencies: [ - .product(.MachOKit), - .product(.MachOKitExtensions), - .target(.MachOReading), - ], - path: "Sources/MachO/MachOResolving", - ) - - static let MachOSymbols = Target.target( - name: "MachOSymbols", - dependencies: [ - .product(.MachOKit), .product(.Demangling), - .target(.MachOReading), - .target(.MachOResolving), + .product(.MachOReading), + .product(.MachOResolving), + .product(.MachOSymbols), + .product(.MachOCaches), .target(.Utilities), - .target(.MachOCaches), ], - path: "Sources/MachO/MachOSymbols", - ) - - static let MachOPointers = Target.target( - name: "MachOPointers", - dependencies: [ - .product(.MachOKit), - .product(.MachOKitExtensions), - .target(.MachOReading), - .target(.MachOResolving), - .target(.Utilities), - ], - path: "Sources/MachO/MachOPointers", - ) - - /// The reader / resolver / pointer layer as one import: everything the - /// ABI model is allowed to depend on. `MachOFoundation` adds the symbol - /// index and dependency resolution on top (evolution proposal - /// `self-contained-abi-layer`). - static let MachOBase = Target.target( - name: "MachOBase", - dependencies: [ - .product(.MachOKitExtensions), - .target(.MachOReading), - .target(.MachOResolving), - .target(.MachOPointers), - .target(.Utilities), - ], - path: "Sources/MachO/MachOBase", - ) - - static let MachOFoundation = Target.target( - name: "MachOFoundation", - dependencies: [ - .product(.MachOKit), - .target(.MachOBase), - .target(.MachOSymbols), - .target(.MachODependencies), - ], - path: "Sources/MachO/MachOFoundation", + path: "Sources/Symbols/SwiftSymbols", ) static let MachOSwiftSectionC = Target.target( @@ -449,9 +459,10 @@ extension Target { name: "MachOSwiftSection", dependencies: [ .product(.MachOKit), - .target(.MachOBase), + .product(.MachOBase), .target(.Utilities), .target(.MachOSwiftSectionC), + .target(.SwiftSectionMacros), ], path: "Sources/ABI/MachOSwiftSection", ) @@ -480,13 +491,13 @@ extension Target { name: "SwiftInspection", dependencies: [ .product(.MachOKit), - .product(.MachOObjCSection), .product(.Semantic), .product(.Demangling), .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .target(.Utilities), - .target(.MachOCaches), - .target(.MachOFoundation), + .product(.MachOCaches), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.MachOSwiftSectionC), .target(.SwiftOutputTransformer), @@ -494,6 +505,30 @@ extension Target { path: "Sources/Analysis/SwiftInspection", ) + /// The Objective-C side of Swift types: the class objects of Swift + /// classes, `@objc @implementation` classes, `@objc` protocols declared + /// in Swift, ObjC method tables and ancestor chains, and the + /// ClangImporter's naming rules (evolution proposal + /// `swift-objc-interop-module`). Sits directly above `SwiftInspection`, + /// whose demangler it uses; this is where `MachOObjCSection` enters the + /// Swift-facing stack. + static let SwiftObjCInterop = Target.target( + name: "SwiftObjCInterop", + dependencies: [ + .product(.MachOKit), + .product(.MachOObjCSection), + .product(.Demangling), + .product(name: "FoundationToolbox", package: "FrameworkToolbox"), + .target(.Utilities), + .product(.MachOCaches), + .product(.MachOFoundation), + .target(.SwiftSymbols), + .target(.MachOSwiftSection), + .target(.SwiftInspection), + ], + path: "Sources/Analysis/SwiftObjCInterop", + ) + /// Static aggregate-layout engine: computes Swift struct/class field /// offsets offline from a Mach-O file without loading the process or /// calling the runtime. Ports the runtime `performBasicLayout` algorithm @@ -507,10 +542,13 @@ extension Target { .product(.MachOObjCSection), .product(.Demangling), .target(.Utilities), - .target(.MachODependencies), - .target(.MachOFoundation), + .product(.MachOCaches), + .product(.MachODependencies), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), ], path: "Sources/Analysis/SwiftLayout", ) @@ -530,14 +568,17 @@ extension Target { .product(.Demangling), .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .target(.Utilities), - .target(.MachOCaches), - .target(.MachODependencies), - .target(.MachOFoundation), + .product(.MachOCaches), + .product(.MachODependencies), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftOutputTransformer), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftLayout), .target(.SwiftThunkAnalysis), + .product(.MachOAddressResolution), ], path: "Sources/Output/SwiftDeclarationRendering", ) @@ -556,35 +597,42 @@ extension Target { static let SwiftThunkAnalysis = Target.target( name: "SwiftThunkAnalysis", dependencies: [ + .product(.MachOAddressResolution), .product(.MachOKit), .product(.MachOKitExtensions), .product(.Demangling), .product(.Capstone), .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .target(.Utilities), - .target(.ARM64InstructionDecoding), - .target(.MachOCaches), - .target(.MachOFoundation), + .product(.MachOCaches), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), ], path: "Sources/Analysis/SwiftThunkAnalysis", ) /// What each function of an image references, read from its arm64 - /// machine code in process (evolution proposal `cross-reference-analysis`). + /// machine code (evolution proposals `cross-reference-analysis`, + /// `offline-cross-references-and-symbolication`): the Swift layer and + /// the public facade over the two layers below it. static let CrossReferenceAnalysis = Target.target( name: "CrossReferenceAnalysis", dependencies: [ .product(.MachOKit), .product(.MachOObjCSection), .product(.Demangling), - .target(.ARM64InstructionDecoding), - .target(.MachOFoundation), + .product(.ARM64InstructionDecoding), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), // `SymbolicDemangler`: a type's name from its descriptor when no // symbol spells it. .target(.SwiftInspection), + .product(.MachOCodeReferences), + .product(.ObjCCodeReferences), ], path: "Sources/Analysis/CrossReferenceAnalysis", ) @@ -597,9 +645,11 @@ extension Target { .product(.Semantic), .product(.Demangling), .target(.Utilities), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftDeclarationRendering), .target(.SwiftThunkAnalysis), ], @@ -624,9 +674,11 @@ extension Target { // deploys to macOS 10.15, below `Logger`'s macOS 11. .product(name: "FoundationToolbox", package: "FrameworkToolbox"), .target(.Utilities), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftDeclarationRendering), .target(.SwiftThunkAnalysis), ], @@ -649,9 +701,11 @@ extension Target { .product(.Semantic), .product(.Demangling), .target(.Utilities), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftThunkAnalysis), .target(.SwiftDeclaration), .target(.SwiftDeclarationRendering), @@ -670,7 +724,8 @@ extension Target { .product(.MachOKit), .product(.MachOObjCSection), .product(.Demangling), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), .target(.SwiftDeclaration), @@ -724,10 +779,12 @@ extension Target { .product(.Semantic), .product(.Demangling), .target(.Utilities), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftOutputTransformer), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftDeclarationRendering), .target(.SwiftDeclaration), .target(.SwiftAttributeInference), @@ -748,7 +805,7 @@ extension Target { .product(.Semantic), .product(.Demangling), .target(.Utilities), - .target(.MachOSymbols), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), // The host's runtime names for `.metatype` arguments and the @@ -771,8 +828,9 @@ extension Target { .product(.Semantic), .product(.Demangling), .target(.Utilities), - .target(.MachODependencies), - .target(.MachOFoundation), + .product(.MachODependencies), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), .target(.SwiftDeclarationRendering), @@ -815,10 +873,12 @@ extension Target { static let SwiftSectionKit = Target.target( name: "SwiftSectionKit", dependencies: [ - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.MachOSwiftSection), .target(.SwiftDump), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftOutputTransformer), .target(.SwiftDeclaration), .target(.SwiftDeclarationRendering), @@ -829,6 +889,8 @@ extension Target { .target(.SwiftPrivateDiscriminators), .target(.TypeIndexing), .target(.Utilities), + // `refs` and `symbolicate`. + .target(.CrossReferenceAnalysis), .product(.MachOKit), .product(.MachOKitExtensions), .product(.Semantic), @@ -856,7 +918,8 @@ extension Target { // library's requests: `DependencySearchPath`, `DemangleOptions`, // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, the // ObjC generation options and C type presets. - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.SwiftDump), .target(.SwiftOutputTransformer), .target(.SwiftDeclaration), @@ -871,10 +934,29 @@ extension Target { path: "Sources/Executables/swift-section", ) + /// Maintainer tool, not a product: times indexing and printing one image's + /// interface through `MachOImage` or `MachOFile` in an ordinary process + /// (evolution proposal `machofile-performance`). + static let reader_benchmark = Target.executableTarget( + name: "reader-benchmark", + dependencies: [ + .target(.SwiftSectionKit), + .product(.MachOFoundation), + .target(.SwiftSymbols), + .target(.SwiftIndexing), + .target(.SwiftPrinting), + .target(.SwiftInterface), + .target(.SwiftDeclarationRendering), + .product(.MachOKit), + .product(name: "ArgumentParser", package: "swift-argument-parser"), + ], + path: "Sources/Executables/reader-benchmark", + ) + static let baseline_generator = Target.executableTarget( name: "baseline-generator", dependencies: [ - .target(.MachOFixtureSupport), + .target(.SwiftSectionFixtureSupport), .product(name: "ArgumentParser", package: "swift-argument-parser"), ], path: "Sources/Executables/baseline-generator", @@ -906,15 +988,15 @@ extension Target { // MARK: - Macros - static let MachOMacros = Target.macro( - name: "MachOMacros", + static let SwiftSectionMacros = Target.macro( + name: "SwiftSectionMacros", dependencies: [ .product(.SwiftSyntax), .product(.SwiftSyntaxMacros), .product(.SwiftCompilerPlugin), .product(.SwiftSyntaxBuilder), ], - path: "Sources/Support/MachOMacros", + path: "Sources/Support/SwiftSectionMacros", ) // MARK: - Testing @@ -922,69 +1004,72 @@ extension Target { /// Fixture-loading helpers, baseline generators, coverage scanners, and /// non-Testing-dependent code. Importable from non-test targets (e.g. /// `baseline-generator`) without dragging in `Testing.framework`. - static let MachOFixtureSupport = Target.target( - name: "MachOFixtureSupport", + static let SwiftSectionFixtureSupport = Target.target( + name: "SwiftSectionFixtureSupport", dependencies: [ .product(.MachOKit), - .target(.MachOFoundation), - .target(.MachOReading), - .target(.MachOResolving), + .product(.MachOFoundation), + .target(.SwiftSymbols), + .product(.MachOReading), + .product(.MachOResolving), .target(.MachOSwiftSectionC), .target(.SwiftDump), .target(.SwiftDeclaration), .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftInterface), - .target(.MachOTestingSupportC), + .target(.SwiftSectionTestingSupportC), .product(.Demangling), .product(.SwiftSyntax), .product(.SwiftParser), .product(.SwiftSyntaxBuilder), ], - path: "Sources/TestSupport/MachOFixtureSupport", + path: "Sources/TestSupport/SwiftSectionFixtureSupport", swiftSettings: testSettings, ) /// `swift-testing` base classes (`MachOFileTests`, `MachOImageTests`, /// `DyldCacheTests`, `XcodeMachOFileTests`, `MachOSwiftSectionFixtureTests`). - /// Splitting this out from `MachOFixtureSupport` keeps `Testing.framework` + /// Splitting this out from `SwiftSectionFixtureSupport` keeps `Testing.framework` /// out of the link line for non-test targets. - static let MachOTestingSupport = Target.target( - name: "MachOTestingSupport", + static let SwiftSectionTestingSupport = Target.target( + name: "SwiftSectionTestingSupport", dependencies: [ .product(.MachOKit), .product(.Demangling), - .target(.MachOFoundation), - .target(.MachOReading), - .target(.MachOResolving), - .target(.MachOFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), + .product(.MachOReading), + .product(.MachOResolving), + .target(.SwiftSectionFixtureSupport), .target(.MachOSwiftSection), .target(.SwiftDeclaration), .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftSpecialization), .target(.SwiftInterface), + .product(.Semantic), ], - path: "Sources/TestSupport/MachOTestingSupport", + path: "Sources/TestSupport/SwiftSectionTestingSupport", swiftSettings: testSettings, ) - static let MachOTestingSupportC = Target.target( - name: "MachOTestingSupportC", + static let SwiftSectionTestingSupportC = Target.target( + name: "SwiftSectionTestingSupportC", dependencies: [ ], - path: "Sources/TestSupport/MachOTestingSupportC", + path: "Sources/TestSupport/SwiftSectionTestingSupportC", swiftSettings: testSettings, ) - static let MachOSymbolsTests = Target.testTarget( - name: "MachOSymbolsTests", + static let SwiftSymbolsTests = Target.testTarget( + name: "SwiftSymbolsTests", dependencies: [ - .target(.MachOSymbols), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSymbols), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(.Demangling), - .target(.MachOResolving), + .product(.MachOResolving), ], swiftSettings: testSettings, ) @@ -993,36 +1078,17 @@ extension Target { name: "MachOSwiftSectionTests", dependencies: [ .target(.MachOSwiftSection), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .target(.SwiftDump), .target(.SwiftInspection), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .product(.Demangling), ], swiftSettings: testSettings, ) - static let MachOCachesTests = Target.testTarget( - name: "MachOCachesTests", - dependencies: [ - .target(.MachOCaches), - .product(.MachOKitExtensions), - ], - swiftSettings: testSettings, - ) - - static let MachODependenciesTests = Target.testTarget( - name: "MachODependenciesTests", - dependencies: [ - .target(.MachODependencies), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .product(.MachOKit), - .product(.MachOKitExtensions), - ], - swiftSettings: testSettings, - ) static let SwiftOutputTransformerTests = Target.testTarget( name: "SwiftOutputTransformerTests", @@ -1036,10 +1102,25 @@ extension Target { name: "SwiftInspectionTests", dependencies: [ .target(.MachOSwiftSection), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .target(.SwiftOutputTransformer), .target(.SwiftInspection), + // The suites that read ObjC classes through + // `ObjCImplementationClassReading` or evict an ObjC-side index. + .target(.SwiftObjCInterop), + ], + swiftSettings: testSettings, + ) + + static let SwiftObjCInteropTests = Target.testTarget( + name: "SwiftObjCInteropTests", + dependencies: [ + .target(.MachOSwiftSection), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .target(.SwiftInspection), + .target(.SwiftObjCInterop), ], swiftSettings: testSettings, ) @@ -1050,10 +1131,11 @@ extension Target { .target(.MachOSwiftSection), .target(.SwiftInspection), .target(.SwiftLayout), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(.Demangling), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1063,13 +1145,15 @@ extension Target { dependencies: [ .target(.SwiftThunkAnalysis), .target(.SwiftDump), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftObjCInterop), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(.MachOObjCSection), .product(.Semantic), .product(.Demangling), .product(name: "SnapshotTesting", package: "swift-snapshot-testing"), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], exclude: ["Snapshots/__Snapshots__"], swiftSettings: testSettings, @@ -1090,6 +1174,7 @@ extension Target { .target(.SwiftIndexing), .product(name: "ObjCIndexing", package: "MachOObjCSection"), .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), + .target(.SwiftObjCInterop), .target(.SwiftThunkAnalysis), .target(.SwiftPrinting), .target(.SwiftSpecialization), @@ -1097,10 +1182,11 @@ extension Target { // The nested-definition contract with source-file comments on. .target(.SwiftPrivateDiscriminators), .product(.MachOKitExtensions), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(name: "SnapshotTesting", package: "swift-snapshot-testing"), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], exclude: ["Snapshots/__Snapshots__"], swiftSettings: testSettings, @@ -1113,9 +1199,10 @@ extension Target { .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftDump), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .target(.MachOFoundation), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1125,14 +1212,16 @@ extension Target { dependencies: [ .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftLayout), .target(.SwiftDeclarationRendering), .target(.SwiftThunkAnalysis), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(.Semantic), .product(.Demangling), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1140,12 +1229,14 @@ extension Target { static let SwiftThunkAnalysisTests = Target.testTarget( name: "SwiftThunkAnalysisTests", dependencies: [ + .product(.MachOAddressResolution), .target(.SwiftThunkAnalysis), .target(.SwiftDeclarationRendering), .target(.SwiftDump), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .target(.MachOFoundation), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), .product(.Demangling), ], swiftSettings: testSettings, @@ -1155,13 +1246,17 @@ extension Target { name: "CrossReferenceAnalysisTests", dependencies: [ .target(.CrossReferenceAnalysis), - .target(.ARM64InstructionDecoding), + .product(.MachOCodeReferences), + .product(.MachOAddressResolution), + .product(.ObjCCodeReferences), + .product(.ARM64InstructionDecoding), .product(.MachOKit), .product(.Capstone), .product(.Demangling), .target(.MachOSwiftSection), - .target(.MachOReading), + .product(.MachOReading), .target(.SwiftInspection), + .target(.SwiftSectionFixtureSupport), ], swiftSettings: testSettings, ) @@ -1172,9 +1267,10 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftIndexing), .target(.SwiftAttributeInference), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .target(.MachOFoundation), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1184,7 +1280,8 @@ extension Target { dependencies: [ .target(.SwiftDeclaration), .target(.SwiftDiffing), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1194,7 +1291,8 @@ extension Target { dependencies: [ .target(.swift_section), .target(.SwiftSectionKit), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), .target(.SwiftOutputTransformer), .target(.SwiftDeclarationRendering), .target(.SwiftPrinting), @@ -1211,13 +1309,16 @@ extension Target { name: "SwiftSectionKitTests", dependencies: [ .target(.SwiftSectionKit), - .target(.MachOFoundation), + .product(.MachOFoundation), + .target(.SwiftSymbols), // `LocalTypeFixture` and `ExclusiveImageAccess`, for the source // files of a public type's private members. - .target(.MachOTestingSupport), + .target(.SwiftSectionTestingSupport), .target(.SwiftDeclaration), .target(.SwiftDiffing), .target(.SwiftOutputTransformer), + // What `refs` and `symbolicate` return. + .target(.CrossReferenceAnalysis), .product(.Semantic), .product(.OutputTransformer), .product(name: "ObjCDiffing", package: "MachOObjCSection"), @@ -1234,8 +1335,8 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), - .target(.MachOFixtureSupport), - .target(.MachOTestingSupport), + .target(.SwiftSectionFixtureSupport), + .target(.SwiftSectionTestingSupport), ], swiftSettings: testSettings, ) @@ -1248,9 +1349,11 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftAttributeInference), .target(.SwiftInspection), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .target(.MachOFoundation), + .target(.SwiftObjCInterop), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) @@ -1262,18 +1365,19 @@ extension Target { .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftSpecialization), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), - .target(.MachOFoundation), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), + .product(.MachOFoundation), + .target(.SwiftSymbols), ], swiftSettings: testSettings, ) - static let MachOTestingSupportTests = Target.testTarget( - name: "MachOTestingSupportTests", + static let SwiftSectionTestingSupportTests = Target.testTarget( + name: "SwiftSectionTestingSupportTests", dependencies: [ - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .target(.SwiftDeclaration), .product(.Demangling), ], @@ -1288,14 +1392,15 @@ extension Target { name: "IntegrationTests", dependencies: [ .product(.MachOKitExtensions), - .target(.MachOCaches), - .target(.MachOReading), - .target(.MachOResolving), - .target(.MachOSymbols), - .target(.MachOPointers), - .target(.MachOFoundation), + .product(.MachOCaches), + .product(.MachOReading), + .product(.MachOResolving), + .target(.SwiftSymbols), + .product(.MachOPointers), + .product(.MachOFoundation), .target(.MachOSwiftSection), .target(.SwiftInspection), + .target(.SwiftObjCInterop), .target(.SwiftDump), .target(.SwiftDeclaration), .target(.SwiftIndexing), @@ -1303,10 +1408,16 @@ extension Target { .target(.SwiftInterface), .target(.SwiftDiffing), .target(.TypeIndexing), - .target(.MachOTestingSupport), - .target(.MachOFixtureSupport), + .target(.SwiftSectionTestingSupport), + .target(.SwiftSectionFixtureSupport), .product(.MachOKit), .product(.MachOObjCSection), + // The ObjC API evolution dumps run the `swift-section objc + // evolution` pipeline on MachOObjCSection's own modules. + .product(name: "ObjCDiffing", package: "MachOObjCSection"), + .product(name: "ObjCIndexing", package: "MachOObjCSection"), + .product(name: "ObjCInterface", package: "MachOObjCSection"), + .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), .product(.Demangling), .product(.Semantic), .product(name: "Dependencies", package: "swift-dependencies"), @@ -1320,15 +1431,15 @@ let package = Package( platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1)], products: [ .library(.MachOSwiftSection), - // The ABI model no longer re-exports the symbol index (evolution + // The ABI model does not re-export the symbol index (evolution // proposal `self-contained-abi-layer`), so a downstream target that - // uses `SymbolIndexStore` / `DemangledSymbol` / `DependencyClosure` - // depends on `MachOFoundation` (or the lower `MachOBase`) explicitly. - .library(.MachOBase), - .library(.MachOFoundation), - .library(.MachODependencies), + // uses `SwiftSymbolIndexStore` / `DemangledSymbol` depends on + // `SwiftSymbols` explicitly; `MachOBase`, `MachOFoundation` and + // `MachODependencies` are products of MachOKitExtensions. + .library(.SwiftSymbols), .library(.SwiftOutputTransformer), .library(.SwiftInspection), + .library(.SwiftObjCInterop), .library(.SwiftLayout), .library(.SwiftDeclarationRendering), .library(.SwiftThunkAnalysis), @@ -1350,19 +1461,12 @@ let package = Package( targets: [ // Library .Utilities, - .ARM64InstructionDecoding, .SwiftOutputTransformer, - .MachOCaches, - .MachODependencies, - .MachOReading, - .MachOResolving, - .MachOSymbols, - .MachOPointers, - .MachOBase, - .MachOFoundation, + .SwiftSymbols, .MachOSwiftSectionC, .MachOSwiftSection, .SwiftInspection, + .SwiftObjCInterop, .SwiftLayout, .SwiftDeclarationRendering, .SwiftThunkAnalysis, @@ -1378,24 +1482,24 @@ let package = Package( .SwiftInterface, .TypeIndexing, .SwiftSectionKit, - .MachOMacros, - .MachOFixtureSupport, - .MachOTestingSupport, - .MachOTestingSupportC, + .SwiftSectionMacros, + .SwiftSectionFixtureSupport, + .SwiftSectionTestingSupport, + .SwiftSectionTestingSupportC, // Executable .swift_section, + .reader_benchmark, .baseline_generator, // Plugins .RegenerateBaselinesPlugin, // Testing - .MachOSymbolsTests, + .SwiftSymbolsTests, .MachOSwiftSectionTests, - .MachOCachesTests, - .MachODependenciesTests, .SwiftInspectionTests, + .SwiftObjCInteropTests, .SwiftOutputTransformerTests, .SwiftLayoutTests, .SwiftDumpTests, @@ -1412,7 +1516,7 @@ let package = Package( .SwiftPrivateDiscriminatorsTests, .SwiftSpecializationTests, .SwiftInterfaceTests, - .MachOTestingSupportTests, + .SwiftSectionTestingSupportTests, .IntegrationTests, ], ) diff --git a/README.md b/README.md index 4a424f2ab..6e1e59e8c 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Add the package to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.24.0"), + .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.25.0"), ], targets: [ .target( @@ -41,7 +41,7 @@ targets: [ dependencies: [ .product(name: "MachOSwiftSection", package: "MachOSwiftSection"), // Optional higher-level products: - .product(name: "MachOFoundation", package: "MachOSwiftSection"), + .product(name: "SwiftSymbols", package: "MachOSwiftSection"), .product(name: "SwiftInspection", package: "MachOSwiftSection"), .product(name: "SwiftDump", package: "MachOSwiftSection"), .product(name: "SwiftInterface", package: "MachOSwiftSection"), @@ -50,22 +50,25 @@ targets: [ ] ``` -Declare every product whose module you import. In particular, `MachOSwiftSection` no longer re-exports the symbol index (since 0.19.0): a file that uses `SymbolIndexStore`, `DemangledSymbol` or `DependencyClosure` needs `import MachOFoundation` **and** the `MachOFoundation` product on its target. +Declare every product whose module you import. In particular, `MachOSwiftSection` does not re-export the symbol index (since 0.19.0): a file that uses `SwiftSymbolIndexStore` or `DemangledSymbol` needs `import SwiftSymbols` **and** the `SwiftSymbols` product on its target. + +Since 0.25.0 the Mach-O layer underneath — `MachOBase`, `MachOFoundation`, `MachODependencies`, `MachOSymbols`, `MachOCaches`, `MachOPointers`, `MachOReading`, `MachOResolving` — comes from [MachOKitExtensions](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions) 2.0.0 and later, under the same module names. Code that uses one of them directly (`DependencyClosure`, for instance, is in `MachODependencies`) declares that product with `package: "MachOKitExtensions"`. **The ABI model and the Mach-O layer** | Product | Purpose | | --- | --- | | `MachOSwiftSection` | The ABI model: the `__swift5_*` sections, every descriptor in them, and the wrappers built from them (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, …). Depends on `MachOBase` only — no symbol index, no demangler. | -| `MachOBase` | Reading, address resolution and relative pointers — everything the ABI model sees. Re-exported by `MachOSwiftSection`. | -| `MachOFoundation` | `MachOBase` plus the symbol index, demangling, and dependency resolution. | -| `MachODependencies` | Resolves the images a binary links, in process or from files and dyld shared caches. | +| `SwiftSymbols` | The Swift symbol index: `SwiftSymbolIndexStore` demangles and classifies an image's Swift symbols, queried by offset, by name and by type member. | + +`MachOSwiftSection` re-exports MachOKitExtensions' `MachOBase` (reading, address resolution and relative pointers — everything the ABI model sees). `MachOBase`, `MachOFoundation` and `MachODependencies` used to be products of this package; since 0.25.0 they are provided by MachOKitExtensions. **Analysis** | Product | Purpose | | --- | --- | -| `SwiftInspection` | Symbol attribution and runtime metadata analysis — `SymbolicDemangler` (formerly `MetadataReader`), `EnumLayoutCalculator`, `ClassHierarchyDumper`. | +| `SwiftInspection` | Symbol attribution and runtime metadata analysis — `SymbolicDemangler` (formerly `MetadataReader`), `EnumLayoutCalculator`. | +| `SwiftObjCInterop` | The Objective-C side of Swift types: `@objc @implementation` classes, Swift classes renamed for the ObjC runtime, `@objc` protocols declared in Swift, ObjC method tables and ancestor chains, `ClassHierarchyDumper`. Split out of `SwiftInspection` in 0.25.0. | | `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. | @@ -168,9 +171,13 @@ Generated interfaces reflect a wide range of Swift language features: `SwiftInspection` exposes higher-level inspection utilities built on top of `MachOSwiftSection`: - `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. +The Objective-C side of Swift types lives in `SwiftObjCInterop` (part of `SwiftInspection` before 0.25.0 — add `import SwiftObjCInterop` and the product when upgrading): + +- `ObjCImplementationClasses` — the `@objc @implementation` classes an image defines, with their instance variables and method tables. +- `ClassHierarchyDumper` — walk a class's inheritance chain across Swift/ObjC boundaries (requires `@_spi(Internals) import SwiftObjCInterop`, `MachOImage` only). + #### Run a swift-section Command from Code `SwiftSectionKit` runs any `swift-section` subcommand in process and hands its output to you, piece by piece. A request produces what the matching command line prints. @@ -213,7 +220,7 @@ You can get the swift-section CLI tool in three ways: ### Usage -The swift-section CLI tool provides seven subcommands: `dump`, `interface`, `diff`, `snapshot`, `evolution`, `transformer`, and `objc` — the Objective-C side, with five subcommands of its own. +The swift-section CLI tool provides nine subcommands: `dump`, `interface`, `diff`, `snapshot`, `evolution`, `transformer`, `objc` — the Objective-C side, with five subcommands of its own — and `refs` and `symbolicate`, which read arm64 machine code across a whole dyld shared cache or a set of files. > [!IMPORTANT] > As of 0.10.0, when the input is a fat / universal binary you must pass `--architecture `. The tool no longer picks a default slice silently. @@ -469,9 +476,12 @@ swift-section interface --emit-export-status /path/to/binary # --emit-export-status. Types and protocols are ruled by their descriptor # symbol's export-trie entry, extensions by whether their target is an # in-image non-exported declaration, members by the same derived-form verdict -# the annotation uses. Still a symbol-table fact, never an access-level guess: -# anything without export evidence (and every `override` / `@objc` member) is -# kept, so an `-enable-testing` build keeps its `internal` declarations. +# the annotation uses. Still a symbol-table fact, never an access-level guess, +# with one certainty added: a private or local declaration with no symbol to +# judge by (a Swift-declared `@objc` protocol, a type in an image without local +# symbols) is dropped, as the compiler never exports one. Anything else 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. @@ -706,6 +716,16 @@ swift-section objc diff CoreLocation-15.5.json CoreLocation-26.5.json # Every declaration's lifeline across N ordered versions swift-section objc evolution CoreLocation-*.json --labels 15.5,26.0,26.5 --summary-only + +# The versions merged into one header, each declaration rendered as `objc dump` +# renders it and annotated with its lifecycle (binaries or caches only) +swift-section objc evolution \ + 15.5/dyld_shared_cache_arm64e \ + 26.5/dyld_shared_cache_arm64e \ + --dyld-shared-cache -n CoreLocation \ + --labels 15.5,26.5 \ + --interface --emit-available \ + -o CoreLocation-evolution.h ``` Both `diff` and `evolution` support `--json`, `--summary-only`, `--fail-on-breaking` (exit @@ -714,10 +734,81 @@ one written by a different format version is rejected with an error rather than mis-compared, so regenerate it with the current tool. Baselines written by `objc-section` 0.8.106 read unchanged. +`evolution --interface` merges every version into one header instead: a changed declaration carries a `// [○●●] added in 26.5`-style lifecycle comment, and `--emit-available` adds the `API_AVAILABLE` / `API_OBSOLETED` macro where one expresses the lifecycle (the platform is inferred from `LC_BUILD_VERSION`, or named with `--platform macos`). Its inputs must be binaries or caches, since a snapshot carries no rendered declarations. + The contracts that neither the signatures nor `--help` show — how file mode truncates the superclass chain, why pure-Swift classes' ivar records do not line up, and the rest — are in [Objective-C Command Line](Documentations/ObjCCommandLine.md). +#### refs - Find Cross References + +Who sends a selector, calls a function, or references a class, an instance variable or a string — across every image of a dyld shared cache (an archived one, another device's, or the running system's, read from its files) or across a set of Mach-O files read together, such as an app's executable and its frameworks. No disassembler and no process: the code is read from the files, through image stubs, the stub islands between a cache's images, and the selector and GOT stubs macOS 27 shares across a cache. Only the images that can reference the subject are scanned — the ones whose selector references, imports or linkage allow it. + +```bash +# Every send of a selector across a whole cache +swift-section refs --selector makeKeyAndOrderFront: \ + --dyld-shared-cache /path/to/dyld_shared_cache_arm64e + +# The running system's cache, only in the images named (by path or file name) +swift-section refs --class NSWindow --uses-system-dyld-shared-cache --in-image AppKit + +# The callers of a symbol: a C function, a Swift mangled name, +# _OBJC_CLASS_$_ or _OBJC_IVAR_$_. +swift-section refs --symbol _objc_autoreleasePoolPush --uses-system-dyld-shared-cache + +# What one function references, in instruction order +swift-section refs --function 0x18a403858 --callees --uses-system-dyld-shared-cache + +# An app's files; a fat file needs --architecture, as everywhere +swift-section refs --string NSWindowDidBecomeKeyNotification \ + Foo.app/Contents/MacOS/Foo Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e +``` + +Each line is one reference: the referencing instruction, its image, its function and the offset into it, the kind (`call`, `tailCall`, `reference`), the route the code took to the target (`direct`, `imageStub`, `stubIsland`, `cacheSharedStub`, `pointerSlot`, `addressMaterialization`, `literalLoad`, `indirect`), and the target. A summary line goes to stderr. + +``` +0x18a403a08 AppKit -[NSApplication _sendFinishLaunchingNotification]+0x1b0 call cacheSharedStub send makeKeyAndOrderFront: +0x18a521430 AppKit -[NSApplication _handleAppKitDefinedEvent:]+0x264 tailCall cacheSharedStub send makeKeyAndOrderFront: +0x18a6ca864 AppKit -[NSApplication reportException:]+0x38c reference addressMaterialization CFString @"NSApplicationCrashOnExceptions" +``` + +Addresses in and out are unslid — the ones IDA, `ipsw` and `dyld_info` show. A function no symbol names is named from the export trie, the Objective-C method lists or the Swift metadata. `--limit ` keeps the first references in image and address order; `--json` prints one document whose addresses are all hexadecimal strings and whose `isTruncated` says whether `--limit` cut it short: + +```json +{ + "input" : { "imageCount" : 4115, "systemDyldSharedCache" : "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e" }, + "isTruncated" : true, + "query" : { "selector" : "makeKeyAndOrderFront:" }, + "references" : [ + { + "function" : { "address" : "0x18a403858", "name" : "-[NSApplication _sendFinishLaunchingNotification]" }, + "image" : "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit", + "isRuntimeHelperCall" : false, + "kind" : "call", + "route" : "cacheSharedStub", + "site" : "0x18a403a08", + "target" : { "messageSend" : { "receiver" : "unknown", "selector" : "makeKeyAndOrderFront:" } } + } + ], + "scannedImageCount" : 1 +} +``` + +On a 28-core Mac a whole macOS 27.2 cache answers `--selector makeKeyAndOrderFront:` in about a second and `--selector init` (334,624 sends in 2,853 images) in about two. + +#### symbolicate - Say What an Address Is + +```bash +swift-section symbolicate 0x18a403a08 0x10 --uses-system-dyld-shared-cache +``` + +``` +0x18a403a08 AppKit __TEXT,__text -[NSApplication _sendFinishLaunchingNotification]+0x1b0 +0x10 - - unmapped +``` + +Each address is read as a function and the offset into it, a stub or a chain of stub islands and where it leads, a pointer slot (GOT, selector, class, superclass or protocol reference, an instance variable's offset) and what it holds, a C string or `CFString`, or the nearest symbol. Files take `--file `, repeatable; each file keeps its own addresses, so `--in-image` names the one they belong to. `--json` prints `{"symbolications": [ … ]}`. + ## Agent Plugin The `swift-section` plugin teaches coding agents to drive the CLI: which subcommand answers diff --git a/Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md b/Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md new file mode 100644 index 000000000..cf03d5ef3 --- /dev/null +++ b/Roadmaps/2026-10-27-cross-reference-analysis-second-review-findings.md @@ -0,0 +1,77 @@ +# 交叉引用分析第二轮审查记录(0.24.0,2026-10-27) + +审查对象:`0.23.0..0.24.0` 的 61 个提交,重点是 0.24.0 新加的 `CrossReferenceAnalysis`(提案 [0072-cross-reference-analysis](../Documentations/Evolutions/0072-cross-reference-analysis.md))。`main` 与 `next` 在审查时完全相同,0.24.0 已发版。上一轮审查见 [2026-10-17 审查记录](2026-10-17-cross-reference-analysis-review-findings.md)。 + +**方式**:一个审查代理通读,交回 12 条候选(下文编号沿用它的顺序);每条都由本人回到代码与本机的 dyld 缓存复核,四问逐条回答,能造出复现的造复现。核对第 9 条时另发现一条更严重的问题,编为 N1。指令形态的计数用 `dyld_info -disassemble` 直接反汇编运行中的缓存,环境是 macOS 26.6 的 10 核 Mac Studio。 + +**四问的共同答案**:本模块在 0.24.0 新写,0.23.0 没有;GitHub 上没有相关 PR 或 issue;[ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md) 已覆盖第 6 条(A66)与第 8 条(A71),理由仍成立,直接跳过。所以其余每条都是「0.24.0 引入、以前没修过」,例外写在各条的「既往」里。 + +**状态**:用户 2026-10-27 批准修建议修的五条(N1、1、2、11、12)。每条修复都先写了修复前失败的测试:前四条的 9 个测试在原始代码上一起跑过一次,全部按预期失败,两个只核对扫描逻辑本身的测试通过;第 2 条的两组测试(16 个用例)在前四条修好、它自己还没修的代码上跑过,全部按预期失败。修复后全部通过,全量 `swift test --skip IntegrationTests` 在 JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 26.6)上 2588 个测试全部通过。判为不修或误报的五条登记在 ReviewAdjudications A76–A80;横向排查到、交给用户定的两条(MachOKit 的桩解码缺口、单字母泛型参数),用户定暂不处理,登记在 A81、A82。第 2 条要改变查询结果,按提案制先写了精简提案 [0076-objc-runtime-send-entry-points](../Documentations/Evolutions/0076-objc-runtime-send-entry-points.md),用户点头后实现。 + +## 总表 + +| # | 问题 | 严重度 | 处理 | 测试 | +|---|---|---|---|---| +| N1 | 写死的 47 位地址掩码在 iOS 系真机上留下签名位 | 高 | 已修;第 9 条(同一掩码重复六处)并入 | `AddressMaskScanTests` | +| 1 | ld64 改写出的字面量 `ldr` 与 `adr` 不解码 | 中 | 已修;横向排查又修了两处:改写过的桩、SwiftThunkAnalysis 的解码器;MachOKit 的同一缺口暂不报上游(A81) | `LinkerOptimizationHintTests`(4 个)、`linkerRewrittenSlotStub`、`aLiteralLoadNamesItsSlot` | +| 2 | `objc_alloc_init` 一类 libobjc 入口不算消息发送 | 高 | 按精简提案修 | `RuntimeSendEntryPointTests`(16 个用例)、`selectorPrefilterKeepsEverySender` 加 `isKindOfClass:` | +| 3 | 目标算得出来的寄存器调用仍记成 `.indirect` | 低 | 不修(A76) | — | +| 4 | 懒绑定的槽位指向 `__stub_helper` | — | 误报(A80) | `LazyBindingTests`,26.6 上也通过 | +| 5 | 没有符号的类型算 key 时,demangle 结果留在按镜像的缓存里 | — | 不修,有意设计(A78);文档改准 | — | +| 6 | 夹在代码里的数据线性查找 | — | 已裁决(A66),跳过 | — | +| 7 | 映射区间线性查找 | 低 | 不修(A79) | — | +| 8 | 协议打印时多读关联类型名 | — | 已裁决(A71),跳过 | — | +| 9 | 47 位掩码重复六处 | — | 并入 N1 | — | +| 10 | `swiftTypeIdentity` 每次线性走一遍镜像的类 | 低 | 暂不修(A77) | — | +| 11 | 查导入类型时先按 +8 读名字、后判断是不是类型描述符 | 中 | 已修 | `importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs` | +| 12 | 缩写的名字 `pc`、`lhs` / `rhs` | 低 | 已改,全仓库的 `lhs` / `rhs` 一并改;单字母泛型参数暂不改(A82) | `AbbreviatedIdentifierScanTests` | + +## N1 — 47 位地址掩码在 iOS 系真机上算错地址 + +- **问题**:模块从进程内存读指针时,用写死的 `0x0000_7FFF_FFFF_FFFF` 去掉指针认证位:`SwiftTypeIndex.addressMask`、`ObjectiveCClassIndex.addressMask` 两个常量,加上预筛、函数表、扫描器与补充名字里的四处字面量。这是 Mac 的用户地址宽度。XNU 在没有启用大内存配置的设备上把用户地址设为 39 位(`apple_arm64_common.h` 定义 `__ARM64_PMAP_SUBPAGE_L1__`,`proc_reg.h` 据此取 `T0SZ_BOOT = 25`),arm64e 的签名从第 39 位开始,47 位掩码会留下第 39–46 位。受影响的读取:GOT 槽里的函数指针(跨库调用落成 `.unrecognized`,且不退回导入名)、Swift 类元数据 +0x40 与值类型元数据 +8 处的描述符、类列表、`isa`、selector 引用。RuntimeViewer 的 `RuntimeViewerServer` 面向 iphoneos / appletvos / watchos / xros 编译,并无条件装上交叉引用。 +- **复现**:真机上没有复现,那需要真机和用户授权;模拟器用 macOS 的地址空间,复现不了。机制从 XNU 源码核实。`AddressMaskScanTests` 扫遍库的源码,找 33 到 62 位宽的地址掩码常量:修复前报出这六处,修复后为零;`theScanDiscriminates` 核对它认得出掩码、不把 32 位掩码与 `Int64.max` 当成掩码。 +- **修法**:`InProcessContext` 本来就按平台取 MachOKitExtensions 的 `vmaddrMask`(Mac 与 Mac Catalyst 47 位,其余 arm64 平台 36 位),改为 `package` 可见;交叉引用新加 `StoredPointer.address(in:)` 统一用它,六处都换掉,两个常量删掉。测试里的同类一处也一并换掉。 +- **横向排查**:整个 `Sources` 里只有这六处;其余读取都经 `stripPointerTags`,与 `InProcessContext` 同源。`vmaddrMask` 对 iOS 模拟器给 36 位,模拟器进程用的是 Mac 的地址空间,但交叉引用读到的都是镜像里的地址,远低于 64 GiB,不受影响。 +- **既往**:`InProcessContext` 早就用按平台的掩码,这个模块新写时没有沿用;开发与测试都只在 macOS 上,所以一直没暴露。 + +## 1 — ld64 改写出的字面量 `ldr` 与 `adr` + +- **问题**:ld64(Xcode 14 及更早,或 Xcode 15、16 加 `-ld_classic`)排好地址后按 linker optimization hint 改写指令:槽位在一兆字节以内的 `adrp` / `ldr` 变成 `nop` / `ldr xN, <槽>`,地址在一兆字节以内的 `adrp` / `add` 变成 `adr xN, <地址>` / `nop`。`ARM64InstructionWord.load(_:)` 不认字面量 `ldr`,载入的 `x1` 成了未知,这次发送被记成对 `objc_msgSend` 的普通调用;类引用只在 `add` 那一步报,`adr` 不报。 +- **当初为什么这样做**:提案 0072 与模块文档写着「`adr` 与字面量 `ldr` 两种形态在缓存与几个缓存外的系统 App 里都没有,不解码」。那次只量了 Apple 自己的二进制:Xcode 26 的链接器不做这种改写,本机验证过(同一份源码,默认链接器保留 `adrp` / `ldr`,`-ld_classic` 改写成 `nop` / `ldr`),Apple 的二进制里一处都没有。第三方 App 里却常见:抽查 12 个,2 个有,其中 Asset Catalog Viewer(macOS 12 SDK)有 357 处 selector 引用和 71 处类引用以字面量 `ldr` 载入。 +- **横向排查**(同一类:ld64 改写出的形态没人读): + 1. **改写过的桩**。Asset Catalog Viewer 的 212 个桩全是 `nop` / `ldr x16, <槽>` / `br x16`。MachOKit(0.54.101)的 `StubDecoder` 不认这种形态,给 `.unknown`,函数表于是没有槽位,经桩的调用只剩导入名:这个 App 里经桩调用 `objc_msgSend` 的发送一处也认不出来,光修函数体里的字面量 `ldr` 也没用。修法:`ImageFunctionTable` 在 MachOKit 给不出槽位时用 `ARM64Trampoline` 读桩自己的字节,`ARM64Trampoline` 认字面量 `ldr`。SwiftThunkAnalysis 也经 `ARM64Trampoline` 认桩,一并受益。MachOKit 的 `StubDecoder` 出自上游作者,同样的缺口在上游也有;用户定暂不报上游、也不在 fork 里修(A81)。 + 2. **SwiftThunkAnalysis 的 Capstone 解码器**把字面量 `ldr` 当成不建模的指令,载入的值丢失。新增 `ThunkOperation.loadFromSlot`,求值时按槽位读,与 `adrp` / `ldr` 共用一段代码;32 位的 `ldr wN,

( for genericContext: TargetGenericContext
, ownedBy descriptor: ContextDescriptorWrapper, @@ -169,3 +175,206 @@ extension GenericParameterDepthLayout { return argumentLists.map(\.count) } } + +// MARK: - Reading an opaque type descriptor + +extension GenericParameterDepthLayout { + /// The depth layout of an opaque type descriptor's generic context: the + /// depths of the declaration the opaque result belongs to, then one for + /// the opaque parameters themselves. `nil` when the depths cannot be told. + /// + /// An opaque type's parent chain holds what a type's does not: anonymous + /// contexts that add parameters. A generic function's or subscript's adds + /// the declaration's own, one depth, and sits in the type or extension + /// the declaration belongs to. A property's — the parent IRGen gives the + /// opaque type under `-enable-anonymous-context-mangled-names`, which the + /// driver adds to every `-g` build that is not optimized, every Debug + /// build (`OpaqueTypeDescriptorBuilder::getParent`) — carries the generic + /// signature of the property's type or extension, yet sits in that type's + /// PARENT (`AnonymousContextDescriptorBuilder::getParent` asks for the + /// parent of the property's declaration context), so the type itself is + /// nowhere on the chain. Passing anonymous contexts over, as + /// `make(for:ownedBy:in:)` does for a type, read + /// `KeychainStorage.publisher` as declared at the top level and its + /// opaque parameter `τ_1_0` as one at depth 0. So every ancestor that adds + /// parameters opens a depth here, an anonymous one included, as the + /// runtime counts them for an opaque type (`_gatherGenericParameterCounts`), + /// and an extension opens one per level of its extended type that + /// declares parameters, as everywhere in this type. + /// + /// A property declared in an extension is the one context that adds + /// several depths at once: an extension sits in the module, so the + /// property's context adds every parameter of the extended type — + /// `extension Outer.Inner { var values: some Sequence }` adds `Outer`'s + /// `A` and `Inner`'s `B` together. Its mangled name, which every such + /// context carries, names the extended type, and that type's descriptor, + /// found by its `…Mn` symbol, splits them. Without the descriptor — a + /// stripped image's internal type, or, read from a file, a type another + /// image declares — the answer is `nil`: one depth too few would read one + /// of the type's parameters as the opaque one. + package static func make
( + forOpaqueType descriptor: OpaqueTypeDescriptor, + genericContext: TargetGenericContext
, + in context: some ReadingContext + ) -> GenericParameterDepthLayout? { + guard let ancestors = ancestorsInnermostFirst(of: descriptor, in: context) else { return nil } + var parameterCountsByDepth: [Int] = [] + var cumulativeCount = 0 + for (position, ancestor) in ancestors.enumerated().reversed() { + guard ancestor.contextDescriptor.layout.flags.isGeneric else { continue } + guard let ancestorGenericContext = try? ancestor.genericContext(in: context) else { return nil } + let ancestorCount = ancestorGenericContext.parameters.count + guard ancestorCount > cumulativeCount else { continue } + let addedCount = ancestorCount - cumulativeCount + switch ancestor { + case .extension(let extensionDescriptor): + if let extendedLevelCounts = extendedTypeParameterCountsByLevel(of: extensionDescriptor, in: context), + extendedLevelCounts.reduce(0, +) == addedCount { + parameterCountsByDepth.append(contentsOf: extendedLevelCounts) + } else { + parameterCountsByDepth.append(addedCount) + } + case .anonymous(let anonymousDescriptor): + let sitsInModule = ancestors.indices.contains(position + 1) && ancestors[position + 1].isModule + guard let levelCounts = parameterCountsByLevel(addedBy: anonymousDescriptor, addedCount: addedCount, sitsInModule: sitsInModule, in: context) else { + return nil + } + parameterCountsByDepth.append(contentsOf: levelCounts) + default: + parameterCountsByDepth.append(addedCount) + } + cumulativeCount = ancestorCount + } + let opaqueParameterCount = genericContext.parameters.count - cumulativeCount + guard opaqueParameterCount > 0 else { return nil } + parameterCountsByDepth.append(opaqueParameterCount) + return GenericParameterDepthLayout(parameterCountsByDepth: parameterCountsByDepth) + } + + /// Every context above `descriptor`, innermost first, up to its module; + /// `nil` when one cannot be read, a parent bound by name to another image + /// included. + private static func ancestorsInnermostFirst(of descriptor: OpaqueTypeDescriptor, in context: some ReadingContext) -> [ContextDescriptorWrapper]? { + var ancestors: [ContextDescriptorWrapper] = [] + do { + var parentReference = try descriptor.parent(in: context) + while let currentReference = parentReference { + guard let parent = currentReference.resolved else { return nil } + ancestors.append(parent) + parentReference = try parent.parent(in: context) + } + } catch { + return nil + } + return ancestors + } + + /// The depths the `addedCount` parameters an anonymous context adds span, + /// outermost first: one, unless the context is a property's sitting in the + /// module and the property's type is nested in another — a property of + /// an extension of a nested type, whose type's levels split them. A type + /// at the top level of its module opens one depth however its property is + /// declared, and a property in a type's own body sits in that type's + /// parent, below whatever depths the levels above opened. + private static func parameterCountsByLevel(addedBy anonymousDescriptor: AnonymousContextDescriptor, addedCount: Int, sitsInModule: Bool, in context: some ReadingContext) -> [Int]? { + // A property's context exists only under the option that writes its + // mangled name into it, so a context without one is a function's. + guard sitsInModule, + let mangledName = try? anonymousDescriptor.mangledName(in: context), + mangledName.lookupElements.isEmpty, + let nameNode = try? demangleAsNodeTransient(mangledName.symbolString), + let declarationContextNode = propertyNode(named: nameNode)?.children.first + else { return [addedCount] } + var typeNode = declarationContextNode.kind == .extension ? declarationContextNode.children.at(1) : declarationContextNode + if let wrappedTypeNode = typeNode, wrappedTypeNode.kind == .type { + typeNode = wrappedTypeNode.children.first + } + guard let typeNode, let typeContextNode = typeNode.children.first else { return nil } + // A protocol is one depth, its `Self`, wherever it is declared. + guard typeContextNode.kind != .module, typeNode.kind != .protocol else { return [addedCount] } + guard let typeLayout = depthLayout(ofTypeNamed: typeNode, inImageOfDescriptorAt: anonymousDescriptor.offset, in: context), + typeLayout.parameterCount == addedCount + else { return nil } + return typeLayout.parameterCountsByDepth + } + + /// The `variable` an anonymous context's name stands for, a `static` one + /// unwrapped; `nil` for a function's, a subscript's or a closure's. + private static func propertyNode(named nameNode: Node) -> Node? { + var node = nameNode + if node.kind == .global, let entityNode = node.children.first { + node = entityNode + } + if node.kind == .static, let memberNode = node.children.first { + node = memberNode + } + return node.kind == .variable ? node : nil + } + + /// The depth layout of the nominal type `typeNode` names, read from its + /// descriptor, which its `…Mn` symbol locates: in the image holding the + /// descriptor at `descriptorOffset`, where a stripped image keeps the + /// symbol of an exported type alone, and else, for an image loaded in this + /// process, through the loader — a type another module declares is + /// public, so its descriptor is exported. + private static func depthLayout(ofTypeNamed typeNode: Node, inImageOfDescriptorAt descriptorOffset: Int, in context: some ReadingContext) -> GenericParameterDepthLayout? { + let descriptorSymbolNode = Node.createTransient(kind: .global, children: [Node.createTransient(kind: .nominalTypeDescriptor, children: [typeNode])]) + // The remangled name carries the symbol table's leading underscore. + guard let lookupContext = context as? any DescriptorSymbolLookupContext, + let descriptorSymbolName = try? mangleAsString(descriptorSymbolNode) + else { return nil } + if let typeDescriptorOffset = lookupContext.offset(ofSymbolNamed: descriptorSymbolName, inImageOfDescriptorAt: descriptorOffset) { + return depthLayout(ofTypeDescriptorAt: typeDescriptorOffset, in: context) + } + // The loader takes the name without the underscore. + guard lookupContext.readsImageLoadedInProcess, descriptorSymbolName.hasPrefix("_"), + let typeDescriptorAddress = dlsym(UnsafeMutableRawPointer(bitPattern: -2) /* RTLD_DEFAULT */, String(descriptorSymbolName.dropFirst())) + else { return nil } + return depthLayout(ofTypeDescriptorAt: Int(bitPattern: typeDescriptorAddress), in: InProcessContext.shared) + } + + private static func depthLayout(ofTypeDescriptorAt offset: Int, in context: some ReadingContext) -> GenericParameterDepthLayout? { + guard let address = try? context.addressFromOffset(offset), + let typeDescriptor = try? ContextDescriptorWrapper.resolve(at: address, in: context) as ContextDescriptorWrapper, + typeDescriptor.isType + else { return nil } + return try? make(for: typeDescriptor, in: context) + } +} + +/// A reading context that finds a symbol by name in the image a descriptor +/// it reads belongs to — what `GenericParameterDepthLayout` reaches an +/// extended type's descriptor by. +private protocol DescriptorSymbolLookupContext { + func offset(ofSymbolNamed name: String, inImageOfDescriptorAt descriptorOffset: Int) -> Int? + + /// Whether the image read is loaded in this process, so that another + /// image's exported symbol is one `dlsym` away. + var readsImageLoadedInProcess: Bool { get } +} + +extension MachOContext: DescriptorSymbolLookupContext { + fileprivate func offset(ofSymbolNamed name: String, inImageOfDescriptorAt descriptorOffset: Int) -> Int? { + SwiftSymbolIndexStore.shared.offset(ofSymbolNamed: name, in: machO) + } + + fileprivate var readsImageLoadedInProcess: Bool { + machO.asMachOImage != nil + } +} + +extension InProcessContext: DescriptorSymbolLookupContext { + /// An in-process offset is an address, and the symbol index is kept per + /// image, keyed from the image's header. + fileprivate func offset(ofSymbolNamed name: String, inImageOfDescriptorAt descriptorOffset: Int) -> Int? { + guard let descriptorPointer = UnsafeRawPointer(bitPattern: descriptorOffset), + let machOImage = MachOImage.image(for: descriptorPointer), + let imageOffset = SwiftSymbolIndexStore.shared.offset(ofSymbolNamed: name, in: machOImage) + else { return nil } + return Int(bitPattern: machOImage.ptr) + imageOffset + } + + fileprivate var readsImageLoadedInProcess: Bool { + true + } +} diff --git a/Sources/Analysis/SwiftInspection/InitAccessorFieldInference.swift b/Sources/Analysis/SwiftInspection/InitAccessorFieldInference.swift new file mode 100644 index 000000000..3925865b5 --- /dev/null +++ b/Sources/Analysis/SwiftInspection/InitAccessorFieldInference.swift @@ -0,0 +1,74 @@ +@_spi(Internals) import Demangling + +/// What a SE-0400 init accessor initializes, as far as an image tells +/// (evolution proposal `init-accessor-recovery`). +/// +/// The source lists them in `@storageRestrictions(initializes:accesses:)`, +/// and no image records the attribute: the compiler lowers each +/// `initializes:` entry to an indirect result and each `accesses:` entry to +/// an `inout` parameter, pointers straight at the storage, so the init +/// accessor's code does not say which fields they are either. What is left is +/// the naming convention the `@Observable` macro, property wrappers and +/// hand-written storage share: a stored property `_x` with the type of the +/// property `x` is the storage `x`'s init accessor initializes. The type must +/// match — SwiftData's `@Model` keeps a placeholder of another type in `_x`, +/// and its init accessor initializes the value elsewhere. +/// +/// Shared by the declaration model and the dump, which reads no model. +package enum InitAccessorFieldInference { + /// A stored property of the type that declares the init accessor. + package struct StoredField { + package let name: String + + /// The field record's type, `weak` / `unowned` storage included. + package let typeNode: Node + + package init(name: String, typeNode: Node) { + self.name = name + self.typeNode = typeNode + } + } + + /// The fields the init accessor `symbolNode` names is inferred to + /// initialize, by the property name and type its own symbol spells. That + /// type need not be the getter's: SwiftUICore keeps + /// `_GeometryActionModifier2.value`'s getter and setter under the mangling + /// from before the type became `@Sendable` (`@_silgen_name`), and only + /// the init accessor spells the type its field `_value` has. Like every + /// declaration's own mangling it leaves `sending` out, which the + /// comparison sets aside. `nil` when `symbolNode` is no init accessor of + /// a variable. + package static func initializedFieldNames( + ofInitAccessorSymbol symbolNode: NodeReference, + fieldNamed: (String) -> StoredField? + ) -> [String]? { + guard let initAccessorNode = symbolNode.children.first(where: { $0.kind == .initAccessor }), + let variableNode = initAccessorNode.children.first, variableNode.kind == .variable, + let propertyName = variableNode.identifier, + let declaredTypeNode = variableNode.children.first(where: { $0.kind == .type })?.materialize() + else { return nil } + return initializedFieldNames(ofPropertyNamed: propertyName, declaredTypeNode: declaredTypeNode, fieldNamed: fieldNamed) + } + + /// The fields the init accessor of the property `propertyName`, of + /// `declaredTypeNode`, is inferred to initialize: `["_"]` + /// when the type has that field with the property's type — compared the + /// way `StoredTypeMatching` compares a declaration with its storage, + /// `weak` / `unowned` and `sending` set aside — `nil` when nothing + /// tells. Never lists `accesses:`. + /// + /// - Parameter fieldNamed: the type's stored field of a given name, asked + /// for `_` only — a caller holding field records + /// materializes one type node, not every field's. + package static func initializedFieldNames( + ofPropertyNamed propertyName: String, + declaredTypeNode: Node, + fieldNamed: (String) -> StoredField? + ) -> [String]? { + let backingFieldName = "_" + propertyName + guard let backingField = fieldNamed(backingFieldName), + StoredTypeMatching.declaredType(declaredTypeNode, matchesStoredType: StoredTypeMatching.referencedTypeNode(ofStoredType: backingField.typeNode)) + else { return nil } + return [backingFieldName] + } +} diff --git a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift index 3725e9e7d..ceb5b511e 100644 --- a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift +++ b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift @@ -128,15 +128,28 @@ package enum NodeTypeNaming { /// Transient demangle: only the qualified-name string survives this /// call, so the tree must not be interned into the global `NodeCache`. package static func swiftClassQualifiedName(fromRuntimeName runtimeName: String) -> String? { - guard runtimeName.hasPrefix("_Tt") || runtimeName.hasPrefix("$s") else { return nil } - // The demangler wraps the result in `.global`; the qualified-name - // builder wants the bare nominal class node (the same shape + swiftClassNode(fromRuntimeName: runtimeName).flatMap(nominalQualifiedName(of:)) + } + + /// The bare `Class` node a Swift class's ObjC-side name spells: its + /// runtime name (`_TtC7SwiftUI3Foo`, or the `$s…` spelling a nested or + /// generic context gets), or — what a file's category on another + /// image's Swift class is bound to — its class metadata symbol + /// (`_$s7SwiftUI3FooCN`). `nil` for a plain ObjC class name, without + /// invoking the demangler. The tree is transient. + package static func swiftClassNode(fromRuntimeName runtimeName: String) -> Node? { + let mangledName: Substring + if runtimeName.hasPrefix("_Tt") || runtimeName.hasPrefix("$s") { + mangledName = Substring(runtimeName) + } else if runtimeName.hasPrefix("_$s") { + mangledName = runtimeName.dropFirst() + } else { + return nil + } + // The demangler wraps the result in `.global`; the callers want the + // bare nominal class node (the same shape // `SymbolicDemangler.demangleContext` produces on the descriptor side). - guard - let node = try? demangleAsNodeTransient(runtimeName), - let classNode = node.first(of: .class) - else { return nil } - return nominalQualifiedName(of: classNode) + return (try? demangleAsNodeTransient(String(mangledName)))?.first(of: .class) } private static func qualifiedName(ofNominal node: Node) -> String? { diff --git a/Sources/Analysis/SwiftInspection/ObservableMacroRecognition.swift b/Sources/Analysis/SwiftInspection/ObservableMacroRecognition.swift new file mode 100644 index 000000000..e1f62572f --- /dev/null +++ b/Sources/Analysis/SwiftInspection/ObservableMacroRecognition.swift @@ -0,0 +1,123 @@ +@_spi(Internals) import Demangling +import MachOSwiftSection + +/// Recognizes a class the Observation module's `@Observable` macro expanded, +/// from what the expansion left in the binary (evolution proposal +/// `observable-macro-folding`). +/// +/// The compiler keeps no record of an attached macro, only of what the macro +/// generated. Every class `@Observable` expands stores an +/// `Observation.ObservationRegistrar` in a property named +/// `_$observationRegistrar`, and that property's field record survives a +/// stripped symbol table, so the class is recognized from its field records +/// alone — in an OS framework or a shipped app as much as in a debug build. +/// +/// Two look-alikes are told apart: +/// - SwiftData's `@Model` generates a registrar of the same name and type +/// beside its `_$backingData` storage. A class with that field is a +/// persistent model, not an `@Observable` class. +/// - A class that conforms to `Observable` by hand has no registrar field. +/// +/// No conformance record is required: an `@Observable` class deriving from +/// another inherits the conformance, and the macro generates none again. +package enum ObservableMacroRecognition { + /// The stored property the macro adds to every class it expands. + package static let registrarFieldName = "_$observationRegistrar" + + /// The stored property SwiftData's `@Model` adds beside a registrar of + /// the same name and type. + package static let persistentModelBackingDataFieldName = "_$backingData" + + /// The module that declares the macro, its registrar type and its + /// protocol. + package static let observationModuleName = "Observation" + + /// The macro's name, which is also the name of the protocol its + /// generated extension conforms the class to. + package static let observableName = "Observable" + + /// The macro a stored property the macro leaves alone is declared with. + package static let observationIgnoredName = "ObservationIgnored" + + /// The macro `@Observable` attaches to each property it tracks, which + /// writes the property's accessors and its storage. + package static let observationTrackedName = "ObservationTracked" + + /// The type of `registrarFieldName`. + package static let registrarTypeName = "ObservationRegistrar" + + /// Whether the type `descriptor` describes is a class `@Observable` + /// expanded. Reads the field records' names, and the type of the one + /// named `_$observationRegistrar` only when there is one. + /// + /// A field descriptor that cannot be read answers `false`: the + /// definition's own indexing reads the same records and reports the + /// failure, so this does not report it a second time. + package static func isObservableClass(_ descriptor: TypeContextDescriptorWrapper, in context: some ReadingContext) -> Bool { + guard case .class = descriptor, + let records = try? descriptor.typeContextDescriptor.fieldDescriptor(in: context).records(in: context) + else { return false } + var registrarRecord: FieldRecord? + for record in records { + guard let fieldName = try? record.fieldName(in: context) else { continue } + if fieldName == persistentModelBackingDataFieldName { + return false + } + if fieldName == registrarFieldName { + registrarRecord = record + } + } + guard let registrarRecord, + let mangledTypeName = try? registrarRecord.mangledTypeName(in: context), + let registrarTypeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: context) + else { return false } + return isObservationRegistrarType(registrarTypeNode) + } + + /// Whether `typeNode` names `Observation.ObservationRegistrar`, with or + /// without the `type` node around it. + package static func isObservationRegistrarType(_ typeNode: Node) -> Bool { + isNominal(typeNode, kind: .structure, moduleName: observationModuleName, name: registrarTypeName) + } + + /// Whether `protocolNode` names `Observation.Observable`, the protocol + /// the macro's generated extension conforms the class to. + package static func isObservableProtocol(_ protocolNode: Node) -> Bool { + isNominal(protocolNode, kind: .protocol, moduleName: observationModuleName, name: observableName) + } + + /// `Observation.Observable` as a name node: the protocol the macro's + /// generated extension conforms to, whose name the macro shares — what the + /// interface and the dump print the macro's attribute from, so module + /// selectors reach it and the attribute links where the protocol does. + /// Static, so it outlives every print: the interface printer memoizes + /// fragments by node identity, and a node freed mid-print could hand its + /// address to another. + package static let observableAttributeNameNode = nominalTypeNode(.protocol, moduleName: observationModuleName, name: observableName) + + /// `Observation.ObservationIgnored` as a name node, for the attribute of a + /// stored property the macro left alone. A macro no type shares a name + /// with; static for the same reason. + package static let observationIgnoredAttributeNameNode = nominalTypeNode(.structure, moduleName: observationModuleName, name: observationIgnoredName) + + /// `Observation.ObservationTracked` as a name node, for the attribute + /// `@Observable` attaches to each property it tracks (evolution proposal + /// `observable-nested-expansion`). Static for the same reason. + package static let observationTrackedAttributeNameNode = nominalTypeNode(.structure, moduleName: observationModuleName, name: observationTrackedName) + + private static func nominalTypeNode(_ kind: Node.Kind, moduleName: String, name: String) -> Node { + Node.createTransient(kind: .type, child: Node.createTransient(kind: kind, children: [ + Node.createTransient(kind: .module, text: moduleName), + Node.createTransient(kind: .identifier, text: name), + ])) + } + + private static func isNominal(_ node: Node, kind: Node.Kind, moduleName: String, name: String) -> Bool { + let nominalNode = node.kind == .type ? node.firstChild : node + guard let nominalNode, nominalNode.kind == kind, nominalNode.children.count == 2, + let moduleNode = nominalNode.children.first, moduleNode.kind == .module, moduleNode.text == moduleName, + let identifierNode = nominalNode.children.last, identifierNode.kind == .identifier, identifierNode.text == name + else { return false } + return true + } +} diff --git a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift index 8e7a78ac8..0ebf5f25c 100644 --- a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift +++ b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift @@ -558,7 +558,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { return .failure(TypeLookupError("protocol has no requirement base descriptor")) } let accessFunctionRequirements = declaredProtocol.requirements.filter { - $0.flags.kind.isAssociatedTypeAccessFunction + $0.flags.kind?.isAssociatedTypeAccessFunction == true } guard associatedTypeIndex < accessFunctionRequirements.count else { return .failure(TypeLookupError("associated type index \(associatedTypeIndex) exceeds the requirement list")) diff --git a/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift b/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift index e7142c4fc..62d47baf3 100644 --- a/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift +++ b/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift @@ -5,22 +5,9 @@ /// cache that holds the reference. extension SharedCacheEvictionGroup { /// `SymbolicManglingIndex`: holds the symbol store's symbolic-mangling - /// table, so it follows `symbolStore`. + /// table, so it follows `swiftSymbolStore`. package static let symbolicMangling = SharedCacheEvictionGroup("symbolicMangling") - /// `ObjCImplementationClassIndex`: holds `NodeReference`s into the - /// symbol store's arena, so it follows `symbolStore`. - package static let objcImplementationClasses = SharedCacheEvictionGroup("objcImplementationClasses") - - /// `ObjCClassMethodIndex`, `SwiftClassObjectIndex` and the host's - /// `ObjCClassHierarchyProviderStore` registration: ObjC-side per-image - /// state of the symbol store's lifetime, so it follows `symbolStore`. - package static let objcHierarchy = SharedCacheEvictionGroup("objcHierarchy") - - /// `ObjCAncestorResolverStore`: holds the file's dependency images once - /// it has resolved them; same lifetime, follows `symbolStore`. - package static let objcAncestorResolver = SharedCacheEvictionGroup("objcAncestorResolver") - /// `SymbolicDemanglerCache` and `AnonymousContextNameIndex`: /// the memo's values are references into the interned arena, so the /// group follows `internedNames`. diff --git a/Sources/Analysis/SwiftInspection/StoredTypeMatching.swift b/Sources/Analysis/SwiftInspection/StoredTypeMatching.swift new file mode 100644 index 000000000..e632e2271 --- /dev/null +++ b/Sources/Analysis/SwiftInspection/StoredTypeMatching.swift @@ -0,0 +1,57 @@ +@_spi(Internals) import Demangling + +/// How a property's declared type, read off one of its symbols, compares +/// with the type a field record stores. Three recoveries compare the two: +/// rule 1 of the `@Observable` expansion recovery (evolution proposal +/// `observable-macro-folding`), the wrapped-property attribute spelling, and +/// the init accessor inference (`init-accessor-recovery`), which the dump +/// runs too, below the declaration model. +package enum StoredTypeMatching { + /// The type a stored property's accessors traffic in: its field type + /// without the `weak` / `unowned` / `unowned(unsafe)` storage around it, + /// with the `type` node around it — the shape a member variable's + /// declared type has. + package static func referencedTypeNode(ofStoredType storedTypeNode: Node) -> Node { + var node = storedTypeNode + while node.kind == .type, let referenceStorage = node.firstChild, + referenceStorage.kind == .weak || referenceStorage.kind == .unowned || referenceStorage.kind == .unmanaged, + let referencedTypeNode = referenceStorage.firstChild { + node = referencedTypeNode + } + return node + } + + /// Whether a member variable's declared type — read off one of its + /// symbols: the getter's, or the init accessor's — is the type a field + /// record stores, `sending` set aside. The mangler leaves `sending` out + /// of a declaration's own function type, on its result and its + /// parameters (`ASTMangler::appendDeclType`: adding it must not change a + /// symbol), while a field record's type keeps it: the accessors of + /// `var make: () -> sending T` read `() -> T`, its storage + /// `() -> sending T` (SwiftUI's `makeFileCoordinator`). A function type + /// nested deeper carries it on both sides. + package static func declaredType(_ declaredTypeNode: Node, matchesStoredType storedTypeNode: Node) -> Bool { + var pendingPairs: [(declared: Node, stored: Node)] = [(declaredTypeNode, storedTypeNode)] + while let pair = pendingPairs.popLast() { + let declared = withoutSendingParameterMarker(pair.declared) + let stored = withoutSendingParameterMarker(pair.stored) + if declared === stored { continue } + guard declared.kind == stored.kind, declared.contents == stored.contents else { return false } + let declaredChildren = declared.children.filter { $0.kind != .sendingResultFunctionType } + let storedChildren = stored.children.filter { $0.kind != .sendingResultFunctionType } + guard declaredChildren.count == storedChildren.count else { return false } + pendingPairs.append(contentsOf: zip(declaredChildren, storedChildren).map { (declared: $0, stored: $1) }) + } + return true + } + + /// A parameter's type with the `sending` the demangler wraps around it + /// (`type(sending(X))`) taken off, the shape it has without one. + private static func withoutSendingParameterMarker(_ node: Node) -> Node { + var node = node + while node.kind == .sending, let child = node.firstChild { + node = child + } + return node + } +} diff --git a/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift b/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift index a81c0c00f..6937acd72 100644 --- a/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift +++ b/Sources/Analysis/SwiftInspection/SuppressedAssociatedTypeInference.swift @@ -1,6 +1,6 @@ import MachOSwiftSection @_spi(Internals) import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// Which of a protocol's own associated types are declared `~Copyable` or /// `~Escapable` (SE-0503), inferred from the image's extensions of the @@ -29,7 +29,7 @@ import MachOSwiftSection /// 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) + private static let extensionMemberKinds: [SwiftSymbolIndexStore.MemberKind] = SwiftSymbolIndexStore.MemberKind.allCases.filter(\.isInExtension) /// The suppressed invertible protocols of `descriptor`'s own associated /// types, by associated type name; an associated type without evidence @@ -62,7 +62,7 @@ package enum SuppressedAssociatedTypeInference { 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) { + for memberSymbol in SwiftSymbolIndexStore.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. @@ -122,7 +122,7 @@ package enum SuppressedAssociatedTypeInference { } } -extension SymbolIndexStore.MemberKind { +extension SwiftSymbolIndexStore.MemberKind { fileprivate var isInExtension: Bool { switch self { case .allocator(let inExtension), diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index ab44634e4..456e88be1 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -5,7 +5,7 @@ import MachOFoundation import SwiftStdlibToolbox import MachOSwiftSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// Demangles with the symbolic references resolved against a Mach-O image. /// @@ -45,7 +45,7 @@ extension SymbolicDemangler { public static let isCacheEnabled: Bool = true public static func demangleSymbol(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - return SymbolIndexStore.shared.demangledNode(for: symbol, in: machO) + return SwiftSymbolIndexStore.shared.demangledNode(for: symbol, in: machO) } /// Store-backed variant of `demangleSymbol(for:in:)`: returns a @@ -53,7 +53,7 @@ extension SymbolicDemangler { /// mini store for symbols outside the build sweep) without materializing /// a `Node` tree. public static func demangleSymbolReference(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) -> NodeReference? { - return SymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO) + return SwiftSymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO) } /// Drops the per-image demangle memo so the next query rebuilds it. @@ -517,7 +517,10 @@ extension SymbolicDemangler { case .symbol: result = try demangleAsNodeTransient(stringValue, isType: false, symbolicReferenceResolver: symbolicReferenceResolver) } - return result + // A constrained existential reads as its shape plus the arguments that + // instantiate it; hand every consumer the existential type itself. + guard mangledName.refersToExtendedExistentialTypeShape else { return result } + return ExtendedExistentialTypeResolution.resolvingExtendedExistentialTypes(in: result) } private static func buildContextMangling(context: SymbolOrElement, in readingContext: some ReadingContext) throws -> Node? { @@ -1103,8 +1106,8 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { hasher.combine(wrappedValue.elements) } - static func == (lhs: Self, rhs: Self) -> Bool { - lhs.wrappedValue.elements == rhs.wrappedValue.elements + static func == (left: Self, right: Self) -> Bool { + left.wrappedValue.elements == right.wrappedValue.elements } init(_ wrappedValue: MangledName) { @@ -1252,77 +1255,3 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { } } } - -// MARK: - Deprecated Mach-O and pointer forms - -extension SymbolicDemangler { - @available(*, deprecated, message: "Pass a ReadingContext: demangleType(for:in: machO.context).") - public static func demangleType(for mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - try demangleType(for: mangledName, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleType(for:in: machO.context).") - public static func demangleType(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try demangleType(for: symbol, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleContext(for:in: machO.context).") - public static func demangleContext(for context: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - try demangleContext(for: context, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: machO.context).") - public static func buildGenericSignature(for requirement: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try buildGenericSignature(for: [requirement], in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: machO.context).") - public static func buildGenericSignature(for requirements: GenericRequirementDescriptor..., in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try buildGenericSignature(for: requirements, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: machO.context).") - public static func buildGenericSignature(for requirements: [GenericRequirementDescriptor], in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try buildGenericSignature(for: requirements, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: extendedTypeContextDescriptor(forExtendedContext:in: machO.context).") - public static func extendedTypeContextDescriptor(forExtendedContext mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextDescriptorWrapper? { - try extendedTypeContextDescriptor(forExtendedContext: mangledName, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleType(for:in: .inProcess).") - public static func demangleType(for mangledName: MangledName) throws -> Node { - try demangleType(for: mangledName, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleTypeUncached(for:in: .inProcess).") - public static func demangleTypeUncached(for mangledName: MangledName) throws -> Node { - try demangleTypeUncached(for: mangledName, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleType(for:in: .inProcess).") - public static func demangleType(for symbol: Symbol) throws -> Node? { - try demangleType(for: symbol, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: demangleContext(for:in: .inProcess).") - public static func demangleContext(for context: ContextDescriptorWrapper) throws -> Node { - try demangleContext(for: context, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: .inProcess).") - public static func buildGenericSignature(for requirement: GenericRequirementDescriptor) throws -> Node? { - try buildGenericSignature(for: [requirement], in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: .inProcess).") - public static func buildGenericSignature(for requirements: GenericRequirementDescriptor...) throws -> Node? { - try buildGenericSignature(for: requirements, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: buildGenericSignature(for:in: .inProcess).") - public static func buildGenericSignature(for requirements: [GenericRequirementDescriptor]) throws -> Node? { - try buildGenericSignature(for: requirements, in: InProcessContext.shared) - } -} diff --git a/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift b/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift index 16657b580..3a73e230c 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift @@ -5,7 +5,7 @@ import FoundationToolbox import MachOFoundation import MachOSwiftSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// One symbolic reference in a mangled name that a symbolic-mangling symbol /// names, paired with the referent that symbol spells for it. @@ -103,7 +103,7 @@ package struct SymbolicManglingReference: Hashable, Sendable { /// position of its symbol and the index of its referent, and the referent is /// demangled, transiently, when asked for. /// -/// Built once per image, lazily, from what `SymbolIndexStore` collected, and +/// Built once per image, lazily, from what `SwiftSymbolIndexStore` collected, and /// evicted with that store (`SwiftDeclarationIndexer`'s symbol-store claim): /// the storage holds the store's symbolic-mangling table. This module sits /// below the event layer, so symbols that do not pair are reported through @@ -112,7 +112,7 @@ package struct SymbolicManglingReference: Hashable, Sendable { package final class SymbolicManglingIndex: @unchecked Sendable { package static let shared = SymbolicManglingIndex() - private let cache = SharedCache(evictionGroup: .symbolicMangling, follows: [.symbolStore]) + private let cache = SharedCache(evictionGroup: .symbolicMangling, follows: [.swiftSymbolStore]) private init() {} @@ -265,7 +265,7 @@ package final class SymbolicManglingIndex: @unchecked Sendable { // MARK: - Build private static func build(in machO: some MachOSwiftSectionRepresentableWithCache) -> Storage? { - guard let symbols = SymbolIndexStore.shared.symbolicManglingSymbols(in: machO) else { return nil } + guard let symbols = SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machO) else { return nil } var references: [SymbolicManglingReference] = [] var unpairedSymbolCount = 0 for symbolPosition in symbols.indices { diff --git a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift index 88f4a9aee..7b933dad0 100644 --- a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift +++ b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift @@ -42,6 +42,14 @@ import Demangling public struct BuiltinTypeLayoutIndex: Sendable { private let layoutsByTypeName: [String: StaticTypeLayout] + /// No layouts: the index of an image whose builtin descriptors could not + /// be read. + static let empty = BuiltinTypeLayoutIndex(layoutsByTypeName: [:]) + + private init(layoutsByTypeName: [String: StaticTypeLayout]) { + self.layoutsByTypeName = layoutsByTypeName + } + public init(machO: some MachOSwiftSectionRepresentableWithCache) throws { var index: [String: StaticTypeLayout] = [:] // A missing `__swift5_builtin` section is a normal state — most images diff --git a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift index 496bf8340..908cb80f2 100644 --- a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift +++ b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift @@ -178,13 +178,17 @@ enum ClassBoundGenericParameterAnalysis { let protocolNode = symbolNode.kind == .protocol ? symbolNode : symbolNode.first(of: .protocol), let qualifiedProtocolName = NodeTypeNaming.protocolQualifiedName(of: protocolNode) else { return false } - if imageUniverse.resolveProtocolClassConstraint(byQualifiedTypeName: qualifiedProtocolName) == .class { + switch imageUniverse.resolveProtocol(byQualifiedTypeName: qualifiedProtocolName) { + case .swift(let classConstraint): + return classConstraint == .class + case .objC: + // A Swift-declared `@objc` protocol emits no Swift protocol + // descriptor; its `__objc_protolist` record is the recognition + // signal, and such a protocol is always class-bound. return true + case nil: + return false } - // A Swift-declared `@objc` protocol emits no Swift protocol - // descriptor; its `__objc_protolist` record is the recognition - // signal, and such a protocol is always class-bound. - return imageUniverse.isObjCProtocolDeclared(byQualifiedTypeName: qualifiedProtocolName) } } } diff --git a/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift index 9b9d3dbeb..4e4de29d9 100644 --- a/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift +++ b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift @@ -45,12 +45,11 @@ extension StaticTypeLayoutResolver { throw LayoutResolutionError.unknown(.demangleFailure) } - let key = ImageReference.associatedTypeWitnessKey( + guard let witness = imageUniverse.resolveAssociatedTypeWitness( conformingName: conformingName, protocolName: protocolName, associatedTypeName: associatedTypeName - ) - guard let witness = imageUniverse.resolveAssociatedTypeWitness(forKey: key) else { + ) else { throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: "\(conformingName).\(associatedTypeName)")) } diff --git a/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift b/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift index ab8e29ca4..bc47d44f6 100644 --- a/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift +++ b/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift @@ -38,50 +38,27 @@ extension StaticTypeLayoutResolver { return Self.existentialContainer(wordCount: 4 + composition.witnessTableCount) } - /// The layout of a constrained ("extended") existential — `any P` or a - /// same-type-constrained `any Sequence` — encoded via an - /// `extendedExistentialTypeShape` symbolic reference (SE-0353). The - /// generalization arguments and requirement constraints do **not** change the - /// container's size: `any P` has the same representation as `any P` - /// (opaque buffer + metadata + one witness table per protocol). So the shape's - /// inner existential (a plain `protocolList` / `…WithClass` / `…WithAnyObject`) - /// is extracted and routed through the ordinary existential layout, which - /// already handles the class-bound vs opaque distinction. + /// The layout of a constrained ("extended") existential still in its + /// symbolic form — a shape reference plus generalization arguments + /// (SE-0353). `SymbolicDemangler` hands a field's over as the + /// `constrainedExistential` it stands for (evolution proposal + /// `existential-any`), which ``existentialLayout(forNode:in:)`` lays out; + /// this path serves a tree that did not come through it. The arguments and + /// requirements do **not** change the container's size: `any P` has the + /// same representation as `any P` (opaque buffer + metadata + one witness + /// table per protocol). func extendedExistentialLayout(forNode node: Node, in originImage: ImageReference) throws -> StaticTypeLayout { - guard let innerExistential = Self.constrainedExistentialInnerType(of: node) else { + let unwrapped = (node.kind == .type ? node.firstChild : node) ?? node + guard let existentialType = ExtendedExistentialTypeResolution.existentialType(of: unwrapped) else { throw LayoutResolutionError.unknown(.unsupportedTypeKind(nodeKindName: "extendedExistential(no-shape)")) } - // A constrained existential metatype (`any P.Type`) wraps the - // existential in a metatype; route it through the metatype path. - if innerExistential.kind == .existentialMetatype { - return try existentialMetatypeLayout(forNode: innerExistential, in: originImage) - } - return try existentialLayout(forNode: innerExistential, in: originImage) - } - - /// Extracts the plain existential type node (`protocolList` / `…WithClass` / - /// `…WithAnyObject` / `existentialMetatype`) nested inside a - /// `symbolicExtendedExistentialType`'s shape reference: - /// `symbolicExtendedExistentialType → (unique|nonUnique)…ShapeSymbolicReference - /// → constrainedExistential → Type → `. - private static func constrainedExistentialInnerType(of node: Node) -> Node? { - let unwrapped = (node.kind == .type ? node.firstChild : node) ?? node - guard unwrapped.kind == .symbolicExtendedExistentialType else { return nil } - guard let constrainedExistential = firstDescendant(of: unwrapped, kind: .constrainedExistential) else { return nil } - // The constrained existential's first child is the `.type`-wrapped - // existential (a protocol list); its second is the requirement list, - // which does not affect layout. - guard let typeChild = constrainedExistential.children.first(where: { $0.kind == .type }) else { return nil } - return typeChild - } - - /// The first descendant node of the given kind in a pre-order walk. - private static func firstDescendant(of node: Node, kind: Node.Kind) -> Node? { - if node.kind == kind { return node } - for child in node.children { - if let found = firstDescendant(of: child, kind: kind) { return found } + let resolvedExistential = (existentialType.kind == .type ? existentialType.firstChild : existentialType) ?? existentialType + // A constrained existential metatype (`any P.Type`) is a metadata + // word plus the witness tables, not an existential container. + if resolvedExistential.kind == .existentialMetatype { + return try existentialMetatypeLayout(forNode: resolvedExistential, in: originImage) } - return nil + return try existentialLayout(forNode: resolvedExistential, in: originImage) } /// The layout of an existential metatype (`any P.Type`, `Any.Type`, @@ -109,6 +86,12 @@ extension StaticTypeLayoutResolver { in image: ImageReference ) throws -> ExistentialComposition { let unwrapped = (node.kind == .type ? node.firstChild : node) ?? node + // A constrained existential (`any P`, or the instance of + // `any P.Type`) is laid out as its protocol list: the constraints + // pick the witness tables, they do not add any. + if unwrapped.kind == .constrainedExistential, let constrainedProtocols = unwrapped.firstChild { + return try existentialComposition(of: constrainedProtocols, in: image) + } let structurallyClassBound: Bool switch unwrapped.kind { case .protocolList: @@ -143,26 +126,24 @@ extension StaticTypeLayoutResolver { guard let qualifiedName = NodeTypeNaming.protocolQualifiedName(of: protocolNode) else { throw LayoutResolutionError.unknown(.demangleFailure) } - if let classConstraint = imageUniverse.resolveProtocolClassConstraint(byQualifiedTypeName: qualifiedName) { + switch imageUniverse.resolveProtocol(byQualifiedTypeName: qualifiedName) { + case .swift(let classConstraint): if classConstraint == .class { isClassBound = true } witnessTableCount += 1 - continue - } - // `Error` reaching this point is part of a composition, where it - // contributes an ordinary (non-class) witness table. - if qualifiedName == errorProtocolName { - witnessTableCount += 1 - continue - } - // A Swift-declared `@objc` protocol also has no Swift protocol - // descriptor — its only runtime artifact is the ObjC protocol - // record. Like an imported ObjC protocol it is class-bound and - // contributes no Swift witness table. - if imageUniverse.isObjCProtocolDeclared(byQualifiedTypeName: qualifiedName) { + case .objC: + // A Swift-declared `@objc` protocol also has no Swift protocol + // descriptor — its only runtime artifact is the ObjC protocol + // record. Like an imported ObjC protocol it is class-bound and + // contributes no Swift witness table. isClassBound = true - continue + case nil: + // `Error` reaching this point is part of a composition, where it + // contributes an ordinary (non-class) witness table. + guard qualifiedName == errorProtocolName else { + throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: qualifiedName)) + } + witnessTableCount += 1 } - throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: qualifiedName)) } return ExistentialComposition( witnessTableCount: witnessTableCount, diff --git a/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift b/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift index 0f1fac832..d5295f631 100644 --- a/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift +++ b/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift @@ -207,12 +207,19 @@ struct GenericArgumentEnvironment { return classBoundParameterKeys.contains(GenericParameterKey(depth: depth, index: index)) } + /// The qualified name of `classBoundParameterPlaceholderNode()`. No + /// nominal type has it — `AnyObject` is a type alias of a builtin, which + /// no extension can conform to anything — so no image records a + /// conformance of the stand-in, and a witness lookup for it is answered + /// without one (`ImageUniverse.resolveAssociatedTypeWitness(conformingName:protocolName:associatedTypeName:)`). + static let classBoundParameterPlaceholderQualifiedName = "Swift.AnyObject" + /// The stand-in substituted for an unbound class-constrained parameter. Any /// class reference has the identical stored layout (`.pointerSized`, with /// the heap-object extra-inhabitant count), and the resolver stops at every /// class node without reading its name — the spelling exists only for cache - /// keys and diagnostics. - private static func classBoundParameterPlaceholderNode() -> Node { + /// keys, diagnostics and `classBoundParameterPlaceholderQualifiedName`. + static func classBoundParameterPlaceholderNode() -> Node { Node.create(kind: .class, children: [ Node.create(kind: .module, text: "Swift"), Node.create(kind: .identifier, text: "AnyObject"), diff --git a/Sources/Analysis/SwiftLayout/ImageReference.swift b/Sources/Analysis/SwiftLayout/ImageReference.swift index 3606fb25d..7aa8d8ec7 100644 --- a/Sources/Analysis/SwiftLayout/ImageReference.swift +++ b/Sources/Analysis/SwiftLayout/ImageReference.swift @@ -1,4 +1,5 @@ import MachOKit +@_spi(Internals) import MachOCaches import MachOSwiftSection @_spi(Internals) import SwiftInspection import Demangling @@ -10,20 +11,118 @@ import Demangling /// The resolver carries an `ImageReference` through recursion as "the image /// the current type is defined in". In the single-image phase there is exactly /// one; the dependency-closure phase adds more without changing the resolver. +/// +/// Each index is built the first time it is read (evolution proposal +/// `machofile-performance`). A dependency is folded into a universe for one +/// kind of lookup at a time, and most are asked about one kind only: building +/// all seven at once read every dependency's Objective-C protocol list — 2.4 +/// of the 12 seconds the indexes of SwiftUI's dependencies cost — for the +/// rare existential over a Swift-declared `@objc` protocol. An index that +/// cannot be read is empty rather than discarding the image. public final class ImageReference: @unchecked Sendable { public let machO: MachO - let builtinLayoutIndex: BuiltinTypeLayoutIndex + + private let builtinLayoutIndexSlot = LazilyBuiltIndex() + private let typeDescriptorsSlot = LazilyBuiltIndex<[String: TypeContextDescriptorWrapper]>() + private let protocolClassConstraintsSlot = LazilyBuiltIndex<[String: ProtocolClassConstraint]>() + private let objCClassInstanceSizesSlot = LazilyBuiltIndex<[String: (instanceSize: Int, alignmentMask: Int)]>() + private let associatedTypeWitnessRecordsSlot = LazilyBuiltIndex<[String: AssociatedTypeRecord]>() + private let objCProtocolQualifiedNamesSlot = LazilyBuiltIndex>() + private let swiftClassInstanceStartsSlot = LazilyBuiltIndex<[String: Int]>() + + /// Never throws: the indexes are built when first read. Kept throwing so + /// existing `try ImageReference(machO:)` call sites stay valid. + public convenience init(machO: MachO) throws { + self.init(indexingLazily: machO) + } + + init(indexingLazily machO: MachO) { + self.machO = machO + } + + /// The image's reference shared by every universe that folds it in, so + /// an index one root's layouts built serves every other root that + /// depends on the image — RuntimeViewer lays out one root after another + /// against the same system frameworks, and a root has a universe for the + /// printer and another for associated-type projection. + /// + /// A reader of another type that shares the image's key — a wrapper and + /// the reader it wraps share an identifier — gets a reference of its own. + static func shared(for machO: MachO) -> ImageReference { + let sharedReference = ImageReferenceStore.cache.storage(in: machO) { machO -> AnyObject? in + ImageReference(indexingLazily: machO) + } + return sharedReference as? ImageReference ?? ImageReference(indexingLazily: machO) + } + + /// The image's `__swift5_builtin` layouts. + var builtinLayoutIndex: BuiltinTypeLayoutIndex { + builtinLayoutIndexSlot.index { + (try? BuiltinTypeLayoutIndex(machO: machO)) ?? .empty + } + } + /// Exposed (package-internal) so `ImageUniverse` can merge each image's /// per-image index into the closure-wide global index. Keyed by /// fully-qualified type name. - let typeDescriptorsByQualifiedName: [String: TypeContextDescriptorWrapper] + /// + /// `demangleContext` reconstructs the fully-qualified name from the + /// descriptor's parent chain (the descriptor's own `mangledName` is not a + /// demangleable type reference). A dependency image with no Swift type + /// section (a pure-ObjC/C dylib) contributes no types rather than failing + /// the whole closure. + var typeDescriptorsByQualifiedName: [String: TypeContextDescriptorWrapper] { + typeDescriptorsSlot.index { + var typeIndex: [String: TypeContextDescriptorWrapper] = [:] + for contextDescriptor in (try? Self.contextDescriptorsOrEmpty(in: machO)) ?? [] { + guard + let typeDescriptor = contextDescriptor.typeContextDescriptorWrapper, + let contextNode = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context), + let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: contextNode) + else { continue } + typeIndex[qualifiedTypeName] = typeDescriptor + } + return typeIndex + } + } + /// Exposed (package-internal) so `ImageUniverse` can merge each image's /// protocol class-constraint index into the closure-wide global index. - let protocolClassConstraintsByQualifiedName: [String: ProtocolClassConstraint] + /// + /// Every Swift protocol's class constraint, from `__swift5_protos` (a + /// separate section from the type context descriptors), so an + /// existential's representation — opaque vs class-bound — can be derived + /// from its protocol composition. + var protocolClassConstraintsByQualifiedName: [String: ProtocolClassConstraint] { + protocolClassConstraintsSlot.index { + var protocolIndex: [String: ProtocolClassConstraint] = [:] + for protocolDescriptor in (try? Self.protocolDescriptorsOrEmpty(in: machO)) ?? [] { + guard + let classConstraint = protocolDescriptor.flags.kindSpecificFlags?.protocolFlags?.classConstraint, + let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: machO.context), + let qualifiedTypeName = NodeTypeNaming.declaredQualifiedName(of: contextNode) + else { continue } + protocolIndex[qualifiedTypeName] = classConstraint + } + return protocolIndex + } + } + /// Exposed (package-internal) so `ImageUniverse` can merge each image's /// Objective-C class start layouts into the closure-wide index. Keyed by /// bare ObjC class name (ObjC class names carry no module qualifier). - let objCClassInstanceSizesByBareName: [String: (instanceSize: Int, alignmentMask: Int)] + /// + /// Every Objective-C class's instance size, from `__objc_classlist`, so a + /// Swift class with an ObjC ancestor can start its own fields at the + /// ancestor's instance size — the ObjC class has no Swift descriptor, so it + /// is invisible to the type index. Read through the concrete reader + /// because the ObjC accessors are not protocol-generic. + var objCClassInstanceSizesByBareName: [String: (instanceSize: Int, alignmentMask: Int)] { + objCClassInstanceSizesSlot.index { + Self.objCClassInstanceSizes(in: machO) + } + } + /// Exposed (package-internal) so `ImageUniverse` can merge each image's /// associated-type witnesses into the closure-wide index. Keyed by /// `"conformingQualifiedName|protocolQualifiedName|associatedTypeName"`; the @@ -31,99 +130,57 @@ public final class ImageReference + /// class-bound and carries no Swift witness table — so an existential over + /// one can still be laid out as a class-bound component. + var objCProtocolQualifiedNames: Set { + objCProtocolQualifiedNamesSlot.index { + Self.objCProtocolQualifiedNames(in: machO) + } + } + /// Swift qualified name → the class's **own** `class_ro_t.instanceStart`, /// for every statically-emitted Swift class in this image's /// `__objc_classlist`. This is the authoritative field-block start the /// ObjC runtime slides (`moveIvars`) — a cache-resident image carries the - /// pre-slid final value. Queried only for classes defined in this image, - /// so it never merges into the closure-wide index. - let swiftClassInstanceStartsByQualifiedName: [String: Int] - - public init(machO: MachO) throws { - self.machO = machO - self.builtinLayoutIndex = try BuiltinTypeLayoutIndex(machO: machO) - - // `demangleContext` reconstructs the fully-qualified name from the - // descriptor's parent chain (the descriptor's own `mangledName` is not a - // demangleable type reference). A dependency image with no Swift type - // section (a pure-ObjC/C dylib) contributes no types rather than failing - // the whole closure. - var typeIndex: [String: TypeContextDescriptorWrapper] = [:] - for contextDescriptor in try Self.contextDescriptorsOrEmpty(in: machO) { - guard - let typeDescriptor = contextDescriptor.typeContextDescriptorWrapper, - let contextNode = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context), - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: contextNode) - else { continue } - typeIndex[qualifiedTypeName] = typeDescriptor - } - self.typeDescriptorsByQualifiedName = typeIndex - - // Index every Swift protocol's class constraint (from `__swift5_protos`, - // a separate section from the type context descriptors) so an - // existential's representation — opaque vs class-bound — can be derived - // from its protocol composition. - var protocolIndex: [String: ProtocolClassConstraint] = [:] - for protocolDescriptor in try Self.protocolDescriptorsOrEmpty(in: machO) { - guard - let classConstraint = protocolDescriptor.flags.kindSpecificFlags?.protocolFlags?.classConstraint, - let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: machO.context), - let qualifiedTypeName = NodeTypeNaming.declaredQualifiedName(of: contextNode) - else { continue } - protocolIndex[qualifiedTypeName] = classConstraint - } - self.protocolClassConstraintsByQualifiedName = protocolIndex - - // Index every Objective-C class's instance size (from `__objc_classlist`) - // so a Swift class with an ObjC ancestor can start its own fields at the - // ancestor's instance size — the ObjC class has no Swift descriptor, so - // it is invisible to the type index above. Read through the concrete - // reader because the ObjC accessors are not protocol-generic. - self.objCClassInstanceSizesByBareName = Self.objCClassInstanceSizes(in: machO) - - // Index every statically-emitted Swift class's own `instanceStart` - // (also from `__objc_classlist`) — the authoritative field-block start - // the ObjC runtime slides via `moveIvars`. Classlist membership itself - // discriminates the initialization mode: generic and - // singleton-initialized classes are absent and keep the Swift-runtime - // rule (exact superclass size). - self.swiftClassInstanceStartsByQualifiedName = Self.swiftClassInstanceStarts(in: machO) - - // Index every Swift-declared `@objc` protocol (from `__objc_protolist`) - // so an existential over one — which has no Swift protocol descriptor — - // can still be recognized and laid out as a class-bound component with - // no witness table. - self.objCProtocolQualifiedNames = Self.objCProtocolQualifiedNames(in: machO) - - // Index every associated-type witness (from `__swift5_assocty`) so a - // `dependentMemberType` (`SomeType.Index`) can be resolved to its - // concrete witness after the base type is substituted. The conforming - // type and protocol names are demangled to the same qualified-name form - // the resolver computes on the lookup side; a record whose names cannot - // be demangled is skipped. An absent section contributes nothing. - var witnessIndex: [String: AssociatedTypeRecord] = [:] - for descriptor in try Self.associatedTypeDescriptorsOrEmpty(in: machO) { - guard - let conformingNode = try? SymbolicDemangler.demangleType(for: descriptor.conformingTypeName(in: machO.context), in: machO.context), - let conformingName = NodeTypeNaming.nominalQualifiedName(of: conformingNode), - let protocolNode = try? SymbolicDemangler.demangleType(for: descriptor.protocolTypeName(in: machO.context), in: machO.context), - let protocolName = NodeTypeNaming.protocolQualifiedName(of: protocolNode), - let records = try? descriptor.associatedTypeRecords(in: machO.context) - else { continue } - for record in records { - guard let associatedTypeName = try? record.name(in: machO.context) else { continue } - witnessIndex[Self.associatedTypeWitnessKey(conformingName: conformingName, protocolName: protocolName, associatedTypeName: associatedTypeName)] = record - } + /// pre-slid final value. Classlist membership itself discriminates the + /// initialization mode: generic and singleton-initialized classes are + /// absent and keep the Swift-runtime rule (exact superclass size). + /// Queried only for classes defined in this image, so it never merges + /// into the closure-wide index. + var swiftClassInstanceStartsByQualifiedName: [String: Int] { + swiftClassInstanceStartsSlot.index { + Self.swiftClassInstanceStarts(in: machO) } - self.associatedTypeWitnessRecordsByKey = witnessIndex } /// Looks up a type descriptor by its fully-qualified name (as produced by @@ -216,3 +273,26 @@ public final class ImageReference(evictionGroup: .layoutImageIndexes) +} + +extension ImageReference { + /// The indexes built so far, by name, for tests watching which lookups + /// build what. + var builtIndexNamesForTesting: Set { + var builtIndexNames: Set = [] + if builtinLayoutIndexSlot.isBuilt { builtIndexNames.insert("builtinLayouts") } + if typeDescriptorsSlot.isBuilt { builtIndexNames.insert("typeDescriptors") } + if protocolClassConstraintsSlot.isBuilt { builtIndexNames.insert("protocolClassConstraints") } + if objCClassInstanceSizesSlot.isBuilt { builtIndexNames.insert("objCClassInstanceSizes") } + if associatedTypeWitnessRecordsSlot.isBuilt { builtIndexNames.insert("associatedTypeWitnessRecords") } + if objCProtocolQualifiedNamesSlot.isBuilt { builtIndexNames.insert("objCProtocolQualifiedNames") } + if swiftClassInstanceStartsSlot.isBuilt { builtIndexNames.insert("swiftClassInstanceStarts") } + return builtIndexNames + } +} diff --git a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift index bcf05b604..e6e533274 100644 --- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift @@ -48,12 +48,11 @@ extension ImageUniverse { let conformingQualifiedName = NodeTypeNaming.nominalQualifiedName(of: baseTypeNode) else { return nil } - let key = ImageReference.associatedTypeWitnessKey( + guard let witness = resolveAssociatedTypeWitness( conformingName: conformingQualifiedName, protocolName: protocolQualifiedName, associatedTypeName: associatedTypeName - ) - guard let witness = resolveAssociatedTypeWitness(forKey: key) else { return nil } + ) else { return nil } // Demangled in the image that declares the conformance: its symbolic // references are relative to that image. diff --git a/Sources/Analysis/SwiftLayout/ImageUniverse.swift b/Sources/Analysis/SwiftLayout/ImageUniverse.swift index aff99ced7..ac5270963 100644 --- a/Sources/Analysis/SwiftLayout/ImageUniverse.swift +++ b/Sources/Analysis/SwiftLayout/ImageUniverse.swift @@ -9,25 +9,29 @@ import MachOFoundation /// dependency-closure phase adds a root image plus an ordered list of /// dependency images. /// -/// Indexing is **lazy**: the root is indexed eagerly (it is the binary being -/// laid out), but each dependency is indexed only when a lookup misses every -/// already-indexed image, advancing through the dependency list in order and -/// stopping as soon as the name resolves. A transitive closure of the OS can -/// run to hundreds of images; eagerly demangling every one's type section would -/// cost seconds, whereas real lookups hit an early Swift dependency and index -/// only a handful. A genuine miss (a name defined nowhere) indexes the whole -/// list once, after which every further lookup is `O(1)`. +/// Indexing is **lazy**, per kind of lookup: a type lookup folds images — +/// the root first, then the dependencies in order — into the type index only, +/// stopping as soon as the name resolves; protocol, Objective-C class and +/// associated-type witness lookups fold into their own indexes the same way. +/// A transitive closure of the OS can run to hundreds of images; eagerly +/// demangling every one's type section would cost seconds, whereas real +/// lookups hit an early Swift dependency and index only a handful. A genuine +/// miss (a name defined nowhere) folds the whole list once for that kind, +/// after which every further lookup of the kind is `O(1)`. Each image's +/// indexes come from `ImageReference.shared(for:)`, so every universe that +/// folds an image in reuses what another already built. /// /// Because the resolver only ever calls `resolveType(byQualifiedTypeName:)` / -/// `resolveProtocolClassConstraint(byQualifiedTypeName:)`, neither it nor any -/// layout bridge changes when the universe grows from one image to a closure. +/// `resolveProtocol(byQualifiedTypeName:)` and the other `resolve…` seams, +/// neither it nor any layout bridge changes when the universe grows from one +/// image to a closure. /// /// **Threading contract.** `ImageUniverse` is declared `@unchecked Sendable` so /// the rest of the layout pipeline (which transitively holds it through a /// non-`Sendable` `StaticTypeLayoutResolver` and a `StaticLayoutCalculator` /// struct) can be carried into a `Sendable` holder. The universe itself is /// **not internally synchronized**: lazy dependency indexing mutates -/// `nextDependencyToIndex` / `typeIndex` / `protocolIndex` / `objCClassIndex` +/// `foldedImageCountByIndexKind` / `dependencyImages` / `typeIndex` / `protocolIndex` / `objCClassIndex` /// in place during lookups. Concurrent direct sharing is therefore the /// holder's responsibility — the in-tree owner that needs cross-task safety, /// `MachOFileStaticFieldLayoutProvider`, funnels every calculator call through @@ -45,9 +49,32 @@ public final class ImageUniverse /// Held un-indexed until a lookup needs them. private let dependencyMachOs: [MachO] - /// Index of the next dependency in `dependencyMachOs` not yet folded into - /// the merged index. Lookups advance this until they resolve or exhaust it. - private var nextDependencyToIndex = 0 + /// The dependencies' references, made when a lookup of any kind first + /// reaches the dependency; `nil` until then. + private var dependencyImages: [ImageReference?] + + /// The kinds of lookup, each folding images into its own indexes. + /// + /// A type lookup used to fold every index of each dependency it passed, + /// so the one pass that resolved a field type also read the protocol + /// lists, Objective-C classes and associated-type records of every image + /// on the way (evolution proposal `machofile-performance`). The images a + /// kind folds, and the order it folds them in, are the same as before, so + /// each lookup answers what it did. + enum IndexKind: CaseIterable { + case types + /// The Swift protocols' class constraints together with the + /// Swift-declared `@objc` protocols, which a protocol lookup asks in + /// that order of each image as it folds it in. + case protocols + case objCClasses + case associatedTypeWitnesses + } + + /// How many images — the root first, then the dependencies in order — + /// each kind of lookup has folded into its indexes. Lookups advance + /// their kind's count until they resolve or exhaust the images. + private var foldedImageCountByIndexKind: [IndexKind: Int] = [:] /// Closure-wide type index: fully-qualified name → (defining image, /// descriptor). Seeded with the root and grown lazily, first writer wins — @@ -79,18 +106,25 @@ public final class ImageUniverse init(rootImage: ImageReference, dependencyMachOs: [MachO] = []) { self.rootImage = rootImage self.dependencyMachOs = dependencyMachOs - mergeIndexes(of: rootImage) + self.dependencyImages = Array(repeating: nil, count: dependencyMachOs.count) } /// The number of dependency images in the closure (whether or not indexed). public var dependencyImageCount: Int { dependencyMachOs.count } + /// How many dependency images lookups have folded in so far, a malformed + /// one that indexed nothing included: the most any kind of lookup has + /// reached. + var indexedDependencyImageCount: Int { + max(0, (foldedImageCountByIndexKind.values.max() ?? 0) - 1) + } + /// The install paths of the dependency images, in resolution order. public var dependencyImagePaths: [String] { dependencyMachOs.map(\.imagePath) } /// Builds a single-image universe: types resolve only within `machO`. public static func singleImage(_ machO: MachO) throws -> ImageUniverse { - ImageUniverse(rootImage: try ImageReference(machO: machO)) + ImageUniverse(rootImage: ImageReference.shared(for: machO)) } /// The low-level dependency-closure factory: the caller has already located @@ -100,7 +134,7 @@ public final class ImageUniverse /// locating and call through here. The root's types take priority; /// dependencies resolve in the given order, first writer wins. public static func dependencyClosure(root: MachO, dependencyImages: [MachO]) throws -> ImageUniverse { - ImageUniverse(rootImage: try ImageReference(machO: root), dependencyMachOs: dependencyImages) + ImageUniverse(rootImage: ImageReference.shared(for: root), dependencyMachOs: dependencyImages) } /// Resolves a fully-qualified type name to the image that defines it and @@ -109,32 +143,57 @@ public final class ImageUniverse byQualifiedTypeName qualifiedTypeName: String ) -> (image: ImageReference, descriptor: TypeContextDescriptorWrapper)? { if let resolved = typeIndex[qualifiedTypeName] { return resolved } - while typeIndex[qualifiedTypeName] == nil, indexNextDependency() {} + while typeIndex[qualifiedTypeName] == nil, foldNextImage(into: .types) {} return typeIndex[qualifiedTypeName] } - /// Resolves a fully-qualified protocol name to its class constraint, or - /// `nil` if no image in the closure defines that protocol. Used to decide - /// whether an existential is class-bound. - func resolveProtocolClassConstraint( - byQualifiedTypeName qualifiedTypeName: String - ) -> ProtocolClassConstraint? { - if let resolved = protocolIndex[qualifiedTypeName] { return resolved.constraint } - while protocolIndex[qualifiedTypeName] == nil, indexNextDependency() {} - return protocolIndex[qualifiedTypeName]?.constraint + /// What a protocol name resolves to: a Swift protocol descriptor, or only + /// an Objective-C protocol record. + enum ResolvedProtocol: Equatable { + /// A Swift protocol, with the class constraint its descriptor declares. + case swift(ProtocolClassConstraint) + /// A Swift-declared `@objc` protocol, which gets no Swift protocol + /// descriptor — its only runtime artifact is the Objective-C protocol + /// record. Always class-bound, and it contributes no witness table. + case objC + } + + /// Resolves a fully-qualified protocol name, or returns `nil` if no image + /// in the closure declares that protocol. Used to decide whether an + /// existential or a generic parameter is class-bound. + /// + /// Both records are looked for in each image as it is folded in, so a name + /// resolves in the first image that knows it either way. Asked of the Swift + /// descriptors alone first, a Swift-declared `@objc` protocol — which has + /// none — folded in the whole closure before its record, which the root + /// usually holds a copy of, was looked at: one field of Dock's DockHelper + /// indexed the 500-odd images its closure reaches in the system's cache. + func resolveProtocol(byQualifiedTypeName qualifiedTypeName: String) -> ResolvedProtocol? { + if let resolved = indexedProtocol(byQualifiedTypeName: qualifiedTypeName) { return resolved } + while foldNextImage(into: .protocols) { + if let resolved = indexedProtocol(byQualifiedTypeName: qualifiedTypeName) { return resolved } + } + return nil + } + + /// What the images folded in so far say a protocol name is. A Swift + /// protocol descriptor wins over an Objective-C record of the same name, + /// the order the two were asked in before one lookup asked both. + private func indexedProtocol(byQualifiedTypeName qualifiedTypeName: String) -> ResolvedProtocol? { + if let resolved = protocolIndex[qualifiedTypeName] { return .swift(resolved.constraint) } + if objCProtocolQualifiedNames.contains(qualifiedTypeName) { return .objC } + return nil } /// Resolves an Objective-C class's start layout (its instance size and a /// pointer start alignment) by bare name, or `nil` if no image in the - /// closure defines that ObjC class. The third resolution seam, sharing the - /// same lazy fold-in as `resolveType` / `resolveProtocolClassConstraint`: - /// every dependency's ObjC index is merged when that dependency is folded, - /// so this needs no extra scan over the closure. + /// closure defines that ObjC class. The third resolution seam, with the + /// same lazy fold-in as `resolveType` / `resolveProtocol`. func resolveObjCClassInstanceSize( byBareName bareName: String ) -> (instanceSize: Int, alignmentMask: Int)? { if let resolved = objCClassIndex[bareName] { return resolved } - while objCClassIndex[bareName] == nil, indexNextDependency() {} + while objCClassIndex[bareName] == nil, foldNextImage(into: .objCClasses) {} return objCClassIndex[bareName] } @@ -146,50 +205,84 @@ public final class ImageUniverse forKey key: String ) -> (image: ImageReference, record: AssociatedTypeRecord)? { if let resolved = associatedTypeWitnessIndex[key] { return resolved } - while associatedTypeWitnessIndex[key] == nil, indexNextDependency() {} + while associatedTypeWitnessIndex[key] == nil, foldNextImage(into: .associatedTypeWitnesses) {} return associatedTypeWitnessIndex[key] } - /// Whether any image in the closure declares an Objective-C protocol with - /// this Swift qualified name — i.e. whether the name identifies a - /// Swift-declared `@objc` protocol (which emits no Swift protocol - /// descriptor, so `resolveProtocolClassConstraint` misses it). The fifth - /// resolution seam, sharing the same lazy fold-in as the others. - func isObjCProtocolDeclared(byQualifiedTypeName qualifiedTypeName: String) -> Bool { - if objCProtocolQualifiedNames.contains(qualifiedTypeName) { return true } - while !objCProtocolQualifiedNames.contains(qualifiedTypeName), indexNextDependency() {} - return objCProtocolQualifiedNames.contains(qualifiedTypeName) + /// Resolves the witness a conformance of `conformingName` to + /// `protocolName` binds `associatedTypeName` to, or `nil` if no image in + /// the closure records that conformance. + /// + /// The stand-in for an unbound class-bound generic parameter + /// (`GenericArgumentEnvironment.classBoundParameterPlaceholderQualifiedName`) + /// is answered without a lookup: no image records a conformance of it, and + /// asking folded every image of the closure into the witness index before + /// answering `nil` — all 552 of SwiftUI's, for one member of a class-bound + /// parameter (evolution proposal `machofile-performance`). + func resolveAssociatedTypeWitness( + conformingName: String, + protocolName: String, + associatedTypeName: String + ) -> (image: ImageReference, record: AssociatedTypeRecord)? { + guard conformingName != GenericArgumentEnvironment.classBoundParameterPlaceholderQualifiedName else { return nil } + return resolveAssociatedTypeWitness(forKey: ImageReference.associatedTypeWitnessKey( + conformingName: conformingName, + protocolName: protocolName, + associatedTypeName: associatedTypeName + )) } - /// Folds the next un-indexed dependency into the merged indexes. Returns - /// `false` when the dependency list is exhausted. A dependency whose - /// `ImageReference` cannot be built (a malformed binary) is skipped rather - /// than failing the closure. - private func indexNextDependency() -> Bool { - guard nextDependencyToIndex < dependencyMachOs.count else { return false } - let machO = dependencyMachOs[nextDependencyToIndex] - nextDependencyToIndex += 1 - if let reference = try? ImageReference(machO: machO) { - mergeIndexes(of: reference) + /// Folds the next image `kind` has not reached — the root first, then the + /// dependencies in order — into that kind's closure-wide indexes, first + /// writer wins (so already-folded images shadow this one). Returns `false` + /// when every image is folded. + private func foldNextImage(into kind: IndexKind) -> Bool { + let foldedImageCount = foldedImageCountByIndexKind[kind, default: 0] + guard foldedImageCount <= dependencyMachOs.count else { return false } + foldedImageCountByIndexKind[kind] = foldedImageCount + 1 + guard let image = image(atResolutionPosition: foldedImageCount) else { return true } + switch kind { + case .types: + for (qualifiedTypeName, descriptor) in image.typeDescriptorsByQualifiedName where typeIndex[qualifiedTypeName] == nil { + typeIndex[qualifiedTypeName] = (image, descriptor) + } + case .protocols: + for (qualifiedTypeName, classConstraint) in image.protocolClassConstraintsByQualifiedName where protocolIndex[qualifiedTypeName] == nil { + protocolIndex[qualifiedTypeName] = (image, classConstraint) + } + objCProtocolQualifiedNames.formUnion(image.objCProtocolQualifiedNames) + case .objCClasses: + for (bareName, startLayout) in image.objCClassInstanceSizesByBareName where objCClassIndex[bareName] == nil { + objCClassIndex[bareName] = startLayout + } + case .associatedTypeWitnesses: + for (key, record) in image.associatedTypeWitnessRecordsByKey where associatedTypeWitnessIndex[key] == nil { + associatedTypeWitnessIndex[key] = (image, record) + } } return true } - /// Merges one image's per-image indexes into the closure-wide indexes, - /// first writer wins (so already-indexed images shadow this one). - private func mergeIndexes(of image: ImageReference) { - for (qualifiedTypeName, descriptor) in image.typeDescriptorsByQualifiedName where typeIndex[qualifiedTypeName] == nil { - typeIndex[qualifiedTypeName] = (image, descriptor) - } - for (qualifiedTypeName, classConstraint) in image.protocolClassConstraintsByQualifiedName where protocolIndex[qualifiedTypeName] == nil { - protocolIndex[qualifiedTypeName] = (image, classConstraint) + /// The image at `position` in resolution order: the root at 0, then the + /// dependencies. A dependency's reference is made on first use and kept + /// for every kind; one that cannot be made (a malformed binary) is + /// skipped rather than failing the closure. + private func image(atResolutionPosition position: Int) -> ImageReference? { + guard position > 0 else { return rootImage } + let dependencyIndex = position - 1 + if let dependencyImage = dependencyImages[dependencyIndex] { + return dependencyImage } - for (bareName, startLayout) in image.objCClassInstanceSizesByBareName where objCClassIndex[bareName] == nil { - objCClassIndex[bareName] = startLayout - } - for (key, record) in image.associatedTypeWitnessRecordsByKey where associatedTypeWitnessIndex[key] == nil { - associatedTypeWitnessIndex[key] = (image, record) - } - objCProtocolQualifiedNames.formUnion(image.objCProtocolQualifiedNames) + let dependencyImage = ImageReference.shared(for: dependencyMachOs[dependencyIndex]) + dependencyImages[dependencyIndex] = dependencyImage + return dependencyImage + } +} + +extension ImageUniverse { + /// How many images — the root included — lookups of `kind` have folded + /// in, for tests watching which lookups fold what. + func foldedImageCount(for kind: IndexKind) -> Int { + foldedImageCountByIndexKind[kind, default: 0] } } diff --git a/Sources/Analysis/SwiftLayout/LazilyBuiltIndex.swift b/Sources/Analysis/SwiftLayout/LazilyBuiltIndex.swift new file mode 100644 index 000000000..98f222b39 --- /dev/null +++ b/Sources/Analysis/SwiftLayout/LazilyBuiltIndex.swift @@ -0,0 +1,34 @@ +import Foundation + +/// One of an image's indexes, built the first time it is read. +/// +/// The build runs outside the lock — it demangles, and a demangle may hop to +/// a large-stack thread, which must not happen while other readers wait on +/// the lock — and the first finished build is kept: readers racing on the +/// first read may each build the index, and all of them read the one that was +/// kept. +final class LazilyBuiltIndex: @unchecked Sendable { + private let lock = NSLock() + private var builtIndex: Index? + + func index(buildingWith build: () -> Index) -> Index { + if let builtIndex = lock.withLock({ builtIndex }) { + return builtIndex + } + let index = build() + return lock.withLock { + if let builtIndex { + return builtIndex + } + builtIndex = index + return index + } + } +} + +extension LazilyBuiltIndex { + /// Whether the index has been built. + var isBuilt: Bool { + lock.withLock { builtIndex != nil } + } +} diff --git a/Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift b/Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift index 19a6f49e1..c46c65328 100644 --- a/Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift +++ b/Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift @@ -1,11 +1,22 @@ import MachOKit +import MachOFoundation @_spi(Core) import MachOObjCSection +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop /// Builds a per-image index of the Objective-C protocol declarations /// (`__objc_protolist`), keyed by *Swift* qualified name, so an existential /// component that misses the Swift protocol index can be recognized as a /// Swift-declared `@objc` protocol. /// +/// Two sources. Every record with a legacy `_TtP` runtime name — the image's +/// own protocols and the copies Swift emits of the ones it references — +/// and the image's own protocols as `SwiftDeclaredObjCProtocolIndex` pairs +/// them with their field descriptors (evolution proposal +/// `swift-declared-objc-protocols`), which is what recognizes one the source +/// renamed with `@objc(Name)` or declared in a type. Without reflection +/// metadata the second adds nothing the first does not. +/// /// A Swift-declared `@objc` protocol emits **no** Swift protocol descriptor /// (`__swift5_protos`) — its only runtime artifact is the Objective-C protocol /// record, whose name is the legacy `_TtP_` mangling (e.g. @@ -25,9 +36,8 @@ enum ObjCProtocolIndex { /// in-process image. An image with no `__objc_protolist` (or with only /// native ObjC protocols) contributes nothing. static func qualifiedNames(in machO: MachOImage) -> Set { - guard let objCProtocols = machO.objc.protocols64 else { return [] } - var qualifiedNames: Set = [] - for objCProtocol in objCProtocols { + var qualifiedNames = declaredQualifiedNames(in: machO) + for objCProtocol in machO.objc.protocols64 ?? [] { if let qualifiedName = swiftQualifiedName(fromLegacyProtocolMangledName: objCProtocol.mangledName(in: machO)) { qualifiedNames.insert(qualifiedName) } @@ -38,9 +48,8 @@ enum ObjCProtocolIndex { /// The Swift qualified names of every `@objc` protocol declared in a /// file-backed (or dyld-cache-resident) image. static func qualifiedNames(in machO: MachOFile) -> Set { - guard let objCProtocols = machO.objc.protocols64 else { return [] } - var qualifiedNames: Set = [] - for objCProtocol in objCProtocols { + var qualifiedNames = declaredQualifiedNames(in: machO) + for objCProtocol in machO.objc.protocols64 ?? [] { if let qualifiedName = swiftQualifiedName(fromLegacyProtocolMangledName: objCProtocol.mangledName(in: machO)) { qualifiedNames.insert(qualifiedName) } @@ -48,6 +57,12 @@ enum ObjCProtocolIndex { return qualifiedNames } + /// The image's own `@objc` protocols declared in Swift, renamed and + /// nested ones included. + private static func declaredQualifiedNames(in machO: some MachORepresentableWithCache) -> Set { + Set(SwiftDeclaredObjCProtocolIndex.shared.protocols(in: machO).map(\.qualifiedName)) + } + /// Parses the legacy `_TtPmodulename_` protocol mangling /// into `"module.name"`, or `nil` for any other name form (a native ObjC /// protocol's plain name, a Punycode-encoded Unicode identifier, a custom diff --git a/Sources/Analysis/SwiftLayout/SharedCacheEvictionGroup+SwiftLayout.swift b/Sources/Analysis/SwiftLayout/SharedCacheEvictionGroup+SwiftLayout.swift new file mode 100644 index 000000000..ca59b1e52 --- /dev/null +++ b/Sources/Analysis/SwiftLayout/SharedCacheEvictionGroup+SwiftLayout.swift @@ -0,0 +1,9 @@ +@_spi(Internals) import MachOCaches + +/// The eviction group of this module's per-image cache. It points into no +/// other group's storage, so it follows none. +extension SharedCacheEvictionGroup { + /// `ImageReference.shared(for:)`: each image's layout indexes, shared by + /// every universe that folds the image in. + package static let layoutImageIndexes = SharedCacheEvictionGroup("layoutImageIndexes") +} diff --git a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift index 724768631..c288bace3 100644 --- a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift +++ b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift @@ -1,5 +1,6 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection +import SwiftObjCInterop import Demangling /// Resolves a Swift type (given by its mangled name or demangled `Node`) to its @@ -98,7 +99,10 @@ final class StaticTypeLayoutResolver`) has the container of + // its protocols; `SymbolicDemangler` hands a field's one over in + // this form, its shape already resolved. return try existentialLayout(forNode: node, in: originImage) case .symbolicExtendedExistentialType: return try extendedExistentialLayout(forNode: node, in: originImage) @@ -278,7 +282,7 @@ final class StaticTypeLayoutResolver Bool { - lhs.offset == rhs.offset && lhs.layout == rhs.layout + public static func == (left: ObjCClass64, right: ObjCClass64) -> Bool { + left.offset == right.offset && left.layout == right.layout } } -extension ObjCClass64: @retroactive LocatableLayoutWrapper, Resolvable, @unchecked @retroactive Sendable {} +extension ObjCClass64: @retroactive LocatableLayoutWrapper, @retroactive Resolvable, @unchecked @retroactive Sendable {} extension ObjCClass64.Layout: @retroactive Equatable { - public static func == (lhs: ObjCClass64.Layout, rhs: ObjCClass64.Layout) -> Bool { - lhs.isa == rhs.isa && - lhs.superclass == rhs.superclass && - lhs.methodCacheBuckets == rhs.methodCacheBuckets && - lhs.methodCacheProperties == rhs.methodCacheProperties && - lhs.swiftClassFlags == rhs.swiftClassFlags + public static func == (left: ObjCClass64.Layout, right: ObjCClass64.Layout) -> Bool { + left.isa == right.isa && + left.superclass == right.superclass && + left.methodCacheBuckets == right.methodCacheBuckets && + left.methodCacheProperties == right.methodCacheProperties && + left.swiftClassFlags == right.swiftClassFlags } } diff --git a/Sources/Analysis/SwiftInspection/CustomObjCClassName.swift b/Sources/Analysis/SwiftObjCInterop/CustomObjCClassName.swift similarity index 100% rename from Sources/Analysis/SwiftInspection/CustomObjCClassName.swift rename to Sources/Analysis/SwiftObjCInterop/CustomObjCClassName.swift diff --git a/Sources/Analysis/SwiftObjCInterop/Extensions/MachORepresentableWithCache+ObjCReaderKinds.swift b/Sources/Analysis/SwiftObjCInterop/Extensions/MachORepresentableWithCache+ObjCReaderKinds.swift new file mode 100644 index 000000000..752502375 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/Extensions/MachORepresentableWithCache+ObjCReaderKinds.swift @@ -0,0 +1,25 @@ +import MachOKit +import MachOKitExtensions +import MachOSwiftSection + +/// The reader re-typing the ObjC-side indexes' build closures make. +/// +/// Every index is queried through `MachORepresentableWithCache` — the +/// protocol each consumer holds its reader as — and its `SharedCache` is +/// keyed the same way. Building an ObjC-side index reads descriptors and +/// ObjC class data, which that protocol does not offer; both of its +/// conformers (`MachOFile`, `MachOImage`) do. So a build closure re-types +/// the reader 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: +/// `ObjCImplementationClassReading` is this module's own, so no wrapper +/// outside it can conform. +extension MachORepresentableWithCache { + /// 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)? { + underlyingReader as? any ObjCImplementationClassReading & MachOSwiftSectionRepresentableWithCache + } +} diff --git a/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift b/Sources/Analysis/SwiftObjCInterop/ObjCAncestorResolver.swift similarity index 69% rename from Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCAncestorResolver.swift index 6b456300a..7b4b74e2a 100644 --- a/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCAncestorResolver.swift @@ -3,8 +3,9 @@ import FoundationToolbox import MachOKit import MachOKitExtensions import MachOFoundation +import MachOSwiftSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Core) import MachOObjCSection /// Follows a standalone file's bound superclass — or a category's bound @@ -41,7 +42,8 @@ public final class ObjCAncestorResolver: @unchecked Sendable { /// The dependency images, in lookup order: files for a file on disk, /// the loaded images for an in-process root (whose superclass pointers - /// are all real — only the category fold reads those). + /// are all real — only the category fold and a class without a class + /// object, whose superclass only has a name, read those). enum DependencyImages { case files([MachOFile]) case loaded([MachOImage]) @@ -50,8 +52,9 @@ public final class ObjCAncestorResolver: @unchecked Sendable { private let makeDependencyImages: @Sendable () -> DependencyImages private let lock = NSLock() private var dependencyImages: DependencyImages? - private var memoizedClassObjectsByRuntimeName: [String: (MachOFile, ObjCClass64)?] = [:] + private var memoizedClassObjectsByRuntimeName: [String: (any ObjCImplementationClassReading, ObjCClass64)?] = [:] private var memoizedCategorySelectorsByRuntimeName: [String: RawObjCCategorySelectors] = [:] + private var memoizedSwiftDeclaredObjCProtocolsByRuntimeName: [String: SwiftDeclaredObjCProtocol?] = [:] /// - Parameter dependencyImages: Produces the images to look in, in /// lookup order; called once, on the first name that reaches a bind. @@ -73,7 +76,10 @@ public final class ObjCAncestorResolver: @unchecked Sendable { /// superclass pointer is real in-process — but the categories of the /// non-cache images the process loaded are attached by the runtime into /// `class_rw_ext_t`, which the readers do not see, so they are folded - /// from those images' `__objc_catlist` like a file's. + /// from those images' `__objc_catlist` like a file's. A Swift class + /// without a class object has no superclass pointer to follow at all — + /// its descriptor only names the superclass — so names are looked up in + /// the loaded images the way a file's binds are in its closure. public convenience init(inProcessRoot: MachOImage) { self.init(loadedImages: { DependencyClosure(root: inProcessRoot, traversal: .transitive).images }) } @@ -86,9 +92,18 @@ public final class ObjCAncestorResolver: @unchecked Sendable { /// behavior of a reader with no dependency closure at hand. public static let empty = ObjCAncestorResolver(dependencyImages: { [] }) - /// The class object named `runtimeName` and the image defining it, or - /// `nil` when no dependency image exports such a class. + /// The class object named `runtimeName` and the file defining it, or + /// `nil` when no dependency file exports such a class — the file-typed + /// form of `resolvedClassObject(named:)`. package func classObject(named runtimeName: String) -> (MachOFile, ObjCClass64)? { + guard let (reader, classObject) = resolvedClassObject(named: runtimeName), let machOFile = reader.asMachOFile else { return nil } + return (machOFile, classObject) + } + + /// The class object named `runtimeName` and the image defining it — a + /// file of the closure, or an image the process loaded — or `nil` when no + /// dependency image exports such a class. + func resolvedClassObject(named runtimeName: String) -> (any ObjCImplementationClassReading, ObjCClass64)? { lock.lock() defer { lock.unlock() } if let memoized = memoizedClassObjectsByRuntimeName[runtimeName] { @@ -97,19 +112,11 @@ public final class ObjCAncestorResolver: @unchecked Sendable { if dependencyImages == nil { dependencyImages = makeDependencyImages() } - guard case .files(let files) = dependencyImages else { - memoizedClassObjectsByRuntimeName[runtimeName] = .some(nil) - return nil - } let exportedName = "_OBJC_CLASS_$_" + runtimeName - var found: (MachOFile, ObjCClass64)? - for image in files { - // A re-export entry (an umbrella framework's) passes here and - // misses the class list; the defining image follows in the closure. - guard image.exportTrie?.search(by: exportedName) != nil else { continue } - guard let classObject = ObjCClassMethodIndex.shared.storage(in: image)?.classObjectsByRuntimeName[runtimeName] else { continue } - found = (image, classObject) - break + let found: (any ObjCImplementationClassReading, ObjCClass64)? = switch dependencyImages { + case .files(let files): Self.firstClassObject(named: runtimeName, in: files) { $0.exportTrie?.search(by: exportedName) != nil } + case .loaded(let images): Self.firstClassObject(named: runtimeName, in: images) { $0.exportTrie?.search(by: exportedName) != nil } + case nil: nil } if found == nil { #log(.info, "no dependency image defines the ObjC class \(runtimeName, privacy: .public); the chain stops there") @@ -118,6 +125,20 @@ public final class ObjCAncestorResolver: @unchecked Sendable { return found } + /// The first of `images` whose class list holds `runtimeName`, among the + /// ones that export it — an exact pre-check that spares the class-list + /// read of every image not carrying the class. + private static func firstClassObject(named runtimeName: String, in images: [Image], exportsTheClass: (Image) -> Bool) -> (any ObjCImplementationClassReading, ObjCClass64)? { + for image in images { + // A re-export entry (an umbrella framework's) passes here and + // misses the class list; the defining image follows in the closure. + guard exportsTheClass(image) else { continue } + guard let classObject = ObjCClassMethodIndex.shared.storage(in: image)?.classObjectsByRuntimeName[runtimeName] else { continue } + return (image, classObject) + } + return nil + } + /// The selectors that categories in the file's dependency images add to /// the class named `runtimeName`, from the images that are standalone /// files. A class read out of a dyld cache already carries the cache's @@ -156,6 +177,50 @@ public final class ObjCAncestorResolver: @unchecked Sendable { memoizedCategorySelectorsByRuntimeName[runtimeName] = result return result } + + /// The `@objc` protocol declared in Swift that an image of the closure + /// registers under `runtimeName` — another module's protocol renamed with + /// `@objc(Name)`, whose name says nothing of its module — or `nil` when + /// none does (evolution proposal `swift-declared-objc-protocols`). Only an + /// image with reflection metadata can say: its field descriptors are what + /// pair a renamed protocol with its record, so the others — every image + /// clang alone built — are skipped unread. Memoized per name; the images' + /// indexes are built outside the lock, as building one demangles. + func swiftDeclaredObjCProtocol(forRuntimeName runtimeName: String) -> SwiftDeclaredObjCProtocol? { + lock.lock() + if let memoized = memoizedSwiftDeclaredObjCProtocolsByRuntimeName[runtimeName] { + lock.unlock() + return memoized + } + if dependencyImages == nil { + dependencyImages = makeDependencyImages() + } + let images = dependencyImages + lock.unlock() + + let found: SwiftDeclaredObjCProtocol? = switch images { + case .files(let files): Self.firstSwiftDeclaredObjCProtocol(forRuntimeName: runtimeName, in: files) + case .loaded(let images): Self.firstSwiftDeclaredObjCProtocol(forRuntimeName: runtimeName, in: images) + case nil: nil + } + + lock.lock() + defer { lock.unlock() } + if let memoized = memoizedSwiftDeclaredObjCProtocolsByRuntimeName[runtimeName] { + return memoized + } + memoizedSwiftDeclaredObjCProtocolsByRuntimeName[runtimeName] = .some(found) + return found + } + + private static func firstSwiftDeclaredObjCProtocol(forRuntimeName runtimeName: String, in images: [Image]) -> SwiftDeclaredObjCProtocol? { + for image in images where image.sections.contains(where: { $0.sectionName == MachOSwiftSectionName.__swift5_fieldmd.rawValue }) { + if let declaredProtocol = SwiftDeclaredObjCProtocolIndex.shared.declaredProtocol(forRuntimeName: runtimeName, in: image) { + return declaredProtocol + } + } + return nil + } } /// Per-image registry of ``ObjCAncestorResolver``s. Same shape as @@ -168,7 +233,7 @@ public final class ObjCAncestorResolver: @unchecked Sendable { public final class ObjCAncestorResolverStore: @unchecked Sendable { public static let shared = ObjCAncestorResolverStore() - private let cache = SharedCache(evictionGroup: .objcAncestorResolver, follows: [.symbolStore]) + private let cache = SharedCache(evictionGroup: .objcAncestorResolver, follows: [.swiftSymbolStore]) private init() {} diff --git a/Sources/Analysis/SwiftInspection/ObjCClassHierarchy.swift b/Sources/Analysis/SwiftObjCInterop/ObjCClassHierarchy.swift similarity index 99% rename from Sources/Analysis/SwiftInspection/ObjCClassHierarchy.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCClassHierarchy.swift index cd946513d..10dc132f4 100644 --- a/Sources/Analysis/SwiftInspection/ObjCClassHierarchy.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCClassHierarchy.swift @@ -2,7 +2,7 @@ import Foundation import MachOKit import MachOKitExtensions @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// What the ObjC side knows about one class that the member recovery needs /// (evolution proposals `objc-ancestor-override-recovery` and @@ -191,7 +191,7 @@ public final class ObjCClassHierarchyProviderStore: @unchecked Sendable { /// but it is per-image state of the ObjC hierarchy's lifetime, so it /// joins the registry under that group by hand. private init() { - SharedCacheRegistry.shared.register(self, group: .objcHierarchy, follows: [.symbolStore]) + SharedCacheRegistry.shared.register(self, group: .objcHierarchy, follows: [.swiftSymbolStore]) } /// Installs `provider` for `machO`, replacing any earlier registration. diff --git a/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift b/Sources/Analysis/SwiftObjCInterop/ObjCClassMethodIndex.swift similarity index 75% rename from Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCClassMethodIndex.swift index d260578bc..cfbed3956 100644 --- a/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCClassMethodIndex.swift @@ -4,8 +4,9 @@ import MachOKit import MachOKitExtensions @_spi(Core) import MachOObjCSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import MachOReading +import SwiftInspection /// The library's own ``ObjCClassHierarchy`` reader (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): @@ -45,7 +46,7 @@ import MachOReading package final class ObjCClassMethodIndex: @unchecked Sendable { package static let shared = ObjCClassMethodIndex() - private let cache = SharedCache(evictionGroup: .objcHierarchy, follows: [.symbolStore]) + private let cache = SharedCache(evictionGroup: .objcHierarchy, follows: [.swiftSymbolStore]) private init() {} @@ -78,6 +79,8 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { fileprivate struct HierarchyMemoKey: Hashable { let classOffset: Int? let foreignClassName: String? + /// A class without a class object, by its `class_ro_t`. + let readOnlyDataOffset: Int? let resolverIdentity: UUID? } @@ -136,8 +139,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { // MARK: - Queries /// The runtime names of the Swift classes whose qualified name is - /// `qualifiedName`; empty when the image defines no such class object - /// (a generic class has none — it is instantiated at runtime). + /// `qualifiedName`; empty when the image defines no such class. /// /// A class the source renamed (`@objc(NSScrollPocket)`) files under a /// runtime name that demangles to nothing, so the table built here never @@ -145,12 +147,17 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { /// metadata's descriptor gives (evolution proposal /// `objc-custom-class-name`), and both answers count: the qualified name /// drops the private discriminator, so two same-named private classes stay - /// ambiguous whichever of them was renamed. Only an image whose Swift - /// classes are asked about builds that index — the ancestor walk never - /// asks by Swift name. + /// ambiguous whichever of them was renamed. A class without a class + /// object — a generic class, or one the stub list registers — is answered + /// by the name `SwiftClassWithoutClassObjectIndex` gives it (evolution + /// proposal `objc-classes-without-class-objects`), and counts too. Only + /// an image whose Swift classes are asked about builds those indexes — + /// the ancestor walk never asks by Swift name. package func runtimeNames(forSwiftClassQualifiedName qualifiedName: String, in machO: some MachORepresentableWithCache) -> [String] { let demangledRuntimeNames = storage(in: machO)?.runtimeNamesBySwiftQualifiedName[qualifiedName] ?? [] - return demangledRuntimeNames + SwiftClassObjectIndex.shared.customRuntimeNames(forSwiftClassQualifiedName: qualifiedName, in: machO) + return demangledRuntimeNames + + SwiftClassObjectIndex.shared.customRuntimeNames(forSwiftClassQualifiedName: qualifiedName, in: machO) + + SwiftClassWithoutClassObjectIndex.shared.names(forSwiftClassQualifiedName: qualifiedName, in: machO) } /// The hierarchy of the class the image defines under `runtimeName` — @@ -175,7 +182,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { let resolver = ObjCAncestorResolverStore.shared.resolver(forImage: reader) let folding = AncestorCategoryFolding(rootReader: reader, rootStorage: storage, resolver: resolver) if let classObject = storage.classObjectsByRuntimeName[runtimeName] { - let memoKey = Storage.HierarchyMemoKey(classOffset: classObject.offset, foreignClassName: nil, resolverIdentity: resolver?.identity) + let memoKey = Storage.HierarchyMemoKey(classOffset: classObject.offset, foreignClassName: nil, readOnlyDataOffset: nil, resolverIdentity: resolver?.identity) if let memoized = storage.memoizedHierarchy(for: memoKey) { return memoized } @@ -207,10 +214,15 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { return hierarchy } - // No class object of that name here: the image's categories on a - // class another image defines. + // No class object of that name here, but a class whose `class_ro_t` + // only Swift metadata leads to. + if let swiftClass = SwiftClassWithoutClassObjectIndex.shared.swiftClass(named: runtimeName, in: reader) { + return hierarchy(of: swiftClass, categories: categories, storage: storage, reader: reader, resolver: resolver, folding: folding) + } + + // Neither: the image's categories on a class another image defines. guard !categories.isEmpty else { return nil } - let memoKey = Storage.HierarchyMemoKey(classOffset: nil, foreignClassName: runtimeName, resolverIdentity: resolver?.identity) + let memoKey = Storage.HierarchyMemoKey(classOffset: nil, foreignClassName: runtimeName, readOnlyDataOffset: nil, resolverIdentity: resolver?.identity) if let memoized = storage.memoizedHierarchy(for: memoKey) { return memoized } @@ -226,7 +238,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { // in a file; the bind is followed by name like a superclass. var chain = AncestorChain(ancestors: [], isComplete: false, unresolvedAncestorName: runtimeName) var targetClass: (any ObjCImplementationClassReading, ObjCClass64)? = reader.targetClass(of: categories[0]) - if targetClass == nil, let resolver, let (classImage, classObject) = resolver.classObject(named: runtimeName) { + if targetClass == nil, let resolver, let (classImage, classObject) = resolver.resolvedClassObject(named: runtimeName) { targetClass = (classImage, classObject) } if let (classReader, classObject) = targetClass { @@ -251,6 +263,69 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { return hierarchy } + /// The hierarchy of a class without a class object: its methods are its + /// `class_ro_t`'s and its metaclass's, plus the image's categories on + /// it, and its chain starts where its descriptor's superclass names + /// (`superclassLocation(of:in:)`). Which categories are found depends on + /// the kind. A class with generic ancestry has the categories of its + /// `@objc` extensions point at its metadata, whose `class_ro_t` names + /// it, so `targetClassName(of:)` files them under its name. One with + /// resilient ancestry has them point at its stub, which names no class, + /// and listed in `__objc_catlist2`, which `objcCategories()` does not + /// read, so none is found. A generic class has none: Swift rejects + /// `@objc` members in its extensions. + private func hierarchy(of swiftClass: SwiftClassWithoutClassObject, categories: [ObjCCategory64], storage: Storage, reader: some ObjCImplementationClassReading, resolver: ObjCAncestorResolver?, folding: AncestorCategoryFolding) -> ObjCClassHierarchy? { + let memoKey = Storage.HierarchyMemoKey(classOffset: nil, foreignClassName: nil, readOnlyDataOffset: swiftClass.readOnlyDataOffset, resolverIdentity: resolver?.identity) + if let memoized = storage.memoizedHierarchy(for: memoKey) { + return memoized + } + guard let readOnlyData = swiftClass.readOnlyData(in: reader) else { return nil } + var methods: [ObjCClassHierarchy.Method] = reader.methods(of: readOnlyData).map { + ObjCClassHierarchy.Method(selector: $0.selector, isClassMethod: false, implementation: $0.implementationOffset.map { .offset($0) }) + } + if let metaclassReadOnlyData = swiftClass.metaclassReadOnlyData(in: reader) { + methods += reader.methods(of: metaclassReadOnlyData).map { + ObjCClassHierarchy.Method(selector: $0.selector, isClassMethod: true, implementation: $0.implementationOffset.map { .offset($0) }) + } + } + var protocolSelectors = reader.protocolSelectors(of: readOnlyData) + Self.append(categories, to: &methods, protocolSelectors: &protocolSelectors, in: reader) + guard !methods.isEmpty else { return nil } + + let chain = ancestors(startingAt: superclassLocation(of: swiftClass, in: reader), className: swiftClass.name, resolver: resolver, folding: folding) + let hierarchy = ObjCClassHierarchy( + className: swiftClass.name, + methods: methods, + ancestors: chain.ancestors, + isAncestorChainComplete: chain.isComplete, + unresolvedAncestorName: chain.unresolvedAncestorName, + adoptedProtocolSelectors: protocolSelectors.hierarchyValue + ) + storage.memoize(hierarchy, for: memoKey) + return hierarchy + } + + /// Where the superclass of a class without a class object is: a class + /// object of the same image goes by pointer, an Objective-C class of + /// another image by name — the ancestor resolver follows it — another + /// class without a class object through this index, and a Swift class + /// another image defines nowhere: the chain stops, unnamed, since no + /// lookup could answer for its Swift spelling. + private func superclassLocation(of swiftClass: SwiftClassWithoutClassObject, in reader: some ObjCImplementationClassReading) -> ObjCSuperclassLocation { + switch swiftClass.superclass { + case .objectiveC(let runtimeName), .classObject(let runtimeName): + if let classObject = storage(in: reader)?.classObjectsByRuntimeName[runtimeName] { + return .resolved(reader, classObject) + } + return .unresolvable(runtimeName) + case .withoutClassObject(let name): + guard let superclass = SwiftClassWithoutClassObjectIndex.shared.swiftClass(named: name, in: reader) else { return .unresolvable(nil) } + return .withoutClassObject(reader, superclass) + case .swiftClass: + return .unresolvable(nil) + } + } + /// Continues a hierarchy a host's provider handed over with its chain /// broken at a bind — the ObjC indexers stop where a superclass could /// not be followed, exactly where the library's reader does — through @@ -262,7 +337,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { guard !hierarchy.isAncestorChainComplete, let unresolvedAncestorName = hierarchy.unresolvedAncestorName, let resolver = ObjCAncestorResolverStore.shared.resolver(forImage: machO), - let (ancestorImage, ancestorClassObject) = resolver.classObject(named: unresolvedAncestorName) + let (ancestorImage, ancestorClassObject) = resolver.resolvedClassObject(named: unresolvedAncestorName) else { return hierarchy } let folding = folding(for: machO, resolver: resolver) let chain = ancestors(startingAt: .resolved(ancestorImage, ancestorClassObject), className: hierarchy.className, resolver: resolver, folding: folding) @@ -358,7 +433,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { case .root: break walk case .unresolvable(let superclassName): - if let superclassName, let resolver, let (ancestorImage, ancestorClassObject) = resolver.classObject(named: superclassName) { + if let superclassName, let resolver, let (ancestorImage, ancestorClassObject) = resolver.resolvedClassObject(named: superclassName) { location = .resolved(ancestorImage, ancestorClassObject) continue walk } @@ -387,6 +462,27 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { } chain.ancestors.append(ObjCClassHierarchy.Ancestor(className: selectorSets.className, instanceSelectors: instanceSelectors, classSelectors: classSelectors, adoptedProtocolSelectors: protocolSelectors.hierarchyValue)) location = ancestorReader.superclassLocation(of: ancestorClassObject) + case .withoutClassObject(let ancestorReader, let ancestorClass): + hopCount += 1 + guard hopCount <= 64 else { + #log(.error, "superclass chain of \(className, privacy: .public) exceeds 64 hops; treating it as broken") + chain.isComplete = false + break walk + } + guard let selectorSets = selectorSets(of: ancestorClass, in: ancestorReader) else { + chain.isComplete = false + break walk + } + var instanceSelectors = selectorSets.instanceSelectors + var classSelectors = selectorSets.classSelectors + var protocolSelectors = selectorSets.protocolSelectors + if let folded = folding?.selectors(onClassNamed: selectorSets.className), !folded.isEmpty { + instanceSelectors.formUnion(folded.instanceSelectors) + classSelectors.formUnion(folded.classSelectors) + protocolSelectors.merge(folded.protocolSelectors) + } + chain.ancestors.append(ObjCClassHierarchy.Ancestor(className: selectorSets.className, instanceSelectors: instanceSelectors, classSelectors: classSelectors, adoptedProtocolSelectors: protocolSelectors.hierarchyValue)) + location = superclassLocation(of: ancestorClass, in: ancestorReader) } } return chain @@ -430,6 +526,24 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { return compute(in: reader) } + /// The selectors a class without a class object implements, memoized in + /// its image's storage under its `class_ro_t` offset. + private func selectorSets(of swiftClass: SwiftClassWithoutClassObject, in reader: any ObjCImplementationClassReading) -> SelectorSets? { + func compute(in reader: Reader) -> SelectorSets? { + guard let storage = storage(in: reader) else { return nil } + if let memoized = storage.memoizedSelectorSets(forClassOffset: swiftClass.readOnlyDataOffset) { + return memoized + } + guard let readOnlyData = swiftClass.readOnlyData(in: reader) else { return nil } + let instanceSelectors = Set(reader.methods(of: readOnlyData).map(\.selector)) + let classSelectors = swiftClass.metaclassReadOnlyData(in: reader).map { Set(reader.methods(of: $0).map(\.selector)) } ?? [] + let selectorSets = SelectorSets(className: swiftClass.name, instanceSelectors: instanceSelectors, classSelectors: classSelectors, protocolSelectors: reader.protocolSelectors(of: readOnlyData)) + storage.memoize(selectorSets, forClassOffset: swiftClass.readOnlyDataOffset) + return selectorSets + } + return compute(in: reader) + } + // MARK: - Build private static func build(in machO: some ObjCImplementationClassReading) -> Storage { @@ -465,6 +579,12 @@ enum ObjCSuperclassLocation { /// reach (a standalone file's dependency); `String?` is the bound /// symbol's class name when the bind names one. case unresolvable(String?) + /// A class of the reader's image without a class object, which only + /// Swift metadata leads to (evolution proposal + /// `objc-classes-without-class-objects`). No reader's + /// `superclassLocation(of:)` answers it: a class object's superclass has + /// a class object. + case withoutClassObject(any ObjCImplementationClassReading, SwiftClassWithoutClassObject) } /// What categories add to a class: instance and class selectors, and the diff --git a/Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassFacts.swift similarity index 87% rename from Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassFacts.swift index 42d797797..ed3d554cc 100644 --- a/Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassFacts.swift @@ -143,6 +143,25 @@ public final class ObjCImplementationClassFacts: Sendable { public struct Property: Sendable { public let name: String public let attributes: String + + private var attributeCodes: [Substring] { + attributes.split(separator: ",") + } + + /// `R`: the class offers Objective-C no setter. + public var isReadOnly: Bool { + attributeCodes.contains("R") + } + + /// `W`: a `weak` property. + public var isWeak: Bool { + attributeCodes.contains("W") + } + + /// The ivar `V` names, the storage the property is synthesized on. + public var instanceVariableName: String? { + attributeCodes.first { $0.hasPrefix("V") }.map { String($0.dropFirst()) } + } } /// The bare ObjC class name (`NSGlassEffectView`). @@ -192,6 +211,20 @@ public final class ObjCImplementationClassFacts: Sendable { public func storageInstanceVariable(forPropertyNamed name: String) -> InstanceVariable? { instanceVariable(forSwiftPropertyNamed: name) ?? instanceVariables.first { $0.lazyPropertyName == name } } + + /// The Objective-C property a stored property is exposed as: the one + /// synthesized on its ivar (`V`), else the one named like the + /// Swift property. `nil` for storage Objective-C never sees. It says what + /// the symbols may not: under `-O` a stored property's setter is often + /// inlined into its thunk and leaves no symbol, but the property is still + /// settable when the class offers Objective-C a setter (evolution + /// proposal `swift-first-imported-declarations`). + public func objcProperty(storedIn instanceVariable: InstanceVariable, swiftPropertyName: String) -> Property? { + if !instanceVariable.name.isEmpty, let property = properties.first(where: { $0.instanceVariableName == instanceVariable.name }) { + return property + } + return properties.first { $0.name == swiftPropertyName } + } } extension ObjCImplementationClassFacts.Evidence.Reason: CustomStringConvertible { diff --git a/Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassIndex.swift similarity index 82% rename from Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassIndex.swift index 25e5d247a..b90509fc3 100644 --- a/Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassIndex.swift @@ -7,7 +7,7 @@ import MachOReading import MachOSwiftSection @_spi(Core) import MachOObjCSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// Per-image index of the classes implemented through `@objc @implementation` /// (evolution proposal `objc-implementation-class-recognition`), keyed by @@ -37,7 +37,7 @@ import MachOSwiftSection package final class ObjCImplementationClassIndex: @unchecked Sendable { package static let shared = ObjCImplementationClassIndex() - private let cache = SharedCache(evictionGroup: .objcImplementationClasses, follows: [.symbolStore]) + private let cache = SharedCache(evictionGroup: .objcImplementationClasses, follows: [.swiftSymbolStore]) private init() {} @@ -136,7 +136,7 @@ package final class ObjCImplementationClassIndex: @unchecked Sendable { static func collect(in machO: some ObjCImplementationClassReading) -> SwiftSideEvidence { var evidence = SwiftSideEvidence() - let symbolIndexStore = SymbolIndexStore.shared + let symbolIndexStore = SwiftSymbolIndexStore.shared // `$sSoCMa`: global(typeMetadataAccessFunction(type(class(module, identifier)))). // Only an EXPORTED accessor counts. An imported ObjC class has @@ -411,6 +411,21 @@ protocol ObjCImplementationClassReading: MachORepresentableWithCache, Readable { func instanceMethods(of category: ObjCCategory64) -> [RawObjCMethod] func classMethods(of category: ObjCCategory64) -> [RawObjCMethod] func protocolSelectors(of category: ObjCCategory64) -> RawObjCProtocolSelectors + /// The runtime names of the protocols the category adopts. + func protocolNames(of category: ObjCCategory64) -> [String] + /// The category's own name: `NSTouchBar` of `NSView(NSTouchBar)`. + func categoryName(of category: ObjCCategory64) -> String? + func instanceProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] + func classProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] + /// The class data's own methods, properties and protocols — in a dyld + /// cache, the class's own list of the relative list of lists the cache + /// builds when it attaches categories ahead of time, never the attached + /// categories' (`methods(of:)` reads every list). + func importedMethods(of readOnlyData: ObjCClassROData64) -> [RawObjCMethod] + func importedProperties(of readOnlyData: ObjCClassROData64) -> [ObjCImplementationClassFacts.Property] + func importedProtocolNames(of readOnlyData: ObjCClassROData64) -> [String] + /// `__objc_protolist`, every record read in full (`ObjCProtocolRecord.swift`). + func objcProtocolRecords() -> [ObjCProtocolRecord] } extension MachOFile: ObjCImplementationClassReading { @@ -539,6 +554,13 @@ extension MachOFile: ObjCImplementationClassReading { Self.protocolSelectors(of: category.protocolList(in: self), in: self) } + func protocolNames(of category: ObjCCategory64) -> [String] { + guard let protocolList = category.protocolList(in: self), !protocolList.isListOfLists, + let protocols = protocolList.protocols(in: self) + else { return [] } + return protocols.map { $1.mangledName(in: $0) } + } + private func rawMethods(of methodList: ObjCMethodList?) -> [RawObjCMethod] { guard let methodList, !methodList.isListOfLists, let methods = methodList.methods(in: self) else { return [] } return methods.map { RawObjCMethod(selector: $0.name, typeEncoding: $0.types, implementationOffset: $0.imp == 0 ? nil : Int($0.imp)) } @@ -687,6 +709,13 @@ extension MachOImage: ObjCImplementationClassReading { Self.protocolSelectors(of: category.protocolList(in: self), in: self) } + func protocolNames(of category: ObjCCategory64) -> [String] { + guard let protocolList = category.protocolList(in: self), !protocolList.isListOfLists, + let protocols = protocolList.protocols(in: self) + else { return [] } + return protocols.map { $1.mangledName(in: $0) } + } + private func rawMethods(of methodList: ObjCMethodList?) -> [RawObjCMethod] { guard let methodList, !methodList.isListOfLists else { return [] } return methodList.methods(in: self).map { RawObjCMethod(selector: $0.name, typeEncoding: $0.types, implementationOffset: $0.imp == 0 ? nil : resolveOffset(at: $0.imp)) } @@ -720,3 +749,128 @@ extension MachOImage: ObjCImplementationClassReading { return result } } + +// MARK: - Category names and properties + +/// What an imported category's declaration reads beyond its methods +/// (evolution proposal `objc-imported-declarations`). +extension MachOFile { + func categoryName(of category: ObjCCategory64) -> String? { + category.name(in: self) + } + + func instanceProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] { + categoryProperties(of: category.instancePropertyList(in: self)) + } + + func classProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] { + categoryProperties(of: category.classPropertyList(in: self)) + } + + private func categoryProperties(of propertyList: ObjCPropertyList?) -> [ObjCImplementationClassFacts.Property] { + guard let propertyList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: self).map { .init(name: $0.name, attributes: $0.attributes) } + } +} + +extension MachOImage { + func categoryName(of category: ObjCCategory64) -> String? { + category.name(in: self) + } + + func instanceProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] { + categoryProperties(of: category.instancePropertyList(in: self)) + } + + func classProperties(of category: ObjCCategory64) -> [ObjCImplementationClassFacts.Property] { + categoryProperties(of: category.classPropertyList(in: self)) + } + + private func categoryProperties(of propertyList: ObjCPropertyList?) -> [ObjCImplementationClassFacts.Property] { + guard let propertyList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: self).map { .init(name: $0.name, attributes: $0.attributes) } + } +} + +// MARK: - A class's own lists + +/// The class data's own methods, properties and protocols, for importing +/// the class into Swift (evolution proposal `objc-imported-declarations`). +/// +/// In a dyld cache, a class whose image's or other images' categories the +/// cache attached ahead of time lists them in a relative list of lists, the +/// attached categories' lists first and the class's own list last. An +/// imported class shows what its image declares of it, the way a header does: +/// the class's own list alone. Its image's categories are imported on their +/// own; other images' never belong to it. +extension MachOFile { + func importedMethods(of readOnlyData: ObjCClassROData64) -> [RawObjCMethod] { + let ownList: (MachOFile, ObjCMethodList)? + if let methodList = readOnlyData.methodList(in: self) { + ownList = (self, methodList) + } else { + ownList = readOnlyData.methodRelativeListList(in: self)?.lists(in: self).last { $0.0.imagePath == imagePath } + } + guard let (listMachO, methodList) = ownList, !methodList.isListOfLists, let methods = methodList.methods(in: listMachO) else { return [] } + // On a file the reader hands back an offset already. + return methods.map { RawObjCMethod(selector: $0.name, typeEncoding: $0.types, implementationOffset: $0.imp == 0 ? nil : Int($0.imp)) } + } + + func importedProperties(of readOnlyData: ObjCClassROData64) -> [ObjCImplementationClassFacts.Property] { + let ownList: (MachOFile, ObjCPropertyList)? + if let propertyList = readOnlyData.propertyList(in: self) { + ownList = (self, propertyList) + } else { + ownList = readOnlyData.propertyRelativeListList(in: self)?.lists(in: self).last { $0.0.imagePath == imagePath } + } + guard let (listMachO, propertyList) = ownList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: listMachO).map { .init(name: $0.name, attributes: $0.attributes) } + } + + func importedProtocolNames(of readOnlyData: ObjCClassROData64) -> [String] { + let ownList: (MachOFile, ObjCProtocolList64)? + if let protocolList = readOnlyData.protocolList(in: self) { + ownList = (self, protocolList) + } else { + ownList = readOnlyData.protocolRelativeListList(in: self)?.lists(in: self).last { $0.0.imagePath == imagePath } + } + guard let (listMachO, protocolList) = ownList, !protocolList.isListOfLists, let protocols = protocolList.protocols(in: listMachO) else { return [] } + return protocols.map { $1.mangledName(in: $0) } + } +} + +extension MachOImage { + func importedMethods(of readOnlyData: ObjCClassROData64) -> [RawObjCMethod] { + let ownList: (MachOImage, ObjCMethodList)? + if let methodList = readOnlyData.methodList(in: self) { + ownList = (self, methodList) + } else { + ownList = readOnlyData.methodRelativeListList(in: self)?.lists(in: self).last { $0.0.ptr == ptr } + } + guard let (listMachO, methodList) = ownList, !methodList.isListOfLists else { return [] } + // In-process the reader hands back an address. + return methodList.methods(in: listMachO).map { RawObjCMethod(selector: $0.name, typeEncoding: $0.types, implementationOffset: $0.imp == 0 ? nil : listMachO.resolveOffset(at: $0.imp)) } + } + + func importedProperties(of readOnlyData: ObjCClassROData64) -> [ObjCImplementationClassFacts.Property] { + let ownList: (MachOImage, ObjCPropertyList)? + if let propertyList = readOnlyData.propertyList(in: self) { + ownList = (self, propertyList) + } else { + ownList = readOnlyData.propertyRelativeListList(in: self)?.lists(in: self).last { $0.0.ptr == ptr } + } + guard let (listMachO, propertyList) = ownList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: listMachO).map { .init(name: $0.name, attributes: $0.attributes) } + } + + func importedProtocolNames(of readOnlyData: ObjCClassROData64) -> [String] { + let ownList: (MachOImage, ObjCProtocolList64)? + if let protocolList = readOnlyData.protocolList(in: self) { + ownList = (self, protocolList) + } else { + ownList = readOnlyData.protocolRelativeListList(in: self)?.lists(in: self).last { $0.0.ptr == ptr } + } + guard let (listMachO, protocolList) = ownList, !protocolList.isListOfLists, let protocols = protocolList.protocols(in: listMachO) else { return [] } + return protocols.map { $1.mangledName(in: $0) } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift new file mode 100644 index 000000000..484b5f943 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift @@ -0,0 +1,227 @@ +import Foundation +import FoundationToolbox +import MachOKit +import MachOSwiftSection +@_spi(Core) import MachOObjCSection +@_spi(Internals) import MachOCaches + +/// One Objective-C class or category of an image, as read for importing it +/// into Swift (evolution proposal `objc-imported-declarations`): its methods +/// and properties as the method and property lists record them, in their +/// order, before anything is named. +package struct ObjCImportedContainerRecord: Sendable { + package enum Kind: Sendable, Hashable { + case `class` + /// A category, by its own name (`NSTouchBar` of `NSView(NSTouchBar)`). + case category(name: String) + } + + package struct Method: Sendable, Hashable { + package let selector: String + /// The method list's encoding (`v24@0:8@16`): every object is `@`. + package let typeEncoding: String + package let implementationOffset: Int? + } + + package struct Property: Sendable, Hashable { + package let name: String + /// The attribute string (`T@"NSString",C,N,V_title`). + package let attributes: String + } + + package let kind: Kind + /// The class's runtime name — the category's target for a category. + package let classRuntimeName: String + /// A class's superclass by runtime name; `nil` for a root class, a + /// superclass the reader cannot name, and a category. + package let superclassRuntimeName: String? + /// The protocols the class or category adopts, by runtime name. + package let protocolRuntimeNames: [String] + /// Whether the class data's Swift bit is set: a Swift class registered + /// with the Objective-C runtime. Always `false` for a category. + package let isSwiftClass: Bool + package let instanceMethods: [Method] + package let classMethods: [Method] + package let instanceProperties: [Property] + package let classProperties: [Property] + + /// The name a category is listed under, `NSView(NSTouchBar)` — the same + /// `uniqueName` MachOObjCSection's models give it; a class's runtime name. + package var uniqueName: String { + switch kind { + case .class: classRuntimeName + case .category(let name): "\(classRuntimeName)(\(name))" + } + } +} + +/// Per-image index of the Objective-C classes, categories and protocol +/// records an image defines, read for importing them into Swift (evolution +/// proposal `objc-imported-declarations`). Built once per image on first use +/// through the shared-cache machinery, and evicted with the other ObjC-side +/// per-image state. It holds names and encodings only, no `NodeReference`. +@Loggable(.private, subsystem: "com.machoswiftsection.swift-inspection", category: "ObjCImportedContainerIndex") +package final class ObjCImportedContainerIndex: @unchecked Sendable { + package static let shared = ObjCImportedContainerIndex() + + private let cache = SharedCache(evictionGroup: .objcHierarchy) + + private init() {} + + package final class Storage: @unchecked Sendable { + let classRecordsByRuntimeName: [String: ObjCImportedContainerRecord] + let categoryRecordsByUniqueName: [String: ObjCImportedContainerRecord] + /// Swift's record of a protocol when clang emitted one under the + /// same name too, as `SwiftDeclaredObjCProtocolIndex` keeps it. + let protocolRecordsByRuntimeName: [String: ObjCProtocolRecord] + + init(classRecordsByRuntimeName: [String: ObjCImportedContainerRecord], categoryRecordsByUniqueName: [String: ObjCImportedContainerRecord], protocolRecordsByRuntimeName: [String: ObjCProtocolRecord]) { + self.classRecordsByRuntimeName = classRecordsByRuntimeName + self.categoryRecordsByUniqueName = categoryRecordsByUniqueName + self.protocolRecordsByRuntimeName = protocolRecordsByRuntimeName + } + } + + package func storage(in machO: some MachORepresentableWithCache) -> Storage? { + cache.storage(in: machO) { machO in + machO.objcImplementationClassReader.map { Self.build(in: $0) } + } + } + + package func remove(for machO: some MachORepresentableWithCache) { + cache.remove(for: machO) + } + + // MARK: - Queries + + /// The class the Objective-C runtime knows as `runtimeName`, when this + /// image defines it. + package func classRecord(named runtimeName: String, in machO: some MachORepresentableWithCache) -> ObjCImportedContainerRecord? { + storage(in: machO)?.classRecordsByRuntimeName[runtimeName] + } + + /// The category listed as `uniqueName` (`NSView(NSTouchBar)`), when this + /// image defines it. + package func categoryRecord(uniqueName: String, in machO: some MachORepresentableWithCache) -> ObjCImportedContainerRecord? { + storage(in: machO)?.categoryRecordsByUniqueName[uniqueName] + } + + /// The image's record of the protocol the runtime knows as + /// `runtimeName`. An image holds a record of every protocol it adopts or + /// names, not only of the ones it defines. + package func protocolRecord(named runtimeName: String, in machO: some MachORepresentableWithCache) -> ObjCProtocolRecord? { + storage(in: machO)?.protocolRecordsByRuntimeName[runtimeName] + } + + /// Every class of the image by runtime name, sorted. + package func classRuntimeNames(in machO: some MachORepresentableWithCache) -> [String] { + storage(in: machO)?.classRecordsByRuntimeName.keys.sorted() ?? [] + } + + /// Every category of the image by unique name, sorted. + package func categoryUniqueNames(in machO: some MachORepresentableWithCache) -> [String] { + storage(in: machO)?.categoryRecordsByUniqueName.keys.sorted() ?? [] + } + + // MARK: - Build + + private static func build(in machO: MachO) -> Storage { + var classRecordsByRuntimeName: [String: ObjCImportedContainerRecord] = [:] + for classObject in machO.objcImplementationClassObjects() ?? [] { + guard let readOnlyData = machO.instanceReadOnlyData(of: classObject), + let runtimeName = machO.className(of: readOnlyData) + else { + #log(.debug, "Skipped a class object whose class data the reader could not read.") + continue + } + let metaClassReadOnlyData = machO.metaClass(of: classObject).flatMap { machO.instanceReadOnlyData(of: $0) } + // In a dyld cache the class data also lists the categories the + // cache attached ahead of time, other images' among them: only + // the class's own list is read, as a header declares the class. + // The image's categories are records of their own. + let record = ObjCImportedContainerRecord( + kind: .class, + classRuntimeName: runtimeName, + superclassRuntimeName: machO.superclassName(of: classObject), + protocolRuntimeNames: uniqued(machO.importedProtocolNames(of: readOnlyData)), + isSwiftClass: classObject.isSwiftStable, + instanceMethods: methods(machO.importedMethods(of: readOnlyData)), + classMethods: metaClassReadOnlyData.map { methods(machO.importedMethods(of: $0)) } ?? [], + instanceProperties: properties(machO.importedProperties(of: readOnlyData)), + classProperties: metaClassReadOnlyData.map { properties(machO.importedProperties(of: $0)) } ?? [] + ) + // A name listed twice keeps its first class object. + if classRecordsByRuntimeName[runtimeName] == nil { + classRecordsByRuntimeName[runtimeName] = record + } + } + + var categoryRecordsByUniqueName: [String: ObjCImportedContainerRecord] = [:] + for category in machO.objcCategories() ?? [] { + // A file names a target class only when it is bound in from + // another image; one of its own is read through the pointer. + var resolvedTargetClassName = machO.targetClassName(of: category) + if resolvedTargetClassName == nil, let (targetReader, targetClassObject) = machO.targetClass(of: category) { + resolvedTargetClassName = className(of: targetClassObject, in: targetReader) + } + guard let targetClassName = resolvedTargetClassName, + let categoryName = machO.categoryName(of: category) + else { continue } + let record = ObjCImportedContainerRecord( + kind: .category(name: categoryName), + classRuntimeName: targetClassName, + superclassRuntimeName: nil, + protocolRuntimeNames: machO.protocolNames(of: category), + isSwiftClass: false, + instanceMethods: methods(machO.instanceMethods(of: category)), + classMethods: methods(machO.classMethods(of: category)), + instanceProperties: properties(machO.instanceProperties(of: category)), + classProperties: properties(machO.classProperties(of: category)) + ) + if categoryRecordsByUniqueName[record.uniqueName] == nil { + categoryRecordsByUniqueName[record.uniqueName] = record + } + } + + // Swift's record first: a name clang also emitted keeps Swift's. + var protocolRecordsByRuntimeName: [String: ObjCProtocolRecord] = [:] + for record in machO.objcProtocolRecords() where protocolRecordsByRuntimeName[record.runtimeName].map({ !$0.isEmittedBySwift && record.isEmittedBySwift }) ?? true { + protocolRecordsByRuntimeName[record.runtimeName] = record + } + + return Storage( + classRecordsByRuntimeName: classRecordsByRuntimeName, + categoryRecordsByUniqueName: categoryRecordsByUniqueName, + protocolRecordsByRuntimeName: protocolRecordsByRuntimeName + ) + } + + private static func className(of classObject: ObjCClass64, in reader: some ObjCImplementationClassReading) -> String? { + reader.instanceReadOnlyData(of: classObject).flatMap { reader.className(of: $0) } + } + + /// The methods, each selector once: the first list naming it is the one + /// a message reaches, as an attached category's list comes before the + /// class's own. + private static func methods(_ rawMethods: [RawObjCMethod]) -> [ObjCImportedContainerRecord.Method] { + var seenSelectors: Set = [] + return rawMethods.compactMap { rawMethod in + guard seenSelectors.insert(rawMethod.selector).inserted else { return nil } + return ObjCImportedContainerRecord.Method(selector: rawMethod.selector, typeEncoding: rawMethod.typeEncoding, implementationOffset: rawMethod.implementationOffset) + } + } + + /// The properties, each name once. + private static func properties(_ properties: [ObjCImplementationClassFacts.Property]) -> [ObjCImportedContainerRecord.Property] { + var seenNames: Set = [] + return properties.compactMap { property in + guard seenNames.insert(property.name).inserted else { return nil } + return ObjCImportedContainerRecord.Property(name: property.name, attributes: property.attributes) + } + } + + private static func uniqued(_ names: [String]) -> [String] { + var seenNames: Set = [] + return names.filter { seenNames.insert($0).inserted } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberBuilder.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberBuilder.swift new file mode 100644 index 000000000..253ff7398 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberBuilder.swift @@ -0,0 +1,310 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// One member of an Objective-C class or category as Swift imports it +/// (evolution proposal `objc-imported-declarations`), shaped like the member +/// symbol the compiler would have demangled to so the member printers print +/// it as they print any other. Its Swift name follows the importer's rules +/// and may not be the one the SDK gives it: the printer pins the selector +/// with `@objc(selector)`. +package struct ObjCImportedMember: Sendable { + package enum Kind: Sendable, Hashable { + case method + case initializer + /// A class method imported as a convenience initializer. + case factoryInitializer + case property + case `subscript` + } + + /// How an object property holds its value, from its attributes. + package enum Ownership: Sendable, Hashable { + /// `&` (`strong`, `retain`). + case strong + /// `C`: `@NSCopying`. + case copy + /// `W`: `weak`. + case weak + /// None of them on an object: `assign` or `unsafe_unretained`, + /// `unowned(unsafe)`. + case unownedUnsafe + } + + package let kind: Kind + /// The selector the runtime sends: a method's, a property's or a + /// subscript's getter. + package let selector: String + /// A property's or subscript's setter; `nil` when it is read-only. + package let setterSelector: String? + package let isClassMember: Bool + /// The declaration: `Global > Function`, `Global > Static > Getter > + /// Variable`, `Global > Allocator`, `Global > Getter > Subscript`. + package let node: Node + /// The encoding the declaration was built from: the method list's, an + /// adopted protocol's extended one, or the property's attributes. + package let typeEncoding: String + /// An object property's ownership; `nil` for every other member. + package let ownership: Ownership? + /// Whether the interface spells the selector out (`@objc(selector)`): the + /// compiler would derive another one from the Swift name it prints + /// (`ObjCMemberShape.defaultSelector()`), as for `convert(_:fromView:)`, + /// whose selector is `convertPoint:fromView:`. + package let hasExplicitSelector: Bool + /// A property's name in the property list, which a header's + /// `@property` declares (`hidden` for the `isHidden` getter); `nil` for + /// every other member. + package var objcPropertyName: String? = nil + + package var isSettable: Bool { + setterSelector != nil + } +} + +/// Builds the members of an Objective-C class or category from its method +/// and property lists (evolution proposal `objc-imported-declarations`), in +/// list order — the source's — with a property where its getter is, the +/// instance members before the class members. +/// +/// Names follow `ObjCImporterNaming`, a class method restating the class's +/// name imported as an initializer. A method list's encoding names no class; +/// when a protocol the class or category adopts declares the same selector, +/// its extended encoding — classes, protocols, block signatures — gives the +/// types and the names instead. Methods Swift never sees are left out: the +/// compiler's `.cxx_construct` and `.cxx_destruct`, `dealloc`, and the +/// reference counting methods ARC forbids. +package enum ObjCImportedMemberBuilder { + /// The members of `record`, declared on `contextNode` (the `Class` node + /// of the class, or of a category's target), whose name for the + /// importer's rules is `contextTypeName`. + package static func members(of record: ObjCImportedContainerRecord, contextNode: Node, contextTypeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> [ObjCImportedMember] { + Builder(record: record, contextNode: contextNode, contextTypeName: contextTypeName, machO: machO).members() + } + + /// The selectors the importer never imports as members. + private static let unimportedSelectors: Set = [ + ".cxx_construct", ".cxx_destruct", "dealloc", + "retain", "release", "autorelease", "retainCount", + ] + + /// Whether the compiler would derive a selector other than `selector` + /// from the Swift name `name` gives a method (`ObjCMemberShape`). + package static func hasExplicitSelector(_ selector: String, name: ObjCImporterNaming.ImportedName, isClassMember: Bool) -> Bool { + let labels: [String?] = name.argumentLabels.map { $0.isEmpty ? nil : $0 } + let kind: ObjCMemberShape.Kind + switch name.kind { + case .method: + kind = .method(baseName: name.baseName, labels: labels, arity: labels.count) + case .initializer, .factoryInitializer: + kind = .initializer(labels: labels, arity: labels.count) + case .subscriptGetter, .subscriptSetter: + // The four fixed selectors are every subscript's. + return false + } + let shape = ObjCMemberShape(kind: kind, isStatic: isClassMember && name.kind == .method, ownerQualifiedName: nil, isThrowing: name.errorConvention != nil) + return shape.defaultSelector() != selector + } + + /// Whether the compiler would derive a getter other than `getterSelector` + /// from a property's Swift name: `cgPath`'s is `CGPath`. + package static func hasExplicitSelector(getterSelector: String, propertyName: String, isClassMember: Bool) -> Bool { + ObjCMemberShape(kind: .getter(propertyName: propertyName), isStatic: isClassMember, ownerQualifiedName: nil).defaultSelector() != getterSelector + } + + private struct Builder { + let record: ObjCImportedContainerRecord + let contextNode: Node + let contextTypeName: String + let machO: MachO + let nodes: ObjCImportedMemberNodes + + init(record: ObjCImportedContainerRecord, contextNode: Node, contextTypeName: String, machO: MachO) { + self.record = record + self.contextNode = contextNode + self.contextTypeName = contextTypeName + self.machO = machO + self.nodes = ObjCImportedMemberNodes(machO: machO) + } + + private struct PropertyAccessors { + let property: ObjCImportedContainerRecord.Property + let getterSelector: String + let setterSelector: String? + } + + func members() -> [ObjCImportedMember] { + var members: [ObjCImportedMember] = [] + for isClassMember in [false, true] { + let methods = isClassMember ? record.classMethods : record.instanceMethods + let properties = propertyAccessors(of: isClassMember ? record.classProperties : record.instanceProperties) + let propertyNames = Self.propertyNames(properties: properties, methods: methods) + let methodSelectors = Set(methods.map(\.selector)) + var emittedPropertyNames: Set = [] + for method in methods { + // A property prints where its getter is; its setter, and + // a getter seen again, print nothing more. + if let accessors = properties.first(where: { $0.getterSelector == method.selector || $0.setterSelector == method.selector }) { + guard emittedPropertyNames.insert(accessors.property.name).inserted else { continue } + if let member = propertyMember(accessors, isClassMember: isClassMember, propertyNames: propertyNames) { + members.append(member) + } + continue + } + guard !ObjCImportedMemberBuilder.unimportedSelectors.contains(method.selector) else { continue } + if let member = methodMember(method, isClassMember: isClassMember, propertyNames: propertyNames, methodSelectors: methodSelectors) { + members.append(member) + } + } + // A property whose accessors are in no method list — a + // `@dynamic` one, or one an ancestor implements. + for accessors in properties where !emittedPropertyNames.contains(accessors.property.name) { + if let member = propertyMember(accessors, isClassMember: isClassMember, propertyNames: propertyNames) { + members.append(member) + } + } + } + return members + } + + /// `NameImporter::getAllPropertyNames`, as far as the record goes: + /// its property names, and the selectors of its argument-less methods + /// that return something. The importer also takes the superclasses'. + private static func propertyNames(properties: [PropertyAccessors], methods: [ObjCImportedContainerRecord.Method]) -> Set { + var names = Set(properties.map(\.property.name)) + for method in methods where !method.selector.contains(":") && !method.typeEncoding.hasPrefix("v") { + names.insert(method.selector) + } + return names + } + + private func propertyAccessors(of properties: [ObjCImportedContainerRecord.Property]) -> [PropertyAccessors] { + properties.map { property in + let attributes = property.attributes.split(separator: ",").map(String.init) + let getterSelector = attributes.first { $0.hasPrefix("G") }.map { String($0.dropFirst()) } ?? property.name + let isReadOnly = attributes.contains("R") + let setterSelector = isReadOnly ? nil : (attributes.first { $0.hasPrefix("S") }.map { String($0.dropFirst()) } ?? "set" + property.name.prefix(1).uppercased() + property.name.dropFirst() + ":") + return PropertyAccessors(property: property, getterSelector: getterSelector, setterSelector: setterSelector) + } + } + + private func propertyMember(_ accessors: PropertyAccessors, isClassMember: Bool, propertyNames: Set) -> ObjCImportedMember? { + let attributes = accessors.property.attributes + guard let type = ObjCTypeEncodingParser.propertyType(fromAttributes: attributes) else { return nil } + let name = ObjCImporterNaming.importedPropertyName(accessors.property.name, attributes: attributes, contextTypeName: contextTypeName, propertyNames: propertyNames) + return ObjCImportedMember( + kind: .property, + selector: accessors.getterSelector, + setterSelector: accessors.setterSelector, + isClassMember: isClassMember, + node: nodes.propertyNode(contextNode: contextNode, name: name, type: type, isClassMember: isClassMember), + typeEncoding: attributes, + ownership: Self.ownership(type: type, attributes: attributes), + hasExplicitSelector: ObjCImportedMemberBuilder.hasExplicitSelector(getterSelector: accessors.getterSelector, propertyName: name, isClassMember: isClassMember), + objcPropertyName: accessors.property.name + ) + } + + private static func ownership(type: ObjCEncodedType, attributes: String) -> ObjCImportedMember.Ownership? { + guard type.isObjectPointer else { return nil } + let attributeCodes = Set(attributes.split(separator: ",").map(String.init)) + if attributeCodes.contains("W") { return .weak } + if attributeCodes.contains("C") { + // `@NSCopying` takes a class type: not `id`, and not a class + // Swift imports as a value type (`copy` `NSString` is a + // plain `String`). + guard case .object(let className?, _) = type, !ObjCBridgedStructures.importsAsNonClassType(className) else { return nil } + return .copy + } + if attributeCodes.contains("&") { return .strong } + // A read-only property records no ownership it was not given. + if attributeCodes.contains("R") { return nil } + return .unownedUnsafe + } + + private func methodMember(_ method: ObjCImportedContainerRecord.Method, isClassMember: Bool, propertyNames: Set, methodSelectors: Set) -> ObjCImportedMember? { + // An adopted protocol's extended encoding names what the method + // list's leaves as `@`. Either has to take one argument per + // colon of the selector, or the names and types would not pair. + let encoding: String + let methodType: ObjCMethodTypeEncoding + if let extendedEncoding = adoptedProtocolEncoding(of: method.selector, isClassMember: isClassMember), + let extendedMethodType = ObjCTypeEncodingParser.methodType(from: extendedEncoding, matchingArgumentsOf: method.selector) { + encoding = extendedEncoding + methodType = extendedMethodType + } else if let plainMethodType = ObjCTypeEncodingParser.methodType(from: method.typeEncoding, matchingArgumentsOf: method.selector) { + encoding = method.typeEncoding + methodType = plainMethodType + } else { + return nil + } + let name = ObjCImporterNaming.importedName( + selector: method.selector, + isClassMethod: isClassMember, + methodType: methodType, + contextTypeName: contextTypeName, + propertyNames: propertyNames, + undoesSwiftInsertedWith: false, + factoryInitializerClassName: contextTypeName + ) + switch name.kind { + case .subscriptSetter: + // Folded into the getter's subscript. + return nil + case .subscriptGetter: + guard let node = nodes.subscriptNode(contextNode: contextNode, methodType: methodType, isClassMember: isClassMember) else { return nil } + let setterSelector = method.selector == "objectAtIndexedSubscript:" ? "setObject:atIndexedSubscript:" : "setObject:forKeyedSubscript:" + return ObjCImportedMember( + kind: .subscript, + selector: method.selector, + setterSelector: methodSelectors.contains(setterSelector) ? setterSelector : nil, + isClassMember: isClassMember, + node: node, + typeEncoding: encoding, + ownership: nil, + hasExplicitSelector: false + ) + case .initializer, .factoryInitializer, .method: + let kind: ObjCImportedMember.Kind = switch name.kind { + case .initializer: .initializer + case .factoryInitializer: .factoryInitializer + default: .method + } + return ObjCImportedMember( + kind: kind, + selector: method.selector, + setterSelector: nil, + isClassMember: isClassMember && kind == .method, + node: nodes.methodNode(contextNode: contextNode, name: name, methodType: methodType, isClassMember: isClassMember), + typeEncoding: encoding, + ownership: nil, + hasExplicitSelector: ObjCImportedMemberBuilder.hasExplicitSelector(method.selector, name: name, isClassMember: isClassMember) + ) + } + } + + /// The extended encoding of `selector` in a protocol the record + /// adopts, or in one those protocols inherit, among the protocol + /// records of the image. + private func adoptedProtocolEncoding(of selector: String, isClassMember: Bool) -> String? { + var visitedRuntimeNames: Set = [] + var pendingRuntimeNames = record.protocolRuntimeNames + while !pendingRuntimeNames.isEmpty { + let runtimeName = pendingRuntimeNames.removeFirst() + guard visitedRuntimeNames.insert(runtimeName).inserted, + let protocolRecord = ObjCImportedContainerIndex.shared.protocolRecord(named: runtimeName, in: machO) + else { continue } + let methodLists = isClassMember + ? [protocolRecord.requiredClassMethods, protocolRecord.optionalClassMethods] + : [protocolRecord.requiredInstanceMethods, protocolRecord.optionalInstanceMethods] + for methods in methodLists { + if let method = methods.first(where: { $0.selector == selector }), let extendedTypeEncoding = method.extendedTypeEncoding { + return extendedTypeEncoding + } + } + pendingRuntimeNames.append(contentsOf: protocolRecord.inheritedProtocolRuntimeNames) + } + return nil + } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberNodes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberNodes.swift new file mode 100644 index 000000000..5cc06cef2 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedMemberNodes.swift @@ -0,0 +1,95 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// The declaration node of an Objective-C member as Swift imports it, shaped +/// like the member symbol the compiler would have demangled to — `Global > +/// Function`, `Global > Static > Getter > Variable`, `Global > Allocator`, +/// `Global > Getter > Subscript` — so the member printers print it as they +/// print any other (evolution proposals `swift-declared-objc-protocols` and +/// `objc-imported-declarations`). Shared by a protocol's requirements and a +/// class's or category's members; `contextNode` is the `Protocol` or `Class` +/// node the member is declared on. +package struct ObjCImportedMemberNodes { + package let types: ObjCImportedTypes + + package init(machO: MachO) { + self.types = ObjCImportedTypes(machO: machO) + } + + /// A property named `name` of type `type`. + package func propertyNode(contextNode: Node, name: String, type: ObjCEncodedType, isClassMember: Bool) -> Node { + let variable = Node.createTransient(kind: .variable, children: [ + contextNode, + Node.createTransient(kind: .identifier, text: name), + types.typeNode(type, position: .topLevel), + ]) + return Self.global(Node.createTransient(kind: .getter, child: variable), isStatic: isClassMember) + } + + /// The subscript `objectAtIndexedSubscript:` or `objectForKeyedSubscript:` + /// imports as; `nil` when the encoding has no index parameter. + package func subscriptNode(contextNode: Node, methodType: ObjCMethodTypeEncoding, isClassMember: Bool) -> Node? { + guard let indexType = methodType.parameterTypes.first else { return nil } + let functionType = Node.createTransient(kind: .functionType, children: [ + Node.createTransient(kind: .argumentTuple, child: types.typeNode(indexType, position: .topLevel)), + Node.createTransient(kind: .returnType, child: types.typeNode(methodType.returnType, position: .topLevel)), + ]) + let subscriptNode = Node.createTransient(kind: .subscript, children: [ + contextNode, + Node.createTransient(kind: .labelList), + Node.createTransient(kind: .type, child: functionType), + ]) + return Self.global(Node.createTransient(kind: .getter, child: subscriptNode), isStatic: isClassMember) + } + + /// A method or an initializer named `name`: an `Allocator` for an + /// initializer — a factory method's included — a `Function` otherwise. + /// An initializer returns `instancetype` of unknown nullability, `init!`. + package func methodNode(contextNode: Node, name: ObjCImporterNaming.ImportedName, methodType: ObjCMethodTypeEncoding, isClassMember: Bool) -> Node { + let isInitializer = name.kind == .initializer || name.kind == .factoryInitializer + var parameterTypes = name.parameterIndices.map { methodType.parameterTypes.indices.contains($0) ? methodType.parameterTypes[$0] : .unknown } + // An initializer with no argument whose first piece goes on past + // `init` (`initForIncrementalLoad`) takes a label but no parameter: + // the importer gives it a `()` one, `init(forIncrementalLoad: ())`. + if parameterTypes.count < name.argumentLabels.count { + parameterTypes += Array(repeating: .void, count: name.argumentLabels.count - parameterTypes.count) + } + let resultType: Node + if isInitializer { + resultType = ObjCImportedTypes.initializerResultTypeNode + } else { + switch name.errorConvention { + case .booleanResult: resultType = types.typeNode(.void, position: .topLevel) + case .nonNilResult: resultType = types.typeNode(methodType.returnType, position: .nonOptional) + case nil: resultType = types.typeNode(methodType.returnType, position: .topLevel) + } + } + var functionTypeChildren: [Node] = [] + if name.errorConvention != nil { + functionTypeChildren.append(Node.createTransient(kind: .throwsAnnotation)) + } + functionTypeChildren.append(Node.createTransient(kind: .argumentTuple, child: ObjCImportedTypes.type(Node.createTransient(kind: .tuple, children: parameterTypes.map { + Node.createTransient(kind: .tupleElement, child: types.typeNode($0, position: .topLevel)) + })))) + functionTypeChildren.append(Node.createTransient(kind: .returnType, child: resultType)) + var declarationChildren: [Node] = [contextNode] + if !isInitializer { + declarationChildren.append(Node.createTransient(kind: .identifier, text: name.baseName)) + } + if !name.argumentLabels.isEmpty { + declarationChildren.append(Node.createTransient(kind: .labelList, children: name.argumentLabels.map { + $0.isEmpty ? Node.createTransient(kind: .firstElementMarker) : Node.createTransient(kind: .identifier, text: $0) + })) + } + declarationChildren.append(Node.createTransient(kind: .type, child: Node.createTransient(kind: .functionType, children: functionTypeChildren))) + let declaration = Node.createTransient(kind: isInitializer ? .allocator : .function, children: declarationChildren) + // An initializer is never a class member, a factory method's included. + return Self.global(declaration, isStatic: isClassMember && !isInitializer) + } + + private static func global(_ declaration: Node, isStatic: Bool) -> Node { + Node.createTransient(kind: .global, child: isStatic ? Node.createTransient(kind: .static, child: declaration) : declaration) + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift new file mode 100644 index 000000000..bd7ee698c --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift @@ -0,0 +1,237 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// The Swift types the importer gives Objective-C types, as `Type` nodes the +/// member printers print (evolution proposals `swift-declared-objc-protocols` +/// and `objc-imported-declarations`): Foundation's bridged classes import as +/// their Swift value types, `id` as `Any`, a block as a closure, a Swift class +/// or protocol by its Swift name. An object type's nullability is not +/// recorded, so it is `T!` — what the importer makes of an unannotated +/// declaration — and `T?` inside a closure's signature, where `!` cannot be +/// written. +package struct ObjCImportedTypes { + /// Where a type appears, which decides how its unknown nullability reads. + package enum Position { + /// A parameter, a result or a property: `T!`. + case topLevel + /// A closure's parameter or result: `T?`, as `!` cannot nest. + case closureComponent + /// A result the error convention proves non-nil. + case nonOptional + } + + /// The image the names are resolved in: a Swift class or protocol is + /// found under the name the Objective-C runtime knows it by. + package let machO: MachO + + package init(machO: MachO) { + self.machO = machO + } + + /// A `Type` node for `type` in `position`. + package func typeNode(_ type: ObjCEncodedType, position: Position) -> Node { + let base = Self.type(bareTypeNode(type)) + guard Self.isNullable(type) else { return base } + switch position { + case .topLevel: return Self.implicitlyUnwrapped(base) + case .closureComponent: return Self.optional(base) + case .nonOptional: return base + } + } + + /// `instancetype`, of unknown nullability, as an initializer's result: + /// `Self!`. + package static var initializerResultTypeNode: Node { + implicitlyUnwrapped(type(Node.createTransient(kind: .dependentGenericParamType, children: [ + Node.createTransient(kind: .index, index: 0), + Node.createTransient(kind: .index, index: 0), + ]))) + } + + private static func isNullable(_ type: ObjCEncodedType) -> Bool { + switch type { + case .object, .block, .objectClass, .characterString: true + case .pointer: true + default: false + } + } + + /// The type itself, unwrapped: what a `Type` node holds. + private func bareTypeNode(_ type: ObjCEncodedType) -> Node { + switch type { + case .void: return Node.createTransient(kind: .tuple) + case .bool: return Self.swiftStructure("Bool") + case .character: return Self.swiftStructure("Int8") + case .unsignedCharacter: return Self.swiftStructure("UInt8") + case .short: return Self.swiftStructure("Int16") + case .unsignedShort: return Self.swiftStructure("UInt16") + case .int, .long: return Self.swiftStructure("Int32") + case .unsignedInt, .unsignedLong: return Self.swiftStructure("UInt32") + case .longLong: return Self.swiftStructure("Int") + case .unsignedLongLong: return Self.swiftStructure("UInt") + case .float: return Self.swiftStructure("Float") + case .double, .longDouble: return Self.swiftStructure("Double") + case .characterString(let isConst): return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [Self.swiftStructure("Int8")]) + case .selector: return Self.structure(module: "ObjectiveC", name: "Selector") + case .objectClass: return Node.createTransient(kind: .typeAlias, children: [Self.module("Swift"), Node.createTransient(kind: .identifier, text: "AnyClass")]) + case .object(let className, let protocolNames): return objectNode(className: className, protocolNames: protocolNames) + case .block(let signature): + guard let signature else { return Self.anyNode } + return Node.createTransient(kind: .functionType, children: [ + Node.createTransient(kind: .argumentTuple, child: Self.type(Node.createTransient(kind: .tuple, children: signature.parameterTypes.map { + Node.createTransient(kind: .tupleElement, child: typeNode($0, position: .closureComponent)) + }))), + Node.createTransient(kind: .returnType, child: typeNode(signature.returnType, position: .closureComponent)), + ]) + case .pointer(let pointee, let isConst): + switch pointee { + case .void: return Self.swiftStructure(isConst ? "UnsafeRawPointer" : "UnsafeMutableRawPointer") + case .unknown, .object, .block, .objectClass, .bitField: return Self.swiftStructure("OpaquePointer") + // ClangImporter imports a pointer to what it cannot represent as + // `OpaquePointer`. + case .array where Self.flattenedElementCount(of: pointee) == nil: return Self.swiftStructure("OpaquePointer") + default: return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [bareTypeNode(pointee)]) + } + case .structure(let name), .union(let name): + guard let name else { return Self.swiftStructure("OpaquePointer") } + return Self.structure(module: objcModule, name: name) + case .array(let count, let element): + // A C array imports as a tuple of its elements, a single element + // as the element itself; one it cannot represent, as nothing. + guard Self.flattenedElementCount(of: type) != nil else { return Self.anyNode } + if count == 1 { return bareTypeNode(element) } + return Node.createTransient(kind: .tuple, children: (0 ..< count).map { _ in + Node.createTransient(kind: .tupleElement, child: Self.type(bareTypeNode(element))) + }) + case .bitField, .unknown: + return Self.anyNode + } + } + + /// ClangImporter imports a C array of at most this many elements, as a + /// tuple, and no longer one (`VisitConstantArrayType`). + static var maximumImportedArrayCount: Int { 4096 } + + /// The most elements nested arrays may flatten to. Each level within + /// ClangImporter's limit still multiplies, and a tuple of tuples past + /// this would take for ever to build and print — what an encoding + /// crafted to do so asks for — so past it the type reads as one the + /// importer cannot represent. + static var maximumFlattenedArrayElementCount: Int { 65_536 } + + /// How many elements `type` flattens to — 1 for anything but an array — + /// or `nil` for an array ClangImporter cannot represent, or one past + /// `maximumFlattenedArrayElementCount`. + static func flattenedElementCount(of type: ObjCEncodedType) -> Int? { + guard case .array(let count, let element) = type else { return 1 } + guard count >= 0, count <= maximumImportedArrayCount, let elementCount = flattenedElementCount(of: element) else { return nil } + let (flattenedCount, overflowed) = count.multipliedReportingOverflow(by: elementCount) + guard !overflowed, flattenedCount <= maximumFlattenedArrayElementCount else { return nil } + return flattenedCount + } + + private func objectNode(className: String?, protocolNames: [String]) -> Node { + let protocols = protocolNames.map { Self.type(ObjCRuntimeNames.protocolNode(forRuntimeName: $0, in: machO)) } + guard let className else { + // `id`, `id

`, `id`. + return Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList, children: protocols)) + } + if !protocols.isEmpty { + // `NSObject

*` imports as `NSObject & P`. + return Node.createTransient(kind: .protocolListWithClass, children: [ + Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList, children: protocols)), + Self.type(ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO)), + ]) + } + if let bridged = ObjCBridgedStructures.structuresByClassName[className] { + return Self.structure(module: bridged.module, name: bridged.name) + } + switch className { + case "NSArray": + return Self.boundGenericStructure(Self.swiftStructure("Array"), arguments: [Self.anyNode]) + case "NSDictionary": + return Self.boundGenericStructure(Self.swiftStructure("Dictionary"), arguments: [Self.swiftStructure("AnyHashable"), Self.anyNode]) + case "NSSet": + return Self.boundGenericStructure(Self.swiftStructure("Set"), arguments: [Self.swiftStructure("AnyHashable")]) + case "NSError": + return Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList, child: Self.type(Node.createTransient(kind: .protocol, children: [Self.module("Swift"), Node.createTransient(kind: .identifier, text: "Error")])))) + default: + return ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO) + } + } + + // MARK: Node shapes + + private static var anyNode: Node { + Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList)) + } + + /// `node` wrapped in a `Type` node, unless it is one. + package static func type(_ node: Node) -> Node { + node.kind == .type ? node : Node.createTransient(kind: .type, child: node) + } + + private static func module(_ name: String) -> Node { + Node.createTransient(kind: .module, text: name) + } + + private static func structure(module moduleName: String, name: String) -> Node { + Node.createTransient(kind: .structure, children: [module(moduleName), Node.createTransient(kind: .identifier, text: name)]) + } + + private static func swiftStructure(_ name: String) -> Node { + structure(module: "Swift", name: name) + } + + private static func boundGenericStructure(_ structure: Node, arguments: [Node]) -> Node { + Node.createTransient(kind: .boundGenericStructure, children: [ + type(structure), + Node.createTransient(kind: .typeList, children: arguments.map(type)), + ]) + } + + private static func optional(_ wrapped: Node, enumName: String = "Optional") -> Node { + type(Node.createTransient(kind: .boundGenericEnum, children: [ + type(Node.createTransient(kind: .enum, children: [module("Swift"), Node.createTransient(kind: .identifier, text: enumName)])), + Node.createTransient(kind: .typeList, child: type(wrapped)), + ])) + } + + private static func implicitlyUnwrapped(_ wrapped: Node) -> Node { + optional(wrapped, enumName: "ImplicitlyUnwrappedOptional") + } +} + +/// The Foundation classes the importer bridges to Swift value types. Kept out +/// of `ObjCImportedTypes`, which is generic and so cannot hold a static +/// stored property. +package enum ObjCBridgedStructures { + /// Whether the importer gives the class a type that is no class: a + /// bridged value type, one of the three collections, or `Error`. + package static func importsAsNonClassType(_ className: String) -> Bool { + structuresByClassName[className] != nil || ["NSArray", "NSDictionary", "NSSet", "NSError"].contains(className) + } + + static let structuresByClassName: [String: (module: String, name: String)] = [ + "NSString": ("Swift", "String"), + "NSURL": ("Foundation", "URL"), + "NSData": ("Foundation", "Data"), + "NSDate": ("Foundation", "Date"), + "NSUUID": ("Foundation", "UUID"), + "NSIndexSet": ("Foundation", "IndexSet"), + "NSIndexPath": ("Foundation", "IndexPath"), + "NSLocale": ("Foundation", "Locale"), + "NSTimeZone": ("Foundation", "TimeZone"), + "NSCalendar": ("Foundation", "Calendar"), + "NSCharacterSet": ("Foundation", "CharacterSet"), + "NSNotification": ("Foundation", "Notification"), + "NSDateComponents": ("Foundation", "DateComponents"), + "NSDateInterval": ("Foundation", "DateInterval"), + "NSURLComponents": ("Foundation", "URLComponents"), + "NSURLQueryItem": ("Foundation", "URLQueryItem"), + "NSURLRequest": ("Foundation", "URLRequest"), + "NSPersonNameComponents": ("Foundation", "PersonNameComponents"), + ] +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImporterNaming.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImporterNaming.swift new file mode 100644 index 000000000..57f9d3469 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImporterNaming.swift @@ -0,0 +1,1030 @@ +import SwiftInspection + +/// The Swift importer's names for Objective-C methods and properties, from +/// what a binary keeps of them: selectors, type encodings, property +/// attributes. Ported for the requirements of an `@objc` protocol declared in +/// Swift (evolution proposal `swift-declared-objc-protocols`) and used for +/// every Objective-C class, category and protocol an interface imports +/// (evolution proposal `objc-imported-declarations`). The binary keeps no +/// Swift name for such a declaration; the name the importer would give it is +/// what the interface prints, with `@objc(selector)` pinning the selector. +/// +/// Ported from the Swift repository: `omitNeedlessWords` and what it calls +/// in `lib/Basic/StringExtras.cpp` (word splitting, parts of speech, +/// splitting the base name at its last preposition, dropping words a +/// parameter's type makes redundant), and from +/// `lib/ClangImporter/ImportName.cpp` the parts it hands over to: the +/// initializer family, factory methods imported as initializers, the +/// subscript accessors, the error convention, property names. Left out: what +/// needs a header the binary does not keep — nullability, default arguments, +/// API notes and `NS_SWIFT_NAME`, enumeration and option set type names, +/// collection element types, parameter names — and the `async` import, which +/// is kept as a completion handler. Measured on AppKit, names from a method +/// list's encodings alone match the SDK's for about four members in five +/// (`objc-imported-declarations`, its measurement section). +/// +/// One step is the library's own, after the importer's: Swift inserts `With` +/// before a first argument label that starts with no preposition +/// (`hangPoints(input:)` → `hangPointsWithInput:`), so a first label +/// starting with `with` and going on drops it (`hangPoints(withInput:)` → +/// `hangPoints(input:)`). +package enum ObjCImporterNaming { + /// The importer's name for one method. + package struct ImportedName: Sendable, Hashable { + package enum Kind: Sendable, Hashable { + case method + case initializer + /// A class method whose selector restates its class's name and + /// that returns an instance (`+colorWithRed:green:blue:alpha:` + /// of `NSColor`), which the importer imports as a convenience + /// initializer (`init(red:green:blue:alpha:)`). + case factoryInitializer + case subscriptGetter + case subscriptSetter + } + + /// How a method following the error convention imports. + package enum ErrorConvention: Sendable, Hashable { + /// `- (BOOL)…error:`: `throws`, returning nothing. + case booleanResult + /// `- (id)…error:`: `throws`, returning the object non-optional. + case nonNilResult + } + + package let kind: Kind + /// `init` for an initializer, `subscript` for a subscript accessor. + package let baseName: String + /// One label per Swift parameter; empty for an unlabeled one. + package let argumentLabels: [String] + /// For each Swift parameter, the index of the Objective-C parameter + /// it imports: the error parameter has none. + package let parameterIndices: [Int] + package let errorConvention: ErrorConvention? + } + + /// The name the importer gives the method `selector` of a protocol whose + /// name is `contextTypeName`. + /// + /// - Parameters: + /// - methodType: the method's extended type encoding, read; the plain + /// one when the record carries no extended one. + /// - propertyNames: the protocol's property names, which keep a type + /// name in a selector from being dropped as redundant. + /// - undoesSwiftInsertedWith: whether to take the library's own step + /// after the importer's; `false` gives the importer's name exactly. + /// - factoryInitializerClassName: the name of the class whose class + /// method this is, to import a factory method as an initializer the + /// way the importer does (`matchFactoryAsInitName`); `nil` for a + /// protocol's method, which never is one. The importer also demands + /// that the method return `instancetype` or the class itself, which a + /// method list's encoding cannot tell from `id`: any object result + /// counts. + package static func importedName( + selector: String, + isClassMethod: Bool, + methodType: ObjCMethodTypeEncoding, + contextTypeName: String, + propertyNames: Set = [], + undoesSwiftInsertedWith: Bool = true, + factoryInitializerClassName: String? = nil + ) -> ImportedName { + let pieces = selectorPieces(selector) + let parameterTypes = methodType.parameterTypes + + if !isClassMethod, let subscriptKind = subscriptKind(of: selector) { + return ImportedName(kind: subscriptKind, baseName: "subscript", argumentLabels: Array(repeating: "", count: parameterTypes.count), parameterIndices: Array(parameterTypes.indices), errorConvention: nil) + } + + let firstPiece = pieces.first ?? selector + var baseName = firstPiece + // A selector without a colon takes no argument. + var argumentNames: [String] = selector.hasSuffix(":") ? [""] + pieces.dropFirst() : [] + var parameterIndices = Array(0 ..< argumentNames.count) + + // `shouldImportAsInitializer`: how much of the first piece names the + // initializer — `init`, or the class name a factory method restates. + var initializerPrefixLength: Int? + var isFactoryInitializer = false + if !isClassMethod, isInitializerFamily(baseName), isObject(methodType.returnType) { + initializerPrefixLength = 4 + } else if isClassMethod, let factoryInitializerClassName, returnsInstance(methodType.returnType, ofClassNamed: factoryInitializerClassName), + let prefixLength = factoryPrefixLength(of: firstPiece, className: factoryInitializerClassName, takesArguments: selector.hasSuffix(":")) { + initializerPrefixLength = prefixLength + isFactoryInitializer = true + } + let isInitializer = initializerPrefixLength != nil + + if let initializerPrefixLength { + baseName = "init" + var argumentName = String(firstPiece.dropFirst(initializerPrefixLength)) + var droppedWith = false + if argumentName.hasPrefix("With") { + argumentName = String(argumentName.dropFirst(4)) + droppedWith = true + } + argumentName = toLowercaseWord(argumentName) + if droppedWith, isSwiftReservedName(argumentName) { + argumentName = "with" + String(firstPiece.dropFirst(initializerPrefixLength + 4)) + } + if argumentNames.isEmpty { + if !argumentName.isEmpty { + argumentNames.append(argumentName) + } + } else { + argumentNames[0] = argumentName + } + } + + // The error convention: a trailing `NSError **`, past any trailing + // blocks, on a method returning `BOOL` or an object. An encoding + // spells every pointer to an object `^@` — `NSDictionary **` too + // (`initWithRTF:documentAttributes:`) — so the selector piece of the + // parameter has to name an error as well. + var errorConvention: ImportedName.ErrorConvention? + if argumentNames.count == parameterTypes.count { + var index = parameterTypes.count + while index > 0 { + index -= 1 + if case .block = parameterTypes[index] { continue } + guard isErrorOutParameter(parameterTypes[index]), index < pieces.count, namesError(pieces[index]) else { break } + switch methodType.returnType { + case .bool: errorConvention = .booleanResult + case .object, .objectClass: errorConvention = .nonNilResult + default: break + } + guard errorConvention != nil else { break } + // Never the first parameter of an initializer. + if !(isInitializer && index == 0) { + if index == 0, argumentNames[0].isEmpty { + for suffix in ["AndReturnError", "WithError"] where baseName.hasSuffix(suffix) { + let strippedBaseName = String(baseName.dropLast(suffix.count)) + if !strippedBaseName.isEmpty, !isSwiftReservedName(strippedBaseName) { + baseName = strippedBaseName + } + break + } + } + argumentNames.remove(at: index) + parameterIndices.remove(at: index) + } + break + } + } + + let omissionParameterTypes = parameterIndices.map { omissionTypeName(of: parameterTypes[$0]) } + let contextType = OmissionTypeName(name: contextTypeName) + // An initializer returns `instancetype`: the context type. + let resultTypeName = isInitializer ? contextType : omissionTypeName(of: methodType.returnType) + omitNeedlessWords( + baseName: &baseName, + argumentNames: &argumentNames, + resultType: resultTypeName, + contextType: contextType, + parameterTypes: omissionParameterTypes, + allPropertyNames: propertyNames + ) + + // The library's own step: undo the `With` Swift inserts before a + // first label that starts with no preposition. + if undoesSwiftInsertedWith, !isInitializer, let firstLabel = argumentNames.first { + let words = Words(firstLabel) + if words.count > 1, words.word(0) == "with" { + argumentNames[0] = toLowercaseInitialisms(toLowercaseWord(words.rest(1))) + } + } + + let kind: ImportedName.Kind = isFactoryInitializer ? .factoryInitializer : isInitializer ? .initializer : .method + return ImportedName(kind: kind, baseName: baseName, argumentLabels: argumentNames, parameterIndices: parameterIndices, errorConvention: errorConvention) + } + + /// The importer's name for a property (`NameImporter::importNameImpl` and + /// the property branch of `omitNeedlessWords`): a `BOOL` property goes by + /// its getter (`hidden` with `getter=isHidden` is `isHidden`), a name + /// restating a result of the context's own type drops it (`NSColor`'s + /// class property `blackColor` is `black`), and a leading initialism is + /// lowercased (`CGPath` is `cgPath`). + /// + /// - Parameters: + /// - propertyName: the name the property list records. + /// - attributes: the property's attribute string (`T@"NSColor",R,N`). + /// - contextTypeName: the name of the class or protocol declaring it. + /// - propertyNames: the names that keep a type name in the property's + /// name from being dropped (`NameImporter::getAllPropertyNames`). + package static func importedPropertyName(_ propertyName: String, attributes: String, contextTypeName: String, propertyNames: Set = []) -> String { + let type = ObjCTypeEncodingParser.propertyType(fromAttributes: attributes) + var baseName = propertyName + // `BOOL` encodes as `B` on arm64 and as `c`, a `signed char`, elsewhere. + if type == .bool || type == .character, + let getter = attributes.split(separator: ",").first(where: { $0.hasPrefix("G") }) { + baseName = String(getter.dropFirst()) + } + var argumentNames: [String] = [] + omitNeedlessWords( + baseName: &baseName, + argumentNames: &argumentNames, + resultType: type.map(omissionTypeName(of:)) ?? OmissionTypeName(name: ""), + contextType: OmissionTypeName(name: contextTypeName), + parameterTypes: [], + allPropertyNames: propertyNames, + isProperty: true + ) + return baseName + } + + // MARK: - Factory methods + + /// Whether the class method's result can be the instance the importer + /// demands of a factory initializer: an object of unknown class (an + /// encoding keeps `instancetype` as `@`) or of the class itself. + private static func returnsInstance(_ returnType: ObjCEncodedType, ofClassNamed className: String) -> Bool { + guard case .object(let returnedClassName, let protocolNames) = returnType, protocolNames.isEmpty else { return false } + return returnedClassName == nil || returnedClassName == className + } + + /// `matchFactoryAsInitName`: how much of the first selector piece + /// restates the class name (`color` of `colorWithRed` in `NSColor`), or + /// `nil` when it restates none of it. A factory method with no argument + /// must restate the first piece whole (`+date` of `NSDate`). + private static func factoryPrefixLength(of firstPiece: String, className: String, takesArguments: Bool) -> Int? { + guard !firstPiece.isEmpty else { return nil } + let firstArgumentLabel = matchLeadingTypeName(firstPiece, typeName: OmissionTypeName(name: className)) + guard firstArgumentLabel.utf8.count != firstPiece.utf8.count else { return nil } + if !firstArgumentLabel.isEmpty, !takesArguments { + return nil + } + return firstPiece.utf8.count - firstArgumentLabel.utf8.count + } + + // MARK: - Selectors + + static func selectorPieces(_ selector: String) -> [String] { + guard selector.hasSuffix(":") else { return [selector] } + return selector.dropLast().split(separator: ":", omittingEmptySubsequences: false).map(String.init) + } + + private static func subscriptKind(of selector: String) -> ImportedName.Kind? { + switch selector { + case "objectAtIndexedSubscript:", "objectForKeyedSubscript:": .subscriptGetter + case "setObject:atIndexedSubscript:", "setObject:forKeyedSubscript:": .subscriptSetter + default: nil + } + } + + /// The `init` method family: `init` alone, or followed by an uppercase + /// letter (`initWithFrame:`), never by a lowercase one (`initialize`). + private static func isInitializerFamily(_ firstPiece: String) -> Bool { + guard firstPiece.hasPrefix("init") else { return false } + let rest = firstPiece.utf8.dropFirst(4) + guard let next = rest.first else { return true } + return !isLowercase(next) + } + + private static func isObject(_ type: ObjCEncodedType) -> Bool { + if case .object = type { return true } + return false + } + + /// `NSError **`, which an encoding spells `^@`. + private static func isErrorOutParameter(_ type: ObjCEncodedType) -> Bool { + if case .pointer(.object, _) = type { return true } + return false + } + + /// Whether a selector piece names the error a method reports through it: + /// its last word is `error` (`error:`, `outError:`, and the first piece + /// `tokenAndReturnError` or `loadWithError`). + private static func namesError(_ selectorPiece: String) -> Bool { + Words(selectorPiece).lastWord.lowercased() == "error" + } + + // MARK: - Omission type names + + /// How a type takes part in omitting needless words + /// (`swift::OmissionTypeName`). + struct OmissionTypeName: Equatable { + var name: String + var collectionElement: String = "" + var isBoolean = false + var isFunction = false + + var isEmpty: Bool { + name.isEmpty + } + } + + /// The importer's name for a type in this role + /// (`getClangTypeNameForOmission`), from what an encoding keeps of it: a + /// Swift class or protocol goes by the Swift name a generated header + /// gives it, `NSInteger` and `NSUInteger` by their typedef names — which + /// is what Swift's `Int` and `UInt` are exported as. + static func omissionTypeName(of type: ObjCEncodedType) -> OmissionTypeName { + switch type { + case .void: return OmissionTypeName(name: "Void") + case .bool: return OmissionTypeName(name: "Bool", isBoolean: true) + case .character: return OmissionTypeName(name: "Int8") + case .unsignedCharacter: return OmissionTypeName(name: "UInt8") + case .short: return OmissionTypeName(name: "Int16") + case .unsignedShort: return OmissionTypeName(name: "UInt16") + case .int, .long: return OmissionTypeName(name: "Int32") + case .unsignedInt, .unsignedLong: return OmissionTypeName(name: "UInt32") + case .longLong: return OmissionTypeName(name: "NSInteger") + case .unsignedLongLong: return OmissionTypeName(name: "NSUInteger") + case .float: return OmissionTypeName(name: "Float") + case .double: return OmissionTypeName(name: "Double") + case .selector: return OmissionTypeName(name: "Selector") + case .objectClass: return OmissionTypeName(name: "Class") + case .block: return OmissionTypeName(name: "Block", isFunction: true) + // `^?`: a function pointer. + case .pointer(.unknown, _): return OmissionTypeName(name: "Function", isFunction: true) + case .pointer(let pointee, _): return omissionTypeName(of: pointee) + case .structure(let name), .union(let name): + // The tag of `struct _NSRange` is what the encoding keeps; the + // importer goes by the typedef, `NSRange`. + guard let name else { return OmissionTypeName(name: "") } + return OmissionTypeName(name: name.hasPrefix("_") ? String(name.dropFirst()) : name) + case .array(_, let element): + return OmissionTypeName(name: "Array", collectionElement: omissionTypeName(of: element).name) + case .object(let className, let protocolNames): + // `id` and `NSObject` go by the protocol. + if protocolNames.count == 1, className == nil || className == "NSObject" { + return OmissionTypeName(name: swiftName(ofProtocolRuntimeName: protocolNames[0])) + } + guard let className else { + return OmissionTypeName(name: protocolNames.isEmpty ? "Object" : "") + } + let name = swiftName(ofClassRuntimeName: className) + let lastWord = Words(name).lastWord + guard lastWord == "Array" || lastWord == "Set" else { return OmissionTypeName(name: name) } + // Foundation's collections are generic, and with no type + // arguments the element is `Object`; another collection's + // element is the class name before its last word. + if name.hasPrefix("NS") { + return OmissionTypeName(name: name, collectionElement: "Object") + } + return OmissionTypeName(name: name, collectionElement: String(name.dropLast(lastWord.count))) + case .characterString, .longDouble, .bitField, .unknown: + return OmissionTypeName(name: "") + } + } + + /// `DVTTeamCredentialComponents` for `_TtC13DVTFoundation27DVTTeamCredentialComponents`. + private static func swiftName(ofClassRuntimeName runtimeName: String) -> String { + guard runtimeName.hasPrefix("_Tt"), let qualifiedName = NodeTypeNaming.swiftClassQualifiedName(fromRuntimeName: runtimeName) else { return runtimeName } + return qualifiedName.split(separator: ".").last.map(String.init) ?? runtimeName + } + + private static func swiftName(ofProtocolRuntimeName runtimeName: String) -> String { + guard let qualifiedName = SwiftDeclaredObjCProtocolIndex.qualifiedName(ofDefaultRuntimeName: runtimeName) else { return runtimeName } + return qualifiedName.split(separator: ".").last.map(String.init) ?? runtimeName + } + + // MARK: - omitNeedlessWords + + enum NameRole { + case baseName + case firstParameter + case subsequentParameter + case property + case partial + } + + /// `swift::omitNeedlessWords`, for a method not imported as `async` whose + /// parameters take no default arguments (inferring those needs + /// nullability), or for a property (`isProperty`, with no parameters). + static func omitNeedlessWords( + baseName: inout String, + argumentNames: inout [String], + resultType: OmissionTypeName, + contextType: OmissionTypeName, + parameterTypes: [OmissionTypeName], + allPropertyNames: Set?, + isProperty: Bool = false + ) { + defer { + baseName = toLowercaseInitialisms(baseName) + argumentNames = argumentNames.map(toLowercaseInitialisms) + } + + // A result matching the context drops the context's name from the + // front of the base name. + let resultTypeMatchesContext = resultType == contextType + if resultTypeMatchesContext { + baseName = omitNeedlessWordsFromPrefix(baseName, type: contextType) + } + + // Only a method's base name loses the context type's name. + if !isProperty { + baseName = omitSelfTypeFromBaseName(baseName, typeName: contextType, allPropertyNames: allPropertyNames) + } + + if parameterTypes.isEmpty { + if resultTypeMatchesContext { + baseName = omitTrailingTypeName(baseName, typeName: resultType, role: .property, allPropertyNames: allPropertyNames) + } + return + } + + if Words(baseName).firstWord == "set" { + baseName = omitTrailingTypeName(baseName, typeName: contextType, role: .property, allPropertyNames: allPropertyNames) + } + + if !argumentNames.isEmpty { + splitBaseName(&baseName, argumentName: &argumentNames[0], parameterType: parameterTypes[0]) + } + + for index in argumentNames.indices where index < parameterTypes.count { + let role: NameRole = index > 0 ? .subsequentParameter + : argumentNames[0].isEmpty ? .baseName + : baseName == "init" ? .subsequentParameter + : .firstParameter + let name = role == .baseName ? baseName : argumentNames[index] + let newName = omitTrailingTypeName(name, typeName: parameterTypes[index], role: role, allPropertyNames: role == .baseName ? allPropertyNames : nil) + guard newName != name else { continue } + if role == .baseName { + baseName = newName + } else { + argumentNames[index] = newName + } + } + } + + // MARK: Splitting the base name + + /// `splitBaseName`. The importer also leaves an action method (a + /// parameter named `sender`) unsplit; a binary keeps no parameter names. + static func splitBaseName(_ baseName: inout String, argumentName: inout String, parameterType: OmissionTypeName) { + guard argumentName.isEmpty else { return } + let words = Words(baseName) + if parameterType.isBoolean, words.lastWord == "Animated" { + baseName = String(baseName.dropLast("Animated".count)) + argumentName = "animated" + return + } + if words.firstWord == "set" { + return + } + splitBaseNameAfterLastPreposition(&baseName, argumentName: &argumentName, parameterType: parameterType) + } + + private static func splitBaseNameAfterLastPreposition(_ baseName: inout String, argumentName: inout String, parameterType: OmissionTypeName) { + let words = Words(baseName) + guard var prepositionIndex = lastPrepositionIndex(in: words, from: words.count - 1) else { return } + var preposition = words.word(prepositionIndex) + + if prepositionIndex > 0, wordConflictsBeforePreposition(words.word(prepositionIndex - 1), preposition: preposition) { + return + } + if prepositionIndex + 1 < words.count, wordConflictsAfterPreposition(words.word(prepositionIndex + 1), preposition: preposition) { + return + } + + let prepositionEnd = words.end(of: prepositionIndex) + if prepositionIndex > 0, priorWordExtendsPreposition(words.word(prepositionIndex - 1), preposition: preposition) { + prepositionIndex -= 1 + preposition = words.slice(from: words.start(of: prepositionIndex), to: prepositionEnd) + } + let prepositionStart = words.start(of: prepositionIndex) + + let beforePreposition = words.slice(from: 0, to: prepositionStart) + let afterPreposition = words.slice(from: prepositionEnd, to: words.length) + let dropsPreposition = isVacuousPreposition(beforePreposition, preposition: preposition, afterPreposition: afterPreposition, parameterType: parameterType) + let placesPrepositionOnArgumentLabel = !(afterPreposition == "X" || afterPreposition == "Y" || afterPreposition == "Z") + + var startOfArgumentLabel = placesPrepositionOnArgumentLabel ? prepositionStart : prepositionEnd + var endOfBaseName = startOfArgumentLabel + if dropsPreposition { + if placesPrepositionOnArgumentLabel { + startOfArgumentLabel += preposition.utf8.count + } else { + endOfBaseName -= preposition.utf8.count + } + } + guard endOfBaseName > 0 else { return } + + // A base name that would be a keyword or a vacuous word needs more + // than one word after it — two for a vacuous one. + let newBaseName = words.slice(from: 0, to: endOfBaseName) + let newWords = Words(newBaseName) + let firstWord = newWords.firstWord + let isVacuous = isVacuousName(firstWord) + if !canBeMemberName(firstWord) || isVacuous { + if newWords.count == 1 { return } + if newWords.count == 2, isVacuous { return } + } + + argumentName = words.slice(from: startOfArgumentLabel, to: words.length) + baseName = newBaseName + } + + /// `findLastPreposition`: the last preposition, except that an `of` + /// defers to an earlier preposition other than `of` and `for`. + private static func lastPrepositionIndex(in words: Words, from start: Int, isRecursive: Bool = false) -> Int? { + guard start >= 0 else { return nil } + guard let index = stride(from: start, through: 0, by: -1).first(where: { partOfSpeech(words.word($0)) == .preposition }) else { return nil } + if !isRecursive, sameWordIgnoringFirstCase(words.word(index), "of"), + let previous = lastPrepositionIndex(in: words, from: index - 1, isRecursive: true), + !sameWordIgnoringFirstCase(words.word(previous), "of"), !sameWordIgnoringFirstCase(words.word(previous), "for") { + return previous + } + return index + } + + private static func wordConflictsBeforePreposition(_ word: String, preposition: String) -> Bool { + sameWordIgnoringFirstCase(preposition, "in") && sameWordIgnoringFirstCase(word, "plug") + } + + private static func wordConflictsAfterPreposition(_ word: String, preposition: String) -> Bool { + if sameWordIgnoringFirstCase(preposition, "with"), sameWordIgnoringFirstCase(word, "error") || sameWordIgnoringFirstCase(word, "no") { + return true + } + if sameWordIgnoringFirstCase(preposition, "to"), sameWordIgnoringFirstCase(word, "visible") || sameWordIgnoringFirstCase(word, "backing") { + return true + } + if sameWordIgnoringFirstCase(preposition, "from"), sameWordIgnoringFirstCase(word, "backing") { + return true + } + return false + } + + private static func priorWordExtendsPreposition(_ preceding: String, preposition: String) -> Bool { + let extendedPrepositions: [(String, String)] = [ + ("compatible", "with"), ("best", "matching"), ("according", "to"), ("bound", "by"), ("separated", "by"), + ] + return extendedPrepositions.contains { sameWordIgnoringFirstCase(preceding, $0.0) && sameWordIgnoringFirstCase(preposition, $0.1) } + } + + /// A `with` or `using` before a block parameter says nothing; one before + /// `Zone` does. + private static func isVacuousPreposition(_ beforePreposition: String, preposition: String, afterPreposition: String, parameterType: OmissionTypeName) -> Bool { + guard sameWordIgnoringFirstCase(preposition, "with") || sameWordIgnoringFirstCase(preposition, "using") else { return false } + if sameWordIgnoringFirstCase(preposition, "with"), sameWordIgnoringFirstCase(Words(afterPreposition).firstWord, "zone") { + return false + } + return parameterType.isFunction + } + + // MARK: Dropping redundant type names + + static func omitTrailingTypeName(_ name: String, typeName: OmissionTypeName, role: NameRole, allPropertyNames: Set?) -> String { + guard !name.isEmpty, !typeName.isEmpty else { return name } + let words = Words(name) + let matchIndex = matchTypeNameFromBack(words, typeName: typeName, allPropertyNames: allPropertyNames) + if matchIndex == words.count { + return name + } + if matchIndex == 0 { + return role == .partial || role == .firstParameter ? "" : name + } + if matchIndex + 1 == words.count, words.word(matchIndex) == "Error" { + return name + } + + let previousWord = words.word(matchIndex - 1) + switch role { + case .property: + break + case .firstParameter, .partial, .subsequentParameter: + if partOfSpeech(previousWord) == .unknown { + return name + } + case .baseName: + switch partOfSpeech(previousWord) { + case .preposition: + if matchIndex - 1 == 0 { + return name + } + case .verb, .gerund: + if textMatchesPropertyName(words.rest(matchIndex), allPropertyNames: allPropertyNames) { + return name + } + case .unknown: + return name + } + } + + let newName = words.prior(matchIndex) + if role == .baseName || role == .property { + if !canBeMemberName(newName) || isVacuousName(newName) { + return name + } + } + return newName + } + + /// The index of the first word of `words` matching the end of + /// `typeName`, `words.count` when none does + /// (`matchTypeNameFromBackWithSpecialCases`). + static func matchTypeNameFromBack(_ words: Words, typeName originalTypeName: OmissionTypeName, allPropertyNames: Set?) -> Int { + var typeName = originalTypeName + var typeWords = Words(typeName.name) + // Each index is one past the word compared next. + var nameIndex = words.count + var typeIndex = typeWords.count + + while nameIndex > 0, typeIndex > 0 { + let nameWord = words.word(nameIndex - 1) + let typeWord = typeWords.word(typeIndex - 1) + if matchNameWordToTypeWord(nameWord, typeWord) { + nameIndex -= 1 + typeIndex -= 1 + continue + } + + // "Indexes" and "Indices" in the name match "IndexSet". + if matchNameWordToTypeWord(nameWord, "Indexes") || matchNameWordToTypeWord(nameWord, "Indices"), typeWord == "Set", + typeIndex >= 2, matchNameWordToTypeWord("Index", typeWords.word(typeIndex - 2)) { + nameIndex -= 1 + typeIndex -= 2 + continue + } + + // "Index" in the name matches "Int" or "Integer". + if matchNameWordToTypeWord(nameWord, "Index"), matchNameWordToTypeWord("Int", typeWord) || matchNameWordToTypeWord("Integer", typeWord) { + nameIndex -= 1 + typeIndex -= 1 + continue + } + + // "ObjectValue" in the name matches "Object". + if matchNameWordToTypeWord("Object", typeWord), matchNameWordToTypeWord(nameWord, "Value"), + nameIndex >= 2, matchNameWordToTypeWord(words.word(nameIndex - 2), "Object") { + nameIndex -= 2 + typeIndex -= 1 + continue + } + + // A plural of the collection's element. + if !typeName.collectionElement.isEmpty, nameWord.utf8.count > 2, nameWord.hasSuffix("s") { + let shortened = String(words.prior(nameIndex).dropLast()) + let newShortened = omitTrailingTypeName(shortened, typeName: OmissionTypeName(name: typeName.collectionElement), role: .partial, allPropertyNames: allPropertyNames) + if shortened != newShortened, let newIndex = words.index(startingAt: newShortened.utf8.count) { + nameIndex = newIndex + continue + } + } + + // A droppable suffix of the type, before any word matched. + if nameIndex == words.count, let withoutSuffix = skipTypeSuffix(typeName.name) { + typeName.name = withoutSuffix + typeWords = Words(withoutSuffix) + typeIndex = typeWords.count + continue + } + break + } + return nameIndex + } + + /// `omitSelfTypeFromBaseName`: the context type's name, wherever it sits + /// in the base name after a verb (`dismissViewControllerAnimated` in a + /// view controller gives `dismissAnimated`). + static func omitSelfTypeFromBaseName(_ name: String, typeName originalTypeName: OmissionTypeName, allPropertyNames: Set?) -> String { + guard !name.isEmpty, !originalTypeName.isEmpty else { return name } + var typeName = originalTypeName + typeName.collectionElement = "" + let words = Words(name) + + var matchingRange: (start: Int, end: Int)? + var wordIndex = words.count - 1 + while wordIndex >= 0 { + let prefixWords = Words(words.prior(wordIndex + 1)) + let matchIndex = matchTypeNameFromBack(prefixWords, typeName: typeName, allPropertyNames: allPropertyNames) + let matchStart = words.index(startingAt: prefixWords.start(of: matchIndex)) ?? (wordIndex + 1) + if matchStart != wordIndex + 1 { + matchingRange = (matchStart, wordIndex + 1) + break + } + while let withoutSuffix = skipTypeSuffix(typeName.name) { + typeName.name = withoutSuffix + } + wordIndex -= 1 + } + + guard let range = matchingRange, range.start != 0 else { return name } + if range.end == words.count, range.start + 1 == words.count, words.word(range.start) == "Error" { + return name + } + guard partOfSpeech(words.word(range.start - 1)) == .verb else { return name } + + // The importer measures the removed text from the match's start with + // the match's end as a length; ported as it is. + let removedStart = words.start(of: range.start) + let removedText = words.slice(from: removedStart, to: min(words.length, removedStart + words.start(of: range.end))) + if textMatchesPropertyName(removedText, allPropertyNames: allPropertyNames) { + return name + } + + let newName = words.prior(range.start) + words.rest(range.end) + guard canBeMemberName(newName), !isVacuousName(newName) else { return name } + return newName + } + + /// `omitNeedlessWordsFromPrefix`: the type's name at the front of the + /// name, when what follows starts with a preposition. + static func omitNeedlessWordsFromPrefix(_ name: String, type: OmissionTypeName) -> String { + guard !type.isEmpty else { return name } + let newName = matchLeadingTypeName(name, typeName: type) + guard newName != name else { return name } + let newWords = Words(newName) + let firstWord = newWords.firstWord + guard partOfSpeech(firstWord) == .preposition, newName.utf8.count > firstWord.utf8.count else { return name } + // "By" followed by a gerund goes too. + if firstWord == "By", newWords.count > 1, newWords.word(1).hasSuffix("ing") { + return newWords.rest(1) + } + return newName + } + + private static func matchLeadingTypeName(_ name: String, typeName: OmissionTypeName) -> String { + let nameWords = Words(name) + let typeWords = Words(typeName.name) + guard nameWords.count > 0, typeWords.count > 0 else { return name } + // The last word of the type name matching the name's first word. + guard let typeStart = stride(from: typeWords.count - 1, through: 0, by: -1).first(where: { matchNameWordToTypeWord(nameWords.word(0), typeWords.word($0)) }) else { return name } + // From there to the end of the type name, word by word. + var nameIndex = 1 + var typeIndex = typeStart + 1 + while typeIndex < typeWords.count, nameIndex < nameWords.count, matchNameWordToTypeWord(typeWords.word(typeIndex), nameWords.word(nameIndex)) { + typeIndex += 1 + nameIndex += 1 + } + guard typeIndex == typeWords.count else { return name } + return nameWords.rest(nameIndex) + } + + /// `matchNameWordToTypeWord`, as the importer writes it. + static func matchNameWordToTypeWord(_ nameWord: String, _ typeWord: String) -> Bool { + let name = Array(nameWord.utf8) + let type = Array(typeWord.utf8) + if name.count > type.count { return false } + if name.count < type.count { + // A suffix of the type, past an acronym prefix (`NS` in `NSURL`). + if typeWord.lowercased().hasSuffix(nameWord.lowercased()), !isLowercase(type[type.count - name.count]) { + for index in 0 ..< name.count where isLowercase(type[index]) || type[index] == UInt8(ascii: "_") { + return false + } + return true + } + // A prefix of the type, followed by digits only. + if typeWord.lowercased().hasPrefix(nameWord.lowercased()) { + return type[name.count...].allSatisfy(isDigit) + } + return false + } + return nameWord.lowercased() == typeWord.lowercased() + } + + /// `skipTypeSuffix`: `Type`, `Ref`, `Mask`, a dimension (`3D`), `_t`. + static func skipTypeSuffix(_ typeName: String) -> String? { + guard !typeName.isEmpty else { return nil } + let lastWord = Words(typeName).lastWord + let length = typeName.utf8.count + if lastWord == "Type", length > 4 { return String(typeName.dropLast(4)) } + if lastWord == "Ref", length > 3 { return String(typeName.dropLast(3)) } + if lastWord == "Mask", length > 4 { return String(typeName.dropLast(4)) } + let bytes = Array(typeName.utf8) + if bytes.last == UInt8(ascii: "D"), length > 1 { + var firstDigit = length - 1 + while firstDigit > 0, isDigit(bytes[firstDigit - 1]) { + firstDigit -= 1 + } + if firstDigit < length - 1 { + return String(decoding: bytes[.. 2, typeName.hasSuffix("_t") { return String(typeName.dropLast(2)) } + return nil + } + + private static func textMatchesPropertyName(_ text: String, allPropertyNames: Set?) -> Bool { + guard let allPropertyNames, !text.isEmpty else { return false } + let name = toLowercaseWord(text) + if allPropertyNames.contains(name) { return true } + if name.hasSuffix("y") { + return allPropertyNames.contains(String(name.dropLast()) + "ies") + } + return allPropertyNames.contains(name + "s") || allPropertyNames.contains(name + "es") + } + + // MARK: - Words + + /// The importer's camel-case words (`camel_case::WordIterator`): a run + /// of capitals is one word (an acronym) up to the capital that starts the + /// next word, a plural `s` after an acronym belongs to it, and `_` is a + /// word of its own. + struct Words { + let bytes: [UInt8] + /// The start of every word, then the end of the string. + let boundaries: [Int] + + init(_ string: String) { + self.bytes = Array(string.utf8) + var boundaries = [0] + var position = 0 + while position < bytes.count { + position = Self.nextPosition(in: bytes, from: position) + boundaries.append(position) + } + self.boundaries = bytes.isEmpty ? [0] : boundaries + } + + var count: Int { + boundaries.count - 1 + } + + var length: Int { + bytes.count + } + + func start(of index: Int) -> Int { + boundaries[index] + } + + func end(of index: Int) -> Int { + boundaries[index + 1] + } + + func word(_ index: Int) -> String { + slice(from: boundaries[index], to: boundaries[index + 1]) + } + + /// The text before word `index`. + func prior(_ index: Int) -> String { + slice(from: 0, to: boundaries[index]) + } + + /// The text from word `index` on. + func rest(_ index: Int) -> String { + slice(from: boundaries[index], to: bytes.count) + } + + func slice(from start: Int, to end: Int) -> String { + String(decoding: bytes[start ..< end], as: UTF8.self) + } + + /// The word starting at byte offset `position`. + func index(startingAt position: Int) -> Int? { + boundaries.firstIndex(of: position) + } + + var firstWord: String { + count > 0 ? word(0) : "" + } + + var lastWord: String { + count > 0 ? word(count - 1) : "" + } + + private static func nextPosition(in bytes: [UInt8], from position: Int) -> Int { + let count = bytes.count + var index = position + if bytes[index] == UInt8(ascii: "_") { + return index + 1 + } + while index < count, isUppercase(bytes[index]) { + index += 1 + } + if index - position > 1 { + // An acronym ends before its last capital when a lowercase + // word follows (`URLLoader`), after it otherwise (`UTF8`), + // and takes a plural suffix along (`URLs`, but not `Is`). + var endOfNext = index + while endOfNext < count, isLowercase(bytes[endOfNext]) { + endOfNext += 1 + } + let followingLowercase = String(decoding: bytes[index ..< endOfNext], as: UTF8.self) + let lastCapitalAndFollowing = String(decoding: bytes[(index - 1) ..< endOfNext], as: UTF8.self) + if index == count || (isPluralSuffix(followingLowercase) && lastCapitalAndFollowing != "Is") { + return endOfNext + } else if isLowercase(bytes[index]) { + return index - 1 + } else { + return index + } + } + while index < count, !isUppercase(bytes[index]), bytes[index] != UInt8(ascii: "_") { + index += 1 + } + return index + } + + private static func isPluralSuffix(_ word: String) -> Bool { + word == "s" || word == "es" || word == "ies" + } + } + + // MARK: - Parts of speech + + enum PartOfSpeech { + case unknown + case preposition + case verb + case gerund + } + + /// `getPartOfSpeech`, from the importer's word lists. + static func partOfSpeech(_ word: String) -> PartOfSpeech { + let lowercased = word.lowercased() + if ObjCMemberShape.prepositions.contains(lowercased) { return .preposition } + if verbs.contains(lowercased) { return .verb } + + // A gerund ends in "ing" after a verb: `sorting`, `making`, `running`. + if lowercased.hasSuffix("ing"), lowercased.count > 4 { + let possibleVerb = String(lowercased.dropLast(3)) + if partOfSpeech(possibleVerb) == .verb { return .gerund } + if !possibleVerb.hasSuffix("e"), partOfSpeech(possibleVerb + "e") == .verb { return .gerund } + let characters = Array(possibleVerb) + if characters.count >= 2, characters[characters.count - 1] == characters[characters.count - 2], partOfSpeech(String(possibleVerb.dropLast())) == .verb { + return .gerund + } + } + // "auto", "re" and "de" prefix verbs. + for prefix in ["auto", "re", "de"] where lowercased.hasPrefix(prefix) && lowercased.count > prefix.count { + if partOfSpeech(String(lowercased.dropFirst(prefix.count))) == .verb { return .verb } + } + return .unknown + } + + // MARK: - Small rules + + private static func isVacuousName(_ name: String) -> Bool { + ["get", "for", "set", "using", "with"].contains { sameWordIgnoringFirstCase(name, $0) } + } + + private static func canBeMemberName(_ identifier: String) -> Bool { + !["init", "Protocol", "self", "Type"].contains(identifier) + } + + /// An identifier the lexer reads as a keyword. + private static func isSwiftReservedName(_ name: String) -> Bool { + swiftKeywords.contains(name) + } + + private static let swiftKeywords: Set = [ + "associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import", "init", "inout", + "internal", "let", "operator", "precedencegroup", "private", "protocol", "public", "rethrows", "static", + "struct", "subscript", "typealias", "var", "break", "case", "catch", "continue", "default", "defer", "do", + "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "throw", "switch", "where", "while", + "Any", "as", "false", "is", "nil", "self", "Self", "super", "throws", "true", "try", "_", + ] + + private static func sameWordIgnoringFirstCase(_ word: String, _ other: String) -> Bool { + guard word.utf8.count == other.utf8.count, let first = word.first, let otherFirst = other.first else { return false } + return first.lowercased() == otherFirst.lowercased() && word.dropFirst() == other.dropFirst() + } + + /// `camel_case::toLowercaseWord`: the first letter lowercased, unless + /// it starts an acronym. + static func toLowercaseWord(_ string: String) -> String { + let bytes = Array(string.utf8) + guard let first = bytes.first, isUppercase(first) else { return string } + if bytes.count > 1, isUppercase(bytes[1]) { return string } + return String(decoding: [first + 32] + bytes.dropFirst(), as: UTF8.self) + } + + /// `camel_case::toLowercaseInitialisms`: a leading acronym lowercased + /// (`URLForResource` → `urlForResource`, `UTF8String` → `utf8String`). + static func toLowercaseInitialisms(_ string: String) -> String { + let bytes = Array(string.utf8) + guard let first = bytes.first, isUppercase(first) else { return string } + var result: [UInt8] = [] + result.reserveCapacity(bytes.count) + var index = 0 + while index < bytes.count { + if index < bytes.count - 1, !isUppercase(bytes[index + 1]) { + let restWord = Words(String(decoding: bytes[(index + 1)...], as: UTF8.self)).firstWord + if index == 0 || !isLetter(bytes[index + 1]) || ["s", "es", "ies"].contains(restWord) { + result.append(lowercased(bytes[index])) + index += 1 + } + result.append(contentsOf: bytes[index...]) + return String(decoding: result, as: UTF8.self) + } + result.append(lowercased(bytes[index])) + index += 1 + } + return String(decoding: result, as: UTF8.self) + } + + // MARK: - ASCII classes, as clang's CharInfo has them + + private static func isUppercase(_ byte: UInt8) -> Bool { + byte >= UInt8(ascii: "A") && byte <= UInt8(ascii: "Z") + } + + private static func isLowercase(_ byte: UInt8) -> Bool { + byte >= UInt8(ascii: "a") && byte <= UInt8(ascii: "z") + } + + private static func isDigit(_ byte: UInt8) -> Bool { + byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9") + } + + private static func isLetter(_ byte: UInt8) -> Bool { + isUppercase(byte) || isLowercase(byte) + } + + private static func lowercased(_ byte: UInt8) -> UInt8 { + isUppercase(byte) ? byte + 32 : byte + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImporterVerbs.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImporterVerbs.swift new file mode 100644 index 000000000..7f9e0ab4a --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImporterVerbs.swift @@ -0,0 +1,88 @@ +/// The verbs the Swift importer knows (`VERB` entries of `lib/Basic/PartsOfSpeech.def` +/// in the Swift repository, copied verbatim): `ObjCImporterNaming` tells verbs apart +/// from nouns with them, as `getPartOfSpeech` does, when it decides whether a +/// type name in a selector is redundant (evolution proposal +/// `swift-declared-objc-protocols`). +extension ObjCImporterNaming { + static let verbs: Set = [ + "abbreviate", "accept", "activate", "add", "adjust", "admire", "admit", "advise", "afford", "agree", + "alert", "allow", "alter", "amuse", "analyse", "analyze", "animate", "announce", "annoy", "answer", + "apologise", "appear", "append", "applaud", "apply", "apportion", "appreciate", "approve", "argue", "arrange", + "arrest", "arrive", "ask", "assign", "attach", "attack", "attempt", "attend", "attract", "avoid", + "awake", "back", "bake", "balance", "ban", "bang", "bare", "bat", "bathe", "battle", + "be", "beat", "become", "beg", "begin", "behave", "belong", "bend", "bet", "bid", + "bite", "bleach", "bless", "blind", "blink", "blot", "blow", "blush", "boast", "boil", + "bolt", "bomb", "book", "bore", "borrow", "bounce", "bow", "box", "brake", "branch", + "break", "breathe", "bring", "broadcast", "bruise", "brush", "bubble", "build", "bump", "burn", + "bury", "buy", "buzz", "calculate", "call", "camp", "cancel", "capture", "care", "carry", + "carve", "cast", "catch", "cause", "center", "challenge", "change", "charge", "chase", "cheat", + "check", "cheer", "chew", "choke", "choose", "chop", "claim", "clap", "clean", "clear", + "click", "close", "coach", "coil", "collect", "collapse", "colour", "comb", "come", "command", + "commit", "communicate", "compare", "compete", "complain", "complete", "concentrate", "concern", "confess", "confuse", + "connect", "consider", "consist", "contain", "contains", "continue", "convert", "copy", "correct", "cough", + "cost", "count", "cover", "crack", "crash", "crawl", "cross", "crush", "cry", "cure", + "curl", "curve", "customize", "cut", "cycle", "dam", "damage", "dance", "dare", "decay", + "deceive", "decide", "decode", "decorate", "defer", "define", "delay", "delete", "delight", "deliver", + "depend", "describe", "deselect", "desert", "deserve", "destroy", "detach", "detect", "develop", "dig", + "dim", "disagree", "disappear", "disapprove", "disarm", "discover", "dislike", "dismiss", "display", "divide", + "do", "double", "doubt", "drag", "drain", "draw", "dream", "dress", "drink", "drip", + "drive", "drop", "drown", "drum", "dry", "duplicate", "dust", "earn", "eat", "echo", + "edit", "educate", "embarrass", "employ", "empty", "enable", "encode", "encourage", "end", "enjoy", + "enter", "entertain", "enumerate", "enqueue", "escape", "examine", "excite", "excuse", "execute", "exercise", + "exist", "expand", "expect", "explain", "explode", "export", "extend", "face", "fade", "fail", + "fancy", "fasten", "fax", "fear", "feel", "fence", "fetch", "fight", "fill", "film", + "find", "finish", "fire", "fit", "fix", "flap", "flash", "flatten", "flip", "float", + "flood", "flow", "flower", "fly", "focus", "fold", "follow", "fool", "force", "forget", + "forgive", "form", "found", "freeze", "frighten", "fry", "gain", "gather", "gaze", "generate", + "get", "give", "glow", "glue", "go", "grab", "grate", "grease", "greet", "grin", + "grip", "groan", "grow", "guarantee", "guard", "guess", "guide", "hammer", "hand", "handle", + "hang", "happen", "harass", "harm", "hate", "haunt", "head", "heal", "heap", "hear", + "heat", "help", "hide", "highlight", "hit", "hold", "hook", "hop", "hope", "hover", + "hug", "hum", "hunt", "hurry", "hurt", "identify", "ignore", "imagine", "import", "impress", + "improve", "include", "increase", "influence", "inform", "inject", "injure", "insert", "instruct", "intend", + "interest", "interfere", "interrupt", "intersect", "intersects", "introduce", "invent", "invite", "irritate", "itch", + "jail", "jam", "jog", "join", "joke", "judge", "juggle", "jump", "keep", "kick", + "kill", "kiss", "kneel", "knit", "knock", "knot", "know", "label", "land", "last", + "laugh", "launch", "lay", "lead", "learn", "leave", "lend", "let", "level", "license", + "lick", "lie", "lighten", "like", "listen", "live", "load", "localize", "lock", "long", + "look", "lose", "love", "maintain", "make", "man", "manage", "march", "mark", "marry", + "match", "mate", "matter", "mean", "measure", "meddle", "meet", "melt", "memorise", "mend", + "merge", "mess", "milk", "mine", "miss", "minus", "mix", "moan", "moor", "mourn", + "move", "muddle", "mug", "multiply", "murder", "nail", "nest", "nod", "normalize", "note", + "notice", "notify", "number", "obey", "observe", "obtain", "occur", "offend", "offer", "open", + "order", "overflow", "owe", "own", "pack", "paddle", "paint", "park", "part", "pass", + "paste", "pat", "pause", "pay", "peck", "pedal", "peel", "peep", "perform", "permit", + "phone", "pick", "pinch", "pine", "place", "plan", "plant", "play", "please", "plug", + "poke", "polish", "pop", "possess", "post", "pour", "practice", "practise", "pray", "preach", + "precede", "prefer", "preload", "prepare", "prepend", "present", "preserve", "press", "pretend", "prevent", + "prick", "print", "produce", "program", "promise", "protect", "provide", "pull", "pump", "punch", + "puncture", "punish", "push", "put", "question", "queue", "race", "radiate", "rain", "raise", + "reach", "read", "realise", "receive", "recognise", "record", "reduce", "reflect", "refuse", "register", + "regret", "reign", "reject", "rejoice", "relax", "release", "rely", "remain", "remember", "remind", + "remove", "repair", "repeat", "replace", "reply", "report", "request", "require", "resize", "rescue", + "resolve", "retain", "retire", "return", "reverse", "review", "rhyme", "ride", "ring", "rinse", + "rise", "risk", "rob", "rock", "roll", "rot", "rub", "ruin", "rule", "run", + "rush", "sack", "sail", "satisfy", "save", "saw", "say", "scale", "scare", "scatter", + "scold", "scorch", "scrape", "scratch", "scream", "screw", "scribble", "scroll", "scrub", "seal", + "search", "see", "select", "sell", "send", "separate", "serve", "settle", "shade", "share", + "shave", "shelter", "shiver", "shock", "shop", "show", "shrug", "shut", "sigh", "sign", + "signal", "sin", "sing", "sip", "sit", "ski", "skip", "slap", "sleep", "slip", + "slow", "smash", "smell", "smile", "smoke", "snatch", "sneeze", "sniff", "snore", "snow", + "soak", "soothe", "sound", "spare", "spark", "sparkle", "speak", "spell", "spend", "spill", + "spoil", "spot", "spray", "sprout", "squash", "squeak", "squeal", "squeeze", "stain", "stamp", + "stand", "standardise", "standardize", "stare", "start", "stay", "steer", "step", "stir", "stitch", + "stop", "store", "strap", "strengthen", "stretch", "strip", "stroke", "stuff", "subtract", "succeed", + "suck", "suffer", "suggest", "suit", "supply", "support", "suppose", "suppress", "surprise", "surround", + "suspect", "suspend", "swim", "switch", "take", "talk", "tame", "tap", "taste", "teach", + "tear", "tease", "telephone", "tell", "tempt", "terrify", "test", "thank", "thaw", "think", + "throw", "tick", "tickle", "tie", "time", "tip", "tire", "toggle", "touch", "tour", + "tow", "trace", "trade", "train", "translate", "transform", "transport", "trap", "travel", "traverse", + "treat", "tremble", "trick", "trip", "trot", "trouble", "truncate", "trust", "try", "tug", + "tumble", "turn", "twist", "understand", "undress", "unfasten", "union", "unite", "unload", "unlock", + "unpack", "untidy", "up", "update", "use", "validate", "vanish", "visit", "wail", "wait", + "wake", "walk", "wander", "want", "warm", "warn", "wash", "waste", "watch", "water", + "wave", "wear", "weigh", "welcome", "whine", "whip", "whirl", "whisper", "whistle", "win", + "wink", "wipe", "wish", "wobble", "wonder", "work", "worry", "wrap", "wreck", "wrestle", + "wriggle", "write", "yawn", "yell", "zip", "zoom", + ] +} diff --git a/Sources/Analysis/SwiftInspection/ObjCMember.swift b/Sources/Analysis/SwiftObjCInterop/ObjCMember.swift similarity index 100% rename from Sources/Analysis/SwiftInspection/ObjCMember.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCMember.swift diff --git a/Sources/Analysis/SwiftInspection/ObjCMemberShape.swift b/Sources/Analysis/SwiftObjCInterop/ObjCMemberShape.swift similarity index 90% rename from Sources/Analysis/SwiftInspection/ObjCMemberShape.swift rename to Sources/Analysis/SwiftObjCInterop/ObjCMemberShape.swift index 876dec74f..cfb3fc29a 100644 --- a/Sources/Analysis/SwiftInspection/ObjCMemberShape.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCMemberShape.swift @@ -1,5 +1,6 @@ import Foundation @_spi(Internals) import Demangling +import SwiftInspection /// The shape of a Swift member as far as its ObjC selector is concerned /// (evolution proposals `objc-ancestor-override-recovery` and @@ -177,6 +178,44 @@ public struct ObjCMemberShape: Sendable, Hashable { } } + // MARK: - NS_REFINED_FOR_SWIFT + + /// What the importer puts in front of the Swift name of a member a header + /// marks `NS_REFINED_FOR_SWIFT` (`SwiftPrivate` in API notes). + public static let refinedForSwiftPrefix = "__" + + /// The shape with the importer's `NS_REFINED_FOR_SWIFT` prefix taken off + /// the name it goes on — a property's name, a method's base name, an + /// initializer's first argument label — or `nil` when that name does not + /// carry it. An `@objc @implementation` body implements such a member + /// under the prefixed name (`__layerFilter` answers `layerFilter`), so + /// matching a selector against this shape is the importer's rule for it + /// (evolution proposal `swift-first-imported-declarations`). + public var removingRefinedForSwiftPrefix: ObjCMemberShape? { + func unprefixed(_ name: String) -> String? { + guard name.hasPrefix(Self.refinedForSwiftPrefix), name.count > Self.refinedForSwiftPrefix.count else { return nil } + return String(name.dropFirst(Self.refinedForSwiftPrefix.count)) + } + let unprefixedKind: Kind + switch kind { + case .getter(let propertyName): + guard let name = unprefixed(propertyName) else { return nil } + unprefixedKind = .getter(propertyName: name) + case .setter(let propertyName): + guard let name = unprefixed(propertyName) else { return nil } + unprefixedKind = .setter(propertyName: name) + case .method(let baseName, let labels, let arity): + guard let name = unprefixed(baseName) else { return nil } + unprefixedKind = .method(baseName: name, labels: labels, arity: arity) + case .initializer(let labels, let arity): + guard let firstLabel = labels.first ?? nil, let label = unprefixed(firstLabel) else { return nil } + unprefixedKind = .initializer(labels: [label] + labels.dropFirst(), arity: arity) + case .subscriptGetter, .subscriptSetter: + return nil + } + return ObjCMemberShape(kind: unprefixedKind, isStatic: isStatic, ownerQualifiedName: ownerQualifiedName, isThrowing: isThrowing, isAsync: isAsync) + } + private static func piecesMatch(_ pieces: [String], baseName: String, labels: [String?], arity: Int, skippingLeadingWith: Bool) -> Bool { guard pieces.count == arity, let firstPiece = pieces.first, firstPiece.hasPrefix(baseName) else { return false } for index in 0 ..< arity { diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift new file mode 100644 index 000000000..ea8895205 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift @@ -0,0 +1,284 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Core) import MachOObjCSection +@_spi(Internals) import MachOCaches +@_spi(Internals) import SwiftInspection + +/// The Objective-C protocols one Swift class of the image adopts in its own +/// class data (evolution proposal `swift-declared-objc-protocols`). An +/// `@objc` protocol has no witness table, so the compiler emits no +/// conformance record for it; what records the conformance is Objective-C +/// metadata. The compiler lists the protocols a declaration names in the +/// protocol list of the class data it emits for it (`GenClass.cpp`'s +/// `visitConformances`, over `getLocalConformances(.OnlyExplicit)`) — and it +/// folds the extensions the class's own module declares into the class's +/// own data, so `class_ro_t` lists theirs too. A non-`@objc` protocol a +/// declaration names contributes the `@objc` protocols it inherits +/// (`getObjCProtocols`). +package struct ObjCProtocolAdoption: Sendable, Hashable { + /// The class's runtime name. + package let classRuntimeName: String + /// The class's Swift qualified name, the key a declaration looks its + /// adoption up by; `nil` when the runtime name names no Swift class. + package let swiftClassQualifiedName: String? + /// The protocols the class's `class_ro_t` lists, by runtime name. + package let declaredProtocolRuntimeNames: [String] + /// The listed protocols a Swift protocol the class conforms to inherits: + /// the compiler lists those too, so they say nothing the Swift + /// conformance does not. Known for the image's own Swift protocols only — + /// another image's requirement signature is not read. + package let impliedProtocolRuntimeNames: Set +} + +/// The Objective-C protocols one of the image's categories lists: an +/// extension the image declares of a class another module declares — an +/// Objective-C class, or a Swift class of another module — since one of the +/// class's own module is folded into the class's data. +package struct ObjCCategoryProtocolAdoption: Sendable, Hashable { + /// The category's offset in the image. + package let offset: Int + /// The extended class's runtime name. + package let classRuntimeName: String + /// The protocols the category lists, by runtime name. + package let protocolRuntimeNames: [String] + /// Those a Swift protocol the image conforms the class to inherits, as + /// for ``ObjCProtocolAdoption/impliedProtocolRuntimeNames``. + package let impliedProtocolRuntimeNames: Set +} + +/// Per-image index of the Objective-C protocols the image adopts: the ones +/// each Swift class of `__objc_classlist` and each without a class object +/// (`SwiftClassWithoutClassObjectIndex`) lists in its own class data, and +/// the ones each category lists. A category on a class with resilient +/// ancestry targets the class's stub, whose name the reader cannot read, +/// and is missed. +/// +/// Built once per image, lazily, and evicted with the other ObjC-side +/// per-image state. +package final class ObjCProtocolAdoptionIndex: @unchecked Sendable { + package static let shared = ObjCProtocolAdoptionIndex() + + private let cache = SharedCache(evictionGroup: .objcHierarchy) + + private init() {} + + package final class Storage: @unchecked Sendable { + /// Class-list order, then the classes without a class object. + let adoptions: [ObjCProtocolAdoption] + + /// Category-list order; only the categories that list a protocol. + let categoryAdoptions: [ObjCCategoryProtocolAdoption] + + /// Keyed by Swift qualified name; a name several classes print as + /// (same-named private classes) keys none of them. + let adoptionsBySwiftClassQualifiedName: [String: ObjCProtocolAdoption] + + /// Protocol runtime name → the runtime names of the classes adopting + /// it directly: the image's classes in the order of `adoptions`, then + /// the classes its categories extend. + let adopterClassRuntimeNamesByProtocolRuntimeName: [String: [String]] + + init(adoptions: [ObjCProtocolAdoption], categoryAdoptions: [ObjCCategoryProtocolAdoption]) { + self.adoptions = adoptions + self.categoryAdoptions = categoryAdoptions + var adoptionsBySwiftClassQualifiedName: [String: ObjCProtocolAdoption] = [:] + var ambiguousQualifiedNames: Set = [] + var adopterClassRuntimeNamesByProtocolRuntimeName: [String: [String]] = [:] + func noteAdopter(_ classRuntimeName: String, of protocolRuntimeNames: [String]) { + for protocolRuntimeName in Set(protocolRuntimeNames) where adopterClassRuntimeNamesByProtocolRuntimeName[protocolRuntimeName]?.contains(classRuntimeName) != true { + adopterClassRuntimeNamesByProtocolRuntimeName[protocolRuntimeName, default: []].append(classRuntimeName) + } + } + for adoption in adoptions { + if let qualifiedName = adoption.swiftClassQualifiedName, + adoptionsBySwiftClassQualifiedName.updateValue(adoption, forKey: qualifiedName) != nil { + ambiguousQualifiedNames.insert(qualifiedName) + } + noteAdopter(adoption.classRuntimeName, of: adoption.declaredProtocolRuntimeNames) + } + for categoryAdoption in categoryAdoptions { + noteAdopter(categoryAdoption.classRuntimeName, of: categoryAdoption.protocolRuntimeNames) + } + for qualifiedName in ambiguousQualifiedNames { + adoptionsBySwiftClassQualifiedName[qualifiedName] = nil + } + self.adoptionsBySwiftClassQualifiedName = adoptionsBySwiftClassQualifiedName + self.adopterClassRuntimeNamesByProtocolRuntimeName = adopterClassRuntimeNamesByProtocolRuntimeName + } + } + + package func storage(in machO: some MachORepresentableWithCache) -> Storage? { + cache.storage(in: machO) { machO in + machO.objcImplementationClassReader.map { Self.build(in: $0) } + } + } + + package func contains(in machO: some MachORepresentableWithCache) -> Bool { + cache.contains(in: machO) + } + + package func remove(for machO: some MachORepresentableWithCache) { + cache.remove(for: machO) + } + + // MARK: - Queries + + /// What the Swift class whose qualified name is `qualifiedName` adopts in + /// its own class data; `nil` when the image defines no such class, or + /// several print as that name. + package func adoption(ofSwiftClassQualifiedName qualifiedName: String, in machO: some MachORepresentableWithCache) -> ObjCProtocolAdoption? { + storage(in: machO)?.adoptionsBySwiftClassQualifiedName[qualifiedName] + } + + /// The image's categories that list a protocol, in category-list order. + package func categoryAdoptions(in machO: some MachORepresentableWithCache) -> [ObjCCategoryProtocolAdoption] { + storage(in: machO)?.categoryAdoptions ?? [] + } + + /// The runtime names of the classes adopting the protocol directly: the + /// image's Swift classes in class-list order, then the classes its + /// categories extend. + package func adopterClassRuntimeNames(ofProtocolRuntimeName protocolRuntimeName: String, in machO: some MachORepresentableWithCache) -> [String] { + storage(in: machO)?.adopterClassRuntimeNamesByProtocolRuntimeName[protocolRuntimeName] ?? [] + } + + // MARK: - Build + + private static func build(in machO: MachO) -> Storage { + var classRuntimeNames: [String] = [] + var declaredProtocolsByClass: [String: [String]] = [:] + var qualifiedNamesByClass: [String: String] = [:] + for classObject in machO.objcImplementationClassObjects() ?? [] where classObject.isSwift { + guard let readOnlyData = machO.instanceReadOnlyData(of: classObject), + let className = machO.className(of: readOnlyData), !className.isEmpty, + declaredProtocolsByClass[className] == nil + else { continue } + classRuntimeNames.append(className) + declaredProtocolsByClass[className] = machO.protocolNames(of: readOnlyData) + qualifiedNamesByClass[className] = ObjCRuntimeNames.swiftClassNode(forRuntimeName: className, in: machO).flatMap(NodeTypeNaming.nominalQualifiedName(of:)) + } + for swiftClass in SwiftClassWithoutClassObjectIndex.shared.classes(in: machO) where declaredProtocolsByClass[swiftClass.name] == nil { + guard let readOnlyData = swiftClass.readOnlyData(in: machO) else { continue } + classRuntimeNames.append(swiftClass.name) + declaredProtocolsByClass[swiftClass.name] = machO.protocolNames(of: readOnlyData) + qualifiedNamesByClass[swiftClass.name] = swiftClass.qualifiedName + } + + var categories: [(offset: Int, classRuntimeName: String, protocolRuntimeNames: [String])] = [] + for category in machO.objcCategories() ?? [] { + guard let targetClassName = machO.targetClassName(of: category), !targetClassName.isEmpty else { continue } + let protocolNames = machO.protocolNames(of: category) + if !protocolNames.isEmpty { + categories.append((category.offset, targetClassName, protocolNames)) + } + } + + // The classes implied protocols are looked for on: the image's own by + // qualified name, the ones its categories extend by runtime name. + var classKeys: Set = [] + for className in classRuntimeNames where !(declaredProtocolsByClass[className] ?? []).isEmpty { + if let qualifiedName = qualifiedNamesByClass[className] { + classKeys.insert(.swift(qualifiedName: qualifiedName)) + } + } + for category in categories { + classKeys.insert(classKey(ofRuntimeName: category.classRuntimeName, qualifiedNamesByClass: qualifiedNamesByClass)) + } + let impliedProtocolsByClass = impliedProtocolRuntimeNames(ofClasses: classKeys, in: machO) + + let adoptions = classRuntimeNames.map { className in + let qualifiedName = qualifiedNamesByClass[className] + return ObjCProtocolAdoption( + classRuntimeName: className, + swiftClassQualifiedName: qualifiedName, + declaredProtocolRuntimeNames: declaredProtocolsByClass[className] ?? [], + impliedProtocolRuntimeNames: qualifiedName.flatMap { impliedProtocolsByClass[.swift(qualifiedName: $0)] } ?? [] + ) + } + let categoryAdoptions = categories.map { category in + ObjCCategoryProtocolAdoption( + offset: category.offset, + classRuntimeName: category.classRuntimeName, + protocolRuntimeNames: category.protocolRuntimeNames, + impliedProtocolRuntimeNames: impliedProtocolsByClass[classKey(ofRuntimeName: category.classRuntimeName, qualifiedNamesByClass: qualifiedNamesByClass)] ?? [] + ) + } + return Storage(adoptions: adoptions, categoryAdoptions: categoryAdoptions) + } + + /// A class as a conformance record names it: a Swift class by its + /// descriptor, read as its qualified name; an Objective-C class by its + /// runtime name. + private enum ClassKey: Hashable { + case swift(qualifiedName: String) + case objc(runtimeName: String) + } + + private static func classKey(ofRuntimeName runtimeName: String, qualifiedNamesByClass: [String: String]) -> ClassKey { + if let qualifiedName = qualifiedNamesByClass[runtimeName] ?? NodeTypeNaming.swiftClassQualifiedName(fromRuntimeName: runtimeName) { + return .swift(qualifiedName: qualifiedName) + } + return .objc(runtimeName: runtimeName) + } + + /// For each class of `classKeys`, the Objective-C protocols the image's + /// own Swift protocols it conforms to inherit, at any depth. A + /// conformance to a protocol without such an ancestor is skipped before + /// its type is named, which is most of them. + private static func impliedProtocolRuntimeNames(ofClasses classKeys: Set, in machO: some MachOSwiftSectionRepresentableWithCache) -> [ClassKey: Set] { + guard !classKeys.isEmpty, let conformances = try? machO.swift.protocolConformances else { return [:] } + var inheritedByProtocolOffset: [Int: Set] = [:] + var impliedByClass: [ClassKey: Set] = [:] + for conformance in conformances { + guard case .element(let protocolDescriptor)? = conformance.protocol else { continue } + let inherited = inheritedObjCProtocolRuntimeNames(of: protocolDescriptor, cache: &inheritedByProtocolOffset, in: machO) + guard !inherited.isEmpty, let classKey = classKey(of: conformance.typeReference, in: machO), classKeys.contains(classKey) else { continue } + impliedByClass[classKey, default: []].formUnion(inherited) + } + return impliedByClass + } + + private static func classKey(of typeReference: ResolvedTypeReference, in machO: some MachOSwiftSectionRepresentableWithCache) -> ClassKey? { + switch typeReference { + case .directTypeDescriptor(.type(.class(let classDescriptor))?): + guard let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machO.context), + let qualifiedName = NodeTypeNaming.nominalQualifiedName(of: contextNode) + else { return nil } + return .swift(qualifiedName: qualifiedName) + case .directObjCClassName(let runtimeName?): + return .objc(runtimeName: runtimeName) + case .indirectObjCClass(.symbol(let symbol)?): + let prefix = "_OBJC_CLASS_$_" + guard symbol.name.hasPrefix(prefix) else { return nil } + return .objc(runtimeName: String(symbol.name.dropFirst(prefix.count))) + default: + return nil + } + } + + /// The Objective-C protocols a Swift protocol of the image inherits, + /// directly or through the image's other Swift protocols; memoized per + /// descriptor, which also ends a cycle. + private static func inheritedObjCProtocolRuntimeNames(of descriptor: ProtocolDescriptor, cache: inout [Int: Set], in machO: some MachOSwiftSectionRepresentableWithCache) -> Set { + if let cached = cache[descriptor.offset] { return cached } + cache[descriptor.offset] = [] + guard let protocolType = try? MachOSwiftSection.`Protocol`(descriptor: descriptor, in: machO.context) else { return [] } + var names: Set = [] + // `Self`'s protocol requirements are the inherited protocols. + for requirement in protocolType.requirementInSignatures where requirement.paramManagledName.rawString == "x" { + guard case .protocol(.element(let reference)) = requirement.content else { continue } + switch reference { + case .objc(let objcProtocol): + if let name = try? objcProtocol.name(in: machO.context) { + names.insert(name) + } + case .swift(let inheritedDescriptor): + names.formUnion(inheritedObjCProtocolRuntimeNames(of: inheritedDescriptor, cache: &cache, in: machO)) + } + } + cache[descriptor.offset] = names + return names + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRecord.swift b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRecord.swift new file mode 100644 index 000000000..fadda5ffa --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRecord.swift @@ -0,0 +1,233 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Core) import MachOObjCSection + +/// An Objective-C protocol record (`protocol_t`) as `__objc_protolist` lists +/// it, read in full. For an `@objc` protocol declared in Swift this is all the +/// binary keeps of its requirements: the compiler emits no Swift protocol +/// descriptor for it, and no Swift symbol for any requirement (evolution +/// proposal `swift-declared-objc-protocols`). +package struct ObjCProtocolRecord: Sendable, Hashable { + package struct Method: Sendable, Hashable { + package let selector: String + /// The method list's type encoding (`@24@0:8@16`). + package let typeEncoding: String + /// The extended encoding, which names classes, protocols and block + /// signatures (`@"NSString"24@0:8@"NSString"16`); `nil` when the + /// record carries none. + package let extendedTypeEncoding: String? + } + + package struct Property: Sendable, Hashable { + package let name: String + /// The property attribute string (`T@"NSString",R,N`). + package let attributes: String + } + + package let offset: Int + /// The name the Objective-C runtime registers: `_TtP_` for + /// a Swift protocol the source did not rename, the `@objc(Name)` name for + /// one it did, the plain name for a protocol declared in Objective-C. + package let runtimeName: String + package let flags: UInt32 + /// The runtime names of the protocols this one inherits. + package let inheritedProtocolRuntimeNames: [String] + package let requiredInstanceMethods: [Method] + package let requiredClassMethods: [Method] + package let optionalInstanceMethods: [Method] + package let optionalClassMethods: [Method] + package let instanceProperties: [Property] + package let classProperties: [Property] + + /// Bit 0 of the flags (`ProtocolDescriptorFlags::IsSwift`): the Swift + /// compiler emitted this record. It says which compiler wrote the record, + /// not which image defines the protocol: Swift emits a copy of every + /// Swift `@objc` protocol an image references, and clang emits one with + /// the bit clear when Objective-C code references a Swift protocol + /// through a generated `-Swift.h` header. Only the low bits are the + /// compiler's; the runtime and dyld set bits 29–31. + package var isEmittedBySwift: Bool { + flags & 1 != 0 + } + + /// Every method of the four lists, in the order the extended method + /// types array follows. + package var allMethods: [Method] { + requiredInstanceMethods + requiredClassMethods + optionalInstanceMethods + optionalClassMethods + } +} + +// MARK: - Reading + +extension ObjCProtocolRecord { + /// Where `protocol_t` keeps the pointer to its extended method types. + private static let extendedMethodTypesFieldOffset = MemoryLayout.offset(of: \ObjCProtocol64.Layout._extendedMethodTypes)! + + /// The four method lists' entries before the extended types join them: + /// required instance, required class, optional instance, optional class. + typealias RawMethodLists = [[(selector: String, typeEncoding: String)]] + + static func make( + offset: Int, + runtimeName: String, + flags: UInt32, + recordSize: UInt32, + inheritedProtocolRuntimeNames: [String], + methodLists: RawMethodLists, + instanceProperties: [Property], + classProperties: [Property], + in machO: some MachORepresentableWithCache & Readable + ) -> ObjCProtocolRecord { + let methodCount = methodLists.reduce(0) { $0 + $1.count } + var extendedTypeEncodings = extendedMethodTypes(ofRecordAt: offset, recordSize: recordSize, methodCount: methodCount, in: machO) + // The array follows every method of the four lists in order, so a + // list the reader could not read moves every later method onto + // another method's encoding. Each slot has to describe its method's + // signature, or none is used. + if let encodings = extendedTypeEncodings, + !zip(methodLists.joined(), encodings).allSatisfy({ describeTheSameSignature(extended: $1, plain: $0.typeEncoding) }) { + extendedTypeEncodings = nil + } + var slot = 0 + let lists: [[Method]] = methodLists.map { list in + list.map { entry in + defer { slot += 1 } + return Method(selector: entry.selector, typeEncoding: entry.typeEncoding, extendedTypeEncoding: extendedTypeEncodings?[slot]) + } + } + return ObjCProtocolRecord( + offset: offset, + runtimeName: runtimeName, + flags: flags, + inheritedProtocolRuntimeNames: inheritedProtocolRuntimeNames, + requiredInstanceMethods: lists[0], + requiredClassMethods: lists[1], + optionalInstanceMethods: lists[2], + optionalClassMethods: lists[3], + instanceProperties: instanceProperties, + classProperties: classProperties + ) + } + + /// Whether an extended method encoding is the one the compiler wrote for + /// the method whose method-list encoding is `plain`: the same types, once + /// the class and protocol names and block signatures only the extended + /// one spells are set aside. Either one not parsing tells nothing. + private static func describeTheSameSignature(extended: String, plain: String) -> Bool { + guard let extendedMethodType = ObjCTypeEncodingParser.methodType(from: extended), + let plainMethodType = ObjCTypeEncodingParser.methodType(from: plain) + else { return true } + return extendedMethodType.returnType.withoutExtendedNames == plainMethodType.returnType.withoutExtendedNames + && extendedMethodType.parameterTypes.map(\.withoutExtendedNames) == plainMethodType.parameterTypes.map(\.withoutExtendedNames) + } + + /// The extended method types, one per method. MachOObjCSection's + /// `extendedMethodTypes(in:)` reads only the array's first element, so + /// the array is walked here. Each slot is a pointer like the field that + /// leads to it, resolved through the reader's rebase in a file and read + /// directly in process — the same path every absolute pointer of this + /// library takes, in all three offset accountings. `nil` when the record + /// is too short to carry the field, carries none, or a slot is null or + /// unreadable: a partial array would misalign every later method. + private static func extendedMethodTypes(ofRecordAt offset: Int, recordSize: UInt32, methodCount: Int, in machO: some MachORepresentableWithCache & Readable) -> [String]? { + guard methodCount > 0, Int(recordSize) >= extendedMethodTypesFieldOffset + MemoryLayout.size else { return nil } + let context = machO.context + do { + let arrayPointer = try RawPointer.resolve(at: context.addressFromOffset(offset + extendedMethodTypesFieldOffset), in: context) + guard arrayPointer.address != 0 else { return nil } + let arrayAddress = try arrayPointer.resolveAddress(in: context) + var encodings: [String] = [] + encodings.reserveCapacity(methodCount) + for index in 0 ..< methodCount { + let slotAddress = context.advanceAddress(arrayAddress, by: index * MemoryLayout.size) + let encodingPointer = try Pointer.resolve(at: slotAddress, in: context) + guard encodingPointer.address != 0 else { return nil } + encodings.append(try encodingPointer.resolve(in: context)) + } + return encodings + } catch { + return nil + } + } +} + +extension MachOFile { + /// `__objc_protolist`, every record read in full. + func objcProtocolRecords() -> [ObjCProtocolRecord] { + guard let objcProtocols = objc.protocols64 else { return [] } + return objcProtocols.map { objcProtocolRecord(of: $0) } + } + + private func objcProtocolRecord(of objcProtocol: ObjCProtocol64) -> ObjCProtocolRecord { + let methodLists: ObjCProtocolRecord.RawMethodLists = [ + objcProtocol.instanceMethodList(in: self), + objcProtocol.classMethodList(in: self), + objcProtocol.optionalInstanceMethodList(in: self), + objcProtocol.optionalClassMethodList(in: self), + ].map { methodList in + guard let methodList, !methodList.isListOfLists, let methods = methodList.methods(in: self) else { return [] } + return methods.map { (selector: $0.name, typeEncoding: $0.types) } + } + var inheritedProtocolRuntimeNames: [String] = [] + if let protocolList = objcProtocol.protocolList(in: self), !protocolList.isListOfLists, let protocols = protocolList.protocols(in: self) { + inheritedProtocolRuntimeNames = protocols.map { $1.mangledName(in: $0) } + } + return ObjCProtocolRecord.make( + offset: objcProtocol.offset, + runtimeName: objcProtocol.mangledName(in: self), + flags: objcProtocol.flags, + recordSize: objcProtocol.size, + inheritedProtocolRuntimeNames: inheritedProtocolRuntimeNames, + methodLists: methodLists, + instanceProperties: properties(of: objcProtocol.instancePropertyList(in: self)), + classProperties: properties(of: objcProtocol.classPropertyList(in: self)), + in: self + ) + } + + private func properties(of propertyList: ObjCPropertyList?) -> [ObjCProtocolRecord.Property] { + guard let propertyList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: self).map { .init(name: $0.name, attributes: $0.attributes) } + } +} + +extension MachOImage { + /// `__objc_protolist`, every record read in full. + func objcProtocolRecords() -> [ObjCProtocolRecord] { + guard let objcProtocols = objc.protocols64 else { return [] } + return objcProtocols.map { objcProtocolRecord(of: $0) } + } + + private func objcProtocolRecord(of objcProtocol: ObjCProtocol64) -> ObjCProtocolRecord { + let methodLists: ObjCProtocolRecord.RawMethodLists = [ + objcProtocol.instanceMethodList(in: self), + objcProtocol.classMethodList(in: self), + objcProtocol.optionalInstanceMethodList(in: self), + objcProtocol.optionalClassMethodList(in: self), + ].map { methodList in + guard let methodList, !methodList.isListOfLists else { return [] } + return methodList.methods(in: self).map { (selector: $0.name, typeEncoding: $0.types) } + } + var inheritedProtocolRuntimeNames: [String] = [] + if let protocolList = objcProtocol.protocolList(in: self), !protocolList.isListOfLists, let protocols = protocolList.protocols(in: self) { + inheritedProtocolRuntimeNames = protocols.map { $1.mangledName(in: $0) } + } + return ObjCProtocolRecord.make( + offset: objcProtocol.offset, + runtimeName: objcProtocol.mangledName(in: self), + flags: objcProtocol.flags, + recordSize: objcProtocol.size, + inheritedProtocolRuntimeNames: inheritedProtocolRuntimeNames, + methodLists: methodLists, + instanceProperties: properties(of: objcProtocol.instancePropertyList(in: self)), + classProperties: properties(of: objcProtocol.classPropertyList(in: self)), + in: self + ) + } + + private func properties(of propertyList: ObjCPropertyList?) -> [ObjCProtocolRecord.Property] { + guard let propertyList, !propertyList.isListOfLists else { return [] } + return propertyList.properties(in: self).map { .init(name: $0.name, attributes: $0.attributes) } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRequirements.swift b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRequirements.swift new file mode 100644 index 000000000..86a4d6805 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolRequirements.swift @@ -0,0 +1,235 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// One requirement of an `@objc` protocol declared in Swift, as a Swift +/// declaration (evolution proposal `swift-declared-objc-protocols`). The +/// binary keeps no Swift symbol for it; the declaration is built from the +/// protocol's Objective-C record by the importer's rules, shaped like the +/// member symbol the compiler would have demangled to, so the member +/// printers print it as they print any other. Its Swift name may differ +/// from the source's: the printer pins the selector with `@objc(selector)`. +package struct ObjCProtocolRequirement: Sendable { + package enum Kind: Sendable, Hashable { + case method + case initializer + case property + case `subscript` + } + + package let kind: Kind + /// The selector the runtime sends: a method's, a property's or a + /// subscript's getter. + package let selector: String + /// A property's or subscript's setter; `nil` when it is read-only. + package let setterSelector: String? + package let isClassMember: Bool + package let isOptional: Bool + /// The declaration, shaped like a demangled member symbol: `Global > + /// Function`, `Global > Static > Getter > Variable`, `Global > Allocator`, + /// `Global > Getter > Subscript`. + package let node: Node + /// What the declaration was built from: the method's type encoding + /// (extended when the record carries one), or the property's attributes. + package let typeEncoding: String + /// Whether the compiler would derive a selector other than `selector` + /// from the Swift name the declaration prints — what an imported + /// protocol pins with `@objc(selector)` (evolution proposal + /// `objc-imported-declarations`). A protocol declared in Swift pins + /// every requirement named from its selector instead. + package let hasExplicitSelector: Bool + + package var isSettable: Bool { + setterSelector != nil + } + + package init(kind: Kind, selector: String, setterSelector: String?, isClassMember: Bool, isOptional: Bool, node: Node, typeEncoding: String, hasExplicitSelector: Bool) { + self.kind = kind + self.selector = selector + self.setterSelector = setterSelector + self.isClassMember = isClassMember + self.isOptional = isOptional + self.node = node + self.typeEncoding = typeEncoding + self.hasExplicitSelector = hasExplicitSelector + } +} + +/// Builds the requirements of an `@objc` protocol declared in Swift from its +/// Objective-C record: every method and property of the four method lists +/// and two property lists, in record order — which is the source's order +/// within each list — with a property or subscript where its getter is. +/// +/// Names follow `ObjCImporterNaming`; a property keeps the name its record +/// carries, which is the Swift name unless the source renamed it. Types +/// follow the importer too (`ObjCImportedTypes`), and the declarations take +/// the shapes `ObjCImportedMemberNodes` gives every imported member. +package enum ObjCProtocolRequirementBuilder { + /// The language a protocol was declared in, which decides how its + /// requirements are named. + package enum DeclaringLanguage: Sendable { + /// An `@objc` protocol declared in Swift: a property keeps the name + /// its record carries — the Swift name — and a method's first label + /// loses the `With` Swift inserts into the selector it derives. + case swift + /// A protocol declared in Objective-C: every name is the importer's. + case objectiveC + } + + /// The requirements of `record`, declared on `protocolNode` (a + /// `Protocol` node, as the protocol's mangled name demangles to). + package static func requirements(of record: ObjCProtocolRecord, protocolNode: Node, declaredIn declaringLanguage: DeclaringLanguage = .swift, in machO: some MachOSwiftSectionRepresentableWithCache) -> [ObjCProtocolRequirement] { + let builder = Builder(protocolNode: protocolNode, record: record, declaringLanguage: declaringLanguage, machO: machO) + return builder.requirements() + } + + private struct Builder { + let protocolNode: Node + let record: ObjCProtocolRecord + let declaringLanguage: DeclaringLanguage + let contextTypeName: String + let propertyNames: Set + let nodes: ObjCImportedMemberNodes + + init(protocolNode: Node, record: ObjCProtocolRecord, declaringLanguage: DeclaringLanguage, machO: MachO) { + self.protocolNode = protocolNode + self.record = record + self.declaringLanguage = declaringLanguage + self.contextTypeName = protocolNode.children.at(1)?.text ?? record.runtimeName + self.propertyNames = Set((record.instanceProperties + record.classProperties).map(\.name)) + self.nodes = ObjCImportedMemberNodes(machO: machO) + } + + private struct PropertyAccessors { + let property: ObjCProtocolRecord.Property + let getterSelector: String + let setterSelector: String? + } + + func requirements() -> [ObjCProtocolRequirement] { + let instanceProperties = propertyAccessors(of: record.instanceProperties) + let classProperties = propertyAccessors(of: record.classProperties) + var requirements: [ObjCProtocolRequirement] = [] + var emittedPropertyNames: (instance: Set, class: Set) = ([], []) + let lists: [(methods: [ObjCProtocolRecord.Method], isClassMethod: Bool, isOptional: Bool)] = [ + (record.requiredInstanceMethods, false, false), + (record.requiredClassMethods, true, false), + (record.optionalInstanceMethods, false, true), + (record.optionalClassMethods, true, true), + ] + for list in lists { + let properties = list.isClassMethod ? classProperties : instanceProperties + let methodsBySelector = Dictionary(list.methods.map { ($0.selector, $0) }, uniquingKeysWith: { first, _ in first }) + for method in list.methods { + // A property prints where its getter is; its setter, and + // a getter seen again, print nothing more. + if let accessors = properties.first(where: { $0.getterSelector == method.selector || $0.setterSelector == method.selector }) { + let alreadyEmitted = list.isClassMethod ? emittedPropertyNames.class.contains(accessors.property.name) : emittedPropertyNames.instance.contains(accessors.property.name) + guard !alreadyEmitted else { continue } + if list.isClassMethod { + emittedPropertyNames.class.insert(accessors.property.name) + } else { + emittedPropertyNames.instance.insert(accessors.property.name) + } + if let requirement = propertyRequirement(accessors, isClassMember: list.isClassMethod, isOptional: list.isOptional) { + requirements.append(requirement) + } + continue + } + if let requirement = methodRequirement(method, isClassMethod: list.isClassMethod, isOptional: list.isOptional, methodsBySelector: methodsBySelector) { + requirements.append(requirement) + } + } + } + // A property whose accessors are in no method list (a record of + // an unusual compiler): still a requirement. + for (accessors, isClassMember) in instanceProperties.map({ ($0, false) }) + classProperties.map({ ($0, true) }) { + let emitted = isClassMember ? emittedPropertyNames.class : emittedPropertyNames.instance + guard !emitted.contains(accessors.property.name), let requirement = propertyRequirement(accessors, isClassMember: isClassMember, isOptional: false) else { continue } + requirements.append(requirement) + } + return requirements + } + + private func propertyAccessors(of properties: [ObjCProtocolRecord.Property]) -> [PropertyAccessors] { + properties.map { property in + let attributes = property.attributes.split(separator: ",").map(String.init) + let getterSelector = attributes.first { $0.hasPrefix("G") }.map { String($0.dropFirst()) } ?? property.name + let isReadOnly = attributes.contains("R") + let setterSelector = isReadOnly ? nil : (attributes.first { $0.hasPrefix("S") }.map { String($0.dropFirst()) } ?? "set" + property.name.prefix(1).uppercased() + property.name.dropFirst() + ":") + return PropertyAccessors(property: property, getterSelector: getterSelector, setterSelector: setterSelector) + } + } + + private func propertyRequirement(_ accessors: PropertyAccessors, isClassMember: Bool, isOptional: Bool) -> ObjCProtocolRequirement? { + guard let type = ObjCTypeEncodingParser.propertyType(fromAttributes: accessors.property.attributes) else { return nil } + let name = switch declaringLanguage { + case .swift: accessors.property.name + case .objectiveC: ObjCImporterNaming.importedPropertyName(accessors.property.name, attributes: accessors.property.attributes, contextTypeName: contextTypeName, propertyNames: propertyNames) + } + return ObjCProtocolRequirement( + kind: .property, + selector: accessors.getterSelector, + setterSelector: accessors.setterSelector, + isClassMember: isClassMember, + isOptional: isOptional, + node: nodes.propertyNode(contextNode: protocolNode, name: name, type: type, isClassMember: isClassMember), + typeEncoding: accessors.property.attributes, + hasExplicitSelector: ObjCImportedMemberBuilder.hasExplicitSelector(getterSelector: accessors.getterSelector, propertyName: name, isClassMember: isClassMember) + ) + } + + private func methodRequirement(_ method: ObjCProtocolRecord.Method, isClassMethod: Bool, isOptional: Bool, methodsBySelector: [String: ObjCProtocolRecord.Method]) -> ObjCProtocolRequirement? { + // The extended encoding names what the method list's leaves as + // `@`. Either has to take one argument per colon of the + // selector, or the names and types would not pair — as for a + // class's members (`ObjCImportedMemberBuilder`). + let encoding: String + let methodType: ObjCMethodTypeEncoding + if let extendedTypeEncoding = method.extendedTypeEncoding, + let extendedMethodType = ObjCTypeEncodingParser.methodType(from: extendedTypeEncoding, matchingArgumentsOf: method.selector) { + encoding = extendedTypeEncoding + methodType = extendedMethodType + } else if let plainMethodType = ObjCTypeEncodingParser.methodType(from: method.typeEncoding, matchingArgumentsOf: method.selector) { + encoding = method.typeEncoding + methodType = plainMethodType + } else { + return nil + } + let name = ObjCImporterNaming.importedName(selector: method.selector, isClassMethod: isClassMethod, methodType: methodType, contextTypeName: contextTypeName, propertyNames: propertyNames, undoesSwiftInsertedWith: declaringLanguage == .swift) + switch name.kind { + case .subscriptSetter: + // Folded into the getter's subscript. + return nil + case .subscriptGetter: + guard let node = nodes.subscriptNode(contextNode: protocolNode, methodType: methodType, isClassMember: isClassMethod) else { return nil } + let setterSelector = method.selector == "objectAtIndexedSubscript:" ? "setObject:atIndexedSubscript:" : "setObject:forKeyedSubscript:" + return ObjCProtocolRequirement( + kind: .subscript, + selector: method.selector, + setterSelector: methodsBySelector[setterSelector] != nil ? setterSelector : nil, + isClassMember: isClassMethod, + isOptional: isOptional, + node: node, + typeEncoding: encoding, + hasExplicitSelector: false + ) + case .initializer, .factoryInitializer, .method: + // A protocol's method is never a factory initializer: the + // naming is asked for one only on behalf of a class. + let isInitializer = name.kind != .method + return ObjCProtocolRequirement( + kind: isInitializer ? .initializer : .method, + selector: method.selector, + setterSelector: nil, + isClassMember: isClassMethod && !isInitializer, + isOptional: isOptional, + node: nodes.methodNode(contextNode: protocolNode, name: name, methodType: methodType, isClassMember: isClassMethod), + typeEncoding: encoding, + hasExplicitSelector: ObjCImportedMemberBuilder.hasExplicitSelector(method.selector, name: name, isClassMember: isClassMethod) + ) + } + } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCRuntimeNames.swift b/Sources/Analysis/SwiftObjCInterop/ObjCRuntimeNames.swift new file mode 100644 index 000000000..0532da3dc --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCRuntimeNames.swift @@ -0,0 +1,82 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftInspection + +/// The Swift nodes for the names the Objective-C runtime knows protocols and +/// classes by (evolution proposal `swift-declared-objc-protocols`): what an +/// `@objc` protocol's record and a class's protocol list spell, read back +/// the way Swift names them. +package enum ObjCRuntimeNames { + /// A `Protocol` node for the protocol the Objective-C runtime knows as + /// `runtimeName`: a Swift one by its `_TtP` mangling, or as the image — + /// or, for another module's, the image of the dependency closure that + /// declares it — declares it renamed; an imported one in `__C` under its + /// Objective-C name, the way the compiler mangles it (`So8NSObject_p`). + /// The Swift name an imported protocol goes by (`NSObjectProtocol`) is + /// the type database's to give when the name prints, as for every `__C` + /// name. Another module's renamed protocol no image of the closure + /// declares keeps its Objective-C name too. + package static func protocolNode(forRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> Node { + if let protocolNode = swiftProtocolNode(forRuntimeName: runtimeName, in: machO) { + return protocolNode + } + return Node.createTransient(kind: .protocol, children: [ + Node.createTransient(kind: .module, text: objcModule), + Node.createTransient(kind: .identifier, text: runtimeName), + ]) + } + + /// The node of a protocol declared in Swift — by its `_TtP` mangling, or + /// renamed by `machO` or by another module — and `nil` for any other + /// name. Another module's is looked for only under a name `machO` holds + /// a Swift-emitted record of and claims for none of its own protocols: + /// a clang-emitted record names an Objective-C protocol. + package static func swiftProtocolNode(forRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> Node? { + if runtimeName.hasPrefix("_TtP"), let node = try? demangleAsNodeTransient(runtimeName), let protocolNode = node.first(of: .protocol) { + return protocolNode + } + let declared = SwiftDeclaredObjCProtocolIndex.shared.declaredProtocol(forRuntimeName: runtimeName, in: machO) + ?? otherModuleDeclaredProtocol(forRuntimeName: runtimeName, in: machO) + if let declared, let node = try? demangleAsNodeTransient(declared.mangledName), let protocolNode = node.first(of: .protocol) { + return protocolNode + } + return nil + } + + private static func otherModuleDeclaredProtocol(forRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> SwiftDeclaredObjCProtocol? { + guard SwiftDeclaredObjCProtocolIndex.shared.unclaimedSwiftEmittedRecords(in: machO).contains(where: { $0.runtimeName == runtimeName }) else { return nil } + return ObjCAncestorResolverStore.shared.resolver(forImage: machO)?.swiftDeclaredObjCProtocol(forRuntimeName: runtimeName) + } + + /// A `Class` node for the class the Objective-C runtime knows as + /// `runtimeName`: a Swift one by its `_TtC` mangling or, renamed with + /// `@objc(Name)`, through its descriptor; any other in `__C`. + package static func classNode(forRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> Node { + if let classNode = swiftClassNode(forRuntimeName: runtimeName, in: machO) { + return classNode + } + return Node.createTransient(kind: .class, children: [ + Node.createTransient(kind: .module, text: objcModule), + Node.createTransient(kind: .identifier, text: runtimeName), + ]) + } + + /// The node of a class declared in Swift — by its `_TtC` mangling or the + /// class metadata symbol a file's category is bound to + /// (`NodeTypeNaming.swiftClassNode(fromRuntimeName:)`), or renamed by + /// `machO` — and `nil` for any other name. + package static func swiftClassNode(forRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> Node? { + if let classNode = NodeTypeNaming.swiftClassNode(fromRuntimeName: runtimeName) { + return classNode + } + if let descriptorOffset = SwiftClassObjectIndex.shared.classDescriptorOffset(forCustomRuntimeName: runtimeName, in: machO), + let descriptor = try? ClassDescriptor.resolve(at: machO.context.addressFromOffset(descriptorOffset), in: machO.context), + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(descriptor)), in: machO.context), + let classNode = contextNode.first(of: .class) { + return classNode + } + return nil + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift b/Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift new file mode 100644 index 000000000..62bd6cc45 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift @@ -0,0 +1,142 @@ +import Foundation +@_spi(Internals) import Demangling +import SwiftInspection + +/// Whether a Swift member's type can be the type of the Objective-C member it +/// is paired with by name (evolution proposal +/// `swift-first-imported-declarations`). It guards the name-only pairing of +/// an imported declaration's members, and it is the evidence that a Swift +/// property of the same name is another declaration — the one a header's +/// `NS_REFINED_FOR_SWIFT` leaves the plain name to. +/// +/// Only a clear mismatch counts; whatever might bridge is compatible, so a +/// guess never refuses a pairing: +/// +/// - an object (`@`, a block excluded) against a struct or an enum the +/// implementing module itself defines. A framework's own value type does +/// not bridge to an Objective-C object: `SceneHosting.ScenePresentationSettings` +/// cannot be what `-[SHScenePresentation settings]` returns. A value type +/// of another module may (`String`, `Data`, `UTType`), so it is not judged. +/// - a scalar (an integer, a floating-point number, `BOOL`) against a class or +/// an existential, which are always references. +package enum ObjCSwiftTypeCompatibility { + /// Whether `swiftType` (a type node, `Optional` included) clearly cannot + /// be `objcType`. `implementingModuleName` is the Swift module that + /// implements the Objective-C member; without it no value type is judged. + package static func isClearlyIncompatible(objcType: ObjCEncodedType, swiftType: Node, implementingModuleName: String?) -> Bool { + let swiftType = unwrappingOptional(swiftType) + if case .object = objcType { + guard let implementingModuleName, + let nominal = NodeTypeNaming.unwrappedNominal(of: swiftType), + nominal.kind == .structure || nominal.kind == .enum + else { return false } + return moduleName(of: nominal) == implementingModuleName + } + if isScalar(objcType) { + return isReference(swiftType) + } + return false + } + + /// Whether any position of a method clearly mismatches: the return type + /// or a parameter, compared where both sides have one. An initializer's + /// result is its class on both sides and is not compared. + package static func isClearlyIncompatible(objcMethodType: ObjCMethodTypeEncoding, swiftFunctionType: Node, comparesResult: Bool, implementingModuleName: String?) -> Bool { + let swiftParameterTypes = parameterTypes(ofFunctionType: swiftFunctionType) + if swiftParameterTypes.count == objcMethodType.parameterTypes.count { + for (objcParameterType, swiftParameterType) in zip(objcMethodType.parameterTypes, swiftParameterTypes) + where isClearlyIncompatible(objcType: objcParameterType, swiftType: swiftParameterType, implementingModuleName: implementingModuleName) { + return true + } + } + if comparesResult, let swiftResultType = resultType(ofFunctionType: swiftFunctionType) { + return isClearlyIncompatible(objcType: objcMethodType.returnType, swiftType: swiftResultType, implementingModuleName: implementingModuleName) + } + return false + } + + // MARK: - Swift type nodes + + /// The function type of a demangled member symbol: `Function`, + /// `Allocator` or `Constructor` > `Type` > `FunctionType`. + package static func functionType(ofDemangledMember root: Node) -> Node? { + guard let entity = root.first(of: .function) ?? root.first(of: .allocator) ?? root.first(of: .constructor), + let typeNode = entity.children.last(where: { $0.kind == .type }) + else { return nil } + return typeNode.children.first { $0.kind == .functionType || $0.kind == .noEscapeFunctionType } + } + + /// The declared type of a demangled property symbol: `Variable` > `Type`. + package static func propertyType(ofDemangledMember root: Node) -> Node? { + root.first(of: .variable)?.children.last { $0.kind == .type } + } + + private static func parameterTypes(ofFunctionType functionType: Node) -> [Node] { + guard let argumentTuple = functionType.children.first(where: { $0.kind == .argumentTuple }), + let argumentType = argumentTuple.children.first(where: { $0.kind == .type }), + let argument = argumentType.children.first + else { return [] } + guard argument.kind == .tuple else { return [argumentType] } + return argument.children.compactMap { element in + element.children.last { $0.kind == .type } + } + } + + private static func resultType(ofFunctionType functionType: Node) -> Node? { + functionType.children.first { $0.kind == .returnType }?.children.first + } + + private static func unwrappingOptional(_ node: Node) -> Node { + var current = node + while true { + if current.kind == .type, let child = current.firstChild { + current = child + continue + } + if current.kind == .sugaredOptional, let child = current.firstChild { + current = child + continue + } + if current.kind == .boundGenericEnum, + let nominal = current.firstChild.flatMap(NodeTypeNaming.unwrappedNominal), + nominal.identifier == "Optional", moduleName(of: nominal) == "Swift", + let typeList = current.children.first(where: { $0.kind == .typeList }), + let wrapped = typeList.firstChild { + current = wrapped + continue + } + return current + } + } + + /// The module a nominal is declared in, through its enclosing types. + private static func moduleName(of nominal: Node) -> String? { + var context = nominal.firstChild + while let current = context { + if current.kind == .module { + return current.text + } + context = current.firstChild + } + return nil + } + + private static func isScalar(_ type: ObjCEncodedType) -> Bool { + switch type { + case .bool, .character, .unsignedCharacter, .short, .unsignedShort, .int, .unsignedInt, + .long, .unsignedLong, .longLong, .unsignedLongLong, .float, .double, .longDouble: + true + default: + false + } + } + + private static func isReference(_ node: Node) -> Bool { + switch node.kind { + case .class, .boundGenericClass, .protocolList, .protocolListWithClass, .protocolListWithAnyObject: + true + default: + false + } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift b/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift new file mode 100644 index 000000000..2ee3a1da8 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift @@ -0,0 +1,297 @@ +/// One type of an Objective-C type encoding, as an Objective-C protocol +/// record spells its methods' and properties' types (evolution proposal +/// `swift-declared-objc-protocols`). The extended encoding a Swift-emitted +/// record carries names classes, protocols and block signatures +/// (`@"NSString"`, `@""`, `@?`); nullability and +/// collection element types are never recorded. +package indirect enum ObjCEncodedType: Sendable, Hashable { + case void + /// `B`: `BOOL` on arm64, Swift's `Bool`. + case bool + case character + case unsignedCharacter + case short + case unsignedShort + case int + case unsignedInt + /// `l`: a 32-bit `long`, which a 64-bit encoding spells `q`. + case long + case unsignedLong + /// `q`: `NSInteger`, `long` and `long long` alike — and Swift's `Int`. + case longLong + /// `Q`: `NSUInteger`, and Swift's `UInt`. + case unsignedLongLong + case float + case double + case longDouble + /// `*`; `r*`, a `const char *`, is constant. + case characterString(isConst: Bool) + /// `:` + case selector + /// `#` + case objectClass + /// `@`, `@"Class"`, `@""`, `@"Class"`: the class + /// name is `nil` for `id`. + case object(className: String?, protocolNames: [String]) + /// `@?`, with its signature when the extended encoding carries one. + case block(ObjCBlockSignature?) + /// `^type`; `^?` is a function pointer, read as a pointer to `unknown`. + case pointer(ObjCEncodedType, isConst: Bool) + case structure(name: String?) + case union(name: String?) + case array(count: Int, element: ObjCEncodedType) + case bitField(width: Int) + /// `?`, or what the parser could not read. + case unknown + + /// Whether the type is an Objective-C object or block — a pointer the + /// importer makes optional when nothing annotates its nullability. + package var isObjectPointer: Bool { + switch self { + case .object, .block, .objectClass: true + default: false + } + } + + /// The type as a method list's encoding spells it: no class or protocol + /// named for an object, no signature for a block — what only an + /// extended encoding carries. + package var withoutExtendedNames: ObjCEncodedType { + switch self { + case .object: .object(className: nil, protocolNames: []) + case .block: .block(nil) + case .pointer(let pointee, let isConst): .pointer(pointee.withoutExtendedNames, isConst: isConst) + case .array(let count, let element): .array(count: count, element: element.withoutExtendedNames) + default: self + } + } +} + +/// A block's signature: its result and the parameters after the block +/// literal itself. +package struct ObjCBlockSignature: Sendable, Hashable { + package let returnType: ObjCEncodedType + package let parameterTypes: [ObjCEncodedType] +} + +/// A method's type encoding: its result and the parameters after `self` and +/// `_cmd`. +package struct ObjCMethodTypeEncoding: Sendable, Hashable { + package let returnType: ObjCEncodedType + package let parameterTypes: [ObjCEncodedType] +} + +/// Reads Objective-C type encodings. Only what the runtime and the compilers +/// write is accepted; anything else reads as `nil` rather than a guess. +package enum ObjCTypeEncodingParser { + /// A method's encoding (`@"NSString"32@0:8@"NSString"16^@24`), with the + /// stack offsets skipped. + package static func methodType(from encoding: String) -> ObjCMethodTypeEncoding? { + var reader = Reader(encoding) + guard let returnType = reader.readType() else { return nil } + reader.skipOffset() + var argumentTypes: [ObjCEncodedType] = [] + while !reader.isAtEnd { + guard let argumentType = reader.readType() else { return nil } + reader.skipOffset() + argumentTypes.append(argumentType) + } + // `self` and `_cmd`. + guard argumentTypes.count >= 2 else { return nil } + return ObjCMethodTypeEncoding(returnType: returnType, parameterTypes: Array(argumentTypes.dropFirst(2))) + } + + /// A method's encoding, only when it takes one argument per colon of + /// `selector` — what the importer pairs the selector's pieces and the + /// types by. An encoding another method's slot handed over (a shifted + /// extended types array) or a malformed one takes another count, and + /// pairing it would index past its arguments. + package static func methodType(from encoding: String, matchingArgumentsOf selector: String) -> ObjCMethodTypeEncoding? { + guard let methodType = methodType(from: encoding), methodType.parameterTypes.count == selector.count(where: { $0 == ":" }) else { return nil } + return methodType + } + + /// One type (`@"NSString"`), as a property's `T` attribute spells it. + package static func type(from encoding: String) -> ObjCEncodedType? { + var reader = Reader(encoding) + guard let type = reader.readType(), reader.isAtEnd else { return nil } + return type + } + + /// A property's type: the `T` attribute of its attribute string + /// (`T@"NSString",N,R`). + package static func propertyType(fromAttributes attributes: String) -> ObjCEncodedType? { + // The type may itself hold commas (a structure's field list), so it + // runs to the first comma that follows a complete type. + guard attributes.hasPrefix("T") else { return nil } + var reader = Reader(String(attributes.dropFirst())) + guard let type = reader.readType() else { return nil } + guard reader.isAtEnd || reader.peek == "," else { return nil } + return type + } + + private struct Reader { + private let characters: [Character] + private var position = 0 + + init(_ text: String) { + self.characters = Array(text) + } + + var isAtEnd: Bool { + position >= characters.count + } + + var peek: Character? { + isAtEnd ? nil : characters[position] + } + + mutating func skipOffset() { + while let character = peek, character.isNumber || character == "-" { + position += 1 + } + } + + mutating func readNumber() -> Int? { + var digits = "" + while let character = peek, character.isNumber { + digits.append(character) + position += 1 + } + return Int(digits) + } + + /// A quoted name (`"NSString"`); the opening quote is next. + mutating func readQuoted() -> String? { + guard peek == "\"" else { return nil } + position += 1 + var name = "" + while let character = peek, character != "\"" { + name.append(character) + position += 1 + } + guard peek == "\"" else { return nil } + position += 1 + return name + } + + mutating func readType() -> ObjCEncodedType? { + var isConst = false + while let character = peek, "rnNoORVAj".contains(character) { + if character == "r" { + isConst = true + } + position += 1 + } + guard let character = peek else { return nil } + position += 1 + switch character { + case "v": return .void + case "B": return .bool + case "c": return .character + case "C": return .unsignedCharacter + case "s": return .short + case "S": return .unsignedShort + case "i": return .int + case "I": return .unsignedInt + case "l": return .long + case "L": return .unsignedLong + case "q": return .longLong + case "Q": return .unsignedLongLong + case "f": return .float + case "d": return .double + case "D": return .longDouble + case "*": return .characterString(isConst: isConst) + case ":": return .selector + case "#": return .objectClass + case "?": return .unknown + case "@": return readObject() + case "^": + guard let pointee = readType() else { return nil } + return .pointer(pointee, isConst: isConst) + case "{": return readAggregate(closing: "}").map { .structure(name: $0) } + case "(": return readAggregate(closing: ")").map { .union(name: $0) } + case "[": + guard let count = readNumber(), let element = readType(), peek == "]" else { return nil } + position += 1 + return .array(count: count, element: element) + case "b": + guard let width = readNumber() else { return nil } + return .bitField(width: width) + default: + return nil + } + } + + private mutating func readObject() -> ObjCEncodedType? { + if peek == "?" { + position += 1 + guard peek == "<" else { return .block(nil) } + position += 1 + // The block's own encoding: its result, the block literal, + // then its parameters. The compilers write no offsets here; + // any are skipped all the same. + guard let returnType = readType() else { return nil } + skipOffset() + guard readType() != nil else { return nil } + skipOffset() + var parameterTypes: [ObjCEncodedType] = [] + while let character = peek, character != ">" { + guard let parameterType = readType() else { return nil } + skipOffset() + parameterTypes.append(parameterType) + } + guard peek == ">" else { return nil } + position += 1 + return .block(ObjCBlockSignature(returnType: returnType, parameterTypes: parameterTypes)) + } + guard peek == "\"" else { return .object(className: nil, protocolNames: []) } + guard let quoted = readQuoted() else { return nil } + // `NSObject` or ``. + var className = "" + var protocolNames: [String] = [] + var index = quoted.startIndex + while index < quoted.endIndex, quoted[index] != "<" { + className.append(quoted[index]) + index = quoted.index(after: index) + } + while index < quoted.endIndex { + guard quoted[index] == "<", let closing = quoted[index...].firstIndex(of: ">") else { return nil } + protocolNames.append(String(quoted[quoted.index(after: index) ..< closing])) + index = quoted.index(after: closing) + } + return .object(className: className.isEmpty ? nil : className, protocolNames: protocolNames) + } + + /// A structure or union: its name, with the field list skipped — + /// which may nest aggregates and quote field names. + private mutating func readAggregate(closing: Character) -> String?? { + var name = "" + while let character = peek, character != "=", character != closing { + name.append(character) + position += 1 + } + var depth = 1 + while let character = peek { + position += 1 + switch character { + case "\"": + while let quotedCharacter = peek, quotedCharacter != "\"" { + position += 1 + } + position += 1 + case "{", "(": + depth += 1 + case "}", ")": + depth -= 1 + if depth == 0 { + return .some(name.isEmpty || name == "?" ? nil : name) + } + default: + break + } + } + return nil + } + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/SharedCacheEvictionGroup+SwiftObjCInterop.swift b/Sources/Analysis/SwiftObjCInterop/SharedCacheEvictionGroup+SwiftObjCInterop.swift new file mode 100644 index 000000000..18b09e1d8 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/SharedCacheEvictionGroup+SwiftObjCInterop.swift @@ -0,0 +1,19 @@ +@_spi(Internals) import MachOCaches + +/// The eviction groups of this module's per-image caches. Which of them +/// follow another group is declared where the cache is created — by the +/// cache that holds the reference. +extension SharedCacheEvictionGroup { + /// `ObjCImplementationClassIndex`: holds `NodeReference`s into the + /// symbol store's arena, so it follows `swiftSymbolStore`. + package static let objcImplementationClasses = SharedCacheEvictionGroup("objcImplementationClasses") + + /// `ObjCClassMethodIndex`, `SwiftClassObjectIndex` and the host's + /// `ObjCClassHierarchyProviderStore` registration: ObjC-side per-image + /// state of the symbol store's lifetime, so it follows `swiftSymbolStore`. + package static let objcHierarchy = SharedCacheEvictionGroup("objcHierarchy") + + /// `ObjCAncestorResolverStore`: holds the file's dependency images once + /// it has resolved them; same lifetime, follows `swiftSymbolStore`. + package static let objcAncestorResolver = SharedCacheEvictionGroup("objcAncestorResolver") +} diff --git a/Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift b/Sources/Analysis/SwiftObjCInterop/SwiftClassObjectIndex.swift similarity index 94% rename from Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift rename to Sources/Analysis/SwiftObjCInterop/SwiftClassObjectIndex.swift index 676305b05..4b202eeec 100644 --- a/Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift +++ b/Sources/Analysis/SwiftObjCInterop/SwiftClassObjectIndex.swift @@ -7,7 +7,8 @@ import MachOSwiftSection import Demangling @_spi(Core) import MachOObjCSection @_spi(Internals) import MachOCaches -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection /// Per-image index of the Swift classes whose source renamed them for the /// Objective-C runtime — `@objc(Name)` or `@_objcRuntimeName(Name)` — @@ -50,7 +51,7 @@ import Demangling package final class SwiftClassObjectIndex: @unchecked Sendable { package static let shared = SwiftClassObjectIndex() - private let cache = SharedCache(evictionGroup: .objcHierarchy, follows: [.symbolStore]) + private let cache = SharedCache(evictionGroup: .objcHierarchy, follows: [.swiftSymbolStore]) private init() {} @@ -120,6 +121,15 @@ package final class SwiftClassObjectIndex: @unchecked Sendable { storage(in: machO)?.customRuntimeNamesBySwiftQualifiedName[qualifiedName] ?? [] } + /// The nominal type descriptor of the renamed class the Objective-C + /// runtime knows as `runtimeName`; `nil` when no class of the image goes + /// by it, or more than one does. + package func classDescriptorOffset(forCustomRuntimeName runtimeName: String, in machO: some MachORepresentableWithCache) -> Int? { + guard let renamedClassesByDescriptorOffset = storage(in: machO)?.renamedClassesByDescriptorOffset else { return nil } + let offsets = renamedClassesByDescriptorOffset.filter { $0.value.customObjCClassName.name == runtimeName }.map(\.key) + return offsets.count == 1 ? offsets[0] : nil + } + // MARK: - Build /// `IsStaticSpecialization | IsCanonicalStaticSpecialization`: metadata diff --git a/Sources/Analysis/SwiftObjCInterop/SwiftClassWithoutClassObjectIndex.swift b/Sources/Analysis/SwiftObjCInterop/SwiftClassWithoutClassObjectIndex.swift new file mode 100644 index 000000000..fabe3791b --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/SwiftClassWithoutClassObjectIndex.swift @@ -0,0 +1,466 @@ +import Foundation +import FoundationToolbox +import MachOKit +import MachOKitExtensions +import MachOReading +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Core) import MachOObjCSection +@_spi(Internals) import MachOCaches +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection + +/// A Swift class the image keeps no class object for (evolution proposal +/// `objc-classes-without-class-objects`): `__objc_classlist` does not list +/// it, yet its `class_ro_t` is emitted statically — the Objective-C runtime +/// only ever sees the class through metadata the Swift runtime builds or +/// initializes first. The fields are what `ObjCIndexing.ObjCSuppliedClass` +/// takes, plus what the library's own ObjC member table asks by. +package struct SwiftClassWithoutClassObject: Sendable, Hashable { + /// Why the image keeps no class object — which of the compiler's class + /// metadata strategies the class takes. + package enum Kind: Sendable, Hashable { + /// A generic class: each instantiation is built from the generic + /// metadata pattern, whose extra data carries the `class_ro_t` + /// template (its name a null pointer the runtime fills per + /// instantiation). + case generic + /// A non-generic class whose superclass lives in another resilience + /// domain (the Resilient strategy): the metadata is allocated at + /// runtime from a `ResilientClassMetadataPattern`. + case resilientAncestry + /// A non-generic class whose metadata is emitted statically but must + /// be initialized before the Objective-C runtime may see it (the + /// Singleton strategy) — in practice a class with generic ancestry. + case genericAncestry + } + + /// How the class's superclass is named for the Objective-C side. + package enum Superclass: Sendable, Hashable { + /// An Objective-C class — or `_TtCs12_SwiftObject`, the superclass + /// the runtime gives a Swift root class — by its runtime name, which + /// is what the ancestor resolver looks a class up by. + case objectiveC(runtimeName: String) + /// A Swift class of the same image that has a class object, by the + /// runtime name its `class_ro_t` carries. + case classObject(runtimeName: String) + /// Another class of the same image without a class object, by its + /// ``SwiftClassWithoutClassObject/name``. + case withoutClassObject(name: String) + /// A Swift class this index cannot name for the Objective-C runtime — + /// one another image defines — by its Swift spelling, for display. + /// No ancestor walk can continue from it. + case swiftClass(displayName: String) + + package var name: String { + switch self { + case .objectiveC(let runtimeName), .classObject(let runtimeName): runtimeName + case .withoutClassObject(let name): name + case .swiftClass(let displayName): displayName + } + } + } + + package let kind: Kind + /// The class's nominal type descriptor. + package let descriptorOffset: Int + /// The Swift qualified name, the key `ObjCMembers.table(forSwiftClassQualifiedName:in:)` + /// is asked by (`Xcode_Service.MenuBarPanelWindow`). + package let qualifiedName: String + /// The name the class goes by on the Objective-C side: the `class_ro_t` + /// name for a non-generic class (`_TtC13Xcode_Service23MenuBarLabelHostingView`); + /// for a generic class, whose template names nothing, the qualified name + /// with its generic parameters (`Xcode_Service.MenuBarPanelWindow`). + package let name: String + package let superclass: Superclass + /// Whether an Objective-C class is among the ancestors — what makes the + /// compiler register a non-generic class's stub in `__objc_stublist` + /// (`checkAncestry(AncestryFlags::ObjC)`). Read off the class flags: the + /// Objective-C object model leaves `UsesSwiftRefcounting` clear, and an + /// actor deriving from `NSObject`, the one exception, has a superclass. + package let hasObjectiveCAncestry: Bool + package let readOnlyDataOffset: Int + package let metaclassReadOnlyDataOffset: Int? + /// The isa word of the class's Objective-C class stub: `…CMs` for a + /// class with resilient ancestry, one reserved word into `…CMt` for one + /// with generic ancestry. `nil` when the class has no stub (a generic + /// class never has one) or, with generic ancestry, when the image is + /// stripped of the local `…CMt` symbol, the stub's only name. Only a + /// class with resilient ancestry has the categories of its `@objc` + /// extensions point at its stub; one with generic ancestry has them + /// point at its metadata, whose `class_ro_t` names the class. + package let classStubOffset: Int? +} + +extension SwiftClassWithoutClassObject { + func readOnlyData(in reader: some ObjCImplementationClassReading) -> ObjCClassROData64? { + Self.readOnlyData(at: readOnlyDataOffset, in: reader) + } + + func metaclassReadOnlyData(in reader: some ObjCImplementationClassReading) -> ObjCClassROData64? { + metaclassReadOnlyDataOffset.flatMap { Self.readOnlyData(at: $0, in: reader) } + } + + private static func readOnlyData(at offset: Int, in reader: some ObjCImplementationClassReading) -> ObjCClassROData64? { + // `as`: bound to an optional, the `try?` read would take the + // Optional's in-memory shape, one tag byte past the layout. + guard let layout = try? reader.readElement(offset: offset) as ObjCClassROData64.Layout else { return nil } + return ObjCClassROData64(layout: layout, offset: offset) + } +} + +/// Per-image index of the Swift classes without a class object (evolution +/// proposal `objc-classes-without-class-objects`), read from the type +/// context descriptors: +/// +/// - A **generic** class's `class_ro_t` and metaclass `class_ro_t` sit in +/// the extra-data pattern of its generic metadata pattern. The runtime +/// copies that pattern into an instantiation's extra data at +/// `OffsetInWords` and points the metadata at word `ClassRODataOffset` of +/// the extra data (`initializeClassMetadataFromPattern`), so within the +/// pattern the template is word `ClassRODataOffset − OffsetInWords`. +/// - A class with a **resilient superclass** has its singleton metadata +/// initialization point at a `ResilientClassMetadataPattern` — its `data` +/// is the `class_ro_t`, its `metaclass` the static metaclass object — and +/// its descriptor at the class stub. +/// - A class initialized by the **singleton** pattern otherwise points at +/// the statically emitted incomplete metadata, a class object in shape; +/// only the stub list registers it, through a stub the descriptor does not +/// record, found here through its `…CMt` symbol. The Update and +/// FixedOrUpdate strategies initialize statically emitted metadata too, +/// but theirs is in the class list, and is left out here. +/// +/// Every class is recorded whether or not it has Objective-C ancestry, as +/// the class list records every Swift class with a class object; what the +/// Objective-C side is handed is narrower (`ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)` +/// in SwiftIndexing). Absolute +/// pointers — the data and isa words of a class object — are read through +/// the ObjC reader, which decodes them in every accounting; the rest are +/// relative. +/// +/// Built once per image, lazily, the first time the ObjC side asks about a +/// class the class list misses — an image that is merely an ObjC ancestor +/// never builds one — and evicted with the other ObjC-side per-image state. +/// This module sits below the event layer, so a class that could not be read +/// is only logged. +@Loggable(.private, subsystem: "com.machoswiftsection.swift-inspection", category: "SwiftClassWithoutClassObjectIndex") +package final class SwiftClassWithoutClassObjectIndex: @unchecked Sendable { + package static let shared = SwiftClassWithoutClassObjectIndex() + + private let cache = SharedCache(evictionGroup: .objcHierarchy, follows: [.swiftSymbolStore]) + + private init() {} + + package final class Storage: @unchecked Sendable { + /// In type-context-descriptor order. + let classes: [SwiftClassWithoutClassObject] + + /// The classes by name, a name several classes share left out: no + /// lookup by it can tell which is meant. + let classesByName: [String: SwiftClassWithoutClassObject] + + /// Swift qualified name → names, one per class. More than one entry + /// means same-named private classes from different files, as in the + /// ObjC-side indexes — the same name twice for two generic ones, + /// which the name does not tell apart (`Module.Box`). + let namesBySwiftQualifiedName: [String: [String]] + + init(classes: [SwiftClassWithoutClassObject]) { + self.classes = classes + var classesByName: [String: SwiftClassWithoutClassObject] = [:] + var sharedNames: Set = [] + var namesBySwiftQualifiedName: [String: [String]] = [:] + for swiftClass in classes { + namesBySwiftQualifiedName[swiftClass.qualifiedName, default: []].append(swiftClass.name) + if classesByName.updateValue(swiftClass, forKey: swiftClass.name) != nil { + sharedNames.insert(swiftClass.name) + } + } + for name in sharedNames { + classesByName[name] = nil + } + self.classesByName = classesByName + self.namesBySwiftQualifiedName = namesBySwiftQualifiedName + } + } + + /// The image's index, built on first use. The build re-types the reader + /// once (`objcImplementationClassReader`): it needs the descriptors and + /// the ObjC reads. + package func storage(in machO: some MachORepresentableWithCache) -> Storage? { + cache.storage(in: machO) { machO in + machO.objcImplementationClassReader.map { Self.build(in: $0) } + } + } + + package func contains(in machO: some MachORepresentableWithCache) -> Bool { + cache.contains(in: machO) + } + + package func remove(for machO: some MachORepresentableWithCache) { + cache.remove(for: machO) + } + + // MARK: - Queries + + /// Every class of the image without a class object, in descriptor order. + package func classes(in machO: some MachORepresentableWithCache) -> [SwiftClassWithoutClassObject] { + storage(in: machO)?.classes ?? [] + } + + /// The class that goes by `name` on the Objective-C side; `nil` when + /// none does, or when several do. + package func swiftClass(named name: String, in machO: some MachORepresentableWithCache) -> SwiftClassWithoutClassObject? { + storage(in: machO)?.classesByName[name] + } + + /// The Objective-C-side names of the classes whose Swift qualified name + /// is `qualifiedName`; empty when there is none. + package func names(forSwiftClassQualifiedName qualifiedName: String, in machO: some MachORepresentableWithCache) -> [String] { + storage(in: machO)?.namesBySwiftQualifiedName[qualifiedName] ?? [] + } + + // MARK: - Build + + /// The superclass the runtime gives a Swift class that declares none. + private static let swiftRootClassRuntimeName = "_TtCs12_SwiftObject" + + private static let classFlagsFieldOffset = ClassMetadataObjCInterop.Layout.offset(of: .flags) + + /// What one descriptor yields before its superclass is named: naming it + /// needs every other class's name. + private struct Reading { + let descriptor: ClassDescriptor + let kind: SwiftClassWithoutClassObject.Kind + let qualifiedName: String + let name: String + let hasObjectiveCAncestry: Bool + let readOnlyDataOffset: Int + let metaclassReadOnlyDataOffset: Int? + let classStubOffset: Int? + } + + private static func build(in machO: MachO) -> Storage { + // The class list's own index: which metadata is a class object, and + // the runtime names of the Swift classes that have one. + let classObjectStorage = ObjCClassMethodIndex.shared.storage(in: machO) + let classObjectOffsets = Set(classObjectStorage?.classObjectsByRuntimeName.values.map(\.offset) ?? []) + + var readings: [Reading] = [] + let typeContextDescriptors = (try? machO.swift.typeContextDescriptors) ?? [] + for case .class(let descriptor) in typeContextDescriptors { + if let reading = reading(of: descriptor, classObjectOffsets: classObjectOffsets, in: machO) { + readings.append(reading) + } + } + + var namesByQualifiedName: [String: [String]] = [:] + for reading in readings { + namesByQualifiedName[reading.qualifiedName, default: []].append(reading.name) + } + let classes = readings.map { reading in + SwiftClassWithoutClassObject( + kind: reading.kind, + descriptorOffset: reading.descriptor.offset, + qualifiedName: reading.qualifiedName, + name: reading.name, + superclass: superclass( + of: reading.descriptor, + namesByQualifiedName: namesByQualifiedName, + classObjectRuntimeNamesByQualifiedName: classObjectStorage?.runtimeNamesBySwiftQualifiedName ?? [:], + in: machO + ), + hasObjectiveCAncestry: reading.hasObjectiveCAncestry, + readOnlyDataOffset: reading.readOnlyDataOffset, + metaclassReadOnlyDataOffset: reading.metaclassReadOnlyDataOffset, + classStubOffset: reading.classStubOffset + ) + } + return Storage(classes: classes) + } + + private static func reading(of descriptor: ClassDescriptor, classObjectOffsets: Set, in machO: MachO) -> Reading? { + let context = machO.context + do { + let kind: SwiftClassWithoutClassObject.Kind + let readOnlyData: ObjCClassROData64 + let metaclassReadOnlyData: ObjCClassROData64? + let classFlags: UInt32 + var classStubOffset: Int? + if descriptor.layout.flags.isGeneric { + guard let genericContext = try descriptor.typeGenericContext(in: context), + let patternOffset = genericContext.header.resolvedDirectOffset(from: \.defaultInstantiationPattern) + else { return nil } + let pattern = try GenericClassMetadataPattern.resolve(at: patternOffset, in: context) + // No extra-data pattern: a build without Objective-C interop. + guard let extraDataPattern = try pattern.extraDataPattern(in: context), + let extraDataOffset = extraDataPattern.resolvedDirectOffset(from: \.pattern) + else { return nil } + func offset(ofExtraDataWordAt wordOffset: UInt16) -> Int? { + let wordIndex = Int(wordOffset) - Int(extraDataPattern.layout.offsetInWords) + guard wordIndex >= 0, wordIndex < Int(extraDataPattern.layout.sizeInWords) else { return nil } + return extraDataOffset + wordIndex * MemoryLayout.size + } + guard let readOnlyDataOffset = offset(ofExtraDataWordAt: pattern.layout.classReadOnlyDataOffsetInWords) else { + #log(.error, "skipped the generic class with descriptor at offset \(descriptor.offset, privacy: .public): its class_ro_t lies outside the extra-data pattern") + return nil + } + kind = .generic + classFlags = pattern.layout.classFlags + readOnlyData = try readOnlyDataTemplate(at: readOnlyDataOffset, in: machO) + metaclassReadOnlyData = try offset(ofExtraDataWordAt: pattern.layout.metaclassReadOnlyDataOffsetInWords).map { try readOnlyDataTemplate(at: $0, in: machO) } + } else if descriptor.hasSingletonMetadataInitialization { + // The wrapper walks the trailing objects to the initialization + // record; transient, like every other materialization. + let classWrapper = try Class(descriptor: descriptor, in: context) + guard let initialization = classWrapper.singletonMetadataInitialization, + let metadataOffset = initialization.resolvedDirectOffset(from: \.incompleteMetadata) + else { return nil } + if descriptor.hasResilientSuperclass { + // The field names the resilient pattern instead. + let pattern = try ResilientClassMetadataPattern.resolve(at: metadataOffset, in: context) + guard let readOnlyDataOffset = pattern.resolvedDirectOffset(from: \.data) else { return nil } + kind = .resilientAncestry + classFlags = pattern.layout.classFlags + readOnlyData = try readOnlyDataTemplate(at: readOnlyDataOffset, in: machO) + metaclassReadOnlyData = try pattern.resolvedDirectOffset(from: \.metaclass).flatMap { try instanceReadOnlyData(ofClassObjectAt: $0, in: machO) } + classStubOffset = classWrapper.objcResilientClassStubInfo?.resolvedDirectOffset(from: \.stub) + } else { + guard !classObjectOffsets.contains(metadataOffset) else { return nil } + let classObject = try classObject(at: metadataOffset, in: machO) + guard let instanceReadOnlyData = machO.instanceReadOnlyData(of: classObject) else { + #log(.error, "skipped the class with descriptor at offset \(descriptor.offset, privacy: .public): its incomplete metadata carries no readable class_ro_t") + return nil + } + kind = .genericAncestry + // `as UInt32`: bound to an optional, the read would take + // the Optional's in-memory shape, one tag byte past it. + classFlags = try machO.readElement(offset: metadataOffset + classFlagsFieldOffset) as UInt32 + readOnlyData = instanceReadOnlyData + metaclassReadOnlyData = machO.metaClass(of: classObject).flatMap { machO.instanceReadOnlyData(of: $0) } + classStubOffset = singletonClassStubOffset(of: descriptor, in: machO) + } + } else { + // Fixed strategy: the class object is in the class list. + return nil + } + guard !readOnlyData.isMetaClass else { + #log(.error, "skipped the class with descriptor at offset \(descriptor.offset, privacy: .public): its class_ro_t is marked as a metaclass's") + return nil + } + let contextNode = try SymbolicDemangler.demangleContext(for: .type(.class(descriptor)), in: context) + guard let qualifiedName = NodeTypeNaming.nominalQualifiedName(ofDemangledRoot: contextNode) else { return nil } + let name: String + if kind == .generic { + name = qualifiedName + genericParameterClause(of: descriptor, in: machO) + } else { + guard let runtimeName = machO.className(of: readOnlyData), !runtimeName.isEmpty else { + #log(.error, "skipped the class with descriptor at offset \(descriptor.offset, privacy: .public): class name unreadable") + return nil + } + name = runtimeName + } + let usesSwiftReferenceCounting = classFlags & ClassFlags.usesSwiftRefcounting.rawValue != 0 + let isNSObjectActor = descriptor.isActor && descriptor.resolvedDirectOffset(from: \.superclassType) != nil + return Reading( + descriptor: descriptor, + kind: kind, + qualifiedName: qualifiedName, + name: name, + hasObjectiveCAncestry: !usesSwiftReferenceCounting || isNSObjectActor, + readOnlyDataOffset: readOnlyData.offset, + // A pointer that misread lands on a class's own data, never a + // metaclass's. + metaclassReadOnlyDataOffset: metaclassReadOnlyData.flatMap { $0.isMetaClass ? $0.offset : nil }, + classStubOffset: classStubOffset + ) + } catch { + #log(.error, "skipped the class with descriptor at offset \(descriptor.offset, privacy: .public): metadata unreadable: \(String(describing: error), privacy: .public)") + return nil + } + } + + private static func readOnlyDataTemplate(at offset: Int, in machO: some ObjCImplementationClassReading) throws -> ObjCClassROData64 { + let layout: ObjCClassROData64.Layout = try machO.readElement(offset: offset) + return ObjCClassROData64(layout: layout, offset: offset) + } + + private static func classObject(at offset: Int, in machO: some ObjCImplementationClassReading) throws -> ObjCClass64 { + let layout: ObjCClass64.Layout = try machO.readElement(offset: offset) + return ObjCClass64(layout: layout, offset: offset) + } + + private static func instanceReadOnlyData(ofClassObjectAt offset: Int, in machO: some ObjCImplementationClassReading) throws -> ObjCClassROData64? { + machO.instanceReadOnlyData(of: try classObject(at: offset, in: machO)) + } + + /// ``: the parameters of every depth, named by depth and index as + /// everywhere else the binary keeps no names (`Outer.Inner` gives + /// ``). + private static func genericParameterClause(of descriptor: ClassDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) -> String { + guard let depthLayout = try? GenericParameterDepthLayout.make(for: .type(.class(descriptor)), in: machO.context), depthLayout.parameterCount > 0 else { return "" } + var parameterNames: [String] = [] + for (depth, parameterCount) in depthLayout.parameterCountsByDepth.enumerated() { + for index in 0 ..< parameterCount { + parameterNames.append(genericParameterName(depth: UInt64(depth), index: UInt64(index))) + } + } + return "<" + parameterNames.joined(separator: ", ") + ">" + } + + /// The stub of a class initialized by the singleton pattern, which the + /// descriptor does not record. The compiler emits it non-public + /// (`emitObjCResilientClassStub(_:isPublic: false)`), so only the full + /// stub has a symbol — named like the descriptor's (`…CMn`) with the + /// suffix `…CMt` — and the `…CMs` alias for its isa word, one reserved + /// word further, is never defined. The symbol is local: a stripped image + /// keeps none, and the stub goes unnamed. + private static func singletonClassStubOffset(of descriptor: ClassDescriptor, in machO: some MachORepresentableWithCache) -> Int? { + guard let descriptorSymbolName = machO.symbols(offset: descriptor.offset)?.first(where: { $0.name.hasSuffix("CMn") })?.name, + let fullStubOffset = SwiftSymbolIndexStore.shared.offset(ofSymbolNamed: String(descriptorSymbolName.dropLast()) + "t", in: machO) + else { return nil } + return fullStubOffset + MemoryLayout.size + } + + private static func superclass( + of descriptor: ClassDescriptor, + namesByQualifiedName: [String: [String]], + classObjectRuntimeNamesByQualifiedName: [String: [String]], + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> SwiftClassWithoutClassObject.Superclass { + let context = machO.context + let superclassNode: Node + do { + guard let mangledName = try descriptor.superclassTypeMangledName(in: context) else { + return .objectiveC(runtimeName: swiftRootClassRuntimeName) + } + superclassNode = try SymbolicDemangler.demangleTypeUncached(for: mangledName, in: context) + } catch { + #log(.error, "the superclass of the class with descriptor at offset \(descriptor.offset, privacy: .public) is unreadable: \(String(describing: error), privacy: .public)") + return .swiftClass(displayName: "") + } + // `.interface`, not `.interfaceType`: that one removes the bound + // generic arguments, and `NSHostingView`, with /// nothing left unbound in the type — see ``isConcreteTypeAccessorSymbol(_:)``. @@ -378,7 +377,7 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun return .unknown } let image = location.image - let imageAddressSpace = ThunkAddressSpace(of: image) + let imageAddressSpace = ImageAddressSpace(of: image) guard let exportedAddress = imageAddressSpace.address(forExportedSymbolOffset: location.exportedSymbolOffset), let exportedOffset = imageAddressSpace.offset(forAddress: exportedAddress) else { return .unknown } @@ -391,7 +390,7 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun private func foreignCallee(at address: UInt64, targetAddress: UInt64) -> ThunkCallee { guard let cacheImages, let foreignImage = cacheImages.image(containing: targetAddress) else { return .unknown } - let foreignAddressSpace = ThunkAddressSpace(of: foreignImage) + let foreignAddressSpace = ImageAddressSpace(of: foreignImage) guard let foreignOffset = foreignAddressSpace.offset(forAddress: targetAddress) else { return .unknown } if let descriptorOffset = MetadataAccessorIndex.index(for: foreignImage).descriptorOffset(forAccessorOffset: foreignOffset) { return metadataAccessor(at: address, descriptorOffset: descriptorOffset, in: foreignImage) @@ -434,75 +433,3 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun } } } - -/// Finds, inside a dyld shared cache, the image an address belongs to. -/// -/// The main cache header lists every image with its load address; the image -/// whose address is the greatest one not above the target is the one that -/// contains it (`__TEXT` segments are laid out contiguously in address -/// order). Images are opened on first use and kept, because one thunk -/// typically calls into the same two images (`SwiftUICore`, `libswiftCore`) -/// many times. -package final class CacheImageResolver { - private let cache: DyldCache - private let imagesByAddress: [(address: UInt64, path: String)] - private var openedImagesByPath: [String: MachOFile?] = [:] - private var entryPointAddressesByImagePath: [String: [UInt64: String]] = [:] - - package init?(cacheOf machO: MachOFile) { - guard let cache = machO.cache else { return nil } - let mainCache = cache.mainCache ?? cache - guard let imageInfos = mainCache.imageInfos else { return nil } - var images: [(address: UInt64, path: String)] = [] - for imageInfo in imageInfos { - guard let path = imageInfo.path(in: mainCache) else { continue } - images.append((address: UInt64(imageInfo.layout.address), path: path)) - } - guard !images.isEmpty else { return nil } - self.cache = cache - self.imagesByAddress = images.sorted { $0.address < $1.address } - } - - package func image(containing address: UInt64) -> MachOFile? { - // Greatest load address not above the target. - var low = 0 - var high = imagesByAddress.count - while low < high { - let middle = (low + high) / 2 - if imagesByAddress[middle].address <= address { low = middle + 1 } else { high = middle } - } - guard low > 0 else { return nil } - let path = imagesByAddress[low - 1].path - if let opened = openedImagesByPath[path] { return opened } - let opened = cache.machOFile(by: .path(path)) - openedImagesByPath[path] = opened - return opened - } - - /// Which of `names` — runtime symbols, by their exported spelling — the - /// address in `image` is, if any. - /// - /// The export trie's offsets are header-relative - /// (``ThunkAddressSpace/address(forExportedSymbolOffset:)``). Until the - /// standalone-file batch this went through the file-offset conversion, - /// which for a cache image lands in `__LINKEDIT`, so the table held - /// wrong addresses and never matched; the cache readings survived only - /// because a witness-table call's result is skipped by the name and a - /// capability flag's unnamed pointer still reads as non-zero. - package func exportedName(atAddress address: UInt64, in image: MachOFile, among names: some Sequence) -> String? { - let path = image.imagePath - if entryPointAddressesByImagePath[path] == nil { - var addressesByName: [UInt64: String] = [:] - let addressSpace = ThunkAddressSpace(of: image) - for name in names { - guard let exported = image.exportTrie?.search(by: name), - let exportedSymbolOffset = exported.offset, - let exportedAddress = addressSpace.address(forExportedSymbolOffset: exportedSymbolOffset) - else { continue } - addressesByName[exportedAddress] = name - } - entryPointAddressesByImagePath[path] = addressesByName - } - return entryPointAddressesByImagePath[path]?[address] - } -} diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift index fca286ad6..08a00e8e3 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift @@ -2,7 +2,9 @@ /// The eviction group of this module's per-image caches. extension SharedCacheEvictionGroup { - /// `MetadataAccessorIndex` and `DependencyImageResolver`: the thunk - /// reader's per-root accessor index and dependency image handles. + /// `MetadataAccessorIndex`, `DependencyImageResolver`, `CacheImageLocator` + /// and the image's own runtime symbols `MachOThunkEnvironment` names call + /// targets by: the thunk reader's per-root accessor index, dependency + /// image handles, cache image table and symbol table extract. package static let thunkResolution = SharedCacheEvictionGroup("thunkResolution") } diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift deleted file mode 100644 index a481c4790..000000000 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift +++ /dev/null @@ -1,143 +0,0 @@ -import Foundation -import MachOKit -import MachOFoundation -import MachOSwiftSection - -/// Converts between the offsets `MachOSwiftSection` uses and the virtual -/// addresses a disassembler needs. -/// -/// ## Why this type exists at all -/// -/// For an image **inside a dyld shared cache** the offsets threaded through -/// `MachOSwiftSection` are not file offsets. `MachOFile.Swift`'s -/// `_sectionOffsetAndSize` establishes the convention: -/// -/// ```swift -/// let offset = if let cache = machO.cache { -/// section.address - cache.mainCacheHeader.sharedRegionStart.cast() -/// } else { -/// section.offset -/// } -/// ``` -/// -/// so every descriptor offset, every relative-pointer target, and the offset a -/// kind-9 node carries are all `unslidVirtualAddress - sharedRegionStart`. -/// Converting is one subtraction. -/// -/// Three other conversions look like they would work and do not. All were -/// measured against SwiftUI on the macOS 26 cache, and all fail *silently* — -/// they return a plausible address in the wrong place rather than `nil`: -/// -/// | Used instead | What goes wrong | -/// |---|---| -/// | `segment.fileOffset` / `headerStartOffsetInCache` | subcache file offsets; differ from the above by a constant (557056 for SwiftUI), yielding an address still inside `__TEXT` but off by 0x88000 | -/// | `MachOFile.fileOffset(of:)` | file accounting, **not** the accounting `readElements(offset:)` takes — the two are not inverses here | -/// | `FullDyldCache.address(of:)` | a third accounting again (a further 16384 off) | -/// -/// The damage is subtle because `adrp` computes its page base from the -/// instruction's own address: an error smaller than a page leaves the -/// candidate addresses *computable and wrong*, pointing into a neighbouring -/// image's segments. Measured symptom: SwiftUI's candidates appearing to live -/// in `TextRecognition`'s `__AUTH_CONST`. -package struct ThunkAddressSpace: Sendable { - /// `sharedRegionStart` when the image lives in a shared cache; `nil` for a - /// standalone file, where offsets are ordinary file offsets. - private let sharedRegionStart: UInt64? - - /// File-offset → address mapping for the standalone case, and the - /// address ranges the image spans for ``containsAddress(_:)``. - private let segments: [(fileOffset: Int, fileSize: Int, virtualMemoryAddress: UInt64, virtualMemorySize: UInt64)] - - /// Where the image's mach header sits: the start of `__TEXT`. - private let textSegmentAddress: UInt64? - - /// The addresses `__TEXT` spans — where code the evaluator may follow - /// into lives. - private let textSegmentRange: Range? - - package init(of machO: MachOFile) { - if let cache = machO.cache { - self.sharedRegionStart = numericCast(cache.mainCacheHeader.sharedRegionStart) - } else { - self.sharedRegionStart = nil - } - segments = machO.segments.map { - (fileOffset: $0.fileOffset, fileSize: $0.fileSize, virtualMemoryAddress: UInt64($0.virtualMemoryAddress), virtualMemorySize: UInt64($0.virtualMemorySize)) - } - let textSegment = machO.segments.first { $0.segmentName == "__TEXT" } - textSegmentAddress = textSegment.map { UInt64($0.virtualMemoryAddress) } - textSegmentRange = textSegment.map { UInt64($0.virtualMemoryAddress) ..< UInt64($0.virtualMemoryAddress) &+ UInt64($0.virtualMemorySize) } - } - - /// Whether `address` lies in this image's `__TEXT` segment. - package func isInTextSegment(_ address: UInt64) -> Bool { - textSegmentRange?.contains(address) ?? false - } - - /// Whether `address` lies in any of this image's segments. - /// - /// Not the same question as ``offset(forAddress:)`` answering: inside a - /// shared cache that conversion is one subtraction and answers for - /// EVERY address in the cache, another image's included — so a callee - /// reached through a rebased pointer (libswiftSynchronization's `Mutex` - /// accessor from SwiftUICore) has an offset here that means nothing to - /// this image's indexes. This is the test that sends such an address to - /// the cache's image table instead. - package func containsAddress(_ address: UInt64) -> Bool { - segments.contains { address >= $0.virtualMemoryAddress && address < $0.virtualMemoryAddress &+ $0.virtualMemorySize } - } - - /// An `ExportedSymbol.offset` → address. - /// - /// The export trie stores each symbol as an offset **from the mach - /// header**, and `MachOKit` hands that number over unchanged for a cache - /// image — so it is NOT a file offset there, and mapping it through the - /// segments' file ranges lands inside `__LINKEDIT` (measured: - /// `libswiftCore`'s `_$sShMa`, header offset 4598948, "found" at - /// 0x1FFD3E9A4 — a computable, plausible, wrong address 1.8 GB past the - /// real one). The header is the first byte of `__TEXT`, so the address - /// is `__TEXT`'s plus the offset, which is also right for a standalone - /// dylib (`__TEXT` at 0) and an executable (`__TEXT` at 0x100000000). - package func address(forExportedSymbolOffset offset: Int) -> UInt64? { - textSegmentAddress.map { $0 &+ UInt64(offset) } - } - - package func address(forOffset offset: Int) -> UInt64? { - if let sharedRegionStart { - return UInt64(offset) &+ sharedRegionStart - } - for segment in segments where offset >= segment.fileOffset && offset < segment.fileOffset + segment.fileSize { - return segment.virtualMemoryAddress &+ UInt64(offset - segment.fileOffset) - } - return nil - } - - /// A `MachOFile` symbol table entry's value (`Symbol.offset`) → address, - /// when it lies in one of this image's segments. - /// - /// `MachOKit` hands over the raw `n_value`, which already IS the unslid - /// address — in a standalone file and inside a shared cache alike. It - /// used to be run through the segment table as a file offset: right by - /// coincidence for a dylib, whose `__TEXT` sits at 0, and nothing found - /// for a main executable, whose `__TEXT` sits at 0x100000000 — so an - /// executable's own runtime helpers went unrecognized. An export trie's - /// offset is neither — see ``address(forExportedSymbolOffset:)``. - package func address(forSymbolValue symbolValue: Int) -> UInt64? { - guard symbolValue >= 0 else { return nil } - let address = UInt64(symbolValue) - return containsAddress(address) ? address : nil - } - - package func offset(forAddress address: UInt64) -> Int? { - if let sharedRegionStart { - guard address >= sharedRegionStart else { return nil } - return Int(address - sharedRegionStart) - } - for segment in segments { - let segmentEnd = segment.virtualMemoryAddress &+ UInt64(segment.fileSize) - guard address >= segment.virtualMemoryAddress, address < segmentEnd else { continue } - return segment.fileOffset + Int(address - segment.virtualMemoryAddress) - } - return nil - } -} diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift index a88cd0030..6a62357cf 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift @@ -1,7 +1,9 @@ import Foundation import FoundationToolbox import MachOKit +@_spi(Internals) import MachOAddressResolution import MachOFoundation +import SwiftSymbols import MachOSwiftSection @_spi(Internals) import Demangling @_spi(Internals) import SwiftInspection @@ -224,7 +226,7 @@ package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { /// Names a metadata record: its exported `…VN` symbol first, then the /// record's own descriptor. package enum MetadataNaming { - package static func typeNode(forMetadataAt address: UInt64, addressSpace: ThunkAddressSpace, in machO: MachOFile) -> Node? { + package static func typeNode(forMetadataAt address: UInt64, addressSpace: ImageAddressSpace, in machO: MachOFile) -> Node? { guard let offset = addressSpace.offset(forAddress: address) else { return nil } // The metadata symbol first: `…VN` is an *exported* symbol, so it // survives the stripping that removes the thunk's own diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift new file mode 100644 index 000000000..2521db514 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift @@ -0,0 +1,245 @@ +import Foundation +import CrossReferenceAnalysis + +/// A JSON value of a `refs` or `symbolicate` document. Addresses are always +/// hexadecimal strings, never numbers: a client parsing JSON numbers as +/// doubles loses the low bits of a 64-bit address. +enum CrossReferenceJSONValue: Encodable, Sendable, Hashable { + case string(String) + case integer(Int) + case bool(Bool) + case array([CrossReferenceJSONValue]) + case object([String: CrossReferenceJSONValue]) + case null + + static func address(_ value: UInt64) -> CrossReferenceJSONValue { + .string(CrossReferenceFormatting.hexadecimal(value)) + } + + static func optionalString(_ value: String?) -> CrossReferenceJSONValue { + value.map { .string($0) } ?? .null + } + + func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .string(let value): try container.encode(value) + case .integer(let value): try container.encode(value) + case .bool(let value): try container.encode(value) + case .array(let values): try container.encode(values) + case .object(let members): try container.encode(members) + case .null: try container.encodeNil() + } + } + + /// The document's bytes: indented, keys sorted, so that two runs over the + /// same input print the same bytes. + func encoded() throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + return try encoder.encode(self) + } +} + +/// How `refs` and `symbolicate` spell what they report, as text and as JSON. +/// The JSON names are a contract: renaming one is a breaking change of the +/// command line. +enum CrossReferenceFormatting { + static func hexadecimal(_ value: UInt64) -> String { + "0x" + String(value, radix: 16) + } + + /// An image's file name, which the text rows show for its path. + static func imageName(ofPath path: String) -> String { + (path as NSString).lastPathComponent + } + + static func name(of kind: CodeReferenceKind) -> String { + switch kind { + case .call: "call" + case .tailCall: "tailCall" + case .reference: "reference" + } + } + + static func name(of route: CodeReferenceRoute) -> String { + switch route { + case .direct: "direct" + case .imageStub: "imageStub" + case .stubIsland: "stubIsland" + case .cacheSharedStub: "cacheSharedStub" + case .pointerSlot: "pointerSlot" + case .addressMaterialization: "addressMaterialization" + case .literalLoad: "literalLoad" + case .indirect: "indirect" + } + } + + static func name(of slotKind: AddressSymbolication.PointerSlotKind) -> String { + switch slotKind { + case .globalOffsetTable: "globalOffsetTable" + case .selectorReference: "selectorReference" + case .classReference: "classReference" + case .superclassReference: "superclassReference" + case .protocolReference: "protocolReference" + case .instanceVariableOffset: "instanceVariableOffset" + } + } + + /// `characters` in double quotes, with the characters that would break a + /// line escaped. + static func quoted(_ characters: String) -> String { + var quoted = "\"" + for character in characters.unicodeScalars { + switch character { + case "\"": quoted += "\\\"" + case "\\": quoted += "\\\\" + case "\n": quoted += "\\n" + case "\r": quoted += "\\r" + case "\t": quoted += "\\t" + default: quoted.unicodeScalars.append(character) + } + } + return quoted + "\"" + } +} + +/// Names what references point at, for one request: the functions are looked +/// up in one pass over their images (``prepareFunctions(at:)``), the Swift +/// types as they come. +final class CrossReferenceTargetNaming { + let analyzer: CrossReferenceAnalyzer + private var functionsByLocation: [CodeLocation: CodeFunction] = [:] + private var swiftTypeKeysByLocation: [CodeLocation: String?] = [:] + + init(analyzer: CrossReferenceAnalyzer) { + self.analyzer = analyzer + } + + /// Looks up the functions at `locations` together, each image's function + /// table built for the lookup and dropped. + func prepareFunctions(at locations: some Sequence) { + let missing = Set(locations).subtracting(functionsByLocation.keys) + guard !missing.isEmpty else { return } + functionsByLocation.merge(analyzer.functions(containing: missing)) { existing, _ in existing } + } + + func function(at location: CodeLocation) -> CodeFunction? { + if let function = functionsByLocation[location] { return function } + prepareFunctions(at: [location]) + return functionsByLocation[location] + } + + func imagePath(of location: CodeLocation) -> String { + analyzer.imagePaths[location.imageIndex] + } + + /// The name of the function at `location`, or its address when nothing + /// names it — with the offset of `address` into it, when that is not its + /// first instruction. + func functionText(at location: CodeLocation, address: UInt64? = nil) -> String { + let base = function(at: location)?.name?.spelling ?? CrossReferenceFormatting.hexadecimal(location.address) + guard let address, address > location.address else { return base } + return base + "+" + CrossReferenceFormatting.hexadecimal(address - location.address) + } + + private func swiftTypeKey(at location: CodeLocation) -> String? { + if let key = swiftTypeKeysByLocation[location] { return key } + let key = analyzer.swiftTypeIdentity(ofDescriptorAt: location)?.key + swiftTypeKeysByLocation[location] = key + return key + } + + private func locationJSON(_ location: CodeLocation) -> [String: CrossReferenceJSONValue] { + ["image": .string(imagePath(of: location)), "address": .address(location.address)] + } + + func json(_ target: CodeReferenceTarget) -> CrossReferenceJSONValue { + switch target { + case .function(let location): + var members = locationJSON(location) + members["name"] = .optionalString(function(at: location)?.name?.spelling) + return .object(["function": .object(members)]) + case .importedSymbol(let name): + return .object(["importedSymbol": .string(name)]) + case .messageSend(let selector, let receiver): + var members: [String: CrossReferenceJSONValue] = ["selector": .string(selector)] + switch receiver { + case .methodReceiver: members["receiver"] = .string("methodReceiver") + case .classLiteral(let className): + members["receiver"] = .string("classLiteral") + members["receiverClass"] = .string(className) + case .unknown: members["receiver"] = .string("unknown") + } + return .object(["messageSend": .object(members)]) + case .superMessageSend(let selector, let className): + return .object(["superMessageSend": .object(["selector": .string(selector), "class": .optionalString(className)])]) + case .swiftType(let descriptor): + var members = locationJSON(descriptor) + members["key"] = .optionalString(swiftTypeKey(at: descriptor)) + return .object(["swiftType": .object(members)]) + case .swiftTypeName(.mangledName(let location, let length)): + var members = locationJSON(location) + members["length"] = .integer(length) + return .object(["swiftTypeName": .object(members)]) + case .swiftTypeName(.accessorSymbol(let symbol)): + return .object(["swiftTypeName": .object(["accessorSymbol": .string(symbol)])]) + case .objectiveCClass(let name, let location): + var members = locationJSON(location) + members["name"] = .string(name) + return .object(["objectiveCClass": .object(members)]) + case .objectiveCInstanceVariable(let className, let name): + return .object(["instanceVariable": .object(["class": .string(className), "name": .string(name)])]) + case .cString(let characters): + return .object(["cString": .string(characters)]) + case .constantString(let characters): + return .object(["constantString": .string(characters)]) + case .indirect(let evidence): + return .object(["indirect": .object([ + "tableOffset": evidence.tableOffset.map { .integer(Int($0)) } ?? .null, + "pointerAuthenticationConstant": evidence.pointerAuthenticationConstant.map { .address(UInt64($0)) } ?? .null, + "isAddressBlended": .bool(evidence.isAddressBlended), + ])]) + case .unrecognized(let address): + return .object(["unrecognized": .address(address)]) + } + } + + func text(_ target: CodeReferenceTarget) -> String { + switch target { + case .function(let location): + return "\(functionText(at: location)) (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: location))))" + case .importedSymbol(let name): + return "\(name) (imported)" + case .messageSend(let selector, let receiver): + switch receiver { + case .methodReceiver: return "send \(selector) to self" + case .classLiteral(let className): return "send \(selector) to \(className)" + case .unknown: return "send \(selector)" + } + case .superMessageSend(let selector, let className): + return "send super \(selector)" + (className.map { " above \($0)" } ?? "") + case .swiftType(let descriptor): + let name = swiftTypeKey(at: descriptor) ?? CrossReferenceFormatting.hexadecimal(descriptor.address) + return "type \(name) (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: descriptor))))" + case .swiftTypeName(.mangledName(let location, let length)): + return "type name at \(CrossReferenceFormatting.hexadecimal(location.address)), \(length) bytes (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: location))))" + case .swiftTypeName(.accessorSymbol(let symbol)): + return "type accessor \(symbol)" + case .objectiveCClass(let name, let location): + return "class \(name) (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: location))))" + case .objectiveCInstanceVariable(let className, let name): + return "ivar \(className).\(name)" + case .cString(let characters): + return "C string \(CrossReferenceFormatting.quoted(characters))" + case .constantString(let characters): + return "CFString @\(CrossReferenceFormatting.quoted(characters))" + case .indirect(let evidence): + var text = "indirect" + if let tableOffset = evidence.tableOffset { text += " at offset \(tableOffset)" } + return text + case .unrecognized(let address): + return "unrecognized \(CrossReferenceFormatting.hexadecimal(address))" + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift new file mode 100644 index 000000000..7b350a793 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift @@ -0,0 +1,121 @@ +import Foundation +import MachOKit +import MachOKitExtensions +import CrossReferenceAnalysis + +/// The images a cross-reference request analyzes: every image of a dyld +/// shared cache, or a set of standalone files read together, as dyld would +/// load them — an app's executable and the frameworks it embeds. +/// +/// Addresses in and out are unslid: the cache's own, or each file's own. +public enum CrossReferenceInput: Sendable, Hashable { + /// Standalone Mach-O files. `architecture` picks a fat binary's slice, + /// and a fat binary needs one: only arm64 slices can be analyzed. + case files(paths: [String], architecture: Architecture?) + /// Every image of the dyld shared cache at `path`. + case dyldSharedCache(path: String) + /// Every image of the running system's dyld shared cache, read from its + /// files rather than from the process. + case systemDyldSharedCache +} + +/// Why a cross-reference request could not run. +public enum CrossReferenceRequestError: Error, LocalizedError, Sendable, Equatable { + /// A ``CrossReferenceInput/files(paths:architecture:)`` input naming no + /// file. + case noFile + /// No analyzed image has this name or path. + case imageNotFound(name: String) + /// No analyzed image defines or imports a symbol of this name. + case symbolNotFound(name: String) + /// The symbol names no function's first instruction: a variable, or data. + case symbolIsNoFunction(name: String) + /// No analyzed image defines or imports a class of this name. + case classNotFound(name: String) + /// No function of the image the address was looked up in holds it. + case noFunction(address: UInt64) + /// Several of the files hold a function at the address; the image must + /// be named. + case ambiguousFunction(address: UInt64, imagePaths: [String]) + /// Only a function's callees can be listed. + case calleesRequireFunction + /// A file or cache that holds no arm64 code. + case unsupportedArchitecture(path: String) + + public var errorDescription: String? { + switch self { + case .noFile: + "No Mach-O file to analyze." + case .imageNotFound(let name): + "No analyzed image is named '\(name)'." + case .symbolNotFound(let name): + "No analyzed image defines or imports a symbol named '\(name)'." + case .symbolIsNoFunction(let name): + "The symbol '\(name)' does not name the start of a function." + case .classNotFound(let name): + "No analyzed image defines or imports an Objective-C class named '\(name)'." + case .noFunction(let address): + "No function holds the address \(CrossReferenceFormatting.hexadecimal(address))." + case .ambiguousFunction(let address, let imagePaths): + "Several images hold a function at \(CrossReferenceFormatting.hexadecimal(address)): \(imagePaths.joined(separator: ", "))." + case .calleesRequireFunction: + "Only a function's callees can be listed." + case .unsupportedArchitecture(let path): + "\(path) holds no arm64 code; cross references are read from arm64 code only." + } + } +} + +extension CrossReferenceInput { + /// The analyzer over the images this input names. + func makeAnalyzer() throws -> CrossReferenceAnalyzer { + do { + switch self { + case .files(let paths, let architecture): + guard !paths.isEmpty else { throw CrossReferenceRequestError.noFile } + // A fat file needs its slice named, as everywhere else on + // the command line: the one shared loader refuses to pick. + return try CrossReferenceAnalyzer(machOFiles: paths.map { try MachOSource.file(path: $0, architecture: architecture).load() }) + case .dyldSharedCache(let path): + return try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: URL(fileURLWithPath: path))) + case .systemDyldSharedCache: + guard let dyldCache = FullDyldCache.cachedHost else { throw MachOSourceError.systemDyldSharedCacheUnavailable } + return try CrossReferenceAnalyzer(dyldCache: dyldCache) + } + } catch let error as CrossReferenceAnalyzer.FileAnalysisError where error.code == .unsupportedArchitecture { + throw CrossReferenceRequestError.unsupportedArchitecture(path: error.path) + } + } + + /// The input, as the JSON document names it. + var jsonDescription: [String: CrossReferenceJSONValue] { + switch self { + case .files(let paths, _): + ["files": .array(paths.map { .string($0) })] + case .dyldSharedCache(let path): + ["dyldSharedCache": .string(path)] + case .systemDyldSharedCache: + ["systemDyldSharedCache": .string(FullDyldCache.cachedHost?.url.path ?? "")] + } + } +} + +extension CrossReferenceAnalyzer { + /// The positions of the images `names` name — each by its path, or by + /// its file name (`AppKit`, `libobjc.A.dylib`), which may name more than + /// one: a cache carries the macOS and the Mac Catalyst variant of some + /// frameworks. Every image, sorted, when `names` is empty. + func imageIndices(named names: [String]) throws -> [Int] { + guard !names.isEmpty else { return Array(0 ..< imageCount) } + var imageIndices = Set() + for name in names { + let matches = imagePaths.indices.filter { imageIndex in + let path = imagePaths[imageIndex] + return path == name || (path as NSString).lastPathComponent == name + } + guard !matches.isEmpty else { throw CrossReferenceRequestError.imageNotFound(name: name) } + imageIndices.formUnion(matches) + } + return imageIndices.sorted() + } +} diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift new file mode 100644 index 000000000..445981e22 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift @@ -0,0 +1,410 @@ +import Foundation +import CrossReferenceAnalysis + +/// What `refs` looks for. +public enum CrossReferenceSubject: Sendable, Hashable { + /// Every send of the selector, `super` sends included. + case selector(String) + /// A symbol, with its leading underscore: a C function, a Swift mangled + /// name, `_OBJC_CLASS_$_` (the class) or + /// `_OBJC_IVAR_$_.` (the instance variable). A function + /// none of the analyzed images defines is looked for as the imported + /// symbol it is. + case symbol(String) + /// An Objective-C class by its runtime name: `NSWindow`, + /// `_TtC7SwiftUI20FilePresenterWrapper`. + case objectiveCClass(String) + /// The function holding the unslid `address`, in the image `imageName` + /// names — needed only when several of a set of standalone files hold a + /// function there. + case function(address: UInt64, imageName: String?) + /// Loads of the instance variable's offset variable. + case instanceVariable(className: String, name: String) + /// A C string or constant `CFString` literal with these characters. + case string(String) +} + +/// Which way `refs` follows a function. +public enum CrossReferenceDirection: Sendable, Hashable { + /// What references the subject. + case callers + /// What the subject function references, in instruction order. + case callees +} + +public enum CrossReferenceOutputFormat: Sendable, Hashable { + /// One reference, or one address, a line. + case text + /// One JSON document, whose addresses are hexadecimal strings. + case json +} + +/// `swift-section refs`: the code that references a selector, a symbol, a +/// class, a function, an instance variable or a string — or, for a function, +/// what it references — across a dyld shared cache or a set of files. +/// +/// The images that can reference the subject are found first, from their +/// symbol tables, selector references and linkage; only those are scanned, +/// concurrently. +public struct ReferencesRequest: Sendable, Equatable { + public var input: CrossReferenceInput + public var subject: CrossReferenceSubject + public var direction: CrossReferenceDirection + /// The images to look in, by path or file name; empty for every image. + /// The subject itself is found in any image. + public var imageNames: [String] + /// At most this many references are reported, the first in image and + /// address order; ``ReferencesResult/isTruncated`` says whether there + /// were more. + public var limit: Int? + public var format: CrossReferenceOutputFormat + + public init( + input: CrossReferenceInput, + subject: CrossReferenceSubject, + direction: CrossReferenceDirection = .callers, + imageNames: [String] = [], + limit: Int? = nil, + format: CrossReferenceOutputFormat = .text + ) { + self.input = input + self.subject = subject + self.direction = direction + self.imageNames = imageNames + self.limit = limit + self.format = format + } + + /// Finds the references, delivers them, and returns them. + @discardableResult + public func run(output: some SwiftSectionOutput) async throws -> ReferencesResult { + let analyzer = try input.makeAnalyzer() + let scope = try analyzer.imageIndices(named: imageNames) + let query = try ResolvedQuery(subject: subject, direction: direction, input: input, scope: scope, analyzer: analyzer) + + var references: [CodeReference] + let scannedImageCount: Int + switch query.search { + case .callees(let function): + references = analyzer.references(madeBy: function) + scannedImageCount = 1 + case .callers(let keys, let candidates): + references = await Self.references(to: keys, inImagesAt: candidates, analyzer: analyzer).filter(query.acceptsReference) + scannedImageCount = candidates.count + } + let referenceCount = references.count + let referencingImageCount = Set(references.map(\.function.imageIndex)).count + let isTruncated = limit.map { referenceCount > $0 } ?? false + if let limit, isTruncated { references = Array(references.prefix(limit)) } + + let naming = CrossReferenceTargetNaming(analyzer: analyzer) + naming.prepareFunctions(at: references.map(\.function) + references.compactMap { reference in + if case .function(let location) = reference.target { location } else { nil } + }) + let rows = references.map { reference in + ReferencesResult.Row( + reference: reference, + imagePath: analyzer.imagePaths[reference.function.imageIndex], + functionName: naming.function(at: reference.function)?.name?.spelling + ) + } + let result = ReferencesResult(rows: rows, scannedImageCount: scannedImageCount, isTruncated: isTruncated) + + switch format { + case .text: + for row in rows { + output.write(.text(Self.text(of: row, naming: naming))) + } + case .json: + output.write(.data(try Self.document(of: result, query: query, input: input, analyzer: analyzer, naming: naming).encoded())) + } + let truncation = isTruncated ? ", the first \(rows.count) of \(referenceCount) reported" : "" + output.reportNote( + "\(Self.counted(referenceCount, "reference")) in \(Self.counted(referencingImageCount, "image")), " + + "\(scannedImageCount) of \(Self.counted(analyzer.imageCount, "image")) scanned\(truncation)" + ) + return result + } + + private static func counted(_ count: Int, _ noun: String) -> String { + "\(count) \(noun)\(count == 1 ? "" : "s")" + } + + // MARK: - Scanning + + /// One serial queue for every request: work waited on synchronously + /// goes to a serial queue, whose target always has a thread to give, and + /// `concurrentPerform` started there still spreads over every core. + private static let scanQueue = DispatchQueue(label: "com.machoswiftsection.swiftsectionkit.cross-references") + + /// The references to `keys` in each candidate image, concurrently, in + /// candidate order. + private static func references(to keys: Set, inImagesAt candidates: [Int], analyzer: CrossReferenceAnalyzer) async -> [CodeReference] { + await withCheckedContinuation { continuation in + scanQueue.async { + let results = ImageResults(count: candidates.count) + DispatchQueue.concurrentPerform(iterations: candidates.count) { position in + results.store(analyzer.references(to: keys, inImageAt: candidates[position]), at: position) + } + continuation.resume(returning: results.joined()) + } + } + } + + /// One slot an image, each written by one iteration alone. + private final class ImageResults: @unchecked Sendable { + private var slots: [[CodeReference]] + private let lock = NSLock() + + init(count: Int) { + slots = Array(repeating: [], count: count) + } + + func store(_ references: [CodeReference], at position: Int) { + lock.withLock { slots[position] = references } + } + + func joined() -> [CodeReference] { + lock.withLock { slots.flatMap(\.self) } + } + } + + // MARK: - Output + + private static func text(of row: ReferencesResult.Row, naming: CrossReferenceTargetNaming) -> String { + let reference = row.reference + let functionText = naming.functionText(at: reference.function, address: reference.instructionAddress) + return [ + CrossReferenceFormatting.hexadecimal(reference.instructionAddress), + CrossReferenceFormatting.imageName(ofPath: row.imagePath), + functionText, + CrossReferenceFormatting.name(of: reference.kind) + (reference.isRuntimeHelperCall ? " (runtime helper)" : ""), + CrossReferenceFormatting.name(of: reference.route), + naming.text(reference.target), + ].joined(separator: " ") + } + + private static func document( + of result: ReferencesResult, + query: ResolvedQuery, + input: CrossReferenceInput, + analyzer: CrossReferenceAnalyzer, + naming: CrossReferenceTargetNaming + ) -> CrossReferenceJSONValue { + var inputMembers = input.jsonDescription + inputMembers["imageCount"] = .integer(analyzer.imageCount) + return .object([ + "query": .object(query.jsonDescription), + "input": .object(inputMembers), + "scannedImageCount": .integer(result.scannedImageCount), + "isTruncated": .bool(result.isTruncated), + "references": .array(result.rows.map { row in + .object([ + "image": .string(row.imagePath), + "function": .object(["address": .address(row.reference.function.address), "name": .optionalString(row.functionName)]), + "site": .address(row.reference.instructionAddress), + "kind": .string(CrossReferenceFormatting.name(of: row.reference.kind)), + "route": .string(CrossReferenceFormatting.name(of: row.reference.route)), + "target": naming.json(row.reference.target), + "isRuntimeHelperCall": .bool(row.reference.isRuntimeHelperCall), + ]) + }), + ]) + } +} + +/// What `refs` found. +public struct ReferencesResult: Sendable { + public struct Row: Sendable, Hashable { + public let reference: CodeReference + /// The path of the image the referencing function lies in. + public let imagePath: String + /// The referencing function's name, when anything names it. + public let functionName: String? + } + + /// In image order, then in the order of the functions and their + /// instructions. + public let rows: [Row] + /// How many images were scanned: the ones that could reference the + /// subject. + public let scannedImageCount: Int + /// Whether ``ReferencesRequest/limit`` left references out. + public let isTruncated: Bool +} + +// MARK: - Resolving the subject + +/// A subject, resolved against the analyzed images: what to scan for and +/// where, or the function whose callees are listed. +private struct ResolvedQuery { + enum Search { + case callers(keys: Set, candidates: [Int]) + case callees(CodeFunction) + } + + var search: Search + /// Drops what the keys match beyond the subject: another class of the + /// same name. + var acceptsReference: (CodeReference) -> Bool = { _ in true } + var jsonDescription: [String: CrossReferenceJSONValue] + + init(subject: CrossReferenceSubject, direction: CrossReferenceDirection, input: CrossReferenceInput, scope: [Int], analyzer: CrossReferenceAnalyzer) throws { + if direction == .callees { + guard case .function(let address, let imageName) = subject else { throw CrossReferenceRequestError.calleesRequireFunction } + let function = try Self.function(at: address, imageName: imageName, input: input, analyzer: analyzer) + search = .callees(function) + jsonDescription = ["function": Self.functionJSON(function, analyzer: analyzer), "direction": .string("callees")] + return + } + let allImages = 0 ..< analyzer.imageCount + switch subject { + case .selector(let selector): + search = .callers(keys: [.selector(selector)], candidates: analyzer.imageIndices(referencingSelector: selector, among: scope)) + jsonDescription = ["selector": .string(selector)] + case .symbol(let name): + if let className = Self.suffix(of: name, after: "_OBJC_CLASS_$_") ?? Self.suffix(of: name, after: "_OBJC_METACLASS_$_") { + self = try Self.objectiveCClass(className, scope: scope, analyzer: analyzer) + jsonDescription = ["symbol": .string(name)] + return + } + if let qualifiedName = Self.suffix(of: name, after: "_OBJC_IVAR_$_"), let dot = qualifiedName.lastIndex(of: ".") { + self = try Self.instanceVariable( + className: String(qualifiedName[.. = [.importedSymbol(name)] + var candidates = Set(analyzer.imageIndices(importing: name, among: scope)) + var functions: [CodeFunction] = [] + for location in locations { + guard let function = analyzer.function(containing: location), function.location == location else { continue } + functions.append(function) + keys.insert(.function(location)) + let names = Self.symbolNames(of: function, adding: name) + keys.formUnion(names.map { .importedSymbol($0) }) + candidates.formUnion(analyzer.imageIndices(callingFunctionAt: location, symbolNames: names, among: scope)) + } + if functions.isEmpty, !locations.isEmpty { throw CrossReferenceRequestError.symbolIsNoFunction(name: name) } + if locations.isEmpty, candidates.isEmpty { throw CrossReferenceRequestError.symbolNotFound(name: name) } + search = .callers(keys: keys, candidates: candidates.sorted()) + jsonDescription = ["symbol": .string(name)] + case .objectiveCClass(let name): + self = try Self.objectiveCClass(name, scope: scope, analyzer: analyzer) + case .function(let address, let imageName): + let function = try Self.function(at: address, imageName: imageName, input: input, analyzer: analyzer) + let names = Self.symbolNames(of: function, adding: nil) + var keys: Set = [.function(function.location)] + keys.formUnion(names.map { .importedSymbol($0) }) + search = .callers(keys: keys, candidates: analyzer.imageIndices(callingFunctionAt: function.location, symbolNames: names, among: scope)) + jsonDescription = ["function": Self.functionJSON(function, analyzer: analyzer), "direction": .string("callers")] + case .instanceVariable(let className, let name): + self = try Self.instanceVariable(className: className, name: name, scope: scope, analyzer: analyzer) + case .string(let characters): + // Any image can hold the literal; none is ruled out. + search = .callers(keys: [.cString(characters), .constantString(characters)], candidates: scope) + jsonDescription = ["string": .string(characters)] + } + } + + private init(search: Search, acceptsReference: @escaping (CodeReference) -> Bool, jsonDescription: [String: CrossReferenceJSONValue]) { + self.search = search + self.acceptsReference = acceptsReference + self.jsonDescription = jsonDescription + } + + private static func suffix(of name: String, after prefix: String) -> String? { + name.hasPrefix(prefix) && name.count > prefix.count ? String(name.dropFirst(prefix.count)) : nil + } + + /// Every name the function's image gives it, `name` first when given. + private static func symbolNames(of function: CodeFunction, adding name: String?) -> [String] { + var names: [String] = name.map { [$0] } ?? [] + if case .symbol(let symbol)? = function.name, !names.contains(symbol) { names.append(symbol) } + for folded in function.foldedSymbolNames where !names.contains(folded) { + names.append(folded) + } + return names + } + + /// Where the class is defined: by its `_OBJC_CLASS_$_` symbol, or — for + /// a class no symbol names, as most private classes in a shared cache — + /// by the images' class lists. + private static func classLocations(named name: String, analyzer: CrossReferenceAnalyzer) -> [CodeLocation] { + let symbolLocations = analyzer.locations(ofSymbolNamed: "_OBJC_CLASS_$_" + name, among: 0 ..< analyzer.imageCount) + if !symbolLocations.isEmpty { return symbolLocations } + return (0 ..< analyzer.imageCount).flatMap { analyzer.objectiveCClassLocations(named: name, inImageAt: $0) } + } + + private static func objectiveCClass(_ name: String, scope: [Int], analyzer: CrossReferenceAnalyzer) throws -> ResolvedQuery { + let locations = classLocations(named: name, analyzer: analyzer) + let importedNames = ["_OBJC_CLASS_$_" + name, "_OBJC_METACLASS_$_" + name] + var candidates = Set(analyzer.imageIndices(importingAnyOf: importedNames, among: scope)) + for location in locations { + candidates.formUnion(analyzer.imageIndices(referencingObjectiveCClassAt: location, among: scope)) + } + if locations.isEmpty, candidates.isEmpty { throw CrossReferenceRequestError.classNotFound(name: name) } + var keys: Set = [.objectiveCClass(name)] + keys.formUnion(importedNames.map { .importedSymbol($0) }) + let classLocations = Set(locations) + return ResolvedQuery( + search: .callers(keys: keys, candidates: candidates.sorted()), + acceptsReference: { reference in + guard case .objectiveCClass(_, let location) = reference.target else { return true } + return classLocations.isEmpty || classLocations.contains(location) + }, + jsonDescription: ["class": .string(name)] + ) + } + + private static func instanceVariable(className: String, name: String, scope: [Int], analyzer: CrossReferenceAnalyzer) throws -> ResolvedQuery { + let definingImages = Set(classLocations(named: className, analyzer: analyzer).map(\.imageIndex)) + var candidates = Set(scope).intersection(definingImages) + candidates.formUnion(analyzer.imageIndices(importing: "_OBJC_IVAR_$_\(className).\(name)", among: scope)) + if definingImages.isEmpty, candidates.isEmpty { throw CrossReferenceRequestError.classNotFound(name: className) } + return ResolvedQuery( + search: .callers(keys: [.instanceVariable(className: className, name: name)], candidates: candidates.sorted()), + acceptsReference: { _ in true }, + jsonDescription: ["instanceVariable": .object(["class": .string(className), "name": .string(name)])] + ) + } + + /// The function holding `address`. A shared cache's images share one + /// address space; a set of files each have their own, so every file + /// holding a function there is a candidate, and two are ambiguous. + private static func function(at address: UInt64, imageName: String?, input: CrossReferenceInput, analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + let imageIndices: [Int?] + if let imageName { + imageIndices = try analyzer.imageIndices(named: [imageName]) + } else if case .files = input { + imageIndices = Array(0 ..< analyzer.imageCount) + } else { + imageIndices = [nil] + } + var functions: [CodeFunction] = [] + for imageIndex in imageIndices { + guard case .function(let start, _, _) = analyzer.symbolication(of: address, inImageAt: imageIndex).meaning, + let function = analyzer.function(containing: start) + else { continue } + functions.append(function) + } + guard let function = functions.first else { throw CrossReferenceRequestError.noFunction(address: address) } + guard functions.count == 1 else { + throw CrossReferenceRequestError.ambiguousFunction(address: address, imagePaths: functions.map { analyzer.imagePaths[$0.location.imageIndex] }) + } + return function + } + + private static func functionJSON(_ function: CodeFunction, analyzer: CrossReferenceAnalyzer) -> CrossReferenceJSONValue { + .object([ + "image": .string(analyzer.imagePaths[function.location.imageIndex]), + "address": .address(function.location.address), + "name": .optionalString(function.name?.spelling), + ]) + } +} diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift new file mode 100644 index 000000000..4eec7bc6d --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift @@ -0,0 +1,111 @@ +import Foundation +import CrossReferenceAnalysis + +/// `swift-section symbolicate`: what each unslid address is — inside which +/// function, a stub and where it leads, a pointer slot and what it holds, a +/// string, the nearest symbol — in a dyld shared cache or a set of files. +public struct SymbolicateRequest: Sendable, Equatable { + public var input: CrossReferenceInput + public var addresses: [UInt64] + /// The image whose addresses these are, by path or file name: a set of + /// standalone files each have their own addresses, and without it an + /// address is read in the first file that maps it. A shared cache's + /// images share theirs, and need none named. + public var imageName: String? + public var format: CrossReferenceOutputFormat + + public init(input: CrossReferenceInput, addresses: [UInt64], imageName: String? = nil, format: CrossReferenceOutputFormat = .text) { + self.input = input + self.addresses = addresses + self.imageName = imageName + self.format = format + } + + /// Symbolicates the addresses, in order, delivers them, and returns them. + @discardableResult + public func run(output: some SwiftSectionOutput) async throws -> [AddressSymbolication] { + let analyzer = try input.makeAnalyzer() + let imageIndex = try imageName.map { name -> Int in + // A name two images answer to — the macOS and the Mac Catalyst + // variant — means the first; their addresses are apart. + try analyzer.imageIndices(named: [name])[0] + } + let symbolications = addresses.map { analyzer.symbolication(of: $0, inImageAt: imageIndex) } + let naming = CrossReferenceTargetNaming(analyzer: analyzer) + switch format { + case .text: + for symbolication in symbolications { + output.write(.text(Self.text(of: symbolication, naming: naming))) + } + case .json: + let document = CrossReferenceJSONValue.object(["symbolications": .array(symbolications.map { Self.json(of: $0, naming: naming) })]) + output.write(.data(try document.encoded())) + } + return symbolications + } + + private static func text(of symbolication: AddressSymbolication, naming: CrossReferenceTargetNaming) -> String { + var columns = [CrossReferenceFormatting.hexadecimal(symbolication.address)] + columns.append(symbolication.imagePath.map(CrossReferenceFormatting.imageName(ofPath:)) ?? "-") + if let segmentName = symbolication.segmentName { + columns.append(segmentName + (symbolication.sectionName.map { "," + $0 } ?? "")) + } else { + columns.append("-") + } + columns.append(meaningText(symbolication.meaning, naming: naming)) + return columns.joined(separator: " ") + } + + private static func meaningText(_ meaning: AddressSymbolication.Meaning, naming: CrossReferenceTargetNaming) -> String { + switch meaning { + case .function(let start, let name, let offset): + let base = name ?? CrossReferenceFormatting.hexadecimal(start.address) + return offset == 0 ? base : base + "+" + CrossReferenceFormatting.hexadecimal(offset) + case .stub(let hops, let target): + return "stub " + hops.map(CrossReferenceFormatting.hexadecimal).joined(separator: " -> ") + " -> " + naming.text(target) + case .pointerSlot(let kind, let target): + return "\(CrossReferenceFormatting.name(of: kind)) slot -> \(naming.text(target))" + case .cString(let characters): + return "C string \(CrossReferenceFormatting.quoted(characters))" + case .constantString(let characters): + return "CFString @\(CrossReferenceFormatting.quoted(characters))" + case .symbol(let name, let offset): + return offset == 0 ? name : name + "+" + CrossReferenceFormatting.hexadecimal(offset) + case .data: + return "data" + case .unmapped: + return "unmapped" + } + } + + private static func json(of symbolication: AddressSymbolication, naming: CrossReferenceTargetNaming) -> CrossReferenceJSONValue { + .object([ + "address": .address(symbolication.address), + "image": .optionalString(symbolication.imagePath), + "segment": .optionalString(symbolication.segmentName), + "section": .optionalString(symbolication.sectionName), + "meaning": meaningJSON(symbolication.meaning, naming: naming), + ]) + } + + private static func meaningJSON(_ meaning: AddressSymbolication.Meaning, naming: CrossReferenceTargetNaming) -> CrossReferenceJSONValue { + switch meaning { + case .function(let start, let name, let offset): + return .object(["function": .object(["start": .address(start.address), "name": .optionalString(name), "offset": .address(offset)])]) + case .stub(let hops, let target): + return .object(["stub": .object(["hops": .array(hops.map { .address($0) }), "target": naming.json(target)])]) + case .pointerSlot(let kind, let target): + return .object(["pointerSlot": .object(["kind": .string(CrossReferenceFormatting.name(of: kind)), "target": naming.json(target)])]) + case .cString(let characters): + return .object(["cString": .string(characters)]) + case .constantString(let characters): + return .object(["constantString": .string(characters)]) + case .symbol(let name, let offset): + return .object(["symbol": .object(["name": .string(name), "offset": .address(offset)])]) + case .data: + return .object(["data": .object([:])]) + case .unmapped: + return .object(["unmapped": .object([:])]) + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift index b2726c91f..a2046d3d1 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift @@ -4,6 +4,7 @@ import ObjCDiffing import ObjCIndexing import ObjCInterface import ObjCMetadataSource +import SwiftIndexing /// `swift-section objc snapshot`: index a binary's ObjC API and persist it as a /// baseline document — or relabel an existing document. @@ -124,6 +125,32 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { case summary /// The evolution as JSON. case json + /// The union header annotated with per-declaration lifecycle + /// comments, each declaration rendered the way `objc dump` renders + /// it. Every input must be a binary. `availabilityAttributes` says + /// whether a lifecycle one availability macro can express is also + /// spelled as that macro. + case annotatedInterface(availabilityAttributes: AvailabilityAttributes) + } + + /// Whether the annotated header also spells lifecycles as availability + /// macros (`API_AVAILABLE`, `API_OBSOLETED`), and for which platform. + /// + /// A declaration gets the macro only when one macro expresses its whole + /// lifecycle: one unbroken run of versions carrying it, every label + /// involved a numeric version (`26.0`), and an addition or a removal + /// inside the axis. Its lifecycle comment stays either way. + public enum AvailabilityAttributes: Sendable, Hashable { + /// The lifecycle comments alone. + case none + /// For the platform every input's `LC_BUILD_VERSION` names, a + /// simulator counting as its device. Inputs that name no platform the + /// availability macros can spell, or different ones, throw + /// ``ObjCAvailabilityPlatformInferenceError``. + case inferredPlatform + /// For this platform, spelled the way the availability macros spell + /// it: `macos`, `ios`, `macCatalyst`. + case platform(String) } /// The inputs in version order, oldest first. They are loaded one after @@ -154,6 +181,9 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { if let labels, labels.count != inputs.count { throw ObjCAPIEvolutionError.labelCountMismatch(labelCount: labels.count, versionCount: inputs.count) } + if case .annotatedInterface(let availabilityAttributes) = report { + return try await runAnnotatedInterface(availabilityAttributes: availabilityAttributes, output: output, environment: environment) + } var documents: [ObjCAPISnapshotDocument] = [] for (inputIndex, input) in inputs.enumerated() { @@ -180,7 +210,7 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self) case .summary: ObjCAPIEvolutionReporter().summary(evolution) - case .lineage: + case .lineage, .annotatedInterface: ObjCAPIEvolutionReporter().report(evolution) } try destination.deliver( @@ -190,6 +220,143 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { ) return ObjCAPIEvolutionOutcome(evolution: evolution) } + + /// The union header with lifecycle annotations, rendered from the live + /// declarations of every version — which is why snapshot inputs are + /// rejected, the same constraint as the Swift `evolution --interface`. + private func runAnnotatedInterface( + availabilityAttributes: AvailabilityAttributes, + output: some SwiftSectionOutput, + environment: SwiftSectionEnvironment + ) async throws -> ObjCAPIEvolutionOutcome { + try SnapshotSource.requireBinaries(inputs) + + var machOFiles: [MachOFile] = [] + for input in inputs { + output.reportProgress("Loading \(input.path)…") + machOFiles.append(try binaryLoading.machOSource(forBinaryAt: input.path).load()) + } + let resolvedLabels = inputs.enumerated().map { inputIndex, input in + labels?[inputIndex] ?? input.defaultLabel + } + // Before indexing, so that a platform that cannot be inferred costs + // only the loading. + let availabilityPlatform = try availabilityAttributes.platform(forInputsAt: inputs.map(\.path), loadedAs: machOFiles) + + // One version at a time, oldest first: the builder keeps what it + // rendered and snapshotted, never the indexer, so each version's index + // is released before the next one is built. + var builder = ObjCEvolutionInterfaceBuilder() + for (inputIndex, machOFile) in machOFiles.enumerated() { + output.reportProgress("Indexing \(inputs[inputIndex].path)…") + let indexer = ObjCInterfaceIndexer( + machO: machOFile, + imagePath: machOFile.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machOFile) + ) + try await indexer.prepare() + builder.addVersion( + indexer: indexer, + machO: machOFile, + version: ObjCAPIVersionDescriptor( + label: resolvedLabels[inputIndex], + provenance: ObjCAPIProvenance( + label: resolvedLabels[inputIndex], + binaryPath: inputs[inputIndex].path + binaryLoading.provenancePathSuffix, + generatorVersion: environment.generator.version, + createdAt: environment.currentDate() + ) + ) + ) + } + output.reportProgress("Rendering annotated header…") + let evolutionInterface = try builder.build(availabilityPlatform: availabilityPlatform) + let annotatedHeader = evolutionInterface.interface.string + + switch destination { + case .output: + output.write(.annotatedInterface(annotatedHeader, style: .evolution)) + case .file(let path): + // The newline printing adds, so that the two destinations hold the + // same bytes. + try (annotatedHeader + "\n").write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + output.reportProgress("Annotated header written to \(path)") + } + return ObjCAPIEvolutionOutcome(evolution: evolutionInterface.evolution) + } +} + +/// Why ``ObjCAPIEvolutionRequest/AvailabilityAttributes/inferredPlatform`` +/// found no one platform to spell the availability macros for. Naming the +/// platform with ``ObjCAPIEvolutionRequest/AvailabilityAttributes/platform(_:)`` +/// avoids both. +public enum ObjCAvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { + /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform + /// the availability macros have no name for, such as bridgeOS. + case noPlatform(path: String) + /// The inputs name different platforms, spelled the availability macros' + /// way and sorted. + case conflictingPlatforms([String]) + + public var errorDescription: String? { + switch self { + case .noPlatform(let path): + "No availability platform can be inferred from '\(path)': it has no LC_BUILD_VERSION, or names a platform the availability macros have no name for." + case .conflictingPlatforms(let platforms): + "The inputs name different availability platforms (\(platforms.joined(separator: ", ")))." + } + } +} + +extension ObjCAPIEvolutionRequest.AvailabilityAttributes { + /// The platform the availability macros are spelled for, `nil` for none. + /// `paths[index]` names `machOFiles[index]` in an error. + func platform(forInputsAt paths: [String], loadedAs machOFiles: [MachOFile]) throws -> String? { + switch self { + case .none: + return nil + case .platform(let platform): + return platform + case .inferredPlatform: + var platforms: Set = [] + for (path, machOFile) in zip(paths, machOFiles) { + guard let buildPlatform = machOFile.loadCommands.buildVersionCommand?.platform, + let platform = Self.availabilityMacroSpelling(of: buildPlatform) else { + throw ObjCAvailabilityPlatformInferenceError.noPlatform(path: path) + } + platforms.insert(platform) + } + if platforms.count > 1 { + throw ObjCAvailabilityPlatformInferenceError.conflictingPlatforms(platforms.sorted()) + } + // No inputs at all is left to the renderer, which needs two. + return platforms.first + } + } + + /// How the availability macros (`API_AVAILABLE(macos(13.0))`) spell a + /// Mach-O build platform, `nil` for one they have no name for (bridgeOS, + /// firmware, …). A simulator shares its device's availability domain. + static func availabilityMacroSpelling(of buildPlatform: MachOKit.Platform) -> String? { + switch buildPlatform { + case .macOS: + "macos" + case .iOS, .iOSSimulator: + "ios" + case .tvOS, .tvOSSimulator: + "tvos" + case .watchOS, .watchOSSimulator: + "watchos" + case .visionOS, .visionOSSimulator: + "visionos" + case .macCatalyst: + "macCatalyst" + case .driverKit: + "driverkit" + default: + nil + } + } } public struct ObjCAPIEvolutionOutcome: Sendable { @@ -228,7 +395,7 @@ enum ObjCAPISnapshotLoading { output.reportProgress("Indexing \(source.path)…") let machOFile = try binaryLoading.machOSource(forBinaryAt: source.path).load() - let indexer = ObjCInterfaceIndexer(machO: machOFile, imagePath: machOFile.imagePath) + let indexer = ObjCInterfaceIndexer(machO: machOFile, imagePath: machOFile.imagePath, suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machOFile)) try await indexer.prepare() let snapshotBuilder = ObjCAPISnapshotBuilder(indexer: indexer) let provenance = ObjCAPIProvenance( diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift index f0637f9fc..7e19229b7 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift @@ -1,7 +1,13 @@ import Foundation +import MachOKit import ObjCDeclarationRendering import ObjCOutputTransformer import OutputTransformer +import Semantic +import SwiftDeclaration +@_spi(Support) import SwiftIndexing +@_spi(Support) import SwiftInterface +@_spi(Support) import SwiftPrinting /// `swift-section objc interface`: print the interface of one Objective-C /// declaration. @@ -21,6 +27,12 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { public var ivarOffsetComment: Transformer.ObjCIvarOffset? public var reportsIndexingProgress: Bool public var destination: ProductDestination + /// Print the declaration as Swift imports it — names by the + /// ClangImporter's rules, members Swift implements as their Swift + /// declarations — instead of as an Objective-C header (evolution + /// proposal `objc-imported-declarations`). Classes, categories and + /// protocols only; the header options do not apply. + public var printsSwiftImport: Bool public init( declarationName: String, @@ -30,7 +42,8 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { cTypeReplacements: [ObjCPrimitiveTypePattern: String] = [:], ivarOffsetComment: Transformer.ObjCIvarOffset? = nil, reportsIndexingProgress: Bool = false, - destination: ProductDestination = .output + destination: ProductDestination = .output, + printsSwiftImport: Bool = false ) { self.declarationName = declarationName self.kind = kind @@ -40,9 +53,14 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { self.ivarOffsetComment = ivarOffsetComment self.reportsIndexingProgress = reportsIndexingProgress self.destination = destination + self.printsSwiftImport = printsSwiftImport } public func run(output: some SwiftSectionOutput) async throws { + if printsSwiftImport { + try await runPrintingSwiftImport(output: output) + return + } let session = try await ObjCInterfaceSession.make( source: source, generation: generation, @@ -68,9 +86,45 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { throw ObjCDeclarationLookupError.declarationNotFound(declarationName) } + + /// The Swift side: the image's declaration index, which pairs a class or + /// category Swift implements with its Swift definitions. + private func runPrintingSwiftImport(output: some SwiftSectionOutput) async throws { + let machOFile = try source.load() + let builder = try SwiftInterfaceBuilder(eventHandlers: output.indexEventHandlers(forInputLabeled: nil), in: machOFile) + output.reportProgress("Indexing Swift declarations...") + try await builder.prepare() + + for candidateKind in kind.map({ [$0] }) ?? ObjCDeclarationKind.allCases { + let interface: SemanticString + switch candidateKind { + case .classes: + guard let definition = builder.indexer.objcImportedClassDefinition(named: declarationName) else { continue } + interface = try await builder.printer.printObjCImportedClassDefinition(definition) + case .protocols: + guard let definition = builder.indexer.objcImportedProtocolDefinition(named: declarationName) else { continue } + interface = try await builder.printer.printObjCImportedProtocolDefinition(definition) + case .categories: + guard let definition = builder.indexer.objcImportedCategoryDefinition(uniqueName: declarationName) else { continue } + interface = try await builder.printer.printObjCImportedCategoryDefinition(definition) + case .structs, .unions: + // C aggregates are no Objective-C declarations to import. + continue + } + switch destination { + case .file(let path): + try interface.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + case .output: + output.write(.declarations(interface)) + } + return + } + + throw ObjCDeclarationLookupError.declarationNotFound(declarationName) + } } -public enum ObjCDeclarationLookupError: Error, LocalizedError, Sendable, Equatable { +public enum ObjCDeclarationLookupError: Swift.Error, LocalizedError, Sendable, Equatable { case declarationNotFound(String) public var errorDescription: String? { diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift index 4355c2dcd..8fd58a93d 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift @@ -8,6 +8,7 @@ import ObjCMetadataSource import ObjCOutputTransformer import OutputTransformer import Semantic +import SwiftIndexing /// The kinds of Objective-C declaration `objc dump` and `objc interface` can /// print. With none given, `objc dump` prints all of them in this order. @@ -53,9 +54,12 @@ struct ObjCInterfaceSession { let eventHandler: (@Sendable (ObjCIndexingEvent) -> Void)? = reportsIndexingProgress ? { @Sendable event in reportProgress(event, to: output) } : nil + // Generic Swift classes and the ones `__objc_stublist` registers have + // no class object; their `class_ro_t` is found through Swift metadata. let indexer = ObjCInterfaceIndexer( machO: machOFile, imagePath: machOFile.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machOFile), eventHandler: eventHandler ) try await indexer.prepare() diff --git a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift index 6de8cf911..9623f2474 100644 --- a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift +++ b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift @@ -77,14 +77,19 @@ extension InterfaceAnnotationStyle { // A trailing lifecycle annotation, or an overflow annotation on // its own (indented) line. Classified by the annotation text // only, so that a declaration whose name mentions these words - // stays plain. + // stays plain. A change across versions that could not show + // the declaration reads `… between A and B`; an annotation + // that only marks such versions (`inferred present in …`, + // `not observable in …`) records no change. let annotation = line[annotationRange.lowerBound...] - if annotation.contains("removed in") { + if annotation.contains("removed in") || annotation.contains("removed between") { return .removed - } else if annotation.contains("modified in") { + } else if annotation.contains("modified in") || annotation.contains("modified between") { return .modified - } else { + } else if annotation.contains("added in") || annotation.contains("added between") { return .added + } else { + return .plain } } else { return .plain diff --git a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift index e92764d82..5a37dd137 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift @@ -5,6 +5,7 @@ import MachOSwiftSection import SwiftDump import Demangling import SwiftInspection +import SwiftObjCInterop import OutputTransformer import SwiftOutputTransformer import SwiftDeclarationRendering @@ -15,7 +16,13 @@ import Semantic /// A part of a binary's Swift metadata that `dump` can print. public enum DumpSection: String, CaseIterable, Sendable, Hashable { case types + /// The protocols of `__swift5_protos`, then the `@objc` protocols + /// declared in Swift, which have no protocol descriptor: they are + /// recognized from `__swift5_fieldmd` and `__objc_protolist`. case protocols + /// The conformance records of `__swift5_proto`, then the Objective-C + /// protocols the image's categories list — extensions of other modules' + /// classes adopting them, which no conformance record names. case protocolConformances case associatedTypes /// Classes implemented through `@objc @implementation`. They have no @@ -62,6 +69,9 @@ public struct DumpRequest: Sendable, Equatable { public var dependencySearchPaths: [DependencySearchPath] public var sections: SectionSelection public var ordering: Ordering + /// How names print. The default is `.default` with existentials spelled + /// with `any` (`useExistentialAny`), as the CLI prints them; a request + /// passing a preset of its own gets what that preset says. public var demangleOptions: DemangleOptions /// Computed statically through SwiftLayout. public var fieldOffsetComments: FieldOffsetComments @@ -97,7 +107,7 @@ public struct DumpRequest: Sendable, Equatable { dependencySearchPaths: [DependencySearchPath] = [], sections: SectionSelection = .all, ordering: Ordering = .bySection, - demangleOptions: DemangleOptions = .default, + demangleOptions: DemangleOptions = DemangleOptions.default.union(.useExistentialAny), fieldOffsetComments: FieldOffsetComments = .none, emitsMemberAddresses: Bool = false, emitsVTableOffsets: Bool = false, @@ -251,6 +261,13 @@ public struct DumpRequest: Sendable, Equatable { session.reportError(error) } } + // `@objc` protocols declared in Swift have no protocol + // descriptor (evolution proposal + // `swift-declared-objc-protocols`). + for objcProtocol in SwiftDeclaredObjCProtocol.all(in: machOFile) { + try await session.dump(.objcProtocol(objcProtocol), using: configuration, in: machOFile) + } + await writeUnclaimedObjCProtocolRecords(using: configuration, in: machOFile, into: session) case .protocolConformances: do { for protocolConformance in try machOFile.swift.protocolConformances { @@ -261,6 +278,9 @@ public struct DumpRequest: Sendable, Equatable { session.reportError(error) } } + for categoryAdoption in ObjCProtocolAdoptionIndex.shared.categoryAdoptions(in: machOFile) { + try await session.dump(.objcCategoryConformance(categoryAdoption), using: configuration, in: machOFile) + } case .associatedTypes: do { for associatedType in try machOFile.swift.associatedTypes { @@ -311,6 +331,7 @@ public struct DumpRequest: Sendable, Equatable { session.reportError(error) } } + topLevelContexts.append(contentsOf: SwiftDeclaredObjCProtocol.all(in: machOFile).map { .objcProtocol($0) }) } if selectedSections.contains(.objcImplementationClasses) { @@ -327,6 +348,7 @@ public struct DumpRequest: Sendable, Equatable { session.reportError(error) } } + topLevelContexts.append(contentsOf: ObjCProtocolAdoptionIndex.shared.categoryAdoptions(in: machOFile).map { .objcCategoryConformance($0) }) } if selectedSections.contains(.associatedTypes) { @@ -342,6 +364,21 @@ public struct DumpRequest: Sendable, Equatable { for topLevelContext in topLevelContexts { try? await session.dump(topLevelContext, using: configuration, in: machOFile) } + + if selectedSections.contains(.protocols) { + await writeUnclaimedObjCProtocolRecords(using: configuration, in: machOFile, into: session) + } + } + + /// The `@objc` protocol records Swift emitted that no protocol of the + /// image claims, as one comment after the protocols. + private func writeUnclaimedObjCProtocolRecords(using configuration: DumperConfiguration, in machOFile: MachOFile, into session: DumpSession) async { + do { + guard let comment = try await SwiftDeclaredObjCProtocol.unclaimedRecordsComment(using: configuration.demangleResolver, in: machOFile) else { return } + session.write(SemanticString { Comment(comment) }) + } catch { + session.reportError(error) + } } } @@ -352,11 +389,17 @@ private enum DumpTopLevelContext { case protocolConformance(ProtocolConformance) case associatedType(AssociatedType) case objcImplementationClass(ObjCImplementationClass) + case objcProtocol(SwiftDeclaredObjCProtocol) + case objcCategoryConformance(ObjCCategoryProtocolAdoption) var offset: Int { switch self { case .objcImplementationClass(let objcImplementationClass): return objcImplementationClass.offset + case .objcProtocol(let objcProtocol): + return objcProtocol.offset + case .objcCategoryConformance(let categoryAdoption): + return categoryAdoption.offset case .type(let type): switch type { case .enum(let `enum`): @@ -379,9 +422,9 @@ private enum DumpTopLevelContext { switch self { case .type: .types - case .protocol: + case .protocol, .objcProtocol: .protocols - case .protocolConformance: + case .protocolConformance, .objcCategoryConformance: .protocolConformances case .associatedType: .associatedTypes @@ -406,6 +449,10 @@ private enum DumpTopLevelContext { try await associatedType.dump(using: configuration, in: machOFile) case .objcImplementationClass(let objcImplementationClass): try await objcImplementationClass.dump(using: configuration, in: machOFile) + case .objcProtocol(let objcProtocol): + try await objcProtocol.dump(using: configuration, in: machOFile) + case .objcCategoryConformance(let categoryAdoption): + try await categoryAdoption.dump(using: configuration, in: machOFile) } } @@ -436,6 +483,10 @@ private enum DumpTopLevelContext { name = try await associatedType.dumpTypeName(using: configuration, in: context) case .objcImplementationClass(let objcImplementationClass): name = try await objcImplementationClass.dumpName(using: configuration, in: context) + case .objcProtocol(let objcProtocol): + name = try await objcProtocol.dumpName(using: configuration, in: context) + case .objcCategoryConformance(let categoryAdoption): + name = try await categoryAdoption.dumpName(using: configuration, in: context) } return name.string } catch { diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index 7e34ed0f1..e52a62377 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -57,8 +57,9 @@ public struct InterfaceRequest: Sendable, Equatable { 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` - /// members and anything without export evidence are kept. + /// and members with at least one exported symbol. A private or local + /// declaration with no symbol to judge by is dropped too. `override` / + /// `@objc` members and anything else without export evidence are kept. public var printsExportedDeclarationsOnly: Bool public var memberSortOrder: SwiftDeclarationMemberSortOrder /// Whether an ObjC method tied to its Swift member by the member's name @@ -68,6 +69,16 @@ 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 + /// Existential types spelled with the `any` keyword (`any P`, `(any P)?`, + /// `any P.Type`), as the compiler writes a `.swiftinterface`. On by + /// default. + public var usesExistentialAny: Bool + /// What an attached macro generated, as the binary has it: an + /// `@Observable` class's registrar, the storage and computed properties of + /// its tracked properties, the generated methods and conformance. Off by + /// default: the class prints with `@Observation.Observable` and the + /// stored properties its source declared. + public var expandsMacros: 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 @@ -96,6 +107,8 @@ public struct InterfaceRequest: Sendable, Equatable { memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory, infersObjCOverridesFromSelectorNames: Bool = false, usesModuleSelectors: Bool = false, + usesExistentialAny: Bool = true, + expandsMacros: Bool = false, protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause, emitsHeader: Bool = false, commentTransformers: Transformer.SwiftConfiguration? = nil, @@ -117,6 +130,8 @@ public struct InterfaceRequest: Sendable, Equatable { self.memberSortOrder = memberSortOrder self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames self.usesModuleSelectors = usesModuleSelectors + self.usesExistentialAny = usesExistentialAny + self.expandsMacros = expandsMacros self.protocolRequirementPlacement = protocolRequirementPlacement self.emitsHeader = emitsHeader self.commentTransformers = commentTransformers @@ -154,6 +169,8 @@ public struct InterfaceRequest: Sendable, Equatable { // whether it prints as `@objc override`. printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames printConfiguration.usesModuleSelectors = usesModuleSelectors + printConfiguration.usesExistentialAny = usesExistentialAny + printConfiguration.expandsMacros = expandsMacros printConfiguration.protocolRequirementPlacement = protocolRequirementPlacement var configuration = SwiftInterfaceBuilderConfiguration( diff --git a/Sources/Declaration/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift b/Sources/Declaration/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift deleted file mode 100644 index aaee67165..000000000 --- a/Sources/Declaration/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift +++ /dev/null @@ -1,77 +0,0 @@ -import SwiftDeclarationRendering - -/// A conformance extension's associated-type witness, frozen into pure value -/// data at index time. -/// -/// The underlying `MachOSwiftSection.AssociatedType` records resolve their -/// names through Mach-O-bound accessors, so anything Mach-O-free downstream -/// (notably `SwiftDiffing`'s snapshot projection) cannot read them after -/// indexing. The indexer therefore resolves each record into this projection -/// while the Mach-O is still in hand. -public struct AssociatedTypeWitnessProjection: Sendable, Codable, Equatable { - /// The associated-type requirement's name (e.g. `Element`). - public let name: String - /// The witness type, demangled with its opaque types expanded, and printed - /// (e.g. `Swift.Int`). - /// - /// When the witness's underlying type is decided by an - /// availability-conditional accessor thunk (evolution proposal - /// `offline-opaque-accessor-thunk-resolution`), this is the branch the - /// current platform takes; the other branches are in - /// ``conditionalCandidates``. - public let substitutedTypeText: String - /// Every answer an availability-conditional accessor thunk inside the - /// witness can give, one entry per branch; empty when the witness carries - /// no such thunk or its shape could not be read. - /// - /// Filled by the offline reader only: in-process the runtime executes the - /// thunk and answers for this OS alone, so there is nothing to list. - public let conditionalCandidates: [ConditionalWitnessCandidate] - - public init(name: String, substitutedTypeText: String, conditionalCandidates: [ConditionalWitnessCandidate] = []) { - self.name = name - self.substitutedTypeText = substitutedTypeText - self.conditionalCandidates = conditionalCandidates - } - - private enum CodingKeys: String, CodingKey { - case name - case substitutedTypeText - case conditionalCandidates - } - - /// Tolerates the key's absence so a projection persisted before - /// `conditionalCandidates` existed still decodes. - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decode(String.self, forKey: .name) - substitutedTypeText = try container.decode(String.self, forKey: .substitutedTypeText) - conditionalCandidates = try container.decodeIfPresent([ConditionalWitnessCandidate].self, forKey: .conditionalCandidates) ?? [] - } -} - -/// One answer an availability-conditional accessor thunk can give for an -/// associated-type witness. -/// -/// A witness whose underlying type is an SE-0360 `if #available` opaque -/// result has one of these per branch. Both texts are carried on purpose: the -/// candidate type alone says which part of the witness changes, while the -/// whole witness with that branch substituted is what a host shows when asked -/// "what does this read as on that OS" — the thunk can sit anywhere in the -/// tree (`SwiftUI.FeedbackGenerator.Body` carries its inside a -/// `ModifiedContent<…>` chain), and a host should not have to know where. -public struct ConditionalWitnessCandidate: Sendable, Codable, Equatable { - /// The platform version the branch is gated on, or `nil` when the thunk - /// has no version check and this is its only answer. - public let availability: PlatformAvailabilityCondition? - /// The type the thunk yields on this branch, printed. - public let candidateTypeText: String - /// The whole witness with this branch substituted, printed. - public let substitutedTypeText: String - - public init(availability: PlatformAvailabilityCondition?, candidateTypeText: String, substitutedTypeText: String) { - self.availability = availability - self.candidateTypeText = candidateTypeText - self.substitutedTypeText = substitutedTypeText - } -} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift deleted file mode 100644 index d634b7966..000000000 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift +++ /dev/null @@ -1,73 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols - -/// Cross-references `@objc` / `@nonobjc` / `distributed` thunk attribute -/// members (pre-extracted and bucketed by parent type name inside -/// `SymbolIndexStore`) with already-built member definitions, appending the -/// matching attribute to each affected member. Shared by `TypeDefinition` -/// and `ExtensionDefinition` — the sweep unwraps extension contexts when it -/// buckets a thunk, so an extension's members are filed under the extended -/// type's name and node, and one lookup serves both containers. -package enum MemberAttributeApplication { - package static let thunkKindsAndAttributes: [(thunkKind: Node.Kind, attribute: SwiftAttribute)] = [ - (.objCAttribute, .objc), - (.nonObjCAttribute, .nonobjc), - (.distributedThunk, .distributed), - ] - - package static func applyThunkAttributes( - symbolIndexStore: SymbolIndexStore, - typeName: String, - typeNode: NodeReference, - in machO: some MachORepresentableWithCache, - functions: inout [FunctionDefinition], - variables: inout [VariableDefinition], - staticFunctions: inout [FunctionDefinition], - staticVariables: inout [VariableDefinition], - allocators: inout [FunctionDefinition] - ) { - for (thunkKind, attribute) in thunkKindsAndAttributes { - // Node-matched: the member-name matching below is string-based, - // so a same-named private sibling's thunks must never reach it - // (issue #115's family). - let members = symbolIndexStore.thunkAttributeMembers(of: thunkKind, for: typeName, node: typeNode, in: machO) - for member in members { - if member.isStatic { - apply(attribute, toFunctionNamed: member.memberName, in: &staticFunctions) - apply(attribute, toVariableNamed: member.memberName, in: &staticVariables) - } else { - apply(attribute, toFunctionNamed: member.memberName, in: &functions) - apply(attribute, toVariableNamed: member.memberName, in: &variables) - if member.isInit { - apply(attribute, toEveryAllocatorIn: &allocators) - } - } - } - } - } - - package static func apply(_ attribute: SwiftAttribute, toFunctionNamed name: String, in definitions: inout [FunctionDefinition]) { - for definitionIndex in definitions.indices { - if definitions[definitionIndex].name == name && !definitions[definitionIndex].attributes.contains(attribute) { - definitions[definitionIndex].attributes.append(attribute) - } - } - } - - package static func apply(_ attribute: SwiftAttribute, toVariableNamed name: String, in definitions: inout [VariableDefinition]) { - for definitionIndex in definitions.indices { - if definitions[definitionIndex].name == name && !definitions[definitionIndex].attributes.contains(attribute) { - definitions[definitionIndex].attributes.append(attribute) - } - } - } - - package static func apply(_ attribute: SwiftAttribute, toEveryAllocatorIn definitions: inout [FunctionDefinition]) { - for definitionIndex in definitions.indices { - if !definitions[definitionIndex].attributes.contains(attribute) { - definitions[definitionIndex].attributes.append(attribute) - } - } - } -} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift deleted file mode 100644 index a19e4b51f..000000000 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift +++ /dev/null @@ -1,64 +0,0 @@ -import MachOSwiftSection -import Demangling -import OrderedCollections -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection - -/// Finds the implementation symbol declared in `typeNode`'s class, skipping -/// already-visited nodes. -/// -/// The match is on the member's DIRECT declaration context. Matching on -/// `first(of: .class)` — the first class node anywhere in the tree — accepts -/// members of NESTED types as members of the enclosing class -/// (`GraphHost.Data.graph.modify` reports `GraphHost`), which under identical -/// code folding is how a vtable slot acquires a name belonging to something -/// else entirely. -/// -/// `visitedNodes` is keyed structurally: `demangledNodeReference(for:)` can -/// hand back references from different stores, and under store-identity -/// equality the "already claimed this symbol" guard would stop firing across -/// them, letting two descriptors bind the same implementation. -/// -/// Lifted out of `SwiftDump`'s `ClassDumper.demangledSymbol(for:typeNode:…)` -/// so the declaration model can resolve method-override symbols during indexing -/// (`TypeDefinition.index`) without depending on the dump layer. It is purely a -/// symbol-table matcher — no rendering — so it belongs with the model rather -/// than the renderer. -/// The structural key `DefinitionBuilder` joins descriptor-side symbols to -/// member-side symbols on. -/// -/// An async method's descriptor `implementation` points at its `Tu` -/// async-function-pointer constant, whose demangled tree carries a leading -/// `.asyncFunctionPointer` marker child the member symbol's tree does not — -/// keyed verbatim, the two trees never match structurally, so async members -/// never joined (no vtable comment, no `override` keyword and, since evolution -/// proposal 0006, a false `final`). Strip the marker so the key takes the -/// member form; every other tree keys as-is. -package func memberJoinKey( - for node: NodeReference, - in context: some ReadingContext -) -> StructuralNodeReferenceKey { - if node.children.first?.kind == .asyncFunctionPointer, let entityNode = node.children.second { - let strippedTree = Node.create(kind: .global, child: entityNode.materialize()) - return StructuralNodeReferenceKey(InternedNodeReferenceCache.shared.reference(interning: strippedTree, in: context)) - } - return StructuralNodeReferenceKey(node) -} - -package func demangledOverrideSymbol( - for symbols: Symbols, - typeNode: Node, - visitedNodes: borrowing OrderedSet = [], - in machO: some MachOSwiftSectionRepresentableWithCache -) -> DemangledSymbol? { - guard let typeClassNode = typeNode.first(of: .class) else { return nil } - for symbol in symbols { - if let node = SymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO), - let declarationContextNode = node.declarationContextNode, - declarationContextNode.structurallyEquals(typeClassNode), - !visitedNodes.contains(StructuralNodeReferenceKey(node)) { - return .init(symbol: symbol, demangledNode: node) - } - } - return nil -} diff --git a/Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift b/Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift deleted file mode 100644 index 469bc5bed..000000000 --- a/Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift +++ /dev/null @@ -1,184 +0,0 @@ -import Foundation -import Dependencies -import MachOSwiftSection -@_spi(Internals) import Demangling -@_spi(Internals) import MachOSymbols - -/// Whether a declaration's own descriptor symbol has an entry in the image's -/// export trie — the fact evolution proposal 0008 annotates with -/// (`// not exported`) and proposal 0016 filters on (`--exported-only`), -/// lifted onto the declaration model so a host can read it per declaration -/// without holding the Mach-O or reimplementing the verdict. -/// -/// The two non-verdict cases are deliberately distinct, because their scope -/// is: ``imageHasNoExportInformation`` is a fact about the IMAGE (no export -/// trie at all — nothing in it can be judged), while -/// ``descriptorSymbolNameUnresolvable`` is a fact about this one -/// DECLARATION (the image's trie is fine; this name cannot be spelled). Both -/// mean "no verdict", and a consumer must never read either as "not -/// exported" — collapsing the first would report every declaration of a -/// `.o` file as unexported. -/// -/// Empirically neither occurs on shipped binaries: over SwiftUICore (dyld -/// shared cache and iOS 18.5 simulator runtime), in-process libswiftCore and -/// the `SymbolTestsCore` fixture, every type and protocol carried a symbol at -/// its own descriptor, so all 8171 declarations resolved to ``exported`` or -/// ``notExported``. They are correctness branches, not the common path. -public enum ExportStatus: Sendable, Hashable { - /// The descriptor symbol is in the image's export trie. - case exported - - /// The image has export information and this descriptor symbol is - /// provably not in it. - case notExported - - /// The image carries no export information whatsoever (an `.o` object - /// file, a static-library product — anything without an export trie). - /// Image-level: no declaration of this image can be judged. - case imageHasNoExportInformation - - /// The image has export information, but no trustworthy symbol name - /// could be produced for this declaration's descriptor, so it is not - /// judged. Today's only source is a name whose context chain runs - /// through a constrained `extension` — see - /// ``ExportStatus/descriptorSymbolName(for:descriptorKind:)``. - case descriptorSymbolNameUnresolvable -} - -extension ExportStatus { - /// The tri-state projection, shaped exactly like - /// `SymbolIndexStore.isExported(name:in:)`: `nil` for both non-verdict - /// cases. Use it where the caller only distinguishes "provably not - /// exported" from everything else. - public var isExported: Bool? { - switch self { - case .exported: true - case .notExported: false - case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable: nil - } - } - - /// The one condition filtering and annotation may act on: a definitive - /// negative verdict. Every other case keeps the declaration. - public var isDefinitelyNotExported: Bool { - self == .notExported - } -} - -// MARK: - Resolution - -extension ExportStatus { - /// A type's status, ruled by its nominal type descriptor symbol (`…Mn`). - /// The descriptor is the one symbol every nominal type owns regardless of - /// what else got exported — on the `SymbolTestsCore` fixture the exported - /// `Mn` and `Ma` (metadata accessor) sets coincide exactly. - package static func resolve( - forNominalTypeDescriptorAt descriptorOffset: Int, - typeNameNode: NodeReference, - in machO: some MachOSwiftSectionRepresentableWithCache - ) -> ExportStatus { - resolve( - descriptorOffset: descriptorOffset, - nameNode: typeNameNode, - descriptorKind: .nominalTypeDescriptor, - descriptorSymbolSuffix: "Mn", - in: machO - ) - } - - /// A protocol's status, ruled by its protocol descriptor symbol (`…Mp`). - package static func resolve( - forProtocolDescriptorAt descriptorOffset: Int, - protocolNameNode: NodeReference, - in machO: some MachOSwiftSectionRepresentableWithCache - ) -> ExportStatus { - resolve( - descriptorOffset: descriptorOffset, - nameNode: protocolNameNode, - descriptorKind: .protocolDescriptor, - descriptorSymbolSuffix: "Mp", - in: machO - ) - } - - /// Two legs, authoritative first: - /// - /// 1. The symbol actually located AT the descriptor. Every exported - /// descriptor has a trie row at its offset, and an unstripped image - /// also carries a local symtab row for a non-exported one, so this leg - /// answers with the compiler's own spelling of the name — which is - /// what makes it authoritative: a type nested in a CONSTRAINED - /// extension (`extension Foo where A: P { public struct Nested {} }`) - /// mangles only the extension's own requirements into its context, - /// while the model's name node carries the full signature, so a - /// remangled name misses the trie and would drop an exported type. - /// 2. Only when no symbol sits at the descriptor (a stripped image's - /// non-exported type): the remangled descriptor name against the trie, - /// which is complete even when the symtab is not. Restricted to - /// canonical contexts — a name involving an `.extension` context is - /// exactly the shape leg 1 exists for, and yields no verdict here. - private static func resolve( - descriptorOffset: Int, - nameNode: NodeReference, - descriptorKind: Node.Kind, - descriptorSymbolSuffix: String, - in machO: some MachOSwiftSectionRepresentableWithCache - ) -> ExportStatus { - @Dependency(\.symbolIndexStore) - var symbolIndexStore - - if let symbolsAtDescriptor = symbolIndexStore.symbols(for: descriptorOffset, in: machO), - let descriptorSymbol = symbolsAtDescriptor.first(where: { $0.name.isSwiftSymbol && $0.name.hasSuffix(descriptorSymbolSuffix) }) { - return ExportStatus(trieVerdict: symbolIndexStore.isExported(name: descriptorSymbol.name, in: machO)) - } - guard let symbolName = descriptorSymbolName(for: nameNode, descriptorKind: descriptorKind) else { - return .descriptorSymbolNameUnresolvable - } - return ExportStatus(trieVerdict: symbolIndexStore.isExported(name: symbolName, in: machO)) - } - - /// `nil` — the store's "this image has no export information" answer — is - /// the only way ``imageHasNoExportInformation`` is produced. - private init(trieVerdict: Bool?) { - switch trieVerdict { - case true: self = .exported - case false: self = .notExported - case nil: self = .imageHasNoExportInformation - } - } - - /// Remangles a name node into the symbol name of its `descriptorKind` - /// descriptor (`_$sMn` / `_$sMp`), or `nil` when the - /// spelling cannot be trusted. The name node may arrive wrapped in a - /// `.type` envelope, and a specialized definition's name is a - /// bound-generic node (`Box`) — the descriptor belongs to the - /// unbound nominal, so both wrappers are peeled first. A context chain - /// through an `.extension` node is refused (see leg 2 above). The - /// remangling walks a transient tree materialized from the reference; - /// nothing is interned or cached. - package static func descriptorSymbolName(for node: NodeReference, descriptorKind: Node.Kind) -> String? { - var contextNode = node.materialize() - if contextNode.kind == .type, let wrappedNode = contextNode.children.first { - contextNode = wrappedNode - } - switch contextNode.kind { - case .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: - guard var nominalNode = contextNode.children.first else { return nil } - if nominalNode.kind == .type, let wrappedNode = nominalNode.children.first { - nominalNode = wrappedNode - } - contextNode = nominalNode - default: - break - } - guard !containsExtensionContext(contextNode) else { return nil } - let descriptorNode = Node.createTransient(kind: descriptorKind, children: [contextNode]) - let globalNode = Node.createTransient(kind: .global, children: [descriptorNode]) - return try? mangleAsString(globalNode) - } - - private static func containsExtensionContext(_ node: Node) -> Bool { - if node.kind == .extension { return true } - return node.children.contains { containsExtensionContext($0) } - } -} diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift index 070dc0f21..6f20087a0 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension AssociatedType { diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift index 05ce2080c..f6bb9d0f5 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift @@ -10,8 +10,11 @@ extension DemanglingNode where Self: Sequence { /// search for accessors alone found for a static stored property's /// storage symbol, and the property printed as a computed one (evolution /// proposal `local-type-context-names`). + /// + /// An init accessor is one too: read as `.none`, it made its property + /// a stored one (`AccessorRepresentable.isStored`). package var accessorKind: AccessorKind { - guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor, .borrowAccessor, .mutateAccessor, .variable, .subscript) else { return .none } + guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor, .borrowAccessor, .mutateAccessor, .initAccessor, .variable, .subscript) else { return .none } switch node.kind { case .getter: return .getter case .setter: return .setter @@ -19,6 +22,7 @@ extension DemanglingNode where Self: Sequence { case .readAccessor: return .readAccessor case .borrowAccessor: return .borrowAccessor case .mutateAccessor: return .mutateAccessor + case .initAccessor: return .initAccessor default: return .none } } diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift new file mode 100644 index 000000000..ffcbf2ebe --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift @@ -0,0 +1,9 @@ +import Demangling + +extension DemanglingNode where Self: Sequence { + var isStoredVariable: Bool { + guard first(of: .variable) != nil else { return false } + // A stored variable is one not wrapped in an accessor (getter/setter/etc.) + return !hasAccessor + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift index 5840e3acc..6e6ab7a99 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import Semantic extension FieldRecord { diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift index f32dbcb11..c9a25586d 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension MachOSwiftSection.`Protocol` { diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift index 7119559ac..e7d25631b 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift index 8414b1ebb..1ebbe63cb 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension TypeContextWrapper { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/AnnotatedSymbol.swift similarity index 96% rename from Sources/Declaration/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/AnnotatedSymbol.swift index 648b4a67c..0e7b646e7 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/AnnotatedSymbol.swift @@ -1,5 +1,5 @@ import MemberwiseInit -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// A `DemangledSymbol` carried through the build path together with one extra /// value whose meaning belongs to the path, not to the symbol itself. @@ -74,6 +74,6 @@ extension AnnotatedSymbol where Payload == ProtocolWitnessTableOffset? { } } -/// What every `DefinitionBuilder` entry point consumes: a symbol plus the +/// What every `MemberDefinitionBuilder` entry point consumes: a symbol plus the /// witness-table slot it occupies, if its producer knew one. package typealias MemberSymbol = AnnotatedSymbol diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ClassDispatchLookups.swift similarity index 82% rename from Sources/Declaration/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/ClassDispatchLookups.swift index c6dbf7aaa..7cf979444 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ClassDispatchLookups.swift @@ -1,13 +1,13 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// The dynamic-dispatch facts a class's vtable and override tables give up, /// in the two forms the member builders join against. /// /// Empty for every non-class: a struct or enum has no dispatch to describe, /// and the builders then attribute no method descriptor to any member. The -/// default value is what `DefinitionBuilder`'s global / extension / protocol +/// default value is what `MemberDefinitionBuilder`'s global / extension / protocol /// callers pass by omission. /// /// The two keyings are not interchangeable, and their order of use is the @@ -67,25 +67,7 @@ package struct ClassDispatchLookups { /// wins: the stand-ins only fill in what the image lost. package func supplementing(_ memberSymbols: [DemangledSymbol], in category: MemberCategory) -> [DemangledSymbol] { let categorySlotSymbols = vtableSlotMemberSymbols.filter { Self.memberCategory(ofMemberNode: $0.demangledNode) == category } - guard !categorySlotSymbols.isEmpty else { return memberSymbols } - let declaredEntityKeys = Set(memberSymbols.compactMap(Self.declaredEntityKey(of:))) - return memberSymbols + categorySlotSymbols.filter { slotSymbol in - guard let entityKey = Self.declaredEntityKey(of: slotSymbol) else { return false } - return !declaredEntityKeys.contains(entityKey) - } - } - - /// The member a symbol declares, keyed structurally: its entity node, - /// past the marker a merged-function thunk leads with — the builders fold - /// a thunk onto the member it stands for, so it declares that member as - /// much as the canonical symbol does. - private static func declaredEntityKey(of memberSymbol: DemangledSymbol) -> StructuralNodeReferenceKey? { - let children = memberSymbol.demangledNode.children - guard let firstChild = children.first else { return nil } - if firstChild.kind == .mergedFunction { - return children.second.map(StructuralNodeReferenceKey.init) - } - return StructuralNodeReferenceKey(firstChild) + return StandInMemberSymbolBuilder.supplementing(memberSymbols, with: categorySlotSymbols) } /// The builder input a vtable member belongs in, read off its node the diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberDefinitionBuilder.swift similarity index 94% rename from Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberDefinitionBuilder.swift index fa6ae9b29..d18717975 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberDefinitionBuilder.swift @@ -1,9 +1,9 @@ import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import MachOSwiftSection import OrderedCollections -package enum DefinitionBuilder { +package enum MemberDefinitionBuilder { /// The output of `variablesProduct(...)`: the computed-variable definitions /// plus the accessor groups that were suppressed because their name matches /// a stored field record (the property renders once, from the field @@ -51,7 +51,14 @@ package enum DefinitionBuilder { } var storedPropertyAccessorsByFieldName: [String: [Accessor]] = [:] - for (name, accessors) in accessorsByName.sorted(by: { $0.key < $1.key }) { + for (name, symbolOrderedAccessors) in accessorsByName.sorted(by: { $0.key < $1.key }) { + // A SE-0400 init accessor goes last (evolution proposal + // `init-accessor-recovery`): `accessors.first` answers for the + // property's witness table offset, which an init accessor never + // has. A stored property's group keeps it too — SwiftUICore keeps + // a function under a stored property's init accessor name for the + // clients that inlined a call to it. + let accessors = symbolOrderedAccessors.filter { $0.kind != .initAccessor } + symbolOrderedAccessors.filter { $0.kind == .initAccessor } guard !fieldNames.contains(name) else { storedPropertyAccessorsByFieldName[name] = accessors continue @@ -211,11 +218,3 @@ package enum DefinitionBuilder { return functionDefinition } } - -extension DemanglingNode where Self: Sequence { - var isStoredVariable: Bool { - guard first(of: .variable) != nil else { return false } - // A stored variable is one not wrapped in an accessor (getter/setter/etc.) - return !hasAccessor - } -} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift similarity index 70% rename from Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift index fc9e0d86c..5aed201e9 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift @@ -1,8 +1,8 @@ -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import OrderedCollections extension Definition { - func addSymbol(_ symbol: MemberSymbol, memberSymbolsByKind: inout OrderedDictionary, inExtension: Bool) { + func addSymbol(_ symbol: MemberSymbol, memberSymbolsByKind: inout OrderedDictionary, inExtension: Bool) { let node = symbol.demangledNode.memberSubtree if node.contains(.variable) { if node.contains(.static) { @@ -33,28 +33,28 @@ extension Definition { } extension MutableDefinition { - func setDefinitions(for memberSymbolsByKind: OrderedDictionary, inExtension: Bool) { + func setDefinitions(for memberSymbolsByKind: OrderedDictionary, inExtension: Bool) { for (kind, memberSymbols) in memberSymbolsByKind { switch kind { case .variable(inExtension, let isStatic, false): if isStatic { - staticVariables = DefinitionBuilder.variables(for: memberSymbols, fieldNames: [], isGlobalOrStatic: true) + staticVariables = MemberDefinitionBuilder.variables(for: memberSymbols, fieldNames: [], isGlobalOrStatic: true) } else { - variables = DefinitionBuilder.variables(for: memberSymbols, fieldNames: [], isGlobalOrStatic: false) + variables = MemberDefinitionBuilder.variables(for: memberSymbols, fieldNames: [], isGlobalOrStatic: false) } case .allocator: - allocators = DefinitionBuilder.allocators(for: memberSymbols) + allocators = MemberDefinitionBuilder.allocators(for: memberSymbols) case .function(inExtension, let isStatic): if isStatic { - staticFunctions = DefinitionBuilder.functions(for: memberSymbols, isGlobalOrStatic: true) + staticFunctions = MemberDefinitionBuilder.functions(for: memberSymbols, isGlobalOrStatic: true) } else { - functions = DefinitionBuilder.functions(for: memberSymbols, isGlobalOrStatic: false) + functions = MemberDefinitionBuilder.functions(for: memberSymbols, isGlobalOrStatic: false) } case .subscript(inExtension, let isStatic): if isStatic { - staticSubscripts = DefinitionBuilder.subscripts(for: memberSymbols, isStatic: true) + staticSubscripts = MemberDefinitionBuilder.subscripts(for: memberSymbols, isStatic: true) } else { - subscripts = DefinitionBuilder.subscripts(for: memberSymbols, isStatic: false) + subscripts = MemberDefinitionBuilder.subscripts(for: memberSymbols, isStatic: false) } default: break diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift similarity index 99% rename from Sources/Declaration/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift index 4a22234df..8d32cfdb9 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift @@ -1,5 +1,6 @@ import Demangling import SwiftInspection +import SwiftObjCInterop import SwiftThunkAnalysis /// Joins an `ObjCMemberTable` — the class's ObjC method table tied to its @@ -13,7 +14,7 @@ import SwiftThunkAnalysis /// a lookup per member. A member the table knows is `@objc` — the attribute /// is added when the thunk symbols (stripped in OS frameworks) did not /// already supply it. -package enum ObjCMemberApplication { +package enum ObjCMemberMatcher { /// Applies the table and returns how many members it tied. The name-only /// third tier runs afterwards over the overriding methods the table tied /// to no symbol — always: the index RECORDS what it found, and whether a diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCProtocolNameBuilder.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCProtocolNameBuilder.swift new file mode 100644 index 000000000..727efed82 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCProtocolNameBuilder.swift @@ -0,0 +1,17 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// Protocol runtime names as the declaration model's names. +package enum ObjCProtocolNameBuilder { + /// `Type > Protocol` names for `runtimeNames`, without `excluded`. + package static func protocolNames(_ runtimeNames: [String], excluding excluded: Set, in machO: some MachOSwiftSectionRepresentableWithCache) -> [ProtocolName] { + runtimeNames.filter { !excluded.contains($0) }.map { runtimeName in + let typeNode = Node.createTransient(kind: .type, child: ObjCRuntimeNames.protocolNode(forRuntimeName: runtimeName, in: machO)) + return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO)) + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObservableMacroExpansionRecovery.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObservableMacroExpansionRecovery.swift new file mode 100644 index 000000000..303b170e5 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObservableMacroExpansionRecovery.swift @@ -0,0 +1,256 @@ +@_spi(Internals) import Demangling +import SwiftInspection + +/// The rules of `@Observable` expansion recovery (evolution proposal +/// `observable-macro-folding`), kept free of any image so they can be +/// pinned on hand-built inputs. `TypeDefinition.recoverObservableMacroExpansion(in:)` +/// gathers the inputs from the image. +package enum ObservableMacroExpansionRecovery { + /// A stored property, as its field record has it. + package struct StoredProperty { + package let name: String + package let typeNode: Node + /// Declared `var`: the macro tracks no `let`. + package let isVariable: Bool + /// Whether the property's own accessor symbols are in the image. + package let hasAccessors: Bool + + package init(name: String, typeNode: Node, isVariable: Bool, hasAccessors: Bool = false) { + self.name = name + self.typeNode = typeNode + self.isVariable = isVariable + self.hasAccessors = hasAccessors + } + } + + /// An instance member variable with accessors in the image. + package struct MemberVariable { + package let name: String + package let declaredTypeNode: Node? + package let hasSetterOrModify: Bool + + package init(name: String, declaredTypeNode: Node?, hasSetterOrModify: Bool) { + self.name = name + self.declaredTypeNode = declaredTypeNode + self.hasSetterOrModify = hasSetterOrModify + } + } + + /// What the symbol table says about the class's variables. + package struct SymbolEvidence { + /// The variables with an init accessor. + package var initAccessorNames: Set + /// The variables with an initial-value expression — asked for once, + /// and only when a storage's accessors leave it undecided: in an image + /// that keeps its local symbols the expressions are many. + package var initialValueExpressionNames: () -> Set + + package init(initAccessorNames: Set = [], initialValueExpressionNames: @escaping () -> Set = { [] }) { + self.initAccessorNames = initAccessorNames + self.initialValueExpressionNames = initialValueExpressionNames + } + } + + /// The tracked properties and the stored `var`s the macro left alone, + /// both in field order. `claimedBackingFieldNames` are the fields + /// wrapped-property recovery recognized as a wrapper's storage: the + /// macro cannot track a wrapped property, so the source declared it + /// `@ObservationIgnored`. + package static func recover( + storedProperties: [StoredProperty], + memberVariables: [MemberVariable], + claimedBackingFieldNames: Set, + evidence: SymbolEvidence + ) -> (trackedProperties: [ObservableMacroExpansion.TrackedProperty], ignoredStoredPropertyNames: [String]) { + var trackedProperties: [ObservableMacroExpansion.TrackedProperty] = [] + var ignoredStoredPropertyNames: [String] = [] + var initialValueExpressionNames: Set? + for storedProperty in storedProperties where storedProperty.isVariable && storedProperty.name != ObservableMacroRecognition.registrarFieldName { + guard !claimedBackingFieldNames.contains(storedProperty.name), + let propertyName = trackedPropertyName(forBackingFieldName: storedProperty.name) + else { + ignoredStoredPropertyNames.append(storedProperty.name) + continue + } + let memberVariable = memberVariables.first { $0.name == propertyName } + // A member `x` of another type is not what `_x` stores — + // `sending` aside, which its accessor symbols never spell on its + // own function type. + if let declaredTypeNode = memberVariable?.declaredTypeNode, + !StoredTypeMatching.declaredType(declaredTypeNode, matchesStoredType: StoredTypeMatching.referencedTypeNode(ofStoredType: storedProperty.typeNode)) { + ignoredStoredPropertyNames.append(storedProperty.name) + continue + } + let trackingEvidence = trackingEvidence( + propertyName: propertyName, + storedProperty: storedProperty, + memberVariable: memberVariable, + initAccessorNames: evidence.initAccessorNames, + initialValueExpressionNames: { + if let initialValueExpressionNames { return initialValueExpressionNames } + let names = evidence.initialValueExpressionNames() + initialValueExpressionNames = names + return names + } + ) + guard let trackingEvidence else { + ignoredStoredPropertyNames.append(storedProperty.name) + continue + } + trackedProperties.append(ObservableMacroExpansion.TrackedProperty( + name: propertyName, + backingFieldName: storedProperty.name, + origin: memberVariable == nil ? .synthesized : .declaredMember, + evidence: trackingEvidence + )) + } + return (trackedProperties, ignoredStoredPropertyNames) + } + + /// What tells `_x` apart from a stored property the source named so, + /// strongest first, or `nil` when `_x` is one. An optimized, dead-stripped + /// image — an OS framework — drops the init accessor and the accessors of + /// every property nothing calls, local symbols kept or not, so absence + /// alone never rules `_x` out: only a fact of `_x`'s own does. + private static func trackingEvidence( + propertyName: String, + storedProperty: StoredProperty, + memberVariable: MemberVariable?, + initAccessorNames: Set, + initialValueExpressionNames: () -> Set + ) -> ObservableMacroExpansion.TrackedProperty.Evidence? { + if initAccessorNames.contains(propertyName) { + return .initAccessor + } + if memberVariable?.hasSetterOrModify == true { + return .accessors + } + // The initial value belongs to whichever property the source wrote it + // on: `x` when the macro moved the storage, `_x` when it is its own. + let initialValueExpressionNames = initialValueExpressionNames() + if initialValueExpressionNames.contains(storedProperty.name) { + return nil + } + if initialValueExpressionNames.contains(propertyName) { + return .initialValueExpression + } + // The image keeps `_x`'s accessors and none of `x`'s: the macro's + // storage and its computed property go together, kept by the same + // vtable or dropped by the same strip. + if storedProperty.hasAccessors, memberVariable == nil { + return nil + } + return .backingFieldName + } + + /// `x` for the storage `_x` the macro generates; `nil` for a name that + /// cannot be one — no leading underscore, nothing after it, or a `$` + /// after it, which only compiler- and macro-generated names start with. + package static func trackedPropertyName(forBackingFieldName backingFieldName: String) -> String? { + guard backingFieldName.hasPrefix("_") else { return nil } + let propertyName = backingFieldName.dropFirst() + guard let firstCharacter = propertyName.first, firstCharacter != "$" else { return nil } + return String(propertyName) + } + + /// Whether a method of the class, declared by `node`, is one the macro + /// generates — by its base name, its argument labels and its shape: + /// `access(keyPath:)` and `withMutation(keyPath:_:)`, generic over the + /// `KeyPath` they take first, and the `shouldNotifyObservers(_:_:)` + /// overloads, generic, of two parameters. The macro adds none the class + /// declares itself with the same signature, so one written in the source + /// in that shape stands in for the generated one; a method of another + /// shape under one of these names — no parameters, another parameter + /// type — is the source's own, and the macro adds its own beside it. + package static func isGeneratedFunction(name: String, node: Node) -> Bool { + guard let signature = parameterTypes(ofFunction: node), signature.isGeneric else { return false } + let argumentLabels = argumentLabels(ofFunction: node) + switch name { + case "access": + return argumentLabels == ["keyPath"] && signature.types.count == 1 && isKeyPath(signature.types[0]) + case "withMutation": + return argumentLabels == ["keyPath", "_"] && signature.types.count == 2 && isKeyPath(signature.types[0]) + case "shouldNotifyObservers": + // The demangler leaves out the label list of a function whose + // arguments are all unlabeled. + return (argumentLabels.isEmpty || argumentLabels == ["_", "_"]) && signature.types.count == 2 + default: + return false + } + } + + /// The parameter types of a function's own declaration, and whether it + /// is generic — read from the declaration node's direct children, as + /// its labels are. `nil` when the node is not a function or its type + /// does not read as a function type. + private static func parameterTypes(ofFunction node: Node) -> (types: [Node], isGeneric: Bool)? { + guard let declarationNode = functionDeclarationNode(of: node), + var typeNode = declarationNode.children.last(where: { $0.kind == .type })?.firstChild + else { return nil } + var isGeneric = false + if typeNode.kind == .dependentGenericType { + isGeneric = true + guard let genericType = typeNode.children.last(where: { $0.kind == .type })?.firstChild else { return nil } + typeNode = genericType + } + guard typeNode.kind == .functionType, + let argumentTypeNode = typeNode.children.first(where: { $0.kind == .argumentTuple })?.firstChild?.firstChild + else { return nil } + // Several parameters, or none, are a tuple; one is its own type. + guard argumentTypeNode.kind == .tuple else { return ([argumentTypeNode], isGeneric) } + let types = argumentTypeNode.children.compactMap { element in + element.children.last(where: { $0.kind == .type })?.firstChild + } + guard types.count == argumentTypeNode.children.count else { return nil } + return (types, isGeneric) + } + + /// Whether `typeNode` is `Swift.KeyPath<…>`. + private static func isKeyPath(_ typeNode: Node) -> Bool { + guard typeNode.kind == .boundGenericClass, + let classNode = typeNode.firstChild?.firstChild, classNode.kind == .class, + classNode.firstChild?.kind == .module, classNode.firstChild?.text == "Swift" + else { return false } + return classNode.children.at(1)?.text == "KeyPath" + } + + /// The argument labels of a function's own declaration, `_` for an + /// unlabeled argument — read from the declaration node's direct + /// children, never by searching the tree, whose context comes first + /// (`local-type-context-names`). Empty when the node is not a function or + /// has no label list. + package static func argumentLabels(ofFunction node: Node) -> [String] { + guard let declarationNode = functionDeclarationNode(of: node), + let labelList = declarationNode.children.first(where: { $0.kind == .labelList }) + else { return [] } + return labelList.children.map { label in + label.kind == .firstElementMarker ? "_" : label.text ?? "_" + } + } + + /// The `function` node a member function's symbol declares — past the + /// `global` wrapper (skipping an async or merged-function marker), past + /// `static` or a `methodDescriptor`, and past a `protocolWitness`'s + /// conformance. + private static func functionDeclarationNode(of node: Node) -> Node? { + var node = node + for _ in 0 ..< 6 where node.kind != .function { + switch node.kind { + case .global: + guard let first = node.firstChild else { return nil } + 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, .methodDescriptor: + guard let next = node.firstChild else { return nil } + node = next + case .protocolWitness: + guard let next = node.children.dropFirst().first else { return nil } + node = next + default: + return nil + } + } + return node.kind == .function ? node : nil + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/OverrideSymbolMatcher.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/OverrideSymbolMatcher.swift new file mode 100644 index 000000000..5bbae5070 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/OverrideSymbolMatcher.swift @@ -0,0 +1,69 @@ +import MachOSwiftSection +import Demangling +import OrderedCollections +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection + +/// Matches a class's method descriptors to the symbols of the members they +/// dispatch to: the structural key both sides are joined on, and the +/// implementation symbol an override descriptor names. +package enum OverrideSymbolMatcher { + /// The structural key `MemberDefinitionBuilder` joins descriptor-side symbols to + /// member-side symbols on. + /// + /// An async method's descriptor `implementation` points at its `Tu` + /// async-function-pointer constant, whose demangled tree carries a leading + /// `.asyncFunctionPointer` marker child the member symbol's tree does not — + /// keyed verbatim, the two trees never match structurally, so async members + /// never joined (no vtable comment, no `override` keyword and, since evolution + /// proposal 0006, a false `final`). Strip the marker so the key takes the + /// member form; every other tree keys as-is. + package static func memberJoinKey( + for node: NodeReference, + in context: some ReadingContext + ) -> StructuralNodeReferenceKey { + if node.children.first?.kind == .asyncFunctionPointer, let entityNode = node.children.second { + let strippedTree = Node.create(kind: .global, child: entityNode.materialize()) + return StructuralNodeReferenceKey(InternedNodeReferenceCache.shared.reference(interning: strippedTree, in: context)) + } + return StructuralNodeReferenceKey(node) + } + + /// Finds the implementation symbol declared in `typeNode`'s class, skipping + /// already-visited nodes. + /// + /// The match is on the member's DIRECT declaration context. Matching on + /// `first(of: .class)` — the first class node anywhere in the tree — accepts + /// members of NESTED types as members of the enclosing class + /// (`GraphHost.Data.graph.modify` reports `GraphHost`), which under identical + /// code folding is how a vtable slot acquires a name belonging to something + /// else entirely. + /// + /// `visitedNodes` is keyed structurally: `demangledNodeReference(for:)` can + /// hand back references from different stores, and under store-identity + /// equality the "already claimed this symbol" guard would stop firing across + /// them, letting two descriptors bind the same implementation. + /// + /// Lifted out of `SwiftDump`'s `ClassDumper.demangledSymbol(for:typeNode:…)` + /// so the declaration model can resolve method-override symbols during indexing + /// (`TypeDefinition.index`) without depending on the dump layer. It is purely a + /// symbol-table matcher — no rendering — so it belongs with the model rather + /// than the renderer. + package static func demangledOverrideSymbol( + for symbols: Symbols, + typeNode: Node, + visitedNodes: borrowing OrderedSet = [], + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> DemangledSymbol? { + guard let typeClassNode = typeNode.first(of: .class) else { return nil } + for symbol in symbols { + if let node = SwiftSymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO), + let declarationContextNode = node.declarationContextNode, + declarationContextNode.structurallyEquals(typeClassNode), + !visitedNodes.contains(StructuralNodeReferenceKey(node)) { + return .init(symbol: symbol, demangledNode: node) + } + } + return nil + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift new file mode 100644 index 000000000..e61087c92 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift @@ -0,0 +1,300 @@ +@_spi(Internals) import Demangling +import MachOSwiftSection +import OrderedCollections +@_spi(Internals) import SwiftSymbols + +/// Member symbols that stand in for an implementation symbol the image does +/// not have. +/// +/// Every member definition is built from a symbol, and the member builders +/// expect the member's implementation symbol: its own entry point, named by +/// the member's mangling. An optimized image can lack it while keeping +/// another entry point of the same member (evolution proposal +/// `thunk-only-objc-members`): +/// - an `@objc` member whose body the optimizer inlined into its Objective-C +/// thunk (`$s…To`) and whose Swift entry point it then deleted, so the +/// thunk is the only code the member has; +/// - a class initializer whose allocating entry point (`…fC`) was inlined +/// into its callers and deleted, leaving the initializing one (`…fc`); +/// - the same initializer whose initializing entry point the optimizer also +/// replaced by its function signature specialization (`…fcTf…`) and +/// deleted, leaving the specialization — what Swift 6.4's whole-module +/// optimization does to an internal class's initializer. +/// +/// A stand-in is shaped like the implementation symbol it replaces — that +/// symbol's mangled name and member tree — at the address of the entry point +/// the image does have. Everything that derives from the name (the export +/// verdict, the ObjC method table join, the thunk attributes) and from the +/// tree (the vtable join, the ABI identity) then reads it as the symbol it +/// replaces. `ClassDispatchLookups.vtableSlotMemberSymbols` builds the same +/// kind of stand-in from a vtable slot's `Tq` (evolution proposal +/// `interface-descriptor-only-vtable-members`). +package enum StandInMemberSymbolBuilder { + /// `memberSymbols` followed by each of `standIns` whose member none of + /// the symbols before it declares. A real symbol always wins, and among + /// stand-ins for the same member the first one wins. + package static func supplementing(_ memberSymbols: [DemangledSymbol], with standIns: [DemangledSymbol]) -> [DemangledSymbol] { + guard !standIns.isEmpty else { return memberSymbols } + var declaredEntityKeys = Set(memberSymbols.compactMap(declaredEntityKey(of:))) + var supplementedSymbols = memberSymbols + for standIn in standIns { + guard let entityKey = declaredEntityKey(of: standIn), declaredEntityKeys.insert(entityKey).inserted else { continue } + supplementedSymbols.append(standIn) + } + return supplementedSymbols + } + + /// The member a symbol declares, keyed structurally: its entity node, + /// past the marker a merged-function thunk leads with — the builders fold + /// a thunk onto the member it stands for, so it declares that member as + /// much as the canonical symbol does. + package static func declaredEntityKey(of memberSymbol: DemangledSymbol) -> StructuralNodeReferenceKey? { + let children = memberSymbol.demangledNode.children + guard let firstChild = children.first else { return nil } + if firstChild.kind == .mergedFunction { + return children.second.map(StructuralNodeReferenceKey.init) + } + return StructuralNodeReferenceKey(firstChild) + } + + /// The allocating entry point that an initializer's initializing entry + /// point (`…fc`) stands in for: the same tree with the `constructor` + /// entity rewritten to `allocator`, the same name with the `fc` suffix + /// swapped for `fC`, at the initializing entry point's address. Rewritten + /// because the builders file an initializer by its allocating entry + /// point, and because that is what the vtable slot of the initializer, its + /// ObjC method table entry (`ObjCMemberTable.member(forAllocatorSymbolNamed:)`) + /// and its ABI identity are keyed by. `nil` for anything that is not an + /// initializing entry point. + package static func allocatorStandIn( + forInitializerSymbol initializerSymbol: DemangledSymbol, + in machO: some MachORepresentableWithCache + ) -> DemangledSymbol? { + guard let constructorNode = initializerSymbol.demangledNode.children.first, constructorNode.kind == .constructor else { return nil } + return allocatorStandIn(forConstructorNode: constructorNode, initializerName: initializerSymbol.name, offset: initializerSymbol.offset, in: machO) + } + + /// The allocating entry point that an initializer's initializing entry + /// point stands in for, built from that entry point's function signature + /// specialization (`…fcTf4gn_n`) when the optimizer left only the + /// specialization: the specialization's name up to its `Tf` suffix is the + /// initializing entry point's own (`specializedInitializerName(of:)`), and + /// the stand-in is built from it as from the entry point, at the + /// specialization's address. `nil` for anything that is not such a + /// specialization. + package static func allocatorStandIn( + forSpecializedInitializerSymbol specializedSymbol: DemangledSymbol, + in machO: some MachORepresentableWithCache + ) -> DemangledSymbol? { + guard let initializerName = specializedInitializerName(of: specializedSymbol), + let constructorNode = specializedSymbol.demangledNode.children.first(where: { $0.kind == .constructor }) + else { return nil } + return allocatorStandIn(forConstructorNode: constructorNode, initializerName: initializerName, offset: specializedSymbol.offset, in: machO) + } + + /// The name of the initializing entry point a function signature + /// specialization specializes: the specialization's name up to a `Tf` + /// suffix — the last one whose prefix ends in the entry point's `fc`, so a + /// specialization of a specialization reads back to the entry point too. + /// `nil` for anything that is not a specialization of an initializing + /// entry point. + package static func specializedInitializerName(of specializedSymbol: DemangledSymbol) -> String? { + let children = specializedSymbol.demangledNode.children + guard children.first?.kind == .functionSignatureSpecialization, + children.contains(where: { $0.kind == .constructor }) + else { return nil } + let name = specializedSymbol.name + var searchUpperBound = name.endIndex + while let suffixRange = name.range(of: "Tf", options: .backwards, range: name.startIndex ..< searchUpperBound) { + let entryPointName = name[.. DemangledSymbol? { + let thunkName = thunkSymbol.name + guard thunkName.hasSuffix("To"), + thunkSymbol.demangledNode.children.first?.kind == .objCAttribute, + let entityNode = thunkSymbol.demangledNode.children.first(where: { $0.kind != .objCAttribute }) else { return nil } + let implementationName = String(thunkName.dropLast(2)) + if entityNode.kind == .constructor { + return allocatorStandIn(forConstructorNode: entityNode, initializerName: implementationName, offset: thunkSymbol.offset, in: machO) + } + let memberTree = Node.createTransient(kind: .global, child: entityNode.materialize()) + let memberNode = InternedNodeReferenceCache.shared.reference(interning: memberTree, in: machO) + return DemangledSymbol(symbol: Symbol(offset: thunkSymbol.offset, name: implementationName), demangledNode: memberNode) + } + + /// Whether the image has a symbol of its own for the member an entry + /// point stands in for, found by the name the stand-in would carry: the + /// thunk's name without `To` (for an initializer's thunk, either entry + /// point of the initializer), the initializing entry point's name with + /// `fc` swapped for `fC`, and for the specialization of an initializing + /// entry point either entry point of the initializer. One name lookup, + /// made before a stand-in is built, spares building one for every member + /// that kept its implementation — almost every `@objc` member and + /// initializer of an unoptimized or library image. + /// `supplementing(_:with:)` still decides structurally for the stand-ins + /// that are built. + package static func imageKeepsTheMemberSymbol( + replacedBy entryPointSymbol: DemangledSymbol, + symbolIndexStore: SwiftSymbolIndexStore, + in machO: some MachORepresentableWithCache + ) -> Bool { + var memberSymbolName = entryPointSymbol.name + if let initializerName = specializedInitializerName(of: entryPointSymbol) { + if symbolIndexStore.containsSymbol(named: initializerName, in: machO) { + return true + } + memberSymbolName = initializerName + } + if memberSymbolName.hasSuffix("To") { + memberSymbolName.removeLast(2) + if symbolIndexStore.containsSymbol(named: memberSymbolName, in: machO) { + return true + } + } + guard memberSymbolName.hasSuffix("fc") else { return false } + return symbolIndexStore.containsSymbol(named: String(memberSymbolName.dropLast(2)) + "fC", in: machO) + } + + private static func allocatorStandIn( + forConstructorNode constructorNode: NodeReference, + initializerName: String, + offset: Int, + in machO: some MachORepresentableWithCache + ) -> DemangledSymbol? { + guard initializerName.hasSuffix("fc") else { return nil } + let allocatorEntity = Node.createTransient(kind: .allocator, children: constructorNode.children.map { $0.materialize() }) + let allocatorTree = Node.createTransient(kind: .global, child: allocatorEntity) + let allocatorNode = InternedNodeReferenceCache.shared.reference(interning: allocatorTree, in: machO) + let allocatorName = String(initializerName.dropLast(2)) + "fC" + return DemangledSymbol(symbol: Symbol(offset: offset, name: allocatorName), demangledNode: allocatorNode) + } +} + +extension StandInMemberSymbolBuilder { + /// The stand-ins for one type's own members, by the member builder input + /// each belongs in, in the order they are tried: the initializing entry + /// points, then their specializations, then the `@objc` thunks, so an + /// initializer that kept Swift code of its own is located there rather + /// than at its thunk. + package struct TypeMembers { + private var standInsByCategory: [MemberCategory: [DemangledSymbol]] = [:] + + package init( + typeName: String, + typeNode: NodeReference, + symbolIndexStore: SwiftSymbolIndexStore, + in machO: some MachORepresentableWithCache + ) { + func standIns(for entryPointSymbols: [DemangledSymbol], _ makeStandIn: (DemangledSymbol) -> DemangledSymbol?) -> [DemangledSymbol] { + entryPointSymbols + .filter { !StandInMemberSymbolBuilder.imageKeepsTheMemberSymbol(replacedBy: $0, symbolIndexStore: symbolIndexStore, in: machO) } + .compactMap(makeStandIn) + } + func thunkStandIns(_ kinds: SwiftSymbolIndexStore.MemberKind...) -> [DemangledSymbol] { + standIns(for: kinds.flatMap { symbolIndexStore.objcThunkMemberSymbols(of: $0, for: typeName, node: typeNode, in: machO) }) { + StandInMemberSymbolBuilder.memberStandIn(forObjCThunkSymbol: $0, in: machO) + } + } + let initializerStandIns = standIns(for: symbolIndexStore.memberSymbols(of: .constructor(inExtension: false), for: typeName, node: typeNode, in: machO)) { + StandInMemberSymbolBuilder.allocatorStandIn(forInitializerSymbol: $0, in: machO) + } + let specializedInitializerStandIns = standIns(for: symbolIndexStore.specializedInitializerSymbols(of: .constructor(inExtension: false), for: typeName, node: typeNode, in: machO)) { + StandInMemberSymbolBuilder.allocatorStandIn(forSpecializedInitializerSymbol: $0, in: machO) + } + standInsByCategory[.allocators] = initializerStandIns + specializedInitializerStandIns + thunkStandIns(.constructor(inExtension: false), .allocator(inExtension: false)) + standInsByCategory[.functions] = thunkStandIns(.function(inExtension: false, isStatic: false)) + standInsByCategory[.staticFunctions] = thunkStandIns(.function(inExtension: false, isStatic: true)) + standInsByCategory[.variables] = thunkStandIns(.variable(inExtension: false, isStatic: false, isStorage: false)) + standInsByCategory[.staticVariables] = thunkStandIns(.variable(inExtension: false, isStatic: true, isStorage: false)) + standInsByCategory[.subscripts] = thunkStandIns(.subscript(inExtension: false, isStatic: false)) + standInsByCategory[.staticSubscripts] = thunkStandIns(.subscript(inExtension: false, isStatic: true)) + } + + /// `memberSymbols` plus the stand-ins of `category` whose member none + /// of them declares. + package func supplementing(_ memberSymbols: [DemangledSymbol], in category: MemberCategory) -> [DemangledSymbol] { + StandInMemberSymbolBuilder.supplementing(memberSymbols, with: standInsByCategory[category] ?? []) + } + } + + /// `memberSymbolsByTypeNode` — the extension members of every type, as + /// `SwiftSymbolIndexStore.memberSymbols(of:excluding:in:)` groups them — plus + /// the stand-ins of the members none of those symbols declares. A type + /// whose extension members are all stand-ins gains an entry of its own. + package static func supplementingExtensionMembers( + _ memberSymbolsByTypeNode: OrderedDictionary>, + symbolIndexStore: SwiftSymbolIndexStore, + in machO: some MachORepresentableWithCache + ) -> OrderedDictionary> { + var standInsByTypeNode: OrderedDictionary> = [:] + let initializerSymbolsByTypeNode = symbolIndexStore.memberSymbols(of: .constructor(inExtension: true), excluding: [], in: machO) + for (typeNodeKey, initializerSymbolsByKind) in initializerSymbolsByTypeNode { + let standIns = initializerSymbolsByKind.values.joined() + .filter { !imageKeepsTheMemberSymbol(replacedBy: $0, symbolIndexStore: symbolIndexStore, in: machO) } + .compactMap { allocatorStandIn(forInitializerSymbol: $0, in: machO) } + guard !standIns.isEmpty else { continue } + standInsByTypeNode[typeNodeKey, default: [:]][.allocator(inExtension: true), default: []].append(contentsOf: standIns) + } + let specializedInitializerSymbolsByTypeNode = symbolIndexStore.specializedInitializerSymbols(of: .constructor(inExtension: true), excluding: [], in: machO) + for (typeNodeKey, specializedSymbolsByKind) in specializedInitializerSymbolsByTypeNode { + let standIns = specializedSymbolsByKind.values.joined() + .filter { !imageKeepsTheMemberSymbol(replacedBy: $0, symbolIndexStore: symbolIndexStore, in: machO) } + .compactMap { allocatorStandIn(forSpecializedInitializerSymbol: $0, in: machO) } + guard !standIns.isEmpty else { continue } + standInsByTypeNode[typeNodeKey, default: [:]][.allocator(inExtension: true), default: []].append(contentsOf: standIns) + } + let thunkSymbolsByTypeNode = symbolIndexStore.objcThunkMemberSymbols( + of: .constructor(inExtension: true), + .allocator(inExtension: true), + .variable(inExtension: true, isStatic: false, isStorage: false), + .variable(inExtension: true, isStatic: true, isStorage: false), + .function(inExtension: true, isStatic: false), + .function(inExtension: true, isStatic: true), + .subscript(inExtension: true, isStatic: false), + .subscript(inExtension: true, isStatic: true), + excluding: [], + in: machO + ) + for (typeNodeKey, thunkSymbolsByKind) in thunkSymbolsByTypeNode { + for (kind, thunkSymbols) in thunkSymbolsByKind { + let standInKind: SwiftSymbolIndexStore.MemberKind = switch kind { + case .constructor(inExtension: true): .allocator(inExtension: true) + default: kind + } + let standIns = thunkSymbols + .filter { !imageKeepsTheMemberSymbol(replacedBy: $0, symbolIndexStore: symbolIndexStore, in: machO) } + .compactMap { memberStandIn(forObjCThunkSymbol: $0, in: machO) } + guard !standIns.isEmpty else { continue } + standInsByTypeNode[typeNodeKey, default: [:]][standInKind, default: []].append(contentsOf: standIns) + } + } + guard !standInsByTypeNode.isEmpty else { return memberSymbolsByTypeNode } + var supplementedSymbolsByTypeNode = memberSymbolsByTypeNode + for (typeNodeKey, standInsByKind) in standInsByTypeNode { + for (kind, standIns) in standInsByKind { + let memberSymbols = supplementedSymbolsByTypeNode[typeNodeKey]?[kind] ?? [] + let supplementedSymbols = supplementing(memberSymbols, with: standIns) + guard supplementedSymbols.count > memberSymbols.count else { continue } + supplementedSymbolsByTypeNode[typeNodeKey, default: [:]][kind] = supplementedSymbols + } + } + return supplementedSymbolsByTypeNode + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ThunkAttributeMatcher.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ThunkAttributeMatcher.swift new file mode 100644 index 000000000..b2b46d9b5 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ThunkAttributeMatcher.swift @@ -0,0 +1,124 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import SwiftSymbols + +/// Cross-references `@objc` / `@nonobjc` / `distributed` thunk attribute +/// members (pre-extracted and bucketed by parent type name inside +/// `SwiftSymbolIndexStore`) with already-built member definitions, appending the +/// matching attribute to each affected member. Shared by `TypeDefinition` +/// and `ExtensionDefinition` — the sweep unwraps extension contexts when it +/// buckets a thunk, so an extension's members are filed under the extended +/// type's name and node, and one lookup serves both containers. +package enum ThunkAttributeMatcher { + /// Each thunk kind with the attribute it proves and the suffix its + /// mangling appends to the member's name. + package static let thunkKindsAndAttributes: [(thunkKind: Node.Kind, attribute: SwiftAttribute, mangledSuffix: String)] = [ + (.objCAttribute, .objc, "To"), + (.nonObjCAttribute, .nonobjc, "TO"), + (.distributedThunk, .distributed, "TE"), + ] + + package static func applyThunkAttributes( + symbolIndexStore: SwiftSymbolIndexStore, + typeName: String, + typeNode: NodeReference, + in machO: some MachORepresentableWithCache, + functions: inout [FunctionDefinition], + variables: inout [VariableDefinition], + staticFunctions: inout [FunctionDefinition], + staticVariables: inout [VariableDefinition], + allocators: inout [FunctionDefinition] + ) { + for (thunkKind, attribute, mangledSuffix) in thunkKindsAndAttributes { + // Node-matched: the member-name matching below is string-based, + // so a same-named private sibling's thunks must never reach it + // (issue #115's family). + let members = symbolIndexStore.thunkAttributeMembers(of: thunkKind, for: typeName, node: typeNode, in: machO) + var hasInitializerThunk = false + for member in members { + if member.isStatic { + apply(attribute, toFunctionsNamed: member.memberName, withThunkSuffix: mangledSuffix, in: &staticFunctions, symbolIndexStore: symbolIndexStore, in: machO) + apply(attribute, toVariableNamed: member.memberName, in: &staticVariables) + } else { + apply(attribute, toFunctionsNamed: member.memberName, withThunkSuffix: mangledSuffix, in: &functions, symbolIndexStore: symbolIndexStore, in: machO) + apply(attribute, toVariableNamed: member.memberName, in: &variables) + if member.isInit { + hasInitializerThunk = true + } + } + } + if hasInitializerThunk { + apply(attribute, toAllocatorsWithThunkSuffix: mangledSuffix, in: &allocators, symbolIndexStore: symbolIndexStore, in: machO) + } + } + } + + /// `attribute` on each of `definitions` named `name` whose own symbol has + /// the thunk `mangledSuffix` spells: a thunk's name is its member's mangled + /// name plus the suffix. Overloads share a name, and the name alone gave + /// the attribute to a Swift-only overload of an `@objc` method. A merged + /// function (`…Tm`) is the member it was merged from. + package static func apply( + _ attribute: SwiftAttribute, + toFunctionsNamed name: String, + withThunkSuffix mangledSuffix: String, + in definitions: inout [FunctionDefinition], + symbolIndexStore: SwiftSymbolIndexStore, + in machO: some MachORepresentableWithCache + ) { + for definitionIndex in definitions.indices where definitions[definitionIndex].name == name && !definitions[definitionIndex].attributes.contains(attribute) { + var memberSymbolName = definitions[definitionIndex].symbol.name + if memberSymbolName.hasSuffix("Tm") { + memberSymbolName.removeLast(2) + } + if symbolIndexStore.containsSymbol(named: memberSymbolName + mangledSuffix, in: machO) { + definitions[definitionIndex].attributes.append(attribute) + } + } + } + + package static func apply(_ attribute: SwiftAttribute, toFunctionNamed name: String, in definitions: inout [FunctionDefinition]) { + for definitionIndex in definitions.indices { + if definitions[definitionIndex].name == name && !definitions[definitionIndex].attributes.contains(attribute) { + definitions[definitionIndex].attributes.append(attribute) + } + } + } + + package static func apply(_ attribute: SwiftAttribute, toVariableNamed name: String, in definitions: inout [VariableDefinition]) { + for definitionIndex in definitions.indices { + if definitions[definitionIndex].name == name && !definitions[definitionIndex].attributes.contains(attribute) { + definitions[definitionIndex].attributes.append(attribute) + } + } + } + + /// `attribute` on each allocator whose initializer has a thunk of the + /// kind `mangledSuffix` spells. An initializer's thunk records no member + /// name to match by (its `memberName` is the first identifier the tree + /// reaches, the type's), so the initializer is found by mangled name: the + /// thunk enters the initializing entry point, whose name is the + /// allocator's with `fC` swapped for `fc`. Every allocator used to get the + /// attribute as soon as one initializer had the thunk, which printed a + /// Swift-only initializer as `@objc init(rootView:)` beside the class's + /// `@objc init?(coder:)`. + package static func apply( + _ attribute: SwiftAttribute, + toAllocatorsWithThunkSuffix mangledSuffix: String, + in definitions: inout [FunctionDefinition], + symbolIndexStore: SwiftSymbolIndexStore, + in machO: some MachORepresentableWithCache + ) { + for definitionIndex in definitions.indices where !definitions[definitionIndex].attributes.contains(attribute) { + var allocatorName = definitions[definitionIndex].symbol.name + if allocatorName.hasSuffix("Tm") { + allocatorName.removeLast(2) + } + guard allocatorName.hasSuffix("fC") else { continue } + let thunkName = String(allocatorName.dropLast(2)) + "fc" + mangledSuffix + if symbolIndexStore.containsSymbol(named: thunkName, in: machO) { + definitions[definitionIndex].attributes.append(attribute) + } + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/WrappedPropertyRecovery.swift similarity index 96% rename from Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/Building/WrappedPropertyRecovery.swift index adff18ef3..63633d8ab 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/WrappedPropertyRecovery.swift @@ -1,6 +1,7 @@ @_spi(Internals) import Demangling import SwiftDeclarationRendering -@_spi(Internals) import MachOSymbols +import SwiftInspection +@_spi(Internals) import SwiftSymbols /// The node-level rules of wrapped-property recovery, kept free of any /// image so they can be pinned on hand-built trees. @@ -38,7 +39,9 @@ package enum WrappedPropertyRecovery { /// (`@Tagged var count: Int`). Both are valid source. package static func attributeTypeNode(fieldTypeNode: Node, wrapperNominalTypeNode: Node, wrappedPropertyTypeNode: Node?) -> Node { let arguments = genericArguments(ofBoundType: fieldTypeNode) - guard arguments.count == 1, let onlyArgument = arguments.first, let wrappedPropertyTypeNode, onlyArgument == wrappedPropertyTypeNode else { + guard arguments.count == 1, let onlyArgument = arguments.first, let wrappedPropertyTypeNode, + StoredTypeMatching.declaredType(wrappedPropertyTypeNode, matchesStoredType: onlyArgument) + else { return fieldTypeNode } return wrapperNominalTypeNode diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/DefinitionIndexing.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/DefinitionIndexing.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift similarity index 96% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift index 7732af49b..355edf5fa 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift @@ -1,7 +1,7 @@ import Demangling import MachOSwiftSection import OrderedCollections -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension ExtensionDefinition: OnceIndexedDefinition { @@ -44,7 +44,7 @@ extension ExtensionDefinition: OnceIndexedDefinition { // store-identity equality would let the same implementation symbol be // claimed by two witnesses. func _symbol(for symbols: Symbols, typeName: String, visitedNodes: borrowing OrderedSet = []) throws -> DemangledSymbol? { - for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: typeName, ownerKind: .conformingType, printedWith: .interfaceTypeBuilderOnly, in: machO) { + for candidate in SwiftSymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: typeName, ownerKind: .conformingType, printedWith: .interfaceTypeBuilderOnly, in: machO) { if !visitedNodes.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { return candidate } @@ -52,7 +52,7 @@ extension ExtensionDefinition: OnceIndexedDefinition { return nil } var visitedNodes: OrderedSet = [] - var memberSymbolsByKind: OrderedDictionary = [:] + var memberSymbolsByKind: OrderedDictionary = [:] var defaultImplementationSymbolNames: Set = [] for resilientWitness in protocolConformance.resilientWitnesses { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ObjCMembers.swift similarity index 95% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ObjCMembers.swift index 08c5ff246..7b27fbed9 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ObjCMembers.swift @@ -1,4 +1,5 @@ import SwiftInspection +import SwiftObjCInterop extension ExtensionDefinition { /// The extension-side twin of `TypeDefinition.applyObjCMembers` (evolution @@ -13,7 +14,7 @@ extension ExtensionDefinition { /// library's reader folds `__objc_catlist` in for the rest. @discardableResult package func applyObjCMembers(_ table: ObjCMemberTable) -> Int { - ObjCMemberApplication.apply( + ObjCMemberMatcher.apply( table, functions: &functions, variables: &variables, diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ThunkAttributes.swift similarity index 88% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ThunkAttributes.swift index b5fdb3c5a..f2bbb825b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+ThunkAttributes.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols extension ExtensionDefinition { /// The extension-side twin of `TypeDefinition.applyThunkAttributes` @@ -10,12 +10,12 @@ extension ExtensionDefinition { /// decorates the members its extensions add. Before this the interface /// printed `@objc` on a class's members but never on its extensions'. package func applyThunkAttributes( - symbolIndexStore: SymbolIndexStore, + symbolIndexStore: SwiftSymbolIndexStore, typeName: String, typeNode: NodeReference, in machO: some MachORepresentableWithCache ) { - MemberAttributeApplication.applyThunkAttributes( + ThunkAttributeMatcher.applyThunkAttributes( symbolIndexStore: symbolIndexStore, typeName: typeName, typeNode: typeNode, diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/ObjCImportedDefinitions+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ObjCImportedDefinitions+Indexing.swift new file mode 100644 index 000000000..46efab246 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ObjCImportedDefinitions+Indexing.swift @@ -0,0 +1,123 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +// The indexing passes of the imported Objective-C declarations (evolution +// proposal `objc-imported-declarations`). Each is synchronous, runs once +// behind `DefinitionIndexing`'s lock, and indexes no other definition: the +// Swift definitions a class or category is paired with are indexed by the +// printer, which pairs them by selector. + +extension ObjCImportedClassDefinition: OnceIndexedDefinition { + /// Reads the superclass, the protocols and the members. Idempotent, and + /// safe to call from several tasks at once. + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + runIndexingPass(in: machO) + } + } + + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) { + guard let classNode = className.node.materialize().first(of: .class) else { return } + superclassName = record.superclassRuntimeName.map { ObjCImportedDefinitionNames.typeName(ofClassRuntimeName: $0, in: machO) } + protocolNames = record.protocolRuntimeNames.map { ObjCImportedDefinitionNames.protocolName(ofRuntimeName: $0, in: machO) } + members = ObjCImportedMemberBuilder.members(of: record, contextNode: classNode, contextTypeName: classNode.identifier ?? record.classRuntimeName, in: machO) + .map { ObjCImportedMemberDefinition(member: $0, in: machO) } + } +} + +extension ObjCImportedCategoryDefinition: OnceIndexedDefinition { + /// Reads the protocols and the members. + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + runIndexingPass(in: machO) + } + } + + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) { + guard let classNode = extendedClassName.node.materialize().first(of: .class) else { return } + protocolNames = record.protocolRuntimeNames.map { ObjCImportedDefinitionNames.protocolName(ofRuntimeName: $0, in: machO) } + members = ObjCImportedMemberBuilder.members(of: record, contextNode: classNode, contextTypeName: classNode.identifier ?? record.classRuntimeName, in: machO) + .map { ObjCImportedMemberDefinition(member: $0, in: machO) } + } +} + +extension ObjCImportedProtocolDefinition: OnceIndexedDefinition { + /// Reads the inherited protocols and the requirements. + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + runIndexingPass(in: machO) + } + } + + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) { + guard let protocolNode = protocolName.node.materialize().first(of: .protocol) else { return } + inheritedProtocolNames = record.inheritedProtocolRuntimeNames.map { ObjCImportedDefinitionNames.protocolName(ofRuntimeName: $0, in: machO) } + requirements = ObjCProtocolRequirementBuilder.requirements(of: record, protocolNode: protocolNode, declaredIn: .objectiveC, in: machO).map { requirement in + let kind: ObjCProtocolRequirementDefinition.Kind = switch requirement.kind { + case .method: .method + case .initializer: .initializer + case .property: .property + case .subscript: .subscript + } + return ObjCProtocolRequirementDefinition( + kind: kind, + node: InternedNodeReferenceCache.shared.reference(interning: requirement.node, in: machO), + selector: requirement.selector, + setterSelector: requirement.setterSelector, + isClassMember: requirement.isClassMember, + isOptional: requirement.isOptional, + origin: .selector, + hasExplicitSelector: requirement.hasExplicitSelector, + typeEncoding: requirement.typeEncoding + ) + } + } +} + +extension ObjCImportedMemberDefinition { + package init(member: ObjCImportedMember, in machO: some MachOSwiftSectionRepresentableWithCache) { + let kind: Kind = switch member.kind { + case .method: .method + case .initializer: .initializer + case .factoryInitializer: .factoryInitializer + case .property: .property + case .subscript: .subscript + } + let ownership: Ownership? = member.ownership.map { ownership in + switch ownership { + case .strong: .strong + case .copy: .copy + case .weak: .weak + case .unownedUnsafe: .unownedUnsafe + } + } + self.init( + kind: kind, + node: InternedNodeReferenceCache.shared.reference(interning: member.node, in: machO), + selector: member.selector, + setterSelector: member.setterSelector, + isClassMember: member.isClassMember, + ownership: ownership, + hasExplicitSelector: member.hasExplicitSelector, + typeEncoding: member.typeEncoding, + objcPropertyName: member.objcPropertyName + ) + } +} + +/// The names an imported declaration's header prints, from runtime names. +enum ObjCImportedDefinitionNames { + static func typeName(ofClassRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> TypeName { + let typeNode = Node.createTransient(kind: .type, child: ObjCRuntimeNames.classNode(forRuntimeName: runtimeName, in: machO)) + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO), kind: .class) + } + + static func protocolName(ofRuntimeName runtimeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) -> ProtocolName { + let typeNode = Node.createTransient(kind: .type, child: ObjCRuntimeNames.protocolNode(forRuntimeName: runtimeName, in: machO)) + return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO)) + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/ObjCProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ObjCProtocolDefinition+Indexing.swift new file mode 100644 index 000000000..3bbef3001 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ObjCProtocolDefinition+Indexing.swift @@ -0,0 +1,65 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +import SwiftThunkAnalysis +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +extension ObjCProtocolDefinition: OnceIndexedDefinition { + /// Reads the inherited protocols and the requirements. Idempotent, and + /// safe to call from several tasks at once: the first runs the pass, the + /// others wait for it (`DefinitionIndexing`). + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + runIndexingPass(in: machO) + } + } + + /// The pass `index(in:)` runs once. Synchronous, and it never indexes + /// another definition: a conformer's member is read from the class's + /// Objective-C member table, not from its `TypeDefinition`. + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) { + // Unpaired: the image holds no record to read requirements from. + guard let record = declaredProtocol.record, + let protocolNode = protocolName.node.materialize().first(of: .protocol) + else { return } + + inheritedProtocolNames = record.inheritedProtocolRuntimeNames.map { runtimeName in + let typeNode = Node.createTransient(kind: .type, child: ObjCRuntimeNames.protocolNode(forRuntimeName: runtimeName, in: machO)) + return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO)) + } + + let builtRequirements = ObjCProtocolRequirementBuilder.requirements(of: record, protocolNode: protocolNode, in: machO) + let witnesses = ObjCProtocolWitnesses.witnesses(for: builtRequirements, ofProtocolRuntimeName: record.runtimeName, protocolNode: protocolNode, in: machO) + requirements = builtRequirements.enumerated().map { index, requirement in + let witness = witnesses[index] + return ObjCProtocolRequirementDefinition( + kind: Self.kind(of: requirement), + node: InternedNodeReferenceCache.shared.reference(interning: witness?.node ?? requirement.node, in: machO), + selector: requirement.selector, + setterSelector: requirement.setterSelector, + isClassMember: requirement.isClassMember, + isOptional: requirement.isOptional, + origin: witness.map { .conformer(className: Self.className(of: $0, in: machO)) } ?? .selector, + hasExplicitSelector: witness?.hasExplicitSelector ?? true, + typeEncoding: requirement.typeEncoding + ) + } + } + + /// `Type > Class`, the shape a type definition's name takes. + private static func className(of witness: ObjCProtocolWitness, in machO: some MachOSwiftSectionRepresentableWithCache) -> TypeName { + let typeNode = Node.createTransient(kind: .type, child: witness.classNode) + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO), kind: .class) + } + + private static func kind(of requirement: ObjCProtocolRequirement) -> ObjCProtocolRequirementDefinition.Kind { + switch requirement.kind { + case .method: .method + case .initializer: .initializer + case .property: .property + case .subscript: .subscript + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ProtocolDefinition+Indexing.swift similarity index 93% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/ProtocolDefinition+Indexing.swift index f36cd6154..5a5fb96dc 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ProtocolDefinition+Indexing.swift @@ -2,7 +2,7 @@ import Demangling import MachOSwiftSection import OrderedCollections import SwiftStdlibToolbox -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension ProtocolDefinition: OnceIndexedDefinition { @@ -29,7 +29,7 @@ extension ProtocolDefinition: OnceIndexedDefinition { // different stores, and store-identity equality would let the same // implementation symbol be claimed by two requirements. func _symbol(for symbols: Symbols, visitedNodes: borrowing OrderedSet = []) throws -> DemangledSymbol? { - for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: name, ownerKind: .protocol, printedWith: .interfaceTypeBuilderOnly, in: machO) { + for candidate in SwiftSymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: name, ownerKind: .protocol, printedWith: .interfaceTypeBuilderOnly, in: machO) { if !visitedNodes.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { return candidate } @@ -43,8 +43,8 @@ extension ProtocolDefinition: OnceIndexedDefinition { in: machO ) - var requirementMemberSymbolsByKind: OrderedDictionary = [:] - var defaultImplementationMemberSymbolsByKind: OrderedDictionary = [:] + var requirementMemberSymbolsByKind: OrderedDictionary = [:] + var defaultImplementationMemberSymbolsByKind: OrderedDictionary = [:] var requirementVisitedNodes: OrderedSet = [] var defaultImplementationVisitedNodes: OrderedSet = [] diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift similarity index 90% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift index ecbcf1b56..981c08663 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift @@ -2,7 +2,7 @@ import Demangling import MachOSwiftSection import OrderedCollections import SwiftDeclarationRendering -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection extension TypeDefinition { @@ -69,13 +69,13 @@ extension TypeDefinition { lookups.vtableSlotMemberSymbols.append(slotMemberSymbol) } } else if let symbols = descriptor.implementationSymbols(in: machO), - let overrideSymbol = demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) { + let overrideSymbol = OverrideSymbolMatcher.demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) { node = overrideSymbol.demangledNode } else { continue } visitedNodes.append(StructuralNodeReferenceKey(node)) - let joinKey = memberJoinKey(for: node, in: machO.context) + let joinKey = OverrideSymbolMatcher.memberJoinKey(for: node, in: machO.context) lookups.methodDescriptorLookup[joinKey] = .method(descriptor) if let vtableBaseOffset { lookups.vtableOffsetLookup[joinKey] = vtableBaseOffset + index @@ -90,10 +90,10 @@ extension TypeDefinition { // symbol never matches. See // `Descriptor+MethodDescriptorSymbols.swift`. guard let symbols = descriptor.implementationSymbols(in: machO) else { continue } - guard let overrideSymbol = demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) else { continue } + guard let overrideSymbol = OverrideSymbolMatcher.demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) else { continue } let node = overrideSymbol.demangledNode visitedNodes.append(StructuralNodeReferenceKey(node)) - let joinKey = memberJoinKey(for: node, in: machO.context) + let joinKey = OverrideSymbolMatcher.memberJoinKey(for: node, in: machO.context) lookups.methodDescriptorLookup[joinKey] = .methodOverride(descriptor) if let vtableSlot = try? parentVTableCache.slotIndex(for: descriptor, in: machO.context) { @@ -107,10 +107,10 @@ extension TypeDefinition { // symbol never matches. See // `Descriptor+MethodDescriptorSymbols.swift`. guard let symbols = descriptor.implementationSymbols(in: machO) else { continue } - guard let overrideSymbol = demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) else { continue } + guard let overrideSymbol = OverrideSymbolMatcher.demangledOverrideSymbol(for: symbols, typeNode: typeNode, visitedNodes: visitedNodes, in: machO) else { continue } let node = overrideSymbol.demangledNode visitedNodes.append(StructuralNodeReferenceKey(node)) - lookups.methodDescriptorLookup[memberJoinKey(for: node, in: machO.context)] = .methodDefaultOverride(descriptor) + lookups.methodDescriptorLookup[OverrideSymbolMatcher.memberJoinKey(for: node, in: machO.context)] = .methodDefaultOverride(descriptor) } return lookups } @@ -141,7 +141,8 @@ extension TypeDefinition { .setter: break case .modifyCoroutine, - .readCoroutine: + .readCoroutine, + nil: return nil } guard let implementationOffset = descriptor.implementationOffset, diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+FinalRecovery.swift similarity index 78% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+FinalRecovery.swift index a1d279202..4c017dd6f 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+FinalRecovery.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols extension TypeDefinition { /// `final` recovery (evolution proposal 0006) — the mirror image of the @@ -19,7 +19,7 @@ extension TypeDefinition { /// before `orderedMembers` is built (which copies the member values). func recoverFinalMembers( fields: inout [FieldDefinition], - symbolIndexStore: SymbolIndexStore, + symbolIndexStore: SwiftSymbolIndexStore, in machO: some MachOSwiftSectionRepresentableWithCache ) { let name = typeName.name @@ -39,7 +39,7 @@ extension TypeDefinition { // a vtable entry — never `final`, even when the join missed it. var methodDescriptorSymbolMemberNames: Set = [] var subscriptMethodDescriptorNodeKeys: Set = [] - let instanceMemberKinds: [SymbolIndexStore.MemberKind] = [ + let instanceMemberKinds: [SwiftSymbolIndexStore.MemberKind] = [ .function(inExtension: false, isStatic: false), .variable(inExtension: false, isStatic: false, isStorage: false), .subscript(inExtension: false, isStatic: false), @@ -56,7 +56,7 @@ extension TypeDefinition { } else if let subscriptNode = descriptorSymbol.demangledNode.first(of: .subscript) { // Overloaded subscripts share one name, so they key on // the subscript subtree — the same extraction - // `DefinitionBuilder.subscripts` groups accessors by. + // `MemberDefinitionBuilder.subscripts` groups accessors by. subscriptMethodDescriptorNodeKeys.insert(StructuralNodeReferenceKey(subscriptNode)) } } @@ -64,7 +64,7 @@ extension TypeDefinition { for index in functions.indices where functions[index].methodDescriptor == nil && !functions[index].attributes.contains(.objc) && !methodDescriptorSymbolMemberNames.contains(functions[index].name) { functions[index].isFinal = true } - for index in variables.indices where !variables[index].accessors.isEmpty && !variables[index].hasVTableAccessor && !variables[index].attributes.contains(.objc) && !methodDescriptorSymbolMemberNames.contains(variables[index].name) { + for index in variables.indices where variables[index].hasDispatchableAccessorSymbol && !variables[index].hasVTableAccessor && !variables[index].attributes.contains(.objc) && !methodDescriptorSymbolMemberNames.contains(variables[index].name) { variables[index].isFinal = true } for index in subscripts.indices where !subscripts[index].accessors.isEmpty && !subscripts[index].hasVTableAccessor && !subscripts[index].attributes.contains(.objc) { @@ -75,8 +75,20 @@ extension TypeDefinition { // Stored `let`s are not overridable to begin with, so `final` on // them is pure noise — only stored `var`s (field records carrying // the IsVar flag) participate. - for index in fields.indices where fields[index].flags.contains(.isVariable) && !fields[index].accessors.isEmpty && !fields[index].hasVTableAccessor && !objcThunkMemberNames.contains(fields[index].name) && !methodDescriptorSymbolMemberNames.contains(fields[index].name) { + for index in fields.indices where fields[index].flags.contains(.isVariable) && fields[index].hasDispatchableAccessorSymbol && !fields[index].hasVTableAccessor && !objcThunkMemberNames.contains(fields[index].name) && !methodDescriptorSymbolMemberNames.contains(fields[index].name) { fields[index].isFinal = true } } } + +extension AccessorRepresentable { + /// Whether one of the member's accessors that a vtable could hold has a + /// symbol — the evidence `final` recovery needs. A SE-0400 init accessor + /// is never dispatched, so it testifies to nothing: on its own it would + /// mark a class's stored property `final` — the function SwiftUICore + /// keeps under a stored property's init accessor name is one (evolution + /// proposal `init-accessor-recovery`). + fileprivate var hasDispatchableAccessorSymbol: Bool { + accessors.contains { $0.kind != .initAccessor } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift similarity index 93% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift index 49d916584..77ed82a56 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift @@ -4,8 +4,9 @@ import MachOSwiftSection import SwiftDeclarationRendering import SwiftStdlibToolbox import SwiftThunkAnalysis -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import SwiftObjCInterop extension TypeDefinition: OnceIndexedDefinition { /// Fills the definition from the image: fields, members, the facts that @@ -30,7 +31,7 @@ extension TypeDefinition: OnceIndexedDefinition { /// wrapped-property recovery (needs both the folded fields and the member /// variables). private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) throws { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore var indexedFields = try indexedFieldDefinitions(in: machO) @@ -45,6 +46,10 @@ extension TypeDefinition: OnceIndexedDefinition { ) foldStoredPropertyAccessors(storedPropertyAccessorsByFieldName, into: &indexedFields) + // Needs the member variables and the fields: which field each init + // accessor initializes (evolution proposal `init-accessor-recovery`). + recoverInitAccessorFieldNames(fields: indexedFields) + // Cross-reference @objc and @nonobjc thunk symbols with built definitions applyThunkAttributes(symbolIndexStore: symbolIndexStore, typeName: typeName.name, typeNode: typeName.node, in: machO) @@ -94,6 +99,12 @@ extension TypeDefinition: OnceIndexedDefinition { // Needs the fields and the member variables above: which `_x` is a // wrapper's storage, and whether `x` still has accessors of its own. recoverWrappedProperties(in: machO) + + // Needs the wrapped properties: a wrapper's storage is not the + // `@Observable` macro's (evolution proposal `observable-macro-folding`). + recoverObservableMacroExpansion(in: machO) + + applyObjCProtocolAdoption(in: machO) } /// The type's stored fields, read from its field descriptor. Carries no diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+InitAccessors.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+InitAccessors.swift new file mode 100644 index 000000000..a5bf225f0 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+InitAccessors.swift @@ -0,0 +1,29 @@ +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +import SwiftInspection + +/// SE-0400 init accessor recovery, a step of `TypeDefinition.index(in:)` +/// (evolution proposal `init-accessor-recovery`): which fields each init +/// accessor is inferred to initialize, read off the type's stored properties +/// by the rules of `InitAccessorFieldInference`. Runs once the member +/// variables are built and the fields known, and before `orderedMembers` +/// copies the members' values. +extension TypeDefinition { + /// The type compared with a field is the one the init accessor's own + /// symbol spells, not the declaration's — that is the getter's, which + /// can keep an older mangling (`InitAccessorFieldInference`). The dump + /// reads the same symbol, so the two agree. + /// + /// - Parameter fields: the type's fields, which `index(in:)` assigns to + /// `fields` only later. + func recoverInitAccessorFieldNames(fields: [FieldDefinition]) { + guard variables.contains(where: \.hasInitAccessor) else { return } + let fieldsByName = Dictionary(fields.map { ($0.name, $0) }, uniquingKeysWith: { first, _ in first }) + for index in variables.indices { + guard let initAccessor = variables[index].accessors.last(where: { $0.kind == .initAccessor }) else { continue } + variables[index].initializedFieldNames = InitAccessorFieldInference.initializedFieldNames(ofInitAccessorSymbol: initAccessor.symbol.demangledNode) { fieldName in + fieldsByName[fieldName].map { InitAccessorFieldInference.StoredField(name: $0.name, typeNode: $0.typeNode.materialize()) } + } + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+MemberIndexing.swift similarity index 56% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+MemberIndexing.swift index a75411e7c..13820bce0 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+MemberIndexing.swift @@ -1,6 +1,6 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols extension TypeDefinition { /// Builds every symbol-backed member of this type — the six member @@ -16,6 +16,13 @@ extension TypeDefinition { /// binary run through `strip -x` — those members had nothing else to be /// built from and went missing. /// + /// After those, a member none of the symbols declares is built from the + /// entry point an optimized image kept of it + /// (`StandInMemberSymbolBuilder.TypeMembers`, evolution proposal + /// `thunk-only-objc-members`): an initializer from its initializing entry + /// point when the allocating one was inlined away, an `@objc` member from + /// its Objective-C thunk when its Swift body was inlined into the thunk. + /// /// Returns the accessor groups that were suppressed because their name /// matches a stored field record: those carry dispatch facts the field /// still needs, and `foldStoredPropertyAccessors(_:into:)` folds them back @@ -23,14 +30,21 @@ extension TypeDefinition { func indexMembers( fieldNames: Set, dispatchLookups: ClassDispatchLookups, - symbolIndexStore: SymbolIndexStore, + symbolIndexStore: SwiftSymbolIndexStore, in machO: some MachOSwiftSectionRepresentableWithCache ) -> [String: [Accessor]] { let name = typeName.name let node = typeName.node + let standIns = StandInMemberSymbolBuilder.TypeMembers(typeName: name, typeNode: node, symbolIndexStore: symbolIndexStore, in: machO) + + /// The builder input of `category`: the real symbols, then the + /// vtable slots' stand-ins, then the optimized-away entry points'. + func builderInput(_ realSymbols: [DemangledSymbol], in category: MemberCategory) -> [DemangledSymbol] { + standIns.supplementing(dispatchLookups.supplementing(realSymbols, in: category), in: category) + } - allocators = DefinitionBuilder.allocators( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .allocator(inExtension: false), for: name, node: node, in: machO), in: .allocators).mapToAnnotatedSymbols(), + allocators = MemberDefinitionBuilder.allocators( + for: builderInput(symbolIndexStore.memberSymbols(of: .allocator(inExtension: false), for: name, node: node, in: machO), in: .allocators).mapToAnnotatedSymbols(), dispatchLookups: dispatchLookups ) @@ -44,16 +58,16 @@ extension TypeDefinition { deallocatorSymbol = symbolIndexStore.memberSymbols(of: .deallocator, for: name, node: node, in: machO).first?.detachedFromSharedTable() destructorSymbol = symbolIndexStore.memberSymbols(of: .destructor, for: name, node: node, in: machO).first?.detachedFromSharedTable() - let variablesProduct = DefinitionBuilder.variablesProduct( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .variable(inExtension: false, isStatic: false, isStorage: false), for: name, node: node, in: machO), in: .variables).mapToAnnotatedSymbols(), + let variablesProduct = MemberDefinitionBuilder.variablesProduct( + for: builderInput(symbolIndexStore.memberSymbols(of: .variable(inExtension: false, isStatic: false, isStorage: false), for: name, node: node, in: machO), in: .variables).mapToAnnotatedSymbols(), fieldNames: fieldNames, dispatchLookups: dispatchLookups, isGlobalOrStatic: false ) variables = variablesProduct.variables - staticVariables = DefinitionBuilder.variables( - for: dispatchLookups.supplementing( + staticVariables = MemberDefinitionBuilder.variables( + for: builderInput( symbolIndexStore.memberSymbols( of: .variable(inExtension: false, isStatic: true, isStorage: false), .variable(inExtension: false, isStatic: true, isStorage: true), @@ -67,26 +81,26 @@ extension TypeDefinition { isGlobalOrStatic: true ) - functions = DefinitionBuilder.functions( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: false), for: name, node: node, in: machO), in: .functions).mapToAnnotatedSymbols(), + functions = MemberDefinitionBuilder.functions( + for: builderInput(symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: false), for: name, node: node, in: machO), in: .functions).mapToAnnotatedSymbols(), dispatchLookups: dispatchLookups, isGlobalOrStatic: false ) - staticFunctions = DefinitionBuilder.functions( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: true), for: name, node: node, in: machO), in: .staticFunctions).mapToAnnotatedSymbols(), + staticFunctions = MemberDefinitionBuilder.functions( + for: builderInput(symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: true), for: name, node: node, in: machO), in: .staticFunctions).mapToAnnotatedSymbols(), dispatchLookups: dispatchLookups, isGlobalOrStatic: true ) - subscripts = DefinitionBuilder.subscripts( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .subscript(inExtension: false, isStatic: false), for: name, node: node, in: machO), in: .subscripts).mapToAnnotatedSymbols(), + subscripts = MemberDefinitionBuilder.subscripts( + for: builderInput(symbolIndexStore.memberSymbols(of: .subscript(inExtension: false, isStatic: false), for: name, node: node, in: machO), in: .subscripts).mapToAnnotatedSymbols(), dispatchLookups: dispatchLookups, isStatic: false ) - staticSubscripts = DefinitionBuilder.subscripts( - for: dispatchLookups.supplementing(symbolIndexStore.memberSymbols(of: .subscript(inExtension: false, isStatic: true), for: name, node: node, in: machO), in: .staticSubscripts).mapToAnnotatedSymbols(), + staticSubscripts = MemberDefinitionBuilder.subscripts( + for: builderInput(symbolIndexStore.memberSymbols(of: .subscript(inExtension: false, isStatic: true), for: name, node: node, in: machO), in: .staticSubscripts).mapToAnnotatedSymbols(), dispatchLookups: dispatchLookups, isStatic: true ) diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCMembers.swift similarity index 97% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCMembers.swift index 7aefff454..a9ae7f1e2 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCMembers.swift @@ -1,6 +1,7 @@ import Demangling import MachOKitExtensions @_spi(Internals) import SwiftInspection +import SwiftObjCInterop import SwiftThunkAnalysis extension TypeDefinition { @@ -27,7 +28,7 @@ extension TypeDefinition { // ObjC-side index derive from the class's runtime name. guard let qualifiedName = NodeTypeNaming.nominalQualifiedName(ofDemangledRoot: typeName.node.materialize()) else { return nil } guard let table = ObjCMembers.table(forSwiftClassQualifiedName: qualifiedName, in: machO), !table.isEmpty else { return nil } - ObjCMemberApplication.apply( + ObjCMemberMatcher.apply( table, functions: &functions, variables: &variables, diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCProtocols.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCProtocols.swift new file mode 100644 index 000000000..84ca2887e --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObjCProtocols.swift @@ -0,0 +1,20 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +extension TypeDefinition { + /// Reads the Objective-C protocols the class adopts in its own data + /// (evolution proposal `swift-declared-objc-protocols`) into + /// ``objcProtocolNames``. Only a class can; a name several classes print + /// as finds none. + package func applyObjCProtocolAdoption(in machO: some MachOSwiftSectionRepresentableWithCache) { + guard typeName.kind == .class, + let qualifiedName = NodeTypeNaming.nominalQualifiedName(ofDemangledRoot: typeName.node.materialize()), + let adoption = ObjCProtocolAdoptionIndex.shared.adoption(ofSwiftClassQualifiedName: qualifiedName, in: machO) + else { return } + objcProtocolNames = ObjCProtocolNameBuilder.protocolNames(adoption.declaredProtocolRuntimeNames, excluding: adoption.impliedProtocolRuntimeNames, in: machO) + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObservableMacro.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObservableMacro.swift new file mode 100644 index 000000000..35bb64a32 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ObservableMacro.swift @@ -0,0 +1,102 @@ +@_spi(Internals) import Demangling +import Dependencies +import MachOSwiftSection +import SwiftInspection +@_spi(Internals) import SwiftSymbols + +/// `@Observable` expansion recovery, a step of `TypeDefinition.index(in:)` +/// (evolution proposal `observable-macro-folding`). +/// +/// For a class `attachedMacros` marks `.observable`, it sorts the stored +/// `var`s into the storage of the properties the macro tracks and the ones +/// it left alone, and picks out the methods it generated — see +/// `ObservableMacroExpansion` and the rules in +/// `ObservableMacroExpansionRecovery`. Runs after wrapped-property recovery: +/// a wrapper's storage is not the macro's, and the macro cannot track a +/// wrapped property. +extension TypeDefinition { + package func recoverObservableMacroExpansion(in machO: some MachOSwiftSectionRepresentableWithCache) { + guard attachedMacros.contains(.observable) else { + observableMacroExpansion = nil + return + } + @Dependency(\.swiftSymbolIndexStore) + var symbolIndexStore + + let storedProperties = fields.filter { !$0.flags.contains(.isArtificial) } + // The names the evidence can be about: each storage `_x` and the + // property `x` it would be, so a symbol of any other variable is + // passed over before its context is compared. + var candidateNames: Set = [] + for storedProperty in storedProperties where storedProperty.name.hasPrefix("_") { + candidateNames.insert(storedProperty.name) + if let propertyName = ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: storedProperty.name) { + candidateNames.insert(propertyName) + } + } + let typeContextNode = typeName.node.kind == .type ? typeName.node.children.first ?? typeName.node : typeName.node + let evidence = ObservableMacroExpansionRecovery.SymbolEvidence( + initAccessorNames: Self.variableNames(declaredBy: symbolIndexStore.symbols(of: .initAccessor, in: machO), in: typeContextNode, among: candidateNames), + initialValueExpressionNames: { + Self.variableNames(declaredBy: symbolIndexStore.symbols(of: .initializer, in: machO), in: typeContextNode, among: candidateNames) + } + ) + + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: storedProperties.map { field in + ObservableMacroExpansionRecovery.StoredProperty( + name: field.name, + typeNode: field.typeNode.materialize(), + isVariable: field.flags.contains(.isVariable), + hasAccessors: !field.accessors.isEmpty + ) + }, + memberVariables: variables.filter { !$0.isGlobalOrStatic }.map { variable in + ObservableMacroExpansionRecovery.MemberVariable( + name: variable.name, + declaredTypeNode: WrappedPropertyRecovery.declaredTypeNode(of: variable), + hasSetterOrModify: variable.hasSetter || variable.hasModifyAccessor + ) + }, + claimedBackingFieldNames: Set(wrappedProperties.map(\.backingFieldName)), + evidence: evidence + ) + observableMacroExpansion = ObservableMacroExpansion( + trackedProperties: recovered.trackedProperties, + ignoredStoredPropertyNames: recovered.ignoredStoredPropertyNames, + generatedFunctions: functions.filter { function in + !function.isGlobalOrStatic + && ObservableMacroExpansionRecovery.isGeneratedFunction(name: function.name, node: function.node.materialize()) + } + ) + } + + /// The names among `candidateNames` of the variables of the type + /// `typeContextNode` names that `symbols` — init accessors or + /// initial-value expressions — are for. Each symbol's own variable node + /// is read: its first child is the declaring context, its second the + /// name, wrapped in a `privateDeclName` for a private property. + private static func variableNames(declaredBy symbols: [DemangledSymbol], in typeContextNode: NodeReference, among candidateNames: Set) -> Set { + var names: Set = [] + for symbol in symbols { + guard let entityNode = symbol.demangledNode.children.first(where: { $0.kind == .initAccessor || $0.kind == .initializer }), + let variableNode = entityNode.children.first, variableNode.kind == .variable, + let nameNode = variableNode.children.dropFirst().first + else { continue } + let name: String? + switch nameNode.kind { + case .identifier: + name = nameNode.text + case .privateDeclName: + name = nameNode.children.last(where: { $0.kind == .identifier })?.text + default: + name = nil + } + guard let name, candidateNames.contains(name), + let contextNode = variableNode.children.first, contextNode.structurallyEquals(typeContextNode) + else { continue } + names.insert(name) + } + return names + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+SynthesizedMembers.swift similarity index 99% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+SynthesizedMembers.swift index b6321eda0..de3ec06e4 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+SynthesizedMembers.swift @@ -1,5 +1,5 @@ import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols extension TypeDefinition { /// Drops body-side copies of members that Swift auto-synthesizes for diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ThunkAttributes.swift similarity index 61% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ThunkAttributes.swift index 574e48b63..29e253edc 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ThunkAttributes.swift @@ -1,20 +1,20 @@ import Demangling import MachOSwiftSection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols extension TypeDefinition { /// Cross-references `@objc` / `@nonobjc` thunk attribute members (pre-extracted - /// and bucketed by parent type name inside `SymbolIndexStore`) with the + /// and bucketed by parent type name inside `SwiftSymbolIndexStore`) with the /// already-built member definitions of this type, appending the matching /// attribute to each affected member. The matching itself lives in - /// `MemberAttributeApplication`, shared with `ExtensionDefinition`. + /// `ThunkAttributeMatcher`, shared with `ExtensionDefinition`. func applyThunkAttributes( - symbolIndexStore: SymbolIndexStore, + symbolIndexStore: SwiftSymbolIndexStore, typeName: String, typeNode: NodeReference, in machO: some MachORepresentableWithCache ) { - MemberAttributeApplication.applyThunkAttributes( + ThunkAttributeMatcher.applyThunkAttributes( symbolIndexStore: symbolIndexStore, typeName: typeName, typeNode: typeNode, @@ -28,14 +28,10 @@ extension TypeDefinition { } func applyAttributeToFunction(name: String, attribute: SwiftAttribute, in definitions: inout [FunctionDefinition]) { - MemberAttributeApplication.apply(attribute, toFunctionNamed: name, in: &definitions) + ThunkAttributeMatcher.apply(attribute, toFunctionNamed: name, in: &definitions) } func applyAttributeToVariable(name: String, attribute: SwiftAttribute, in definitions: inout [VariableDefinition]) { - MemberAttributeApplication.apply(attribute, toVariableNamed: name, in: &definitions) - } - - func applyAttributeToAllocator(attribute: SwiftAttribute, in definitions: inout [FunctionDefinition]) { - MemberAttributeApplication.apply(attribute, toEveryAllocatorIn: &definitions) + ThunkAttributeMatcher.apply(attribute, toVariableNamed: name, in: &definitions) } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+WrappedProperties.swift similarity index 98% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift rename to Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+WrappedProperties.swift index 4e484a003..199dff97b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+WrappedProperties.swift @@ -2,7 +2,7 @@ import Dependencies import MachOSwiftSection import SwiftDeclarationRendering -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// Wrapped-property recovery, the last step of `TypeDefinition.index(in:)`. /// @@ -17,7 +17,7 @@ import SwiftDeclarationRendering /// `wrappedValue`. extension TypeDefinition { package func recoverWrappedProperties(in machO: some MachOSwiftSectionRepresentableWithCache) { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore let catalog = PropertyWrapperTypeCatalogStore.shared.catalog(for: machO) var recovered: [WrappedPropertyDefinition] = [] diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/Definition.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Definitions/Definition.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ExtensionDefinition.swift similarity index 91% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Definitions/ExtensionDefinition.swift index 07ce012e0..9d3276cb6 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ExtensionDefinition.swift @@ -5,8 +5,9 @@ import OrderedCollections import Demangling import Semantic import SwiftStdlibToolbox -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import SwiftObjCInterop /// An extension block of an image — a conformance, a member extension or a /// typealias-only block — as the declaration model holds it. @@ -42,7 +43,7 @@ public final class ExtensionDefinition: Definition, MutableDefinition, @unchecke /// The associated-type witnesses of `associatedTypes`, resolved into pure /// value data at index time (their `AssociatedTypeRecord` accessors are /// Mach-O-bound, so the snapshot layer cannot resolve them later). - public package(set) var resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] + public package(set) var resolvedAssociatedTypeWitnesses: [ResolvedAssociatedTypeWitness] public package(set) var types: [TypeDefinition] = [] @@ -66,6 +67,20 @@ public final class ExtensionDefinition: Definition, MutableDefinition, @unchecke public package(set) var isRetroactive: Bool = false + /// The macro attached to the extended type whose expansion this + /// extension is, or `nil` (evolution proposal + /// `observable-macro-folding`): `@Observable` writes + /// `extension Model: Observation.Observable {}`, so the conformance + /// extension of an `.observable` class to that protocol carries + /// `.observable`. Set by the indexer when it builds the conformance + /// extensions, which it does after every type definition — and so every + /// `TypeDefinition.attachedMacros` — exists. + /// + /// The folded interface prints the macro attribute in its place; a host + /// showing extensions as objects of their own hides one that carries a + /// macro while the interface folds macro expansions. + public package(set) var generatingMacro: SwiftAttachedMacro? = nil + /// Set by the indexer's container-unification pass (evolution proposal /// 0007) when this symbol-scan protocol-extension block was attached to /// its `ProtocolDefinition.defaultImplementationExtensions` — the @@ -122,7 +137,7 @@ public final class ExtensionDefinition: Definition, MutableDefinition, @unchecke /// parsed wrapper is released once the indexer's grouping pass ends. Its /// `[ResilientWitness]` goes with it, except for the unresolvable subset /// `index(in:)` copies onto `missingSymbolWitnesses`. - public init(extensionName: ExtensionName, genericSignature: NodeReference?, protocolConformance: ProtocolConformance?, conformingProtocolName: ProtocolName? = nil, associatedTypes: [AssociatedType] = [], resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] = []) { + public init(extensionName: ExtensionName, genericSignature: NodeReference?, protocolConformance: ProtocolConformance?, conformingProtocolName: ProtocolName? = nil, associatedTypes: [AssociatedType] = [], resolvedAssociatedTypeWitnesses: [ResolvedAssociatedTypeWitness] = []) { self.extensionName = extensionName self.genericSignature = genericSignature self.protocolConformanceDescriptor = protocolConformance?.descriptor @@ -133,13 +148,13 @@ public final class ExtensionDefinition: Definition, MutableDefinition, @unchecke /// The reader argument was never read. @available(*, deprecated, message: "Drop the reader argument: nothing is read.") - public convenience init(extensionName: ExtensionName, genericSignature: NodeReference?, protocolConformance: ProtocolConformance?, conformingProtocolName: ProtocolName? = nil, associatedTypes: [AssociatedType] = [], resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] = [], in machO: some MachOSwiftSectionRepresentableWithCache) throws { + public convenience init(extensionName: ExtensionName, genericSignature: NodeReference?, protocolConformance: ProtocolConformance?, conformingProtocolName: ProtocolName? = nil, associatedTypes: [AssociatedType] = [], resolvedAssociatedTypeWitnesses: [ResolvedAssociatedTypeWitness] = [], in machO: some MachOSwiftSectionRepresentableWithCache) throws { self.init(extensionName: extensionName, genericSignature: genericSignature, protocolConformance: protocolConformance, conformingProtocolName: conformingProtocolName, associatedTypes: associatedTypes, resolvedAssociatedTypeWitnesses: resolvedAssociatedTypeWitnesses) } /// Mach-O-free initializer for pure-value construction (tests, tooling). /// Carries no conformance descriptor — only the frozen attribution fields. - package init(extensionName: ExtensionName, genericSignature: NodeReference?, conformingProtocolName: ProtocolName? = nil, resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] = []) { + package init(extensionName: ExtensionName, genericSignature: NodeReference?, conformingProtocolName: ProtocolName? = nil, resolvedAssociatedTypeWitnesses: [ResolvedAssociatedTypeWitness] = []) { self.extensionName = extensionName self.genericSignature = genericSignature self.protocolConformanceDescriptor = nil @@ -170,11 +185,6 @@ public final class ExtensionDefinition: Definition, MutableDefinition, @unchecke try protocolConformanceDescriptor.map { try ProtocolConformance(descriptor: $0, in: context) } } - @available(*, deprecated, message: "Pass a ReadingContext: materializedProtocolConformance(in: machO.context).") - public func materializedProtocolConformance(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolConformance? { - try materializedProtocolConformance(in: machO.context) - } - /// Folds another definition's associated types (and their frozen witness /// projections) into this one — the indexer's typealias-only merge path. package func absorbAssociatedTypes(of other: ExtensionDefinition) { diff --git a/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedCategoryDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedCategoryDefinition.swift new file mode 100644 index 000000000..dc1580fd2 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedCategoryDefinition.swift @@ -0,0 +1,57 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// An Objective-C category of the image as Swift imports it (evolution +/// proposal `objc-imported-declarations`): `extension Class: Protocol… { … }` +/// — Swift has no name for a category — its members built from the +/// category's method and property lists by the importer's rules. +/// +/// A category Swift wrote — an `@objc @implementation` of a category a header +/// declares, or `extension NSView { @objc func … }` — takes each member from +/// the image's Swift extension of the class implementing it +/// (``swiftExtensions``), paired by selector as for +/// ``ObjCImportedClassDefinition``. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives. +public final class ObjCImportedCategoryDefinition: @unchecked Sendable { + /// The class the category extends, `Type > Class`. + public let extendedClassName: TypeName + + /// The category's own name: `NSTouchBar` of `NSView(NSTouchBar)`. + public let categoryName: String + + /// The name the category is listed under, `NSView(NSTouchBar)`. + public let uniqueName: String + + /// The image's Swift extensions of the class, which implement a category + /// Swift wrote. + public let swiftExtensions: [ExtensionDefinition] + + /// The protocols the category adopts; read by `index(in:)`. + public package(set) var protocolNames: [ProtocolName] = [] + + /// The members, instance members first; read by `index(in:)`. + public package(set) var members: [ObjCImportedMemberDefinition] = [] + + /// Whether `index(in:)` has completed a pass over this definition. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + var hasCompletedIndexing = false + + package let record: ObjCImportedContainerRecord + + package init(record: ObjCImportedContainerRecord, categoryName: String, swiftExtensions: [ExtensionDefinition], in machO: some MachOSwiftSectionRepresentableWithCache) { + let classNode = ObjCRuntimeNames.classNode(forRuntimeName: record.classRuntimeName, in: machO) + self.extendedClassName = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: Node.createTransient(kind: .type, child: classNode), in: machO), kind: .class) + self.categoryName = categoryName + self.uniqueName = record.uniqueName + self.swiftExtensions = swiftExtensions + self.record = record + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedClassDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedClassDefinition.swift new file mode 100644 index 000000000..ab1904ca1 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedClassDefinition.swift @@ -0,0 +1,83 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// An Objective-C class of the image as Swift imports it (evolution proposal +/// `objc-imported-declarations`): `class Name: Superclass, Protocol… { … }`, +/// its members built from the class's method and property lists by the +/// importer's rules (``ObjCImportedMemberDefinition``). +/// +/// When Swift implements the class, the interface prints Swift's own +/// declarations rather than the names the rules derive: a Swift class +/// registered with the runtime prints as the Swift class it is +/// (``swiftClassDefinition``) with its extensions, and a class declared in +/// Objective-C takes each member Swift implements from the image's Swift +/// extension implementing it (``swiftExtensions``). The linker merges the +/// category an extension with `@objc` members compiles to into the class's +/// own lists when the class is the image's, so those members are the class's +/// methods too. The printer pairs them by selector, through the Objective-C +/// member table of those definitions; a member none of them implements still +/// prints by the rules. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives: written only +/// while the model is built and while `index(in:)` runs once behind +/// `DefinitionIndexing`'s lock; printing writes nothing to it. +public final class ObjCImportedClassDefinition: @unchecked Sendable { + /// `Type > Class`: `__C.NSView` for a class declared in Objective-C, a + /// Swift class under its own name. + public let className: TypeName + + /// The name the Objective-C runtime registers the class under. + public let objcRuntimeName: String + + /// Whether the class data's Swift bit is set: a Swift class registered + /// with the Objective-C runtime. + public let isSwiftClass: Bool + + /// The Swift class's own definition, for a Swift class this image + /// indexes; `nil` otherwise. + public let swiftClassDefinition: TypeDefinition? + + /// The image's Swift extensions of the class: of a Swift class, its + /// extensions and conformances; of a class declared in Objective-C, its + /// `@objc @implementation` bodies and the extensions adding `@objc` + /// members. + public let swiftExtensions: [ExtensionDefinition] + + /// The superclass, by the name Swift gives it; `nil` for a root class + /// and for a superclass the reader cannot name. Read by `index(in:)`. + public package(set) var superclassName: TypeName? + + /// The protocols the class adopts; read by `index(in:)`. + public package(set) var protocolNames: [ProtocolName] = [] + + /// The members, instance members first, each list in its order; read by + /// `index(in:)`. + public package(set) var members: [ObjCImportedMemberDefinition] = [] + + /// Whether `index(in:)` has completed a pass over this definition. Safe + /// to read from any thread. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + /// The flag behind `isIndexed`; `DefinitionIndexing` alone reads and + /// writes it, under its lock. + var hasCompletedIndexing = false + + /// What the image's lists record of the class. + package let record: ObjCImportedContainerRecord + + package init(record: ObjCImportedContainerRecord, swiftClassDefinition: TypeDefinition?, swiftExtensions: [ExtensionDefinition], in machO: some MachOSwiftSectionRepresentableWithCache) { + let classNode = ObjCRuntimeNames.classNode(forRuntimeName: record.classRuntimeName, in: machO) + self.className = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: Node.createTransient(kind: .type, child: classNode), in: machO), kind: .class) + self.objcRuntimeName = record.classRuntimeName + self.isSwiftClass = record.isSwiftClass + self.swiftClassDefinition = swiftClassDefinition + self.swiftExtensions = swiftExtensions + self.record = record + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedProtocolDefinition.swift new file mode 100644 index 000000000..a9d4992c0 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCImportedProtocolDefinition.swift @@ -0,0 +1,47 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// An Objective-C protocol as Swift imports it (evolution proposal +/// `objc-imported-declarations`): `protocol Name: Inherited… { … }`, its +/// requirements built from the image's record of it by the importer's +/// rules, optional ones marked `@objc optional`. An image holds a record of +/// every protocol it adopts or names, not only of the ones it defines. +/// +/// An `@objc` protocol declared in Swift has an ``ObjCProtocolDefinition`` +/// too, which the image's Swift side lists; this one reads the record the +/// way the importer reads a header, for a protocol of any origin. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives. +public final class ObjCImportedProtocolDefinition: @unchecked Sendable { + /// `Type > Protocol`. + public let protocolName: ProtocolName + + /// The name the Objective-C runtime registers the protocol under. + public let objcRuntimeName: String + + /// The protocols it inherits; read by `index(in:)`. + public package(set) var inheritedProtocolNames: [ProtocolName] = [] + + /// The requirements, in the record's order; read by `index(in:)`. + public package(set) var requirements: [ObjCProtocolRequirementDefinition] = [] + + /// Whether `index(in:)` has completed a pass over this definition. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + var hasCompletedIndexing = false + + package let record: ObjCProtocolRecord + + package init(record: ObjCProtocolRecord, in machO: some MachOSwiftSectionRepresentableWithCache) { + let protocolNode = ObjCRuntimeNames.protocolNode(forRuntimeName: record.runtimeName, in: machO) + self.protocolName = ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: Node.createTransient(kind: .type, child: protocolNode), in: machO)) + self.objcRuntimeName = record.runtimeName + self.record = record + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCProtocolDefinition.swift new file mode 100644 index 000000000..cc4a5291a --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ObjCProtocolDefinition.swift @@ -0,0 +1,91 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// An `@objc` protocol declared in Swift that the image defines (evolution +/// proposal `swift-declared-objc-protocols`). +/// +/// The compiler gives such a protocol no Swift protocol descriptor, so it is +/// no ``ProtocolDefinition``: what the image keeps of it is a +/// `__swift5_fieldmd` record naming it and an Objective-C protocol record +/// holding its requirements — with no Swift symbol for any of them. The +/// requirements are rebuilt from that record by `index(in:)`, each +/// spelled from a Swift class of the image that implements it when there is +/// one, and from its selector by the importer's rules when there is not. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives: written only +/// while the model is built and while `index(in:)` runs once behind +/// `DefinitionIndexing`'s lock; printing writes nothing to it. +public final class ObjCProtocolDefinition: @unchecked Sendable { + /// `Type > Protocol`, the shape a Swift protocol's name takes, so the + /// image's `extension` of the protocol files under the same + /// ``ExtensionName``. + public let protocolName: ProtocolName + + /// The name the Objective-C runtime registers the protocol under; `nil` + /// when the image holds no record the declaration could be paired with — + /// the source renamed it with `@objc(Name)` to a name other than its + /// Swift name. + public let objcRuntimeName: String? + + /// Whether the source renamed the protocol for the runtime: its runtime + /// name is not the `_TtP…_` mangling the compiler derives by default. + public let hasExplicitObjCName: Bool + + /// The protocols it inherits, by Swift name; read by `index(in:)`. + public package(set) var inheritedProtocolNames: [ProtocolName] = [] + + /// The requirements, in the record's order; read by `index(in:)`. + public package(set) var requirements: [ObjCProtocolRequirementDefinition] = [] + + /// The image's `extension`s of the protocol: their members' symbols name + /// the protocol as an extended context, as for a Swift protocol. + public package(set) var defaultImplementationExtensions: [ExtensionDefinition] = [] + + /// The protocol has no symbol of its own, so only its name can rule: + /// ``ExportStatus/notExported`` for a private protocol or one nested in a + /// private type, ``ExportStatus/declarationHasNoSymbol`` — no verdict — + /// for any other (evolution proposal `export-verdict-without-local-symbols`). + public let exportStatus: ExportStatus + + /// Whether `index(in:)` has completed a pass over this definition. Safe + /// to read from any thread. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + /// The flag behind `isIndexed`; `DefinitionIndexing` alone reads and + /// writes it, under its lock. + var hasCompletedIndexing = false + + /// What the image's index found: the record, and how the protocol was + /// recognized. + package let declaredProtocol: SwiftDeclaredObjCProtocol + + package init(declaredProtocol: SwiftDeclaredObjCProtocol, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + let node = try demangleAsNodeTransient(declaredProtocol.mangledName) + guard let protocolNode = node.first(of: .protocol) else { + throw ObjCProtocolDefinitionError.nameIsNoProtocol(mangledName: declaredProtocol.mangledName) + } + let typeNode = Node.createTransient(kind: .type, child: protocolNode) + let protocolName = ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO)) + self.protocolName = protocolName + self.exportStatus = ExportStatus.resolve(forSwiftDeclaredObjCProtocolNamed: protocolName.node, in: machO) + self.objcRuntimeName = declaredProtocol.record?.runtimeName + self.hasExplicitObjCName = declaredProtocol.hasExplicitObjCName + self.declaredProtocol = declaredProtocol + } +} + +public enum ObjCProtocolDefinitionError: Error, CustomStringConvertible { + case nameIsNoProtocol(mangledName: String) + + public var description: String { + switch self { + case .nameIsNoProtocol(let mangledName): "the name \(mangledName) of an @objc protocol's field descriptor names no protocol" + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ProtocolDefinition.swift similarity index 95% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Definitions/ProtocolDefinition.swift index 608444e6f..70f607639 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/ProtocolDefinition.swift @@ -5,7 +5,7 @@ import OrderedCollections import Demangling import Semantic import SwiftStdlibToolbox -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection /// A protocol of an image, as the declaration model holds it. @@ -121,7 +121,7 @@ public final class ProtocolDefinition: Definition, MutableDefinition, @unchecked let protocolName = ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO)) self.protocolName = protocolName self.exportStatus = ExportStatus.resolve( - forProtocolDescriptorAt: `protocol`.descriptor.offset, + forProtocolDescriptor: `protocol`.descriptor, protocolNameNode: protocolName.node, in: machO ) @@ -152,9 +152,4 @@ public final class ProtocolDefinition: Definition, MutableDefinition, @unchecked public func materializedProtocol(in context: some ReadingContext) throws -> MachOSwiftSection.`Protocol` { try MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: context) } - - @available(*, deprecated, message: "Pass a ReadingContext: materializedProtocol(in: machO.context).") - public func materializedProtocol(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MachOSwiftSection.`Protocol` { - try materializedProtocol(in: machO.context) - } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Definitions/TypeDefinition.swift similarity index 79% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Definitions/TypeDefinition.swift index 56d05188e..84ed1234c 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Definitions/TypeDefinition.swift @@ -1,6 +1,7 @@ import MachOSwiftSection import SwiftInspection -@_spi(Internals) import MachOSymbols +import SwiftObjCInterop +@_spi(Internals) import SwiftSymbols /// A nominal type of an image, as the declaration model holds it. /// @@ -48,13 +49,27 @@ public final class TypeDefinition: Definition, @unchecked Sendable { /// /// Resolving it queries the image's symbol index, so constructing a /// definition through `init(type:in:)` for an image whose index has not - /// been built yet builds it (`SymbolIndexStore.storage(in:)` is + /// been built yet builds it (`SwiftSymbolIndexStore.storage(in:)` is /// get-or-build). Through `SwiftDeclarationIndexer.prepare()` — the /// normal path — the index is already up by the time definitions are /// constructed, which is why the whole sweep costs well under 1% of /// preparation. public let exportStatus: ExportStatus + /// The macros the source attached to this type, recognized from what + /// their expansion left in the binary (evolution proposal + /// `observable-macro-folding`): `.observable` for a class `@Observable` + /// expanded. Resolved once at construction, from the type's field + /// records alone, so it is there the moment + /// `SwiftDeclarationIndexer.prepare()` returns — a host listing types + /// can mark every row before any of them is indexed. A specialized + /// definition carries the value of the generic definition it was + /// derived from. + /// + /// What the expansion of a recognized macro holds comes with + /// `index(in:)`: see `observableMacroExpansion`. + public let attachedMacros: Set + public package(set) weak var parent: TypeDefinition? /// Nested type definitions whose containing context is `self`. @@ -91,6 +106,39 @@ public final class TypeDefinition: Definition, @unchecked Sendable { /// See `WrappedPropertyDefinition`. public package(set) var wrappedProperties: [WrappedPropertyDefinition] = [] + /// What `@Observable` generated in this class, recovered at index time + /// from the fields and members it left — which stay in `fields`, + /// `variables` and `functions` as the binary has them. `nil` unless + /// `attachedMacros` contains `.observable`, and until `index(in:)` has + /// run. See `ObservableMacroExpansion`. + public package(set) var observableMacroExpansion: ObservableMacroExpansion? { + get { observableMacroExpansionStorage?.expansion } + set { observableMacroExpansionStorage = newValue.map(ObservableMacroExpansionStorage.init(expansion:)) } + } + + /// Boxed, so every definition carries one reference and only the few + /// classes the macro expanded allocate the description: the instance + /// size stays in the descriptor-sized band evolution proposal 0002 + /// guards (`DeclarationModelInstanceSizeTests`). + private var observableMacroExpansionStorage: ObservableMacroExpansionStorage? = nil + + private final class ObservableMacroExpansionStorage: Sendable { + let expansion: ObservableMacroExpansion + + init(expansion: ObservableMacroExpansion) { + self.expansion = expansion + } + } + + /// The Objective-C protocols a class adopts, read at index time from its + /// `class_ro_t` (evolution proposal `swift-declared-objc-protocols`): an + /// `@objc` protocol has no witness table, so no conformance record names + /// it. The compiler folds the extensions the class's own module declares + /// into the class's data, so theirs are here too. Those a Swift protocol + /// the class conforms to inherits are left out — the compiler lists them + /// as well, and the Swift conformance already says so. + public package(set) var objcProtocolNames: [ProtocolName] = [] + public package(set) var variables: [VariableDefinition] = [] public package(set) var functions: [FunctionDefinition] = [] @@ -191,11 +239,12 @@ public final class TypeDefinition: Definition, @unchecked Sendable { /// path holds one anyway (indexing needs it for `typeName(in:)`) — but /// only its descriptor reference is retained, so the caller's parsed /// wrapper is released as soon as construction returns. - package init(type: TypeContextWrapper, typeName: TypeName, isSpecialized: Bool, exportStatus: ExportStatus) { + package init(type: TypeContextWrapper, typeName: TypeName, isSpecialized: Bool, exportStatus: ExportStatus, attachedMacros: Set) { self.typeContextDescriptorWrapper = type.typeContextDescriptorWrapper self.typeName = typeName self.isSpecialized = isSpecialized self.exportStatus = exportStatus + self.attachedMacros = attachedMacros } /// Test/tooling surface: constructs a definition around a RAW descriptor @@ -204,27 +253,36 @@ public final class TypeDefinition: Definition, @unchecked Sendable { /// fails (a real descriptor layout re-wrapped at an out-of-bounds /// offset). /// `exportStatus` defaults to the no-verdict case because a definition - /// built this way has no trustworthy descriptor to rule on. + /// built this way has no trustworthy descriptor to rule on, and + /// `attachedMacros` to none for the same reason. package init( typeContextDescriptorWrapper: TypeContextDescriptorWrapper, typeName: TypeName, isSpecialized: Bool, - exportStatus: ExportStatus = .descriptorSymbolNameUnresolvable + exportStatus: ExportStatus = .descriptorSymbolNameUnresolvable, + attachedMacros: Set = [] ) { self.typeContextDescriptorWrapper = typeContextDescriptorWrapper self.typeName = typeName self.isSpecialized = isSpecialized self.exportStatus = exportStatus + self.attachedMacros = attachedMacros } public convenience init(type: TypeContextWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) async throws { let typeName = try type.typeName(in: machO.context) let exportStatus = ExportStatus.resolve( - forNominalTypeDescriptorAt: type.typeContextDescriptorWrapper.typeContextDescriptor.offset, + forNominalTypeDescriptor: type.typeContextDescriptorWrapper.typeContextDescriptor, typeNameNode: typeName.node, in: machO ) - self.init(type: type, typeName: typeName, isSpecialized: false, exportStatus: exportStatus) + self.init( + type: type, + typeName: typeName, + isSpecialized: false, + exportStatus: exportStatus, + attachedMacros: SwiftAttachedMacro.macros(attachedTo: type.typeContextDescriptorWrapper, in: machO.context) + ) } /// Rebuilds the full `TypeContextWrapper` — trailing objects included — /// from the retained descriptor, exactly the parse the model-build sweep @@ -239,11 +297,6 @@ public final class TypeDefinition: Definition, @unchecked Sendable { try TypeContextWrapper.forTypeContextDescriptorWrapper(typeContextDescriptorWrapper, in: context) } - @available(*, deprecated, message: "Pass a ReadingContext: materializedTypeContext(in: machO.context).") - public func materializedTypeContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextWrapper { - try materializedTypeContext(in: machO.context) - } - /// What a type-level attribute prints in parentheses, or `nil` when it /// takes no argument: the runtime name of `@objc(NSColorModel)` and /// `@_objcRuntimeName(Name)` (evolution proposal `objc-custom-class-name`). diff --git a/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift b/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift new file mode 100644 index 000000000..e07d3f769 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift @@ -0,0 +1,346 @@ +import Foundation +import Dependencies +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols + +/// Whether a declaration's own descriptor symbol has an entry in the image's +/// export trie — the fact evolution proposal 0008 annotates with +/// (`// not exported`) and proposal 0016 filters on (`--exported-only`), +/// lifted onto the declaration model so a host can read it per declaration +/// without holding the Mach-O or reimplementing the verdict. +/// +/// The non-verdict cases are deliberately distinct, because their scope is: +/// ``imageHasNoExportInformation`` is a fact about the IMAGE (no export +/// trie at all — nothing in it can be judged), while the others are facts +/// about one DECLARATION (the image's trie is fine; this declaration has no +/// symbol of its own to judge by). All of them mean "no verdict", and a +/// consumer must never read one as "not exported" — collapsing the first +/// would report every declaration of a `.o` file as unexported, and +/// collapsing ``declarationIsCImported`` would drop this image's public +/// extensions of the C types it uses. +/// +/// The first two are rare on shipped binaries, and which images reach the +/// second depends on how they were stripped. An image that keeps its local +/// symbols carries one at every descriptor: over SwiftUICore (dyld shared +/// cache and iOS 18.5 simulator runtime), in-process libswiftCore and the +/// `SymbolTestsCore` fixture, all 8171 declarations resolved to ``exported`` +/// or ``notExported``. One that does not — AppKit in the macOS 27.2 dyld +/// shared cache keeps only its exported, imported and `_symbolic` symbols — +/// has nothing at a non-exported descriptor, and every Swift type it +/// declares in an extension of an Objective-C class runs through an +/// extension context (`(extension in AppKit):__C.NSView`). Until the +/// remangling leg learned to spell an unconstrained extension context, about +/// 45 AppKit types got no verdict that way (evolution proposal +/// `export-verdict-without-local-symbols`). +public enum ExportStatus: Sendable, Hashable { + /// The descriptor symbol is in the image's export trie. + case exported + + /// The image has export information and this descriptor symbol is + /// provably not in it — or the declaration has no symbol to judge by and + /// is private, fileprivate or local, itself or a declaration it is nested + /// in, which the compiler never exports (evolution proposal + /// `export-verdict-without-local-symbols`). + case notExported + + /// The image carries no export information whatsoever (an `.o` object + /// file, a static-library product — anything without an export trie). + /// Image-level: no declaration of this image can be judged. + case imageHasNoExportInformation + + /// The image has export information, but no trustworthy symbol name + /// could be produced for this declaration's descriptor, so it is not + /// judged. Today's only source is a declaration that is neither private + /// nor local, in an image that keeps no symbol at its descriptor, whose + /// context chain runs through a constrained `extension` — see + /// ``ExportStatus/descriptorSymbolName(for:descriptorKind:)``. + case descriptorSymbolNameUnresolvable + + /// The declaration has no symbol of its own to judge by: an `@objc` + /// protocol declared in Swift gets no protocol descriptor, and its + /// Objective-C protocol record is never exported (evolution proposal + /// `swift-declared-objc-protocols`). Not judged — unless the protocol is + /// private, or nested in a private type: its private discriminator says + /// that no other file, let alone another image, can name it, and it is + /// ``notExported``. + case declarationHasNoSymbol + + /// The declaration is imported from C or Objective-C (`__C.CGSize`, or + /// a `__C_Synthesized` type the importer makes up), and the descriptor + /// in this image is not the declaration's own: the compiler gives a + /// Clang declaration non-unique linkage, so every module that uses the + /// type emits a copy of its descriptor and none exports it. That says + /// nothing about whether the type can be used from outside — this + /// image's extensions of it can be public API + /// (`extension CGSize: VectorArithmetic` in SwiftUI). Not judged + /// (evolution proposal `exported-only-marking-mode`). + case declarationIsCImported +} + +extension ExportStatus { + /// The tri-state projection, shaped exactly like + /// `SwiftSymbolIndexStore.isExported(name:in:)`: `nil` for every non-verdict + /// case. Use it where the caller only distinguishes "provably not + /// exported" from everything else. + public var isExported: Bool? { + switch self { + case .exported: true + case .notExported: false + case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable, .declarationHasNoSymbol, .declarationIsCImported: nil + } + } + + /// The one condition filtering and annotation may act on: a definitive + /// negative verdict. Every other case keeps the declaration. + public var isDefinitelyNotExported: Bool { + self == .notExported + } +} + +// MARK: - Resolution + +extension ExportStatus { + /// A type's status, ruled by its nominal type descriptor symbol (`…Mn`). + /// The descriptor is the one symbol every nominal type owns regardless of + /// what else got exported — on the `SymbolTestsCore` fixture the exported + /// `Mn` and `Ma` (metadata accessor) sets coincide exactly. + package static func resolve( + forNominalTypeDescriptor descriptor: some ContextDescriptorProtocol, + typeNameNode: NodeReference, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> ExportStatus { + resolve( + descriptor: descriptor, + nameNode: typeNameNode, + descriptorKind: .nominalTypeDescriptor, + descriptorSymbolSuffix: "Mn", + in: machO + ) + } + + /// A protocol's status, ruled by its protocol descriptor symbol (`…Mp`). + package static func resolve( + forProtocolDescriptor descriptor: some ContextDescriptorProtocol, + protocolNameNode: NodeReference, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> ExportStatus { + resolve( + descriptor: descriptor, + nameNode: protocolNameNode, + descriptorKind: .protocolDescriptor, + descriptorSymbolSuffix: "Mp", + in: machO + ) + } + + /// A Swift-declared `@objc` protocol's status. It has no protocol + /// descriptor and its Objective-C protocol record is never exported, so + /// its name is the only evidence there is: a private protocol, or one + /// nested in a private type, is ``notExported`` (leg 3 below); any other + /// is ``declarationHasNoSymbol``. + package static func resolve( + forSwiftDeclaredObjCProtocolNamed protocolNameNode: NodeReference, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> ExportStatus { + isPrivateOrLocal(protocolNameNode) ? statusOfPrivateOrLocalDeclaration(in: machO) : .declarationHasNoSymbol + } + + /// A descriptor in the `__C` or `__C_Synthesized` module is the image's + /// own copy of a C declaration's (``declarationIsCImported``) and is not + /// judged; a descriptor whose module cannot be read is judged as usual. + /// + /// Leg 3 runs here, where both the name and the descriptor are at hand: + /// when the first two legs leave the declaration unjudged, a private or + /// local one is ``notExported``. It is recognized by its name + /// (`isPrivateOrLocal(_:)`) or by the anonymous context enclosing its + /// descriptor (`isEnclosedByAnonymousContext(_:in:)`) — the second still + /// answers in an image that names no anonymous context, where a private + /// type's name comes out without its discriminator. Leg 1 has already + /// looked at the descriptor, where the trie would have put a row had the + /// module exported it. + private static func resolve( + descriptor: some ContextDescriptorProtocol, + nameNode: NodeReference, + descriptorKind: Node.Kind, + descriptorSymbolSuffix: String, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> ExportStatus { + if (try? descriptor.isCImportedContextDescriptor(in: machO.context)) == true { + return .declarationIsCImported + } + let status = resolve( + descriptorOffset: descriptor.offset, + nameNode: nameNode, + descriptorKind: descriptorKind, + descriptorSymbolSuffix: descriptorSymbolSuffix, + in: machO + ) + guard status == .descriptorSymbolNameUnresolvable, + isPrivateOrLocal(nameNode) || isEnclosedByAnonymousContext(descriptor, in: machO) else { + return status + } + return statusOfPrivateOrLocalDeclaration(in: machO) + } + + /// The first two legs, authoritative first; the third is in the + /// descriptor-taking `resolve` above: + /// + /// 1. The symbol actually located AT the descriptor. Every exported + /// descriptor has a trie row at its offset, and an unstripped image + /// also carries a local symtab row for a non-exported one, so this leg + /// answers with the compiler's own spelling of the name — which is + /// what makes it authoritative: a type nested in a CONSTRAINED + /// extension (`extension Foo where A: P { public struct Nested {} }`) + /// mangles only the extension's own requirements into its context, + /// while the model's name node carries the full signature, so a + /// remangled name misses the trie and would drop an exported type. + /// 2. Only when no symbol sits at the descriptor (a stripped image's + /// non-exported type): the remangled descriptor name against the trie, + /// which is complete even when the symtab is not. Refused for a name + /// involving a constrained extension — exactly the shape leg 1 exists + /// for. An unconstrained one (`extension NSView { struct Nested {} }`, + /// the shape of every Swift type nested in an Objective-C class) + /// spells as the compiler does, and is remangled. + private static func resolve( + descriptorOffset: Int, + nameNode: NodeReference, + descriptorKind: Node.Kind, + descriptorSymbolSuffix: String, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> ExportStatus { + @Dependency(\.swiftSymbolIndexStore) + var symbolIndexStore + + if let symbolsAtDescriptor = symbolIndexStore.symbols(for: descriptorOffset, in: machO), + let descriptorSymbol = symbolsAtDescriptor.first(where: { $0.name.isSwiftSymbol && $0.name.hasSuffix(descriptorSymbolSuffix) }) { + return ExportStatus(trieVerdict: symbolIndexStore.isExported(name: descriptorSymbol.name, in: machO)) + } + guard let symbolName = descriptorSymbolName(for: nameNode, descriptorKind: descriptorKind) else { + return .descriptorSymbolNameUnresolvable + } + return ExportStatus(trieVerdict: symbolIndexStore.isExported(name: symbolName, in: machO)) + } + + /// Leg 3's verdict on a private or local declaration with no symbol of + /// its own to judge by: ``notExported`` in an image that has export + /// information, ``imageHasNoExportInformation`` in one that has none. + private static func statusOfPrivateOrLocalDeclaration(in machO: some MachOSwiftSectionRepresentableWithCache) -> ExportStatus { + @Dependency(\.swiftSymbolIndexStore) + var symbolIndexStore + return symbolIndexStore.hasExportInformation(in: machO) ? .notExported : .imageHasNoExportInformation + } + + /// Whether an anonymous context encloses the descriptor. The compiler + /// puts one around a private or fileprivate declaration and around the + /// function declaring a local one, so this reads leg 3's fact from the + /// binary's own structure — and still reads it where no symbol names + /// the anonymous context and the declaration's name comes out without + /// its private discriminator. + private static func isEnclosedByAnonymousContext( + _ descriptor: some ContextDescriptorProtocol, + in machO: some MachOSwiftSectionRepresentableWithCache + ) -> Bool { + var parent = try? descriptor.parent(in: machO.context) + while let parentDescriptor = parent?.resolved { + if parentDescriptor.isAnonymous { + return true + } + parent = try? parentDescriptor.parent(in: machO.context) + } + return false + } + + /// `nil` — the store's "this image has no export information" answer — is + /// the only way ``imageHasNoExportInformation`` is produced. + private init(trieVerdict: Bool?) { + switch trieVerdict { + case true: self = .exported + case false: self = .notExported + case nil: self = .imageHasNoExportInformation + } + } + + /// Remangles a name node into the symbol name of its `descriptorKind` + /// descriptor (`_$sMn` / `_$sMp`), or `nil` when the + /// spelling cannot be trusted. The name node may arrive wrapped in a + /// `.type` envelope, and a specialized definition's name is a + /// bound-generic node (`Box`) — the descriptor belongs to the + /// unbound nominal, so both wrappers are peeled first. A name involving + /// a constrained `.extension` node — one carrying a generic signature — + /// is refused (see leg 2 above). The remangling walks a transient tree + /// materialized from the reference; nothing is interned or cached. + package static func descriptorSymbolName(for node: NodeReference, descriptorKind: Node.Kind) -> String? { + var contextNode = node.materialize() + if contextNode.kind == .type, let wrappedNode = contextNode.children.first { + contextNode = wrappedNode + } + switch contextNode.kind { + case .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: + guard var nominalNode = contextNode.children.first else { return nil } + if nominalNode.kind == .type, let wrappedNode = nominalNode.children.first { + nominalNode = wrappedNode + } + contextNode = nominalNode + default: + break + } + guard !containsConstrainedExtensionContext(contextNode) else { return nil } + let descriptorNode = Node.createTransient(kind: descriptorKind, children: [contextNode]) + let globalNode = Node.createTransient(kind: .global, children: [descriptorNode]) + return try? mangleAsString(globalNode) + } + + /// An extension node's children are the extending module, the extended + /// type and — only when the extension is constrained — its generic + /// signature. + private static func containsConstrainedExtensionContext(_ node: Node) -> Bool { + if node.kind == .extension, node.children.contains(where: { $0.kind == .dependentGenericSignature }) { + return true + } + return node.children.contains { containsConstrainedExtensionContext($0) } + } + + /// Whether the declaration a name node names is private, fileprivate or + /// local — itself, or any declaration it is nested in. The compiler gives + /// every one of them a non-public linkage, so none is in an export trie. + /// The exception, a module built with `-enable-private-imports`, exports + /// its private descriptors, and leg 1 finds those first. + /// + /// Only the declaration's context chain is read: its own name, the types + /// it is nested in, an extension's extended type, and an anonymous + /// context or a function, closure or accessor declaring a local type. + /// Generic arguments, an extension's requirements and a function's + /// signature are not — a specialized `Box` is exactly as + /// exported as `Box`. A node of a shape not handled here reads as + /// neither, which leaves the declaration unjudged. + package static func isPrivateOrLocal(_ nameNode: NodeReference) -> Bool { + var currentNode = nameNode + while true { + let children = currentNode.children + switch currentNode.kind { + case .type, + .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: + guard let wrappedNode = children.first else { return false } + currentNode = wrappedNode + case .extension: + // The module, then the extended type. + guard children.count > 1 else { return false } + currentNode = children[1] + case .structure, .class, .enum, .protocol, .typeAlias, .otherNominalType: + // The context, then the declared name. + guard children.count > 1 else { return false } + if children[1].kind == .privateDeclName || children[1].kind == .localDeclName { + return true + } + currentNode = children[0] + case .anonymousContext, .function, .explicitClosure, .implicitClosure, .variable, .subscript, .getter, .setter, .constructor, .allocator: + // Only a local type, or a private one whose context the + // binary does not name, is declared in one of these. + return true + default: + return false + } + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Model/Kinds/AccessorKind.swift similarity index 57% rename from Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift rename to Sources/Declaration/SwiftDeclaration/Model/Kinds/AccessorKind.swift index a93ba29df..7a5bdc85c 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Kinds/AccessorKind.swift @@ -9,6 +9,15 @@ public enum AccessorKind: Sendable, Codable { /// SE-0507: a `mutate` accessor, which returns an `inout` projection of /// the stored value (symbol suffix `vz`). case mutateAccessor + /// SE-0400: an `init` accessor, which initializes the stored properties + /// its `@storageRestrictions(initializes:)` lists when an initializer + /// assigns the property (symbol suffix `vi`). Only the type's own + /// initializers call it, so it is never in a vtable or a witness table, + /// and the compiler gives it `internal` access unless it is declared + /// `@usableFromInline`: an optimized, dead-stripped image keeps only the + /// exported ones. The binary records nothing of the attribute (evolution + /// proposal `init-accessor-recovery`). + case initAccessor case none /// Label used in address comments. Returns `nil` for stored properties (`.none`). @@ -20,6 +29,7 @@ public enum AccessorKind: Sendable, Codable { case .readAccessor: "read" case .borrowAccessor: "borrow" case .mutateAccessor: "mutate" + case .initAccessor: "init" case .none: nil } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Kinds/ExtensionKind.swift b/Sources/Declaration/SwiftDeclaration/Model/Kinds/ExtensionKind.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Kinds/ExtensionKind.swift rename to Sources/Declaration/SwiftDeclaration/Model/Kinds/ExtensionKind.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Kinds/FunctionKind.swift b/Sources/Declaration/SwiftDeclaration/Model/Kinds/FunctionKind.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Kinds/FunctionKind.swift rename to Sources/Declaration/SwiftDeclaration/Model/Kinds/FunctionKind.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Kinds/TypeKind.swift b/Sources/Declaration/SwiftDeclaration/Model/Kinds/TypeKind.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Kinds/TypeKind.swift rename to Sources/Declaration/SwiftDeclaration/Model/Kinds/TypeKind.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/Accessor.swift similarity index 85% rename from Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/Accessor.swift index 3f8c8e4c8..db92f867b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/Accessor.swift @@ -1,7 +1,8 @@ import MemberwiseInit -import MachOSymbols +import SwiftSymbols import MachOSwiftSection import SwiftInspection +import SwiftObjCInterop public protocol AccessorRepresentable: Sendable { var accessors: [Accessor] { get } @@ -33,6 +34,11 @@ extension AccessorRepresentable { /// 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 } } + /// SE-0400. The image keeps the init accessor only while something + /// references it or exports it, so `false` says nothing about the + /// source: an optimized, dead-stripped image drops every one its + /// initializers inlined. + public var hasInitAccessor: Bool { accessors.contains { $0.kind == .initAccessor } } public var hasVTableAccessor: Bool { accessors.contains { $0.methodDescriptor != nil } } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/FieldDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/FieldDefinition.swift similarity index 99% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/FieldDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/FieldDefinition.swift index 16050d5c6..b2f209667 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/FieldDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/FieldDefinition.swift @@ -2,6 +2,7 @@ import MemberwiseInit import Demangling import SwiftDeclarationRendering import SwiftInspection +import SwiftObjCInterop public struct FieldFlags: OptionSet, Sendable { public let rawValue: Int diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/FunctionDefinition.swift similarity index 98% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/FunctionDefinition.swift index 7b0d3187a..7b90c051e 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/FunctionDefinition.swift @@ -2,8 +2,10 @@ import MemberwiseInit import Demangling import MachOSwiftSection import MachOFoundation +import SwiftSymbols import Utilities import SwiftInspection +import SwiftObjCInterop @MemberwiseInit(.public) public struct FunctionDefinition: Sendable { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Members/MemberCategory.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/MemberCategory.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Members/MemberCategory.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/MemberCategory.swift diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCImportedMemberDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCImportedMemberDefinition.swift new file mode 100644 index 000000000..8f3abaa31 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCImportedMemberDefinition.swift @@ -0,0 +1,73 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols + +/// One member of an Objective-C class or category as Swift imports it +/// (evolution proposal `objc-imported-declarations`): a Swift declaration +/// built from the method and property lists by the importer's rules, shaped +/// like the member symbol the compiler would have demangled to. Its Swift +/// name may not be the one the SDK gives it, which only API notes, +/// `NS_SWIFT_NAME` and the header's types decide; the interface pins the +/// selector with `@objc(selector)` where the compiler would derive another +/// from the printed name. +public struct ObjCImportedMemberDefinition: Sendable { + public enum Kind: Sendable, Hashable { + case method + case initializer + /// A class method restating its class's name, which the importer + /// imports as a convenience initializer. + case factoryInitializer + case property + case `subscript` + } + + /// How an object property holds its value, from its attributes. + public enum Ownership: Sendable, Hashable { + case strong + /// `copy`: `@NSCopying`. + case copy + case weak + /// `assign` or `unsafe_unretained` on an object: `unowned(unsafe)`. + case unownedUnsafe + } + + public let kind: Kind + /// `Global > Function`, `Global > Static > Getter > Variable`, + /// `Global > Allocator`, `Global > Getter > Subscript`. + public let node: NodeReference + /// The selector the runtime sends: a method's, a property's or a + /// subscript's getter. + public let selector: String + /// A property's or subscript's setter; `nil` when it is read-only. + public let setterSelector: String? + public let isClassMember: Bool + /// An object property's ownership; `nil` for every other member. + public let ownership: Ownership? + /// Whether the interface spells the selector out (`@objc(selector)`): + /// the compiler would derive another one from the printed Swift name. + public let hasExplicitSelector: Bool + /// The encoding the declaration was built from: the method list's, an + /// adopted protocol's extended one, or the property's attributes. + public let typeEncoding: String + /// A property's name in the property list — what a header's `@property` + /// declares, and what an API notes file keys it by (`hidden` for the + /// `isHidden` getter); `nil` for every other member. + public let objcPropertyName: String? + + public var isSettable: Bool { + setterSelector != nil + } + + package init(kind: Kind, node: NodeReference, selector: String, setterSelector: String?, isClassMember: Bool, ownership: Ownership?, hasExplicitSelector: Bool, typeEncoding: String, objcPropertyName: String? = nil) { + self.kind = kind + self.node = node + self.selector = selector + self.setterSelector = setterSelector + self.isClassMember = isClassMember + self.ownership = ownership + self.hasExplicitSelector = hasExplicitSelector + self.typeEncoding = typeEncoding + self.objcPropertyName = objcPropertyName + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCProtocolRequirementDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCProtocolRequirementDefinition.swift new file mode 100644 index 000000000..ff25e4c9e --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ObjCProtocolRequirementDefinition.swift @@ -0,0 +1,73 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection + +/// One requirement of an ``ObjCProtocolDefinition``: a Swift declaration +/// built from the protocol's Objective-C record, shaped like the member +/// symbol the compiler would have demangled to. +public struct ObjCProtocolRequirementDefinition: Sendable { + public enum Kind: Sendable, Hashable { + case method + case initializer + case property + case `subscript` + } + + /// Where the Swift spelling comes from. + public enum Origin: Sendable, Hashable { + /// The importer's rules applied to the selector and its type + /// encoding: the Swift name may differ from the source's. + case selector + /// The member implementing it in a class of the image that adopts + /// the protocol — a Swift class, or an Objective-C class the image + /// extends in a category: the Swift name and types are the source's. + case conformer(className: TypeName) + } + + public let kind: Kind + /// `Global > Function`, `Global > Static > Getter > Variable`, + /// `Global > Allocator`, `Global > Getter > Subscript`. + public let node: NodeReference + /// The selector the runtime sends: a method's, a property's or a + /// subscript's getter. + public let selector: String + /// A property's or subscript's setter; `nil` when it is read-only. + public let setterSelector: String? + public let isClassMember: Bool + public let isOptional: Bool + public let origin: Origin + /// Whether the interface spells the selector out (`@objc(selector)`): + /// always for a requirement named from its selector; for one taken from + /// a conformer, when the compiler derives another selector from the + /// member's Swift name. + public let hasExplicitSelector: Bool + /// The method's type encoding, extended when the record carries one, or + /// the property's attribute string. + public let typeEncoding: String + + public var isSettable: Bool { + setterSelector != nil + } + + @available(*, deprecated, renamed: "Origin") + public typealias Source = Origin + + @available(*, deprecated, renamed: "origin") + public var source: Origin { + origin + } + + package init(kind: Kind, node: NodeReference, selector: String, setterSelector: String?, isClassMember: Bool, isOptional: Bool, origin: Origin, hasExplicitSelector: Bool, typeEncoding: String) { + self.kind = kind + self.node = node + self.selector = selector + self.setterSelector = setterSelector + self.isClassMember = isClassMember + self.isOptional = isOptional + self.origin = origin + self.hasExplicitSelector = hasExplicitSelector + self.typeEncoding = typeEncoding + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/ObservableMacroExpansion.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ObservableMacroExpansion.swift new file mode 100644 index 000000000..70cd48048 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ObservableMacroExpansion.swift @@ -0,0 +1,104 @@ +/// What the `@Observable` macro generated in a class, recovered at index time +/// (evolution proposal `observable-macro-folding`). +/// +/// The macro rewrites each stored `var x` it tracks into a computed `x` — an +/// init accessor, a getter, a setter and a `_modify` that report to the +/// registrar — over private storage `_x`, adds the registrar +/// `_$observationRegistrar`, the methods `access(keyPath:)`, +/// `withMutation(keyPath:_:)` and the `shouldNotifyObservers(_:_:)` +/// overloads, and an `extension Model: Observation.Observable {}`. A stored +/// property declared `@ObservationIgnored`, and a `let`, it leaves alone. +/// +/// The model keeps all of it as the binary has it — `_x` in +/// `TypeDefinition.fields`, the computed `x` in `variables`, the methods in +/// `functions` — because the ABI diff and snapshot records are built from +/// them. This description sits on top, for the interface printer, which +/// prints the class the way its source reads unless asked to expand macros, +/// and for a host that shows the expansion on its own. +public struct ObservableMacroExpansion: Sendable { + /// A stored property the macro tracks: `var x` in the source, storage + /// `_x` and a computed `x` in the binary. + public struct TrackedProperty: Sendable, Equatable { + /// Where the printable declaration of `x` comes from. + public enum Origin: Sendable, Equatable { + /// The computed `x` the macro generated has accessors in the + /// image: it is the member variable `x` in `variables`. + case declaredMember + + /// `x`'s accessors are stripped — an internal property of a + /// release build with its local symbols removed, as in an OS + /// framework or a shipped app — so no member variable stands for + /// it, and its declaration is synthesized from the storage `_x`, + /// which has the same type. + case synthesized + } + + /// What tells `_x` apart from a stored property the source declared + /// with that name and `@ObservationIgnored`. + public enum Evidence: Sendable, Equatable { + /// `x` has an init accessor: only a property whose storage the + /// macro moved to `_x` has one. + case initAccessor + + /// The computed `x` in the image has a setter or a `_modify` + /// accessor and `_x`'s type. + case accessors + + /// The initial-value expression is `x`'s: the source gave `x` the + /// initial value, and the macro moved only its storage. A stored + /// property of its own would carry the expression itself. + case initialValueExpression + + /// Nothing in the image names `x`, and nothing says `_x` is a + /// stored property of its own — an initial-value expression of its + /// own, or accessors of its own while `x` has none — so the + /// storage's name alone says it. Common in an OS framework or a + /// shipped app: an optimized, dead-stripped image drops the init + /// accessor and the accessors of every property nothing calls, + /// whether it keeps its local symbols or not. An + /// `@ObservationIgnored` property named `_y` with neither reads as + /// the tracked `y` this way, which is why it is told apart from + /// the others. + case backingFieldName + } + + /// The property's name (`x`). + public let name: String + + /// The storage the macro generated (`_x`), a member of + /// `TypeDefinition.fields`. + public let backingFieldName: String + + public let origin: Origin + + public let evidence: Evidence + + public init(name: String, backingFieldName: String, origin: Origin, evidence: Evidence) { + self.name = name + self.backingFieldName = backingFieldName + self.origin = origin + self.evidence = evidence + } + } + + /// The properties the macro tracks, in the order of their storage in + /// `TypeDefinition.fields` — the order the source declares them in. + public let trackedProperties: [TrackedProperty] + + /// The stored `var`s the macro leaves alone, by field name — the source + /// declares them `@ObservationIgnored`. A lazy property is here by its + /// name, a wrapped property by its backing storage (`_x`); a `let` never + /// is, the macro tracks no constant. + public let ignoredStoredPropertyNames: [String] + + /// The methods the macro generated, as `TypeDefinition.functions` holds + /// them: `access(keyPath:)`, `withMutation(keyPath:_:)` and those of the + /// `shouldNotifyObservers(_:_:)` overloads the image keeps. + public let generatedFunctions: [FunctionDefinition] + + public init(trackedProperties: [TrackedProperty], ignoredStoredPropertyNames: [String], generatedFunctions: [FunctionDefinition]) { + self.trackedProperties = trackedProperties + self.ignoredStoredPropertyNames = ignoredStoredPropertyNames + self.generatedFunctions = generatedFunctions + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Members/OrderedMember.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift similarity index 88% rename from Sources/Declaration/SwiftDeclaration/Components/Members/OrderedMember.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift index 71a49d00c..036afcd85 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Members/OrderedMember.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift @@ -19,12 +19,17 @@ public enum OrderedMember: Sendable { } /// The minimum symbol file offset (MachO offset) among all symbols of this member. + /// + /// A variable's SE-0400 init accessor takes no part: whether the image + /// kept it depends on the build, not on where the source declared the + /// property, so it would move the property between builds (evolution + /// proposal `init-accessor-recovery`). public var minSymbolOffset: Int { switch self { case .allocator(let f), .function(let f): return f.symbol.offset case .variable(let v): - return v.accessors.map(\.symbol.offset).min() ?? .max + return v.accessors.lazy.filter { $0.kind != .initAccessor }.map(\.symbol.offset).min() ?? .max case .subscript(let s): return s.accessors.map(\.symbol.offset).min() ?? .max } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift similarity index 99% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift index 1620dabe1..364e26d89 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift @@ -1,4 +1,5 @@ import SwiftInspection +import SwiftObjCInterop /// A member's ObjC-derived source facts, resolved against one consumer's /// verdict on NAME-only evidence (evolution proposal diff --git a/Sources/Declaration/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/StrippedSymbolicRequirement.swift similarity index 73% rename from Sources/Declaration/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/StrippedSymbolicRequirement.swift index 11f0a8f08..52e11b7c0 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/StrippedSymbolicRequirement.swift @@ -28,6 +28,9 @@ extension StrippedSymbolicRequirement { case .modifyCoroutine: return "modifyCoroutine" case .associatedTypeAccessFunction: return "associatedTypeAccessFunction" case .associatedConformanceAccessFunction: return "associatedConformanceAccessFunction" + // A kind this reader does not know. New: reading one used to stop the + // program, so no persisted key spells it yet. + case nil: return "unknown" } } @@ -47,12 +50,13 @@ extension StrippedSymbolicRequirement { } extension StrippedSymbolicRequirement { - @SemanticStringBuilder - package func strippedSymbolicInfo() -> SemanticString { - Comment( - """ - Kind: \(requirement.layout.flags.kind.description), isAsync: \(requirement.layout.flags.isAsync), isInstance: \(requirement.layout.flags.isInstance) - """ - ) + /// `// Kind: Method, isAsync: false, isInstance: true`, marked as a + /// `strippedSymbolicRequirement` when `markingStructure`. + package func strippedSymbolicInfo(markingStructure: Bool) -> SemanticString { + StructuredComment.strippedSymbolicRequirement( + kindDescription: requirement.layout.flags.kind?.description ?? "Unknown", + isAsync: requirement.layout.flags.isAsync, + isInstance: requirement.layout.flags.isInstance + ).printed(markingStructure: markingStructure, as: .strippedSymbolicRequirement) } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/SubscriptDefinition.swift similarity index 98% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/SubscriptDefinition.swift index c95c9d6a9..66898d6e8 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/SubscriptDefinition.swift @@ -1,6 +1,7 @@ import MemberwiseInit import Demangling import SwiftInspection +import SwiftObjCInterop @MemberwiseInit(.public) public struct SubscriptDefinition: Sendable, AccessorRepresentable { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/VariableDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/VariableDefinition.swift similarity index 79% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/VariableDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/VariableDefinition.swift index 350e5fdf3..7e89e4896 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/VariableDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/VariableDefinition.swift @@ -1,8 +1,9 @@ import MemberwiseInit import Demangling -import MachOSymbols +import SwiftSymbols import MachOSwiftSection import SwiftInspection +import SwiftObjCInterop @MemberwiseInit(.public) public struct VariableDefinition: Sendable, AccessorRepresentable { @@ -43,4 +44,13 @@ public struct VariableDefinition: Sendable, AccessorRepresentable { /// printer renders it as one — `var name: Type` with its field offset — /// instead of the `{ get set }` computed shape the symbols alone suggest. public var objcImplementationStorage: ObjCImplementationClassFacts.InstanceVariable? = nil + + /// The fields this property's SE-0400 init accessor initializes — what + /// its `@storageRestrictions(initializes:)` lists — as far as the image + /// tells (evolution proposal `init-accessor-recovery`). No image records + /// the attribute, so it is inferred at index time from the type's stored + /// properties (`InitAccessorFieldInference`): the field named `_` + /// with this property's type. `nil` when nothing tells, and for a + /// property without an init accessor. `accesses:` is never recovered. + public var initializedFieldNames: [String]? = nil } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/WrappedPropertyDefinition.swift similarity index 99% rename from Sources/Declaration/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Model/Members/WrappedPropertyDefinition.swift index b2f863467..b250248f9 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/WrappedPropertyDefinition.swift @@ -1,5 +1,5 @@ import Demangling -import MachOSymbols +import SwiftSymbols /// A property the source declared with a property wrapper (`@Wrapper var x: T`), /// recovered at index time from what the compiler synthesized for it: the diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift b/Sources/Declaration/SwiftDeclaration/Model/Names/DefinitionName+LocalTypeDisplayName.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift rename to Sources/Declaration/SwiftDeclaration/Model/Names/DefinitionName+LocalTypeDisplayName.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName.swift b/Sources/Declaration/SwiftDeclaration/Model/Names/DefinitionName.swift similarity index 100% rename from Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName.swift rename to Sources/Declaration/SwiftDeclaration/Model/Names/DefinitionName.swift diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift b/Sources/Declaration/SwiftDeclaration/Model/Names/ExtensionName.swift similarity index 93% rename from Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift rename to Sources/Declaration/SwiftDeclaration/Model/Names/ExtensionName.swift index 9dc4d1765..2897ea8c8 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Names/ExtensionName.swift @@ -45,8 +45,8 @@ extension ExtensionName { // the node already tells a protocol from a type from a typealias, while the // `TypeKind` inside `.type` is producer-dependent for C-imported types. extension ExtensionName { - public static func == (lhs: ExtensionName, rhs: ExtensionName) -> Bool { - lhs.node.structurallyEquals(rhs.node) + public static func == (left: ExtensionName, right: ExtensionName) -> Bool { + left.node.structurallyEquals(right.node) } public func hash(into hasher: inout Hasher) { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/ProtocolName.swift b/Sources/Declaration/SwiftDeclaration/Model/Names/ProtocolName.swift similarity index 85% rename from Sources/Declaration/SwiftDeclaration/Components/Names/ProtocolName.swift rename to Sources/Declaration/SwiftDeclaration/Model/Names/ProtocolName.swift index 9922ef701..d23b6a47b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Names/ProtocolName.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Names/ProtocolName.swift @@ -23,8 +23,8 @@ extension ProtocolName { // See `TypeName`: names hash and compare by node STRUCTURE, not by // `NodeReference`'s store-identity `Hashable`. extension ProtocolName { - public static func == (lhs: ProtocolName, rhs: ProtocolName) -> Bool { - lhs.node.structurallyEquals(rhs.node) + public static func == (left: ProtocolName, right: ProtocolName) -> Bool { + left.node.structurallyEquals(right.node) } public func hash(into hasher: inout Hasher) { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/TypeName.swift b/Sources/Declaration/SwiftDeclaration/Model/Names/TypeName.swift similarity index 93% rename from Sources/Declaration/SwiftDeclaration/Components/Names/TypeName.swift rename to Sources/Declaration/SwiftDeclaration/Model/Names/TypeName.swift index ec31184b6..ef341af6d 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Names/TypeName.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Names/TypeName.swift @@ -44,8 +44,8 @@ extension TypeName { // record and witness symbols, so the interface printed the conformance // block without its `typealias` witness and the witness as a bare block. extension TypeName { - public static func == (lhs: TypeName, rhs: TypeName) -> Bool { - lhs.node.structurallyEquals(rhs.node) + public static func == (left: TypeName, right: TypeName) -> Bool { + left.node.structurallyEquals(right.node) } public func hash(into hasher: inout Hasher) { diff --git a/Sources/Declaration/SwiftDeclaration/Model/ObjCCategoryConformance.swift b/Sources/Declaration/SwiftDeclaration/Model/ObjCCategoryConformance.swift new file mode 100644 index 000000000..879529734 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/ObjCCategoryConformance.swift @@ -0,0 +1,40 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop + +/// An extension the image declares of a class another module declares, in +/// which it adopts Objective-C protocols (evolution proposal +/// `swift-declared-objc-protocols`) — known from the extension's category, +/// since an `@objc` protocol has no witness table and so no conformance +/// record names it. The compiler emits a category only for a class of +/// another module: it folds an extension of the class's own module into the +/// class's data (``TypeDefinition/objcProtocolNames``). +public struct ObjCCategoryConformance: Sendable { + /// The extended class, `Type > Class`: an Objective-C class in `__C`, or + /// a Swift class of another module. + public let extendedTypeName: TypeName + + /// The protocols the extension adopts, in the category's order, without + /// those a Swift protocol the image conforms the class to inherits. + public let protocolNames: [ProtocolName] + + package init(extendedTypeName: TypeName, protocolNames: [ProtocolName]) { + self.extendedTypeName = extendedTypeName + self.protocolNames = protocolNames + } + + /// The image's, in category-list order. A category whose every protocol + /// is implied gives none. + package static func all(in machO: some MachOSwiftSectionRepresentableWithCache) -> [ObjCCategoryConformance] { + ObjCProtocolAdoptionIndex.shared.categoryAdoptions(in: machO).compactMap { categoryAdoption in + let protocolNames = ObjCProtocolNameBuilder.protocolNames(categoryAdoption.protocolRuntimeNames, excluding: categoryAdoption.impliedProtocolRuntimeNames, in: machO) + guard !protocolNames.isEmpty else { return nil } + let typeNode = Node.createTransient(kind: .type, child: ObjCRuntimeNames.classNode(forRuntimeName: categoryAdoption.classRuntimeName, in: machO)) + let extendedTypeName = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO), kind: .class) + return ObjCCategoryConformance(extendedTypeName: extendedTypeName, protocolNames: protocolNames) + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/ResolvedAssociatedTypeWitness.swift b/Sources/Declaration/SwiftDeclaration/Model/ResolvedAssociatedTypeWitness.swift new file mode 100644 index 000000000..d35f03995 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/ResolvedAssociatedTypeWitness.swift @@ -0,0 +1,85 @@ +import SwiftDeclarationRendering + +/// A conformance extension's associated-type witness, frozen into pure value +/// data at index time. +/// +/// The underlying `MachOSwiftSection.AssociatedType` records resolve their +/// names through Mach-O-bound accessors, so anything Mach-O-free downstream +/// (notably `SwiftDiffing`'s snapshot projection) cannot read them after +/// indexing. The indexer therefore resolves each record into this value +/// while the Mach-O is still in hand. +public struct ResolvedAssociatedTypeWitness: Sendable, Codable, Equatable { + /// The associated-type requirement's name (e.g. `Element`). + public let name: String + /// The witness type, demangled with its opaque types expanded, and printed + /// (e.g. `Swift.Int`). + /// + /// When the witness's underlying type is decided by an + /// availability-conditional accessor thunk (evolution proposal + /// `offline-opaque-accessor-thunk-resolution`), this is the branch the + /// current platform takes; the other branches are in + /// ``conditionalCandidates``. + public let substitutedTypeText: String + /// Every answer an availability-conditional accessor thunk inside the + /// witness can give, one entry per branch; empty when the witness carries + /// no such thunk or its shape could not be read. + /// + /// Filled by the offline reader only: in-process the runtime executes the + /// thunk and answers for this OS alone, so there is nothing to list. + public let conditionalCandidates: [ConditionalCandidate] + + public init(name: String, substitutedTypeText: String, conditionalCandidates: [ConditionalCandidate] = []) { + self.name = name + self.substitutedTypeText = substitutedTypeText + self.conditionalCandidates = conditionalCandidates + } + + private enum CodingKeys: String, CodingKey { + case name + case substitutedTypeText + case conditionalCandidates + } + + /// Tolerates the key's absence so a witness persisted before + /// `conditionalCandidates` existed still decodes. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + name = try container.decode(String.self, forKey: .name) + substitutedTypeText = try container.decode(String.self, forKey: .substitutedTypeText) + conditionalCandidates = try container.decodeIfPresent([ConditionalCandidate].self, forKey: .conditionalCandidates) ?? [] + } +} + +@available(*, deprecated, renamed: "ResolvedAssociatedTypeWitness") +public typealias AssociatedTypeWitnessProjection = ResolvedAssociatedTypeWitness + +@available(*, deprecated, renamed: "ResolvedAssociatedTypeWitness.ConditionalCandidate") +public typealias ConditionalWitnessCandidate = ResolvedAssociatedTypeWitness.ConditionalCandidate + +extension ResolvedAssociatedTypeWitness { + /// One answer an availability-conditional accessor thunk can give for an + /// associated-type witness. + /// + /// A witness whose underlying type is an SE-0360 `if #available` opaque + /// result has one of these per branch. Both texts are carried on purpose: the + /// candidate type alone says which part of the witness changes, while the + /// whole witness with that branch substituted is what a host shows when asked + /// "what does this read as on that OS" — the thunk can sit anywhere in the + /// tree (`SwiftUI.FeedbackGenerator.Body` carries its inside a + /// `ModifiedContent<…>` chain), and a host should not have to know where. + public struct ConditionalCandidate: Sendable, Codable, Equatable { + /// The platform version the branch is gated on, or `nil` when the thunk + /// has no version check and this is its only answer. + public let availability: PlatformAvailabilityCondition? + /// The type the thunk yields on this branch, printed. + public let candidateTypeText: String + /// The whole witness with this branch substituted, printed. + public let substitutedTypeText: String + + public init(availability: PlatformAvailabilityCondition?, candidateTypeText: String, substitutedTypeText: String) { + self.availability = availability + self.candidateTypeText = candidateTypeText + self.substitutedTypeText = substitutedTypeText + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Model/SwiftAttachedMacro.swift b/Sources/Declaration/SwiftDeclaration/Model/SwiftAttachedMacro.swift new file mode 100644 index 000000000..43c477f56 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Model/SwiftAttachedMacro.swift @@ -0,0 +1,52 @@ +import MachOSwiftSection +import SwiftInspection + +/// A macro attached to a declaration in its source, recognized from what its +/// expansion left in the binary (evolution proposal +/// `observable-macro-folding`). +/// +/// The compiler keeps no record of a macro, only of what it generated, so a +/// recognized macro is an inference from that output. +/// `ObservableMacroRecognition` says what the inference for `@Observable` +/// reads. +/// +/// A struct with static members rather than an enum: the set of macros the +/// library recognizes grows, and a host's `switch` over it must not stop +/// compiling when it does. +public struct SwiftAttachedMacro: Hashable, Sendable { + /// The macro's name as its attribute spells it: `Observable`. + public let name: String + + /// The module that declares the macro: `Observation`. + public let moduleName: String + + package init(name: String, moduleName: String) { + self.name = name + self.moduleName = moduleName + } + + /// `@Observable`, from the Observation module: a class whose stored + /// properties tell observers when they change. + public static let observable = SwiftAttachedMacro( + name: ObservableMacroRecognition.observableName, + moduleName: ObservableMacroRecognition.observationModuleName + ) + + /// `@ObservationTracked`, from the Observation module: the macro + /// `@Observable` attaches to each property it tracks, which writes the + /// property's accessors and its storage. It appears in an expansion of + /// `@Observable`, never on a type (evolution proposal + /// `observable-nested-expansion`). + public static let observationTracked = SwiftAttachedMacro( + name: ObservableMacroRecognition.observationTrackedName, + moduleName: ObservableMacroRecognition.observationModuleName + ) +} + +extension SwiftAttachedMacro { + /// The macros the source attached to the type `descriptor` describes, as + /// far as their expansion shows. + package static func macros(attachedTo descriptor: TypeContextDescriptorWrapper, in context: some ReadingContext) -> Set { + ObservableMacroRecognition.isObservableClass(descriptor, in: context) ? [.observable] : [] + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/SwiftAttribute.swift b/Sources/Declaration/SwiftDeclaration/Model/SwiftAttribute.swift similarity index 94% rename from Sources/Declaration/SwiftDeclaration/Components/SwiftAttribute.swift rename to Sources/Declaration/SwiftDeclaration/Model/SwiftAttribute.swift index eabdef6af..290735fa3 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/SwiftAttribute.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/SwiftAttribute.swift @@ -28,8 +28,8 @@ public enum SwiftAttribute: Int, Comparable, Sendable, CaseIterable, Codable { // Declared last so the raw values above stay put. case objcRuntimeName - public static func < (lhs: SwiftAttribute, rhs: SwiftAttribute) -> Bool { - lhs.rawValue < rhs.rawValue + public static func < (left: SwiftAttribute, right: SwiftAttribute) -> Bool { + left.rawValue < right.rawValue } public var annotationString: String { diff --git a/Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift b/Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift index a99cbfaa8..0f82b9252 100644 --- a/Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift +++ b/Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift @@ -4,6 +4,7 @@ import ObjCDump import ObjCIndexing import ObjCMetadataSource import SwiftInspection +import SwiftObjCInterop extension ObjCClassHierarchy { /// Builds the hierarchy from the shape the ObjC indexers keep per class: @@ -107,12 +108,15 @@ public final class ObjCInterfaceIndexerClassHierarchyProvider ObjCClassHierarchy? { - guard let classGroup = indexer.classGroup(forName: runtimeName) else { return nil } + // A class without a class object is a supplied class to the indexer + // (evolution proposal `objc-classes-without-class-objects`), its + // chain built the same way. + guard let classInfoChain = indexer.classGroup(forName: runtimeName)?.info ?? indexer.suppliedClassGroup(forName: runtimeName)?.info else { return nil } // The indexer's chain stops where a superclass could not be followed // (a standalone file's bound dependency); a chain that ends on a class // with no superclass reached the root. - let isAncestorChainComplete = classGroup.info.last?.superClassName == nil - return ObjCClassHierarchy(classInfoChain: classGroup.info, categoryInfos: categoryInfos(forClassNamed: runtimeName), isAncestorChainComplete: isAncestorChainComplete) + let isAncestorChainComplete = classInfoChain.last?.superClassName == nil + return ObjCClassHierarchy(classInfoChain: classInfoChain, categoryInfos: categoryInfos(forClassNamed: runtimeName), isAncestorChainComplete: isAncestorChainComplete) } /// The indexer files categories under their own unique names; grouping diff --git a/Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift b/Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift new file mode 100644 index 000000000..b0c970246 --- /dev/null +++ b/Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift @@ -0,0 +1,48 @@ +import MachOKit +import MachOKitExtensions +import ObjCIndexing +import SwiftInspection +import SwiftObjCInterop + +extension ObjCSuppliedClass { + /// The Swift classes of `machO` the image keeps no class object for, + /// read from their Swift metadata, for + /// `ObjCInterfaceIndexer(machO:imagePath:suppliedClasses:eventHandler:)` + /// (evolution proposal `objc-classes-without-class-objects`): every + /// generic class, under its qualified name with its generic parameters + /// (`Xcode_Service.MenuBarPanelWindow`), and every class + /// `__objc_stublist` registers — one whose metadata the Swift runtime + /// allocates or initializes before the Objective-C runtime sees it (a + /// resilient superclass, generic ancestry), which the compiler registers + /// when an Objective-C class is among its ancestors — under its + /// `class_ro_t` name. The superclass is named by its runtime name + /// wherever the class list or the Objective-C runtime knows one, so the + /// indexer links a chain through the image's own classes; a Swift + /// superclass another image defines keeps its Swift spelling + /// (`SwiftUI.NSHostingView`). + /// + /// Empty for a reader of another kind, and for an image built without + /// Objective-C interop. + public static func swiftClassesWithoutClassObjects(in machO: some MachORepresentableWithCache) -> [ObjCSuppliedClass] { + SwiftClassWithoutClassObjectIndex.shared.classes(in: machO).filter { $0.kind == .generic || $0.hasObjectiveCAncestry }.map { swiftClass in + ObjCSuppliedClass( + name: swiftClass.name, + superClassName: swiftClass.superclass.name.isEmpty ? nil : swiftClass.superclass.name, + readOnlyDataOffset: swiftClass.readOnlyDataOffset, + metaclassReadOnlyDataOffset: swiftClass.metaclassReadOnlyDataOffset, + classStubOffset: swiftClass.classStubOffset, + kind: Kind(swiftClass.kind) + ) + } + } +} + +extension ObjCSuppliedClass.Kind { + init(_ kind: SwiftClassWithoutClassObject.Kind) { + switch kind { + case .generic: self = .genericSwiftClass + case .resilientAncestry: self = .swiftClassWithResilientAncestry + case .genericAncestry: self = .swiftClassWithGenericAncestry + } + } +} diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift new file mode 100644 index 000000000..603a12a44 --- /dev/null +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift @@ -0,0 +1,94 @@ +import Foundation +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftSymbols +@_spi(Internals) import SwiftInspection +import SwiftObjCInterop +import SwiftDeclaration + +/// The image's Objective-C classes, categories and protocols as Swift imports +/// them (evolution proposal `objc-imported-declarations`). A definition is +/// made when asked for — an image can define thousands of classes — and +/// indexes itself on its first print. A class or category Swift implements +/// comes with the Swift definitions the printer takes its members from. +extension SwiftDeclarationIndexer { + /// The runtime names of the Objective-C classes the image defines, sorted. + public var objcImportedClassRuntimeNames: [String] { + ObjCImportedContainerIndex.shared.classRuntimeNames(in: machO) + } + + /// The names the image's Objective-C categories are listed under + /// (`NSView(NSTouchBar)`), sorted. + public var objcImportedCategoryUniqueNames: [String] { + ObjCImportedContainerIndex.shared.categoryUniqueNames(in: machO) + } + + /// The class the Objective-C runtime knows as `runtimeName` as Swift + /// imports it, or `nil` when the image defines no class of that name. + /// It comes with the image's Swift extensions of the class, whose + /// `@objc` members the linker merges into the class's own lists: a + /// Swift class with its own definition, its extensions and its + /// conformances; a class declared in Objective-C with its `@objc + /// @implementation` bodies and the extensions adding `@objc` members. + public func objcImportedClassDefinition(named runtimeName: String) -> ObjCImportedClassDefinition? { + guard let record = ObjCImportedContainerIndex.shared.classRecord(named: runtimeName, in: machO) else { return nil } + guard record.isSwiftClass else { + return ObjCImportedClassDefinition(record: record, swiftClassDefinition: nil, swiftExtensions: swiftExtensions(ofObjCClassNamed: runtimeName), in: machO) + } + guard let classNode = ObjCRuntimeNames.swiftClassNode(forRuntimeName: runtimeName, in: machO) else { + return ObjCImportedClassDefinition(record: record, swiftClassDefinition: nil, swiftExtensions: [], in: machO) + } + let typeNode = Node.createTransient(kind: .type, child: classNode) + let typeName = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO), kind: .class) + guard let swiftClassDefinition = allTypeDefinitions[typeName] else { + return ObjCImportedClassDefinition(record: record, swiftClassDefinition: nil, swiftExtensions: [], in: machO) + } + let extensionName = typeName.extensionName + let swiftExtensions = (typeExtensionDefinitions[extensionName] ?? []) + (conformanceExtensionDefinitions[extensionName] ?? []) + return ObjCImportedClassDefinition(record: record, swiftClassDefinition: swiftClassDefinition, swiftExtensions: swiftExtensions, in: machO) + } + + /// The category listed as `uniqueName` (`NSView(NSTouchBar)`) as Swift + /// imports it, or `nil` when the image defines none. It comes with the + /// image's Swift extensions of the class, which implement a category + /// Swift wrote — an `@objc @implementation` of a category declared in a + /// header, or a plain extension with `@objc` members. + public func objcImportedCategoryDefinition(uniqueName: String) -> ObjCImportedCategoryDefinition? { + guard let record = ObjCImportedContainerIndex.shared.categoryRecord(uniqueName: uniqueName, in: machO), + case .category(let categoryName) = record.kind + else { return nil } + return ObjCImportedCategoryDefinition(record: record, categoryName: categoryName, swiftExtensions: swiftExtensions(ofObjCClassNamed: record.classRuntimeName), in: machO) + } + + /// The runtime names of the classes declared in Objective-C that the + /// image's Swift code extends — its `@objc @implementation` classes + /// among them, whose bodies are extensions too. These are the classes a + /// Swift definition of the image can answer for, and the only ones + /// `SwiftDeclarationPrinter.objcMembersRefinedForSwift(in:)` can find a + /// refined member of (evolution proposal + /// `swift-first-imported-declarations`): a host asking for every class of + /// an image asks for these, not for thousands. One pass over the image's + /// extensions. + public var objcClassRuntimeNamesExtendedInSwift: Set { + Set(typeExtensionDefinitions.values.lazy.flatMap { $0 }.compactMap { extensionDefinition in + ObjCImplementationClasses.cImportedClassName(of: extensionDefinition.extensionName.node) + }) + } + + /// The image's Swift extensions of the class declared in Objective-C as + /// `className` (`extension __C.NSView`). + private func swiftExtensions(ofObjCClassNamed className: String) -> [ExtensionDefinition] { + typeExtensionDefinitions.values.flatMap { $0 }.filter { extensionDefinition in + ObjCImplementationClasses.cImportedClassName(of: extensionDefinition.extensionName.node) == className + } + } + + /// The protocol the Objective-C runtime knows as `runtimeName` as Swift + /// imports it, read from the image's record of it; `nil` when the image + /// holds none. An image holds a record of every protocol it adopts or + /// names, not only of the ones it defines. + public func objcImportedProtocolDefinition(named runtimeName: String) -> ObjCImportedProtocolDefinition? { + guard let record = ObjCImportedContainerIndex.shared.protocolRecord(named: runtimeName, in: machO) else { return nil } + return ObjCImportedProtocolDefinition(record: record, in: machO) + } +} diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift index 44daae8ec..e77b3e5f7 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift @@ -7,12 +7,13 @@ import OrderedCollections @_spi(Internals) import Demangling import SwiftThunkAnalysis import SwiftInspection +import SwiftObjCInterop import SwiftStdlibToolbox import MachOKit import MachOFoundation import Dependencies import Utilities -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Internals) import SwiftInspection @@ -28,8 +29,8 @@ public struct MachOIndexedValue Bool { - lhs.value == rhs.value + public static func == (left: Self, right: Self) -> Bool { + left.value == right.value } } @@ -112,6 +113,18 @@ public final class SwiftDeclarationIndexer = [:] + /// The image's `@objc` protocols declared in Swift (evolution + /// proposal `swift-declared-objc-protocols`), which no protocol + /// descriptor lists. + @usableFromInline @Mutex + var objcProtocolDefinitions: OrderedDictionary = [:] + + /// The Objective-C protocols the image's extensions of other + /// modules' classes adopt, from their categories (evolution proposal + /// `swift-declared-objc-protocols`). + @usableFromInline @Mutex + var objcCategoryConformances: [ObjCCategoryConformance] = [] + @usableFromInline @Mutex var typeExtensionDefinitions: OrderedDictionary = [:] @@ -139,6 +152,7 @@ public final class SwiftDeclarationIndexer>? var allRootProtocolDefinitions: OrderedDictionary>? var allAllProtocolDefinitions: OrderedDictionary>? + var allObjCProtocolDefinitions: OrderedDictionary>? var allTypeExtensionDefinitions: OrderedDictionary]>? var allProtocolExtensionDefinitions: OrderedDictionary]>? var allTypeAliasExtensionDefinitions: OrderedDictionary]>? @@ -231,7 +245,7 @@ public final class SwiftDeclarationIndexer = [:] + for declaredProtocol in SwiftDeclaredObjCProtocolIndex.shared.protocols(in: machO) { + do { + let definition = try ObjCProtocolDefinition(declaredProtocol: declaredProtocol, in: machO) + objcProtocolDefinitions[definition.protocolName] = definition + } catch { + eventDispatcher.dispatch(.protocolProcessingFailed(protocolName: declaredProtocol.qualifiedName, error: error)) + } + } + currentStorage.objcProtocolDefinitions = objcProtocolDefinitions + } + private func indexConformances() async throws { eventDispatcher.dispatch(.conformanceIndexingStarted(input: SwiftIndexEvents.ConformanceIndexingInput(totalConformances: currentStorage.protocolConformances.count, totalAssociatedTypes: currentStorage.associatedTypes.count))) var protocolConformancesByTypeName: OrderedDictionary> = [:] @@ -755,8 +788,9 @@ public final class SwiftDeclarationIndexer SwiftAttachedMacro? { + guard currentStorage.allTypeDefinitions[typeName]?.attachedMacros.contains(.observable) == true, + ObservableMacroRecognition.isObservableProtocol(protocolName.node.materialize()) + else { return nil } + return .observable + } + + /// Freezes associated-type witness records into Mach-O-free values /// while the Mach-O is still in hand — the record accessors cannot be /// resolved later by the snapshot layer. An unresolvable record is skipped /// (same tolerance as the printers' record collection). @@ -830,9 +878,9 @@ public final class SwiftDeclarationIndexer [AssociatedTypeWitnessProjection] { + private func resolvedAssociatedTypeWitnesses(of associatedTypes: [AssociatedType]) -> [ResolvedAssociatedTypeWitness] { var seenNames: Set = [] - var projections: [AssociatedTypeWitnessProjection] = [] + var witnesses: [ResolvedAssociatedTypeWitness] = [] for associatedType in associatedTypes { for record in associatedType.records { guard let recordName = try? record.name(in: machO.context), @@ -846,29 +894,29 @@ public final class SwiftDeclarationIndexer = [:] var protocolExtensionDefinitions: OrderedDictionary = [:] var typeAliasExtensionDefinitions: OrderedDictionary = [:] @@ -904,38 +1007,38 @@ public final class SwiftDeclarationIndexer, genericSignature: NodeReference?) throws -> ExtensionDefinition { + func extensionDefinition(of kind: ExtensionKind, for memberSymbolsByKind: OrderedDictionary, genericSignature: NodeReference?) throws -> ExtensionDefinition { let extensionDefinition = ExtensionDefinition(extensionName: .init(node: node, kind: kind), genericSignature: genericSignature, protocolConformance: nil) var memberCount = 0 for (kind, memberSymbols) in memberSymbolsByKind { switch kind { case .allocator(inExtension: true): - let allocators = DefinitionBuilder.allocators(for: memberSymbols.mapToAnnotatedSymbols()) + let allocators = MemberDefinitionBuilder.allocators(for: memberSymbols.mapToAnnotatedSymbols()) extensionDefinition.allocators.append(contentsOf: allocators) memberCount += allocators.count case .variable(inExtension: true, isStatic: false, isStorage: false): - let variables = DefinitionBuilder.variables(for: memberSymbols.mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: false) + let variables = MemberDefinitionBuilder.variables(for: memberSymbols.mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: false) extensionDefinition.variables.append(contentsOf: variables) memberCount += variables.count case .function(inExtension: true, isStatic: false): - let functions = DefinitionBuilder.functions(for: memberSymbols.mapToAnnotatedSymbols(), isGlobalOrStatic: false) + let functions = MemberDefinitionBuilder.functions(for: memberSymbols.mapToAnnotatedSymbols(), isGlobalOrStatic: false) extensionDefinition.functions.append(contentsOf: functions) memberCount += functions.count case .variable(inExtension: true, isStatic: true, _): - let staticVariables = DefinitionBuilder.variables(for: memberSymbols.mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: true) + let staticVariables = MemberDefinitionBuilder.variables(for: memberSymbols.mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: true) extensionDefinition.staticVariables.append(contentsOf: staticVariables) memberCount += staticVariables.count case .function(inExtension: true, isStatic: true): - let staticFunctions = DefinitionBuilder.functions(for: memberSymbols.mapToAnnotatedSymbols(), isGlobalOrStatic: true) + let staticFunctions = MemberDefinitionBuilder.functions(for: memberSymbols.mapToAnnotatedSymbols(), isGlobalOrStatic: true) extensionDefinition.staticFunctions.append(contentsOf: staticFunctions) memberCount += staticFunctions.count case .subscript(inExtension: true, isStatic: false): - let subscripts = DefinitionBuilder.subscripts(for: memberSymbols.mapToAnnotatedSymbols(), isStatic: false) + let subscripts = MemberDefinitionBuilder.subscripts(for: memberSymbols.mapToAnnotatedSymbols(), isStatic: false) extensionDefinition.subscripts.append(contentsOf: subscripts) memberCount += subscripts.count case .subscript(inExtension: true, isStatic: true): - let staticSubscripts = DefinitionBuilder.subscripts(for: memberSymbols.mapToAnnotatedSymbols(), isStatic: true) + let staticSubscripts = MemberDefinitionBuilder.subscripts(for: memberSymbols.mapToAnnotatedSymbols(), isStatic: true) extensionDefinition.staticSubscripts.append(contentsOf: staticSubscripts) memberCount += staticSubscripts.count default: @@ -985,8 +1088,8 @@ public final class SwiftDeclarationIndexer> = [:] - var memberSymbolsByKind: OrderedDictionary = [:] + var memberSymbolsByGenericSignature: OrderedDictionary> = [:] + var memberSymbolsByKind: OrderedDictionary = [:] for (kind, memberSymbols) in memberSymbols { for memberSymbol in memberSymbols { @@ -1081,7 +1184,7 @@ public final class SwiftDeclarationIndexer String? { + var currentNode: NodeReference? = typeNode.kind == .type ? typeNode.children.first : typeNode + guard let nominalNode = currentNode, [.structure, .class, .enum].contains(nominalNode.kind) else { return nil } + currentNode = nominalNode.children.first + while let contextNode = currentNode { + switch contextNode.kind { + case .module: + return contextNode.text + case .structure, .class, .enum: + currentNode = contextNode.children.first + default: + return nil + } + } + return nil + } + + /// The module a type or protocol name's node is declared in: the module + /// at the root of its context chain, whatever contexts lie on the way. + private static func moduleName(of nameNode: NodeReference) -> String? { + var currentNode: NodeReference? = nameNode + while let node = currentNode { + if node.kind == .module { + return node.text + } + currentNode = node.children.first + } + return nil + } + + /// The extension-member counterpart of `kind`, under which a member of a + /// type another image defines joins the extension members of that type. + private static func extensionMemberKind(of kind: SwiftSymbolIndexStore.MemberKind) -> SwiftSymbolIndexStore.MemberKind { + switch kind { + case .allocator: + .allocator(inExtension: true) + case .constructor: + .constructor(inExtension: true) + case .subscript(_, let isStatic): + .subscript(inExtension: true, isStatic: isStatic) + case .variable(_, let isStatic, let isStorage): + .variable(inExtension: true, isStatic: isStatic, isStorage: isStorage) + case .function(_, let isStatic): + .function(inExtension: true, isStatic: isStatic) + case .deallocator, .destructor: + kind + } + } + private func indexGlobals() async throws { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore - currentStorage.globalVariableDefinitions = DefinitionBuilder.variables(for: symbolIndexStore.globalSymbols(of: .variable(isStorage: false), .variable(isStorage: true), in: machO).mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: true) - currentStorage.globalFunctionDefinitions = DefinitionBuilder.functions(for: symbolIndexStore.globalSymbols(of: .function, in: machO).mapToAnnotatedSymbols(), isGlobalOrStatic: true) + currentStorage.globalVariableDefinitions = MemberDefinitionBuilder.variables(for: symbolIndexStore.globalSymbols(of: .variable(isStorage: false), .variable(isStorage: true), in: machO).mapToAnnotatedSymbols(), fieldNames: [], isGlobalOrStatic: true) + currentStorage.globalFunctionDefinitions = MemberDefinitionBuilder.functions(for: symbolIndexStore.globalSymbols(of: .function, in: machO).mapToAnnotatedSymbols(), isGlobalOrStatic: true) } // MARK: - Extension container unification (evolution proposal 0007) @@ -1163,6 +1321,20 @@ public final class SwiftDeclarationIndexer Protocol` shape for this lookup. + var objcProtocolDefinitionsByName: [ExtensionName: ObjCProtocolDefinition] = [:] + for (protocolName, objcProtocolDefinition) in currentStorage.objcProtocolDefinitions { + objcProtocolDefinitionsByName[protocolName.extensionName] = objcProtocolDefinition + } + for (extensionName, definitions) in currentStorage.protocolExtensionDefinitions { + guard let objcProtocolDefinition = objcProtocolDefinitionsByName[extensionName] else { continue } + for definition in definitions { + definition.isAttachedToProtocolDefinition = true + } + objcProtocolDefinition.defaultImplementationExtensions = definitions + } } private func mergingSameIdentityContainers(_ buckets: OrderedDictionary) -> OrderedDictionary { @@ -1225,6 +1397,11 @@ extension SwiftDeclarationIndexer { @inlinable public var allProtocolDefinitions: OrderedDictionary { currentStorage.allProtocolDefinitions } + /// The image's `@objc` protocols declared in Swift (evolution proposal + /// `swift-declared-objc-protocols`), in field-descriptor order. + @inlinable + public var objcProtocolDefinitions: OrderedDictionary { currentStorage.objcProtocolDefinitions } + @inlinable public var typeExtensionDefinitions: OrderedDictionary { currentStorage.typeExtensionDefinitions } @@ -1237,6 +1414,13 @@ extension SwiftDeclarationIndexer { @inlinable public var conformanceExtensionDefinitions: OrderedDictionary { currentStorage.conformanceExtensionDefinitions } + /// The Objective-C protocols the image's extensions of other modules' + /// classes adopt (evolution proposal `swift-declared-objc-protocols`), + /// in category-list order: no conformance record names them, so no + /// conformance extension carries them. + @inlinable + public var objcCategoryConformances: [ObjCCategoryConformance] { currentStorage.objcCategoryConformances } + @inlinable public var globalVariableDefinitions: [VariableDefinition] { currentStorage.globalVariableDefinitions } @@ -1322,6 +1506,16 @@ extension SwiftDeclarationIndexer { return result } + public var allObjCProtocolDefinitions: OrderedDictionary> { + if let cached = allStorageCache.allObjCProtocolDefinitions { return cached } + var result = currentStorage.objcProtocolDefinitions.mapValues { MachOIndexedValue(machO: machO, value: $0) } + for subIndexer in subIndexers { + result.merge(subIndexer.allObjCProtocolDefinitions) { current, _ in current } + } + allStorageCache.allObjCProtocolDefinitions = result + return result + } + public var allTypeExtensionDefinitions: OrderedDictionary]> { if let cached = allStorageCache.allTypeExtensionDefinitions { return cached } var result: OrderedDictionary]> = currentStorage.typeExtensionDefinitions.mapValues { $0.map { .init(machO: machO, value: $0) } } diff --git a/Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift b/Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift index 0e1e98d1d..199e1a0f9 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift @@ -206,62 +206,86 @@ public struct ConsoleEventHandler: SwiftIndexEvents.Handler { /// so an unlabeled line cannot be attributed to an input. public let label: String? + /// The time a line is stamped with. + private let timestamp: @Sendable () -> String + public init(label: String? = nil) { + self.init(label: label, timestamp: Self.localizedTimestamp) + } + + /// A handler that stamps lines with `timestamp` instead of the local time. + package init(label: String?, timestamp: @escaping @Sendable () -> String) { self.label = label + self.timestamp = timestamp + } + + @Sendable + private static func localizedTimestamp() -> String { + DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium) } + /// Most events — one per type, conformance and printed declaration — + /// print nothing, so the time is read only for a line that is written. + /// Stamping every event built a date formatter per event: a quarter of + /// `swift-section interface` over SwiftUI. public func handle(event: SwiftIndexEvents.Payload) { - let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium) - if let line = line(for: event, timestamp: timestamp) { - report(line) - } + guard let message = message(for: event) else { return } + report(line(withMessage: message, timestamp: timestamp())) } /// The line `handle(event:)` writes for `event`, or `nil` for an event the /// console does not report. `[timestamp] [label] [LEVEL] message`; the /// label bracket is absent when there is no label. package func line(for event: SwiftIndexEvents.Payload, timestamp: String) -> String? { - let prefix = "[\(timestamp)]" + (label.map { " [\($0)]" } ?? "") + message(for: event).map { line(withMessage: $0, timestamp: timestamp) } + } + + private func line(withMessage message: String, timestamp: String) -> String { + "[\(timestamp)]" + (label.map { " [\($0)]" } ?? "") + " " + message + } + /// What follows the timestamp and the label on the line for `event` — + /// `[LEVEL] message` — or `nil` for an event the console does not report. + private func message(for event: SwiftIndexEvents.Payload) -> String? { switch event { case .extractionCompleted(let result): - return "\(prefix) [INFO] Extracted \(result.count) \(sectionName(result.section))" + return "[INFO] Extracted \(result.count) \(sectionName(result.section))" case .typeIndexingCompleted(let result): - return "\(prefix) [INFO] Types: \(result.successful) successful, \(result.failed) failed, \(result.cImportedSkipped) C-imported skipped, \(result.nestedTypes) nested, \(result.extensionTypes) in extensions" + return "[INFO] Types: \(result.successful) successful, \(result.failed) failed, \(result.cImportedSkipped) C-imported skipped, \(result.nestedTypes) nested, \(result.extensionTypes) in extensions" case .protocolIndexingCompleted(let result): - return "\(prefix) [INFO] Protocols: \(result.successful) successful, \(result.failed) failed" + return "[INFO] Protocols: \(result.successful) successful, \(result.failed) failed" case .conformanceIndexingCompleted(let result): - return "\(prefix) [INFO] Conformances: \(result.extensionCount) extensions, \(result.failedConformances + result.failedAssociatedTypes + result.failedExtensions) failed" + return "[INFO] Conformances: \(result.extensionCount) extensions, \(result.failedConformances + result.failedAssociatedTypes + result.failedExtensions) failed" case .extensionIndexingCompleted(let result): - return "\(prefix) [INFO] Extensions: \(result.typeExtensions) type, \(result.protocolExtensions) protocol, \(result.typeAliasExtensions) typealias, \(result.failed) failed" + return "[INFO] Extensions: \(result.typeExtensions) type, \(result.protocolExtensions) protocol, \(result.typeAliasExtensions) typealias, \(result.failed) failed" case .moduleCollectionCompleted(let result): - return "\(prefix) [INFO] Found \(result.moduleCount) modules to import" + return "[INFO] Found \(result.moduleCount) modules to import" case .phaseTransition(let phase, let state): let phaseName = phaseName(phase) switch state { case .completed: - return "\(prefix) [SUCCESS] \(phaseName.capitalized) completed" + return "[SUCCESS] \(phaseName.capitalized) completed" case .failed(let error): - return "\(prefix) [ERROR] \(phaseName.capitalized) failed: \(String(describing: error))" + return "[ERROR] \(phaseName.capitalized) failed: \(String(describing: error))" case .started: return nil // Ignore started events for console output } case .definitionPrintFailed(let context, let error): - return "\(prefix) [ERROR] Failed to print \(context.kind.description) '\(context.name)': \(String(describing: error))" + return "[ERROR] Failed to print \(context.kind.description) '\(context.name)': \(String(describing: error))" case .renderingDegraded(let context, let error): let subject = context.subject.map { " for \($0)" } ?? "" - return "\(prefix) [ERROR] Degraded \(context.source)\(subject): \(String(describing: error))" + return "[ERROR] Degraded \(context.source)\(subject): \(String(describing: error))" case .objcImplementationClassSkipped(let className, let reason): - return "\(prefix) [ERROR] Skipped @objc @implementation recognition for \(className): \(reason)" + return "[ERROR] Skipped @objc @implementation recognition for \(className): \(reason)" default: return nil // Ignore other detailed events diff --git a/Sources/Declaration/SwiftIndexing/SymbolIndexStoreKind+TypeKind.swift b/Sources/Declaration/SwiftIndexing/SymbolIndexStoreKind+TypeKind.swift index 9aa93c3a0..824633d2e 100644 --- a/Sources/Declaration/SwiftIndexing/SymbolIndexStoreKind+TypeKind.swift +++ b/Sources/Declaration/SwiftIndexing/SymbolIndexStoreKind+TypeKind.swift @@ -1,11 +1,11 @@ import SwiftDeclaration -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols -/// Maps `SymbolIndexStore`'s symbol-derived type kind onto the declaration +/// Maps `SwiftSymbolIndexStore`'s symbol-derived type kind onto the declaration /// model's `TypeKind`. Lives in `SwiftIndexing` rather than the base model -/// because `SymbolIndexStore.TypeInfo.Kind` is an `@_spi(Internals)` type and +/// because `SwiftSymbolIndexStore.TypeInfo.Kind` is an `@_spi(Internals)` type and /// this mapping is purely a symbol-index reading concern used by the indexer. -extension SymbolIndexStore.TypeInfo.Kind { +extension SwiftSymbolIndexStore.TypeInfo.Kind { var typeKind: TypeKind? { switch self { case .enum: diff --git a/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift index 769e96b55..9acf40245 100644 --- a/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift +++ b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift @@ -3,7 +3,7 @@ import MachOKit import MachOSwiftSection @_spi(Core) import MachOObjCSection @_spi(Internals) import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import Dependencies import SwiftDeclaration import SwiftDeclarationRendering @@ -191,10 +191,10 @@ public final class PrivateDiscriminatorSourceFileIndex: @unchecked Sendable { /// 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) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore var discriminators: Set = [] - for memberKind in SymbolIndexStore.MemberKind.allCases { + for memberKind in SwiftSymbolIndexStore.MemberKind.allCases { for memberSymbol in symbolIndexStore.memberSymbols(of: memberKind, in: indexer.machO) { discriminators.formUnion(memberSymbol.demangledNode.privateDeclarations.map(\.discriminator)) } diff --git a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift index 28be72719..fd2184abf 100644 --- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift @@ -4,7 +4,7 @@ import Foundation import MachOSwiftSection import OrderedCollections @_spi(Internals) import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection // MARK: - ConformanceProvider Protocol diff --git a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift index 7fee4ffd6..f1a1b7755 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift @@ -4,7 +4,7 @@ import MachOKit import MachOSwiftSection import SwiftDeclaration import SwiftDeclarationRendering -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection /// The arguments of every parameter of one instantiation of a generic type, diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift index b1edc0274..ee2acc7a6 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift @@ -5,7 +5,7 @@ import Foundation import MachOSwiftSection import MachOKit @_spi(Internals) import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection #if canImport(ObjectiveC) import ObjectiveC @@ -605,9 +605,11 @@ extension GenericSpecializer where MachO == MachOFile { } } -/// How a diagnostic spells a type: the way the interface prints it. +/// How a diagnostic spells a type: the way the interface prints it, an +/// existential with the `any` keyword included (evolution proposal +/// `existential-any`). private func displayName(of typeNode: Node) -> String { - typeNode.print(using: .interface) + typeNode.print(using: DemangleOptions.interface.union(.useExistentialAny)) } private func unwrappedTypeNode(_ node: Node) -> Node { diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift index 434644872..e0547d367 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift @@ -4,7 +4,7 @@ import Foundation import MachOSwiftSection import MachOKit import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import OrderedCollections @_spi(Internals) import SwiftInspection @@ -449,6 +449,11 @@ extension GenericSpecializer { // Parameter.invertibleProtocols rather than as a Requirement, because // it relaxes rather than constrains the parameter. return nil + + case nil: + // A kind this reader does not know: there is no telling what it + // asks of an argument, so it is not offered as a requirement. + return nil } } @@ -1086,8 +1091,7 @@ extension GenericSpecializer where MachO == MachOImage { let argumentsPointer = UnsafeRawPointer(argumentsBase) for requirement in mergedRequirements { - let kind = requirement.layout.flags.kind - guard kind == .sameType || kind == .baseClass else { continue } + guard let kind = requirement.layout.flags.kind, kind == .sameType || kind == .baseClass else { continue } evaluateConstraintRequirement( kind: kind, @@ -1992,7 +1996,7 @@ extension GenericSpecializer where MachO == MachOImage { } let accessFunctionRequirements = stepProtocol.requirements.filter { - $0.flags.kind.isAssociatedTypeAccessFunction + $0.flags.kind?.isAssociatedTypeAccessFunction == true } guard let accessFunctionRequirement = accessFunctionRequirements[safe: associatedTypeIndex] else { diff --git a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index c99535154..38f0cf356 100644 --- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -3,7 +3,7 @@ import SwiftDeclaration import MachOSwiftSection import MachOKit import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import FoundationToolbox import AssociatedObject @_spi(Internals) import SwiftInspection @@ -279,13 +279,15 @@ extension TypeDefinition { } // The specialized definition shares this definition's descriptor, so - // it shares its export fact — resolving it again would only re-derive - // the same verdict from the same symbol. + // it shares its export fact and its attached macros — resolving them + // again would only re-derive the same verdicts from the same symbol + // and field records. let specialized = TypeDefinition( type: materializedTypeContext, typeName: finalTypeName, isSpecialized: true, - exportStatus: exportStatus + exportStatus: exportStatus, + attachedMacros: attachedMacros ) specialized.metadata = metadata return specialized @@ -565,7 +567,8 @@ extension TypeDefinition { type: materializedTypeContext, typeName: specializationResult.typeName, isSpecialized: true, - exportStatus: exportStatus + exportStatus: exportStatus, + attachedMacros: attachedMacros ) specialized.staticSpecialization = specializationResult.binding return specialized diff --git a/Sources/Executables/baseline-generator/BaselineGeneratorMain.swift b/Sources/Executables/baseline-generator/BaselineGeneratorMain.swift index a4ef134a1..7fad6fb5f 100644 --- a/Sources/Executables/baseline-generator/BaselineGeneratorMain.swift +++ b/Sources/Executables/baseline-generator/BaselineGeneratorMain.swift @@ -1,6 +1,6 @@ import Foundation import ArgumentParser -import MachOFixtureSupport +import SwiftSectionFixtureSupport @main @available(macOS 12, macCatalyst 15, iOS 15, tvOS 15, watchOS 8, *) diff --git a/Sources/Executables/reader-benchmark/ReaderBenchmark.swift b/Sources/Executables/reader-benchmark/ReaderBenchmark.swift new file mode 100644 index 000000000..c11aa248a --- /dev/null +++ b/Sources/Executables/reader-benchmark/ReaderBenchmark.swift @@ -0,0 +1,285 @@ +import Foundation +import ArgumentParser +import MachOKit +import MachOFoundation +import SwiftSectionKit +@_spi(Support) import SwiftIndexing +import SwiftPrinting +import SwiftInterface +import SwiftDeclarationRendering + +/// Measures how long one image's Swift interface takes to index and to print, +/// read in-process (`MachOImage`) or offline (`MachOFile`), so the two readers +/// can be compared under one configuration in an ordinary process. +/// +/// A test process is no place for this: swift-dependencies looks the test +/// context up with a `dlsym` on every `@Dependency` read there, which took half +/// of a rendering run's time and varies with how many images are loaded. +/// +/// One run measures one reader once. Per-image caches outlive a pass, so a +/// second pass in the same process measures warm caches; repeat the process +/// instead. +@main +struct ReaderBenchmark: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "reader-benchmark", + abstract: "Times indexing and printing one image's Swift interface through MachOImage or MachOFile." + ) + + enum Reader: String, ExpressibleByArgument, CaseIterable { + /// The image loaded into this process (`dlopen`), read through `MachOImage`. + case image + /// The image read from disk through `MachOFile`. + case file + } + + enum Mode: String, ExpressibleByArgument, CaseIterable { + /// `SwiftDeclarationIndexer.prepare()` alone: what a host such as + /// RuntimeViewer waits for while it loads an image. + case index + /// `SwiftInterfaceBuilder.prepare()` and `printRoot()`: what + /// `swift-section interface` does. + case interface + } + + @Option(help: "The reader to measure.") + var reader: Reader + + @Option(help: "What to measure.") + var mode: Mode = .interface + + @Option(help: "The image to read: a framework name loaded into this process for `image`, an image of the running system's dyld shared cache for `file`.") + var imageName: String? + + @Option(help: "A Mach-O file to read instead of a cache image (`file` only).") + var filePath: String? + + @Option(name: .shortAndLong, help: "The slice of a fat file to read (`file` only).") + var architecture: String? + + @Option(help: "A Mach-O file, a dyld cache file or a system root the file's dependencies are found in (`file` only, repeatable).") + var dependencySearchPath: [String] = [] + + @Flag(help: "Print the field offset, member address, vtable offset, witness table offset, type layout and enum layout comments, as RuntimeViewer does by default.") + var layoutComments = false + + @Flag(help: "Index imported C types too, as RuntimeViewer does.") + var showCImportedTypes = false + + @Option(help: "Write the printed interface to this path.") + var outputPath: String? + + @Flag(help: "Report as one JSON object instead of a table.") + var json = false + + func validate() throws { + switch reader { + case .image: + guard imageName != nil else { throw ValidationError("`--reader image` needs `--image-name`.") } + guard filePath == nil, architecture == nil, dependencySearchPath.isEmpty else { + throw ValidationError("`--file-path`, `--architecture` and `--dependency-search-path` only apply to `--reader file`.") + } + case .file: + guard (imageName == nil) != (filePath == nil) else { + throw ValidationError("`--reader file` needs exactly one of `--image-name` and `--file-path`.") + } + } + } + + func run() async throws { + var measurements: [PhaseMeasurement] = [] + switch reader { + case .image: + let loading = ResourceSnapshot.now() + let machOImage = try Self.loadImage(named: imageName ?? "") + measurements.append(PhaseMeasurement(name: "load", from: loading, to: .now())) + measurements += try await measure(machOImage, dependencySearchPaths: []) + case .file: + let searchPaths = dependencySearchPath.map { DependencySearchPath(classifyingPath: $0) } + let loading = ResourceSnapshot.now() + let source: MachOSource = if let filePath { + .file(path: filePath, architecture: try architecture.map { try Self.parseArchitecture($0) }) + } else { + .systemDyldSharedCache(image: .name(imageName ?? "")) + } + let machOFile = try source.load() + measurements.append(PhaseMeasurement(name: "load", from: loading, to: .now())) + measurements += try await Self.withAccessorThunkResolver(searchPaths: searchPaths) { + try await measure(machOFile, dependencySearchPaths: searchPaths) + } + } + report(measurements) + } + + // MARK: - Measuring + + private func measure( + _ machO: MachO, + dependencySearchPaths: [DependencySearchPath] + ) async throws -> [PhaseMeasurement] { + let indexConfiguration = SwiftDeclarationIndexConfiguration( + showCImportedTypes: showCImportedTypes, + dependencySearchPaths: dependencySearchPaths + [.systemDyldSharedCache] + ) + switch mode { + case .index: + let indexing = ResourceSnapshot.now() + let indexer = SwiftDeclarationIndexer(configuration: indexConfiguration, in: machO) + try await indexer.prepare() + return [PhaseMeasurement(name: "index", from: indexing, to: .now())] + case .interface: + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.printStrippedSymbolicItem = true + printConfiguration.printFieldOffset = layoutComments + printConfiguration.printMemberAddress = layoutComments + printConfiguration.printVTableOffset = layoutComments + printConfiguration.printPWTOffset = layoutComments + printConfiguration.printTypeLayout = layoutComments + printConfiguration.printEnumLayout = layoutComments + if !dependencySearchPaths.isEmpty { + // What `swift-section` does with the same paths: the named + // ones first, the running system's cache as the fallback. + printConfiguration.staticLayoutDependencyResolution = .dependencyClosure(searchPaths: dependencySearchPaths + [.systemDyldSharedCache]) + } + let builder = try SwiftInterfaceBuilder( + configuration: SwiftInterfaceBuilderConfiguration(indexConfiguration: indexConfiguration, printConfiguration: printConfiguration), + in: machO + ) + let preparing = ResourceSnapshot.now() + try await builder.prepare() + let printing = ResourceSnapshot.now() + let interface = try await builder.printRoot().string + let printed = ResourceSnapshot.now() + if let outputPath { + try interface.write(toFile: outputPath, atomically: true, encoding: .utf8) + } + return [ + PhaseMeasurement(name: "prepare", from: preparing, to: printing), + PhaseMeasurement(name: "print", from: printing, to: printed, outputByteCount: interface.utf8.count), + ] + } + } + + private static func withAccessorThunkResolver( + searchPaths: [DependencySearchPath], + _ operation: () async throws -> Result + ) async throws -> Result { + guard !searchPaths.isEmpty else { return try await operation() } + return try await AccessorThunkResolution.$taskResolver.withValue(DisassemblingAccessorThunkResolver(searchPaths: searchPaths)) { + try await operation() + } + } + + // MARK: - Loading + + /// Loads the framework into this process when it is not loaded yet, trying + /// the public framework path, the private framework path and the bare name. + private static func loadImage(named name: String) throws -> MachOImage { + if let machOImage = MachOImage(name: name) { return machOImage } + for candidatePath in [ + "/System/Library/Frameworks/\(name).framework/\(name)", + "/System/Library/PrivateFrameworks/\(name).framework/\(name)", + name, + ] { + _ = candidatePath.withCString { dlopen($0, RTLD_LAZY) } + if let machOImage = MachOImage(name: name) { return machOImage } + } + throw ValidationError("`\(name)` could not be loaded into this process.") + } + + private static func parseArchitecture(_ argument: String) throws -> Architecture { + guard let architecture = Architecture(rawValue: argument) else { + throw ValidationError("Unknown architecture `\(argument)`; expected one of \(Architecture.allCases.map(\.rawValue).joined(separator: ", ")).") + } + return architecture + } + + // MARK: - Reporting + + private func report(_ measurements: [PhaseMeasurement]) { + let peakFootprint = ResourceSnapshot.now().lifetimePeakFootprintBytes + if json { + let phases = measurements.map { measurement -> [String: Any] in + var phase: [String: Any] = [ + "name": measurement.name, + "wallSeconds": measurement.wallSeconds, + "processorSeconds": measurement.processorSeconds, + "instructions": measurement.instructions, + ] + if let outputByteCount = measurement.outputByteCount { phase["outputBytes"] = outputByteCount } + return phase + } + let document: [String: Any] = [ + "reader": reader.rawValue, + "mode": mode.rawValue, + "layoutComments": layoutComments, + "phases": phases, + "peakFootprintBytes": peakFootprint, + ] + if let data = try? JSONSerialization.data(withJSONObject: document, options: [.sortedKeys]), + let text = String(data: data, encoding: .utf8) { + print(text) + } + return + } + print("reader \(reader.rawValue), mode \(mode.rawValue), layout comments \(layoutComments ? "on" : "off")") + for measurement in measurements { + var line = " \(measurement.name.padding(toLength: 8, withPad: " ", startingAt: 0))" + line += String(format: " wall %8.3f s cpu %8.3f s instructions %8.3f G", measurement.wallSeconds, measurement.processorSeconds, Double(measurement.instructions) / 1e9) + if let outputByteCount = measurement.outputByteCount { line += " output \(outputByteCount) bytes" } + print(line) + } + print(String(format: " peak footprint %.1f MB", Double(peakFootprint) / 1_048_576)) + } +} + +// MARK: - Resource usage + +/// The process's resource usage at one moment. Processor time is summed over +/// every thread, so a phase that runs on several threads reports more +/// processor time than wall time. +private struct ResourceSnapshot { + let wallClockNanoseconds: UInt64 + let processorSeconds: Double + let instructions: UInt64 + let lifetimePeakFootprintBytes: UInt64 + + static func now() -> ResourceSnapshot { + var usage = rusage() + getrusage(RUSAGE_SELF, &usage) + let processorSeconds = Self.seconds(of: usage.ru_utime) + Self.seconds(of: usage.ru_stime) + + var usageInformation = rusage_info_v4() + let status = withUnsafeMutablePointer(to: &usageInformation) { pointer in + pointer.withMemoryRebound(to: Optional.self, capacity: 1) { + proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) + } + } + return ResourceSnapshot( + wallClockNanoseconds: clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW), + processorSeconds: processorSeconds, + instructions: status == 0 ? usageInformation.ri_instructions : 0, + lifetimePeakFootprintBytes: status == 0 ? usageInformation.ri_lifetime_max_phys_footprint : 0 + ) + } + + private static func seconds(of time: timeval) -> Double { + Double(time.tv_sec) + Double(time.tv_usec) / 1_000_000 + } +} + +private struct PhaseMeasurement { + let name: String + let wallSeconds: Double + let processorSeconds: Double + let instructions: UInt64 + let outputByteCount: Int? + + init(name: String, from start: ResourceSnapshot, to end: ResourceSnapshot, outputByteCount: Int? = nil) { + self.name = name + self.wallSeconds = Double(end.wallClockNanoseconds - start.wallClockNanoseconds) / 1e9 + self.processorSeconds = end.processorSeconds - start.processorSeconds + self.instructions = end.instructions &- start.instructions + self.outputByteCount = outputByteCount + } +} diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 904a99c47..b9af7d7b7 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -62,12 +62,18 @@ struct InterfaceCommand: AsyncParsableCommand { @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.") + @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). A private or local declaration with no symbol to judge by (a Swift-declared `@objc` protocol, a type in an image without local symbols) is dropped too. `override` / `@objc` members and anything else 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("existential-any"), inversion: .prefixedNo, help: "Spell existential types with the any keyword (any P, (any P)?, any P.Type, (any P).Type), the way the compiler writes a .swiftinterface; a lone Any or AnyObject stays bare. On by default; --no-existential-any prints them bare (P, P?, P.Type, P.Protocol).") + var existentialAny: Bool = true + + @Flag(name: .customLong("expand-macros"), help: "Print what an attached macro generated, as the binary has it, instead of folding it into the macro attribute. A class @Observable expanded prints by default with @Observation.Observable, each tracked property as the stored var it was declared as, and a stored var the macro left alone with @Observation.ObservationIgnored; with this flag it prints the registrar, the _x storage and computed x of each tracked property, access(keyPath:), withMutation(keyPath:_:), the shouldNotifyObservers overloads and the generated Observation.Observable conformance instead.") + var expandMacros: 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 @@ -93,6 +99,8 @@ struct InterfaceCommand: AsyncParsableCommand { memberSortOrder: sortMembersByOffset ? .byOffset : .byCategory, infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, usesModuleSelectors: moduleSelectors, + usesExistentialAny: existentialAny, + expandsMacros: expandMacros, protocolRequirementPlacement: requirementsOnAssociatedTypes ? .associatedTypes : .protocolWhereClause, emitsHeader: emitHeader, commentTransformers: try transformerOptions.buildTransformerConfiguration(), diff --git a/Sources/Executables/swift-section/Commands/ReferencesCommand.swift b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift new file mode 100644 index 000000000..14bf059bb --- /dev/null +++ b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift @@ -0,0 +1,103 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +struct ReferencesCommand: AsyncParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "refs", + abstract: "List the code that references a selector, a symbol, a class, a function, an instance variable or a string — or what a function references — across a dyld shared cache or a set of arm64 Mach-O files.", + discussion: "Addresses in and out are unslid, as IDA, ipsw and dyld_info show them. Each line is a reference: the referencing instruction's address, its image, its function and the offset into it, the reference's kind and route, and what it references." + ) + + @Argument(help: "Mach-O files to analyze together, such as an app's executable and its frameworks.", completion: .file()) + var filePaths: [String] = [] + + @OptionGroup var inputOptions: CrossReferenceInputOptionGroup + + @Option(help: "Every send of this selector, super sends included (makeKeyAndOrderFront:).") + var selector: String? + + @Option(help: "The callers of the function this symbol names, with its leading underscore: a C function, a Swift mangled name, _OBJC_CLASS_$_ or _OBJC_IVAR_$_.. A function no analyzed image defines is looked for as the imported symbol it is.") + var symbol: String? + + @Option(name: .customLong("class"), help: "Every reference to the Objective-C class with this runtime name (NSWindow, _TtC7SwiftUI20FilePresenterWrapper).") + var className: String? + + @Option(help: "The callers of the function holding this unslid address (0x… or decimal).") + var function: String? + + @Option(name: .customLong("function-image"), help: "The image --function's address is in, by path or file name: needed only when several of the files hold a function there.") + var functionImage: String? + + @Flag(help: "With --function: list what the function references instead of its callers.") + var callees: Bool = false + + @Option(name: .customLong("ivar"), help: "Every load of the offset of this Objective-C instance variable, written ..") + var instanceVariable: String? + + @Option(help: "Every reference to a C string or constant CFString literal with these characters.") + var string: String? + + @Option(help: "Report at most this many references, the first in image and address order.") + var limit: Int? + + @Flag(help: "Print one JSON document; its addresses are hexadecimal strings.") + var json: Bool = false + + func validate() throws { + let queryCount = [selector, symbol, className, function, instanceVariable, string].compactMap { $0 }.count + guard queryCount == 1 else { + throw ValidationError("Name exactly one of --selector, --symbol, --class, --function, --ivar and --string.") + } + if callees, function == nil { throw ValidationError("--callees lists a function's references; it needs --function.") } + if functionImage != nil, function == nil { throw ValidationError("--function-image names the image of --function's address; it needs --function.") } + if let instanceVariable, !Self.isQualifiedInstanceVariableName(instanceVariable) { + throw ValidationError("--ivar takes ., as in NSWindow._frame.") + } + if let limit, limit < 1 { throw ValidationError("--limit takes a positive number.") } + if let function { _ = try parseAddress(function) } + _ = try inputOptions.input(filePaths: filePaths) + } + + private static func isQualifiedInstanceVariableName(_ text: String) -> Bool { + guard let dot = text.lastIndex(of: ".") else { return false } + return dot != text.startIndex && text.index(after: dot) != text.endIndex + } + + /// The library request these flags describe. + func makeRequest() throws -> ReferencesRequest { + let subject: CrossReferenceSubject + if let selector { + subject = .selector(selector) + } else if let symbol { + subject = .symbol(symbol) + } else if let className { + subject = .objectiveCClass(className) + } else if let function { + subject = .function(address: try parseAddress(function), imageName: functionImage) + } else if let instanceVariable, let dot = instanceVariable.lastIndex(of: ".") { + subject = .instanceVariable(className: String(instanceVariable[.. 1 { + throw ValidationError("--in-image names the one image whose addresses these are.") + } + _ = try inputOptions.input(filePaths: filePaths) + } + + /// The library request these flags describe. + func makeRequest() throws -> SymbolicateRequest { + SymbolicateRequest( + input: try inputOptions.input(filePaths: filePaths), + addresses: try addresses.map(parseAddress), + imageName: inputOptions.imageNames.first, + format: json ? .json : .text + ) + } + + func run() async throws { + let request = try makeRequest() + do { + try await request.run(output: StandardStreamOutput()) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + } +} diff --git a/Sources/Executables/swift-section/Models/CommandLineSupport.swift b/Sources/Executables/swift-section/Models/CommandLineSupport.swift index 95b537300..20e29580d 100644 --- a/Sources/Executables/swift-section/Models/CommandLineSupport.swift +++ b/Sources/Executables/swift-section/Models/CommandLineSupport.swift @@ -98,6 +98,10 @@ enum CommandLineErrorTranslation { case .systemDyldSharedCacheUnavailable: return SwiftSectionCommandError.unsupportedSystemVersionForDyldSharedCache } + case CrossReferenceRequestError.imageNotFound(let name): + return ValidationError("No analyzed image is named '\(name)'; --in-image and --function-image take an image's path or its file name.") + case CrossReferenceRequestError.ambiguousFunction(let address, let imagePaths): + return ValidationError("Several files hold a function at 0x\(String(address, radix: 16)): \(imagePaths.joined(separator: ", ")). Name its image with --function-image.") case SnapshotSourceError.binaryRequired(let snapshotPath): guard let annotatedInterfaceRequiresBinaries else { return error } return ValidationError(annotatedInterfaceRequiresBinaries(snapshotPath)) @@ -105,6 +109,10 @@ enum CommandLineErrorTranslation { return ValidationError("--emit-available could not infer an @available platform from \(path) (no LC_BUILD_VERSION, or a platform with no @available spelling); pass --platform explicitly.") case AvailabilityPlatformInferenceError.conflictingPlatforms(let platforms): return ValidationError("--emit-available found conflicting platforms across the inputs (\(platforms.joined(separator: ", "))); pass --platform explicitly.") + case ObjCAvailabilityPlatformInferenceError.noPlatform(let path): + return ValidationError("--emit-available could not infer an availability-macro platform from \(path) (no LC_BUILD_VERSION, or a platform the availability macros have no name for); pass --platform explicitly.") + case ObjCAvailabilityPlatformInferenceError.conflictingPlatforms(let platforms): + return ValidationError("--emit-available found conflicting platforms across the inputs (\(platforms.joined(separator: ", "))); pass --platform explicitly.") default: return error } diff --git a/Sources/Executables/swift-section/Models/CrossReferenceInputOptionGroup.swift b/Sources/Executables/swift-section/Models/CrossReferenceInputOptionGroup.swift new file mode 100644 index 000000000..561cd27f4 --- /dev/null +++ b/Sources/Executables/swift-section/Models/CrossReferenceInputOptionGroup.swift @@ -0,0 +1,50 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +/// The input of `refs` and `symbolicate`: a whole dyld shared cache, or a set +/// of files read together. Unlike the other subcommands' option groups it +/// names no single image — the cache is read whole — so the cache path is the +/// option's own value. +struct CrossReferenceInputOptionGroup: ParsableArguments, Sendable { + @Option(name: .customLong("dyld-shared-cache"), help: "Analyze every image of the dyld shared cache at this path (dyld_shared_cache_arm64e, its subcaches found beside it).", completion: .file()) + var dyldSharedCachePath: String? + + @Flag(help: "Analyze every image of the running system's dyld shared cache, read from its files.") + var usesSystemDyldSharedCache: Bool = false + + @Option(name: .shortAndLong, help: "The slice of a fat file to read (required for fat binaries): arm64 or arm64e, cross references being read from arm64 code only.") + var architecture: Architecture? + + @Option(name: .customLong("in-image"), help: "An image to look in, by its path or its file name (AppKit, libobjc.A.dylib). Repeatable; without it every image is.") + var imageNames: [String] = [] + + /// The input these options and `filePaths` name: exactly one of a cache, + /// the running system's cache, or files. + func input(filePaths: [String]) throws -> CrossReferenceInput { + switch (dyldSharedCachePath, usesSystemDyldSharedCache, filePaths.isEmpty) { + case (let cachePath?, false, true): + return .dyldSharedCache(path: cachePath) + case (nil, true, true): + return .systemDyldSharedCache + case (nil, false, false): + return .files(paths: filePaths, architecture: architecture) + case (nil, false, true): + throw ValidationError("Name what to analyze: Mach-O files, --dyld-shared-cache , or --uses-system-dyld-shared-cache.") + default: + throw ValidationError("Name one input: Mach-O files, --dyld-shared-cache , or --uses-system-dyld-shared-cache.") + } + } +} + +/// An address on the command line: hexadecimal with `0x`, or decimal. +func parseAddress(_ text: String) throws -> UInt64 { + let value: UInt64? + if text.lowercased().hasPrefix("0x") { + value = UInt64(text.dropFirst(2), radix: 16) + } else { + value = UInt64(text) + } + guard let value else { throw ValidationError("'\(text)' is no address: write it in hexadecimal with 0x, or in decimal.") } + return value +} diff --git a/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift b/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift index 694201a63..88165557f 100644 --- a/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift +++ b/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift @@ -68,6 +68,8 @@ struct DemangleOptionGroup: ParsableArguments, Sendable { var showModuleInDependentMemberType: Bool? @Flag(inversion: .prefixedEnableDisable, help: "Qualify names with SE-0491 module selectors (Swift::Int instead of Swift.Int); every type level carries the module that declared it.") var moduleSelectors: Bool? + @Flag(inversion: .prefixedEnableDisable, help: "Spell existential types with the any keyword (any P, (any P)?, any P.Type, (any P).Type), the way the compiler writes a .swiftinterface; a lone Any or AnyObject stays bare. On by default, whichever --demangle-options preset is chosen.") + var existentialAny: Bool? func buildSwiftDumpDemangleOptions() -> SwiftDump.DemangleOptions { var options = demangleOptions.options @@ -140,6 +142,9 @@ struct DemangleOptionGroup: ParsableArguments, Sendable { if let moduleSelectors { options = options.update(.useModuleSelectors, enabled: moduleSelectors) } + // No preset carries it — the presets print what the toolchain's + // demangler prints — so the dump turns it on itself. + options = options.update(.useExistentialAny, enabled: existentialAny ?? true) return options } } diff --git a/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift index 3f568712e..342789019 100644 --- a/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift @@ -37,6 +37,15 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { @Flag(help: "Emit the evolution as JSON instead of the text report.") var json: Bool = false + @Flag(help: "Emit the union header annotated with per-declaration lifecycle comments instead of the lineage report, each declaration rendered the way `objc dump` renders it. Every input must be a binary (or dyld shared cache); snapshot JSON inputs are rejected.") + var interface: Bool = false + + @Flag(name: .customLong("emit-available"), help: "With --interface: prefix each declaration whose lifecycle one availability macro fully expresses with that macro (API_AVAILABLE, or API_OBSOLETED for a removal; versions resolved from the axis). Inexpressible lifecycles (disappeared-and-returned, non-version labels, modified-only) keep only the bitmap comment. The platform is inferred from every input's LC_BUILD_VERSION unless --platform overrides it.") + var emitAvailable: Bool = false + + @Option(name: .long, help: "The availability-macro platform spelling (e.g. macos, ios, macCatalyst) for --emit-available, overriding LC_BUILD_VERSION inference.") + var platform: String? + @Flag(help: "Exit with a nonzero status when any transition contains an API-breaking change, for CI gating.") var failOnBreaking: Bool = false @@ -45,7 +54,9 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { /// The library request these flags describe. func makeRequest() -> ObjCAPIEvolutionRequest { - let report: ObjCAPIEvolutionRequest.Report = if json { + let report: ObjCAPIEvolutionRequest.Report = if interface { + .annotatedInterface(availabilityAttributes: availabilityAttributes) + } else if json { .json } else if summaryOnly { .summary @@ -67,12 +78,27 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { ) } + /// `--emit-available`, with `--platform` naming the platform instead of + /// leaving it to inference. validate() has already required + /// `--emit-available` for `--platform`. + private var availabilityAttributes: ObjCAPIEvolutionRequest.AvailabilityAttributes { + if !emitAvailable { + .none + } else if let platform { + .platform(platform) + } else { + .inferredPlatform + } + } + func run() async throws { let outcome: ObjCAPIEvolutionOutcome do { outcome = try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) } catch { - throw CommandLineErrorTranslation.translated(error) + throw CommandLineErrorTranslation.translated(error, annotatedInterfaceRequiresBinaries: { snapshotPath in + "--interface needs binaries; snapshot JSON inputs (\(snapshotPath)) only support the lineage report." + }) } if failOnBreaking, outcome.hasBreakingChange { throw ExitCode.failure @@ -82,6 +108,18 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { /// Rejects flag combinations that would otherwise be silently ignored, so /// the user gets immediate feedback instead of a no-op. func validate() throws { + if interface, json { + throw ValidationError("--json and --interface are mutually exclusive.") + } + if interface, summaryOnly { + throw ValidationError("--interface and --summary-only are mutually exclusive.") + } + if emitAvailable, !interface { + throw ValidationError("--emit-available requires --interface.") + } + if platform != nil, !emitAvailable { + throw ValidationError("--platform requires --emit-available.") + } if inputPaths.count < 2 { throw ValidationError("evolution needs at least 2 inputs in version order (oldest first).") } diff --git a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift index da6d5e5d2..a2850cb3a 100644 --- a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift @@ -39,6 +39,9 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { @Flag(name: .shortAndLong, help: "Report indexing progress on stderr.") var verbose: Bool = false + @Flag(name: .customLong("swift"), help: "Print the declaration as Swift imports it — names by the ClangImporter's rules, members Swift implements as their Swift declarations — instead of as an Objective-C header. Classes, categories and protocols only.") + var printsSwiftImport: Bool = false + /// The library request these flags describe. func makeRequest() throws -> ObjCInterfaceRequest { ObjCInterfaceRequest( @@ -49,7 +52,8 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { cTypeReplacements: try transformerOptions.buildCTypeReplacements(), ivarOffsetComment: transformerOptions.buildIvarOffsetComment(), reportsIndexingProgress: verbose, - destination: outputPath.map { .file(path: $0) } ?? .output + destination: outputPath.map { .file(path: $0) } ?? .output, + printsSwiftImport: printsSwiftImport ) } diff --git a/Sources/Executables/swift-section/SwiftSectionCommand.swift b/Sources/Executables/swift-section/SwiftSectionCommand.swift index 5f858f389..7cff01761 100644 --- a/Sources/Executables/swift-section/SwiftSectionCommand.swift +++ b/Sources/Executables/swift-section/SwiftSectionCommand.swift @@ -13,6 +13,8 @@ struct SwiftSectionCommand: AsyncParsableCommand { EvolutionCommand.self, TransformerCommand.self, ObjCCommand.self, + ReferencesCommand.self, + SymbolicateCommand.self, ], defaultSubcommand: DumpCommand.self ) diff --git a/Sources/Executables/swift-section/Version.swift b/Sources/Executables/swift-section/Version.swift index 98c70d337..7dc4faf5e 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.24.0" + static let value = "0.25.0" } diff --git a/Sources/MachO/MachOBase/Exported.swift b/Sources/MachO/MachOBase/Exported.swift deleted file mode 100644 index 996372610..000000000 --- a/Sources/MachO/MachOBase/Exported.swift +++ /dev/null @@ -1,10 +0,0 @@ -// The reader / resolver / pointer layer as one import — everything the ABI -// model (`MachOSwiftSection`) is allowed to depend on, and nothing above it. -// `MachOFoundation` re-exports this plus the symbol index and dependency -// resolution; the ABI layer deliberately stops here (evolution proposal -// `self-contained-abi-layer`). -@_exported import MachOKitExtensions -@_exported import MachOReading -@_exported import MachOResolving -@_exported import MachOPointers -@_exported import Utilities diff --git a/Sources/MachO/MachOCaches/SharedCache.swift b/Sources/MachO/MachOCaches/SharedCache.swift deleted file mode 100644 index 4796eed32..000000000 --- a/Sources/MachO/MachOCaches/SharedCache.swift +++ /dev/null @@ -1,236 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions -import Utilities -import SwiftStdlibToolbox - -/// One lazily built value per Mach-O image, shared by every caller that -/// asks for it. -/// -/// Entries are keyed by ``SharedCacheKey``. A lookup that finds a finished -/// value returns it; one that finds a build in flight joins it; one that -/// finds nothing installs an in-flight marker, runs the caller's build -/// closure **outside** the cache lock, and publishes the result. So callers -/// building entries for different images run in parallel, and callers -/// building the same image's entry share one build. -/// -/// The build closure is the caller's. The cache knows nothing about what a -/// reader can read, so the type that owns an index supplies the build at its -/// own call site, where the reader's concrete capabilities are known. A build -/// that returns `nil` is not cached, and the next lookup tries again. -/// -/// Every cache belongs to a ``SharedCacheEvictionGroup`` and registers -/// itself with a ``SharedCacheRegistry`` at creation; eviction per image is -/// the registry's business. The cache itself never drops an entry on its -/// own — in particular not on memory pressure, which it once did per -/// instance, behind the registry's back and to no effect, since the entries -/// were pinned by live references anyway. -/// -/// `final`: an owning type holds a private instance and forwards to it, -/// rather than subclassing. `@unchecked Sendable` because the mutable state -/// is behind an `os_unfair_lock`. -@_spi(Internals) -public final class SharedCache: SharedCacheEvicting, @unchecked Sendable { - /// The family this cache's entries are evicted with. - public let evictionGroup: SharedCacheEvictionGroup - - /// - Parameters: - /// - evictionGroup: The family the entries belong to. - /// - follows: The families whose storage this cache's entries point - /// into; whenever one of them is claimed and evicted, this cache's - /// family goes with it. Declared here, by the cache that holds the - /// reference, because this is where the fact is known. - /// - registry: Where the cache registers itself. The process-wide - /// registry, except for a test driving a registry of its own. - package init(evictionGroup: SharedCacheEvictionGroup, follows: Set = [], registry: SharedCacheRegistry = .shared) { - self.evictionGroup = evictionGroup - registry.register(self, group: evictionGroup, follows: follows) - } - - /// Per-key state: a finished build (`completed`) or an in-flight build - /// that other callers can join via the promise (`inFlight`). The - /// in-flight marker lets concurrent callers for the same key share one - /// build instead of serializing against the cache lock for the build's - /// entire duration. - private enum Entry { - case completed(Storage) - case inFlight(SharedCacheBuildPromise) - } - - @Mutex - private var storageByKey: [SharedCacheKey: Entry] = [:] - - /// Routing decision the cache lock makes on behalf of `storage(...)`: - /// either return a cached value, await someone else's in-flight build, - /// or run the build ourselves under the freshly-installed promise. - private enum Outcome { - case completed(Storage) - case wait(SharedCacheBuildPromise) - case build(SharedCacheBuildPromise) - } - - /// Atomic get-or-build with a caller-provided build closure. - /// - /// The closure may capture per-call context (progress continuations, - /// options, the reader's concrete type); that context flows through - /// closure capture, never through shared instance state, so concurrent - /// calls cannot interfere. - /// - /// The cache lock is held only long enough to look up the key and either - /// hand back a finished value, attach to an in-flight build, or install - /// our own in-flight marker. The build closure itself executes - /// **outside** the lock, so two callers building entries for different - /// Mach-O identifiers run in parallel; two callers building entries for - /// the same identifier de-duplicate via the in-flight promise. - public func storage( - in machO: MachO, - buildUsing build: (MachO) -> Storage? - ) -> Storage? { - return resolve(key: SharedCacheKey(machO)) { build(machO) } - } - - /// Installs `storage` as the image's finished entry, replacing whatever - /// was there. A build in flight for the same image loses: when it - /// returns it finds a marker that is not its own and does not publish, - /// though it still hands its own result to the callers that joined it. - /// This is what lets an owner with configuration of its own — an - /// indexer with search paths — override the default an earlier lookup - /// built. - public func register(_ storage: Storage, for machO: some MachORepresentableWithCache) { - register(storage, forKey: SharedCacheKey(machO)) - } - - /// Key-taking form of ``register(_:for:)``, for the in-package tests. - package func register(_ storage: Storage, forKey key: SharedCacheKey) { - _storageByKey.withLockUnchecked { dict in - dict[key] = .completed(storage) - } - } - - /// Returns `true` when a finished build is already cached for `machO`'s - /// identifier. In-flight builds count as **not** cached: a caller that - /// observes `false` here, then runs ``storage(in:buildUsing:)``, may end - /// up sharing an existing in-flight build with another caller — but from - /// the "self-triggered" perspective (see ``SharedCacheRegistry``) that is - /// still cooperative ownership, not sole ownership, so reporting `true` - /// for in-flight would mislead the bookkeeping. - public func contains(in machO: some MachORepresentableWithCache) -> Bool { - return containsEntry(for: SharedCacheKey(machO)) - } - - /// Drops the cached entry for `machO`'s identifier so the next lookup - /// rebuilds from scratch. In-flight builds are left alone: their waiters - /// still need the promise to settle, and the next completed result - /// simply won't be re-installed because the in-flight marker has already - /// been removed by the time we check on the build path. Safe to call - /// even when no entry exists. - public func remove(for machO: some MachORepresentableWithCache) { - removeEntry(for: SharedCacheKey(machO)) - } - - /// Drops every cached entry — for tests, or a long-lived process - /// flushing between unrelated batches. Bypasses the registry's - /// ownership rules, so not something library code calls. - public func removeAll() { - _storageByKey.withLockUnchecked { dict in - dict.removeAll(keepingCapacity: false) - } - } - - // MARK: - SharedCacheEvicting - - public func containsEntry(for key: SharedCacheKey) -> Bool { - _storageByKey.withLockUnchecked { dict in - if case .completed = dict[key] { - return true - } - return false - } - } - - public func removeEntry(for key: SharedCacheKey) { - _storageByKey.withLockUnchecked { dict in - if case .completed = dict[key] { - dict.removeValue(forKey: key) - } - } - } - - public var entryKeys: [SharedCacheKey] { - _storageByKey.withLockUnchecked { dict in - dict.compactMap { key, entry in - if case .completed = entry { - return key - } - return nil - } - } - } - - /// The core of ``storage(in:buildUsing:)``. Holds the cache lock only - /// across the dictionary lookup / marker install and across the - /// post-build dictionary update — the actual `build` call runs - /// unsynchronized so that concurrent builds for distinct keys don't - /// serialize. - /// - /// `package`-visible so the in-package test target can exercise the - /// concurrency contract directly without manufacturing a fake - /// `MachORepresentableWithCache` conformer. - package func resolve(key: SharedCacheKey, build: () -> Storage?) -> Storage? { - let outcome: Outcome = _storageByKey.withLockUnchecked { dict in - if let entry = dict[key] { - switch entry { - case .completed(let storage): - return .completed(storage) - case .inFlight(let promise): - return .wait(promise) - } - } - let promise = SharedCacheBuildPromise() - dict[key] = .inFlight(promise) - return .build(promise) - } - - switch outcome { - case .completed(let storage): - return storage - case .wait(let promise): - // A build closure that queries the entry it is itself building - // finds its own in-flight marker here. Waiting would block - // forever: the promise is fulfilled only when that closure - // returns, and the closure is the one waiting. Before the - // promise-based rewrite this trapped on the non-reentrant cache - // lock, which at least left a crash log; a silent hang is worse, - // so the same-thread case traps on purpose. A build that moved - // to another thread first is not detectable at this layer. - precondition( - !promise.isBuilderCurrentThread, - "SharedCache: re-entrant build for key \(key) — the build closure queried the entry it is building, on its own thread; waiting here would never return" - ) - return promise.wait() - case .build(let promise): - let result = build() - _storageByKey.withLockUnchecked { dict in - // Only publish back if our promise is still the in-flight - // marker. `removeAll()` could have cleared the dict - // mid-build, or `register(_:for:)` could have installed a - // finished entry over ours; in either case the dict is not - // ours to write — but our promise still has waiters - // attached, so we always call `fulfill(_:)` below. - if case .inFlight(let installed) = dict[key], installed === promise { - if let storage = result { - dict[key] = .completed(storage) - } else { - // Mirror the original behaviour: a build that returns - // `nil` is not cached, so subsequent callers get a - // fresh attempt instead of being permanently stuck on - // the failure. - dict[key] = nil - } - } - } - promise.fulfill(result) - return result - } - } -} diff --git a/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift b/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift deleted file mode 100644 index ed306be84..000000000 --- a/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift +++ /dev/null @@ -1,74 +0,0 @@ -import Foundation - -/// Sync rendezvous used by ``SharedCache/storage(in:buildUsing:)`` to share -/// one in-flight build between concurrent callers for the same identifier. -/// -/// The first caller installs an instance of this promise as the cache's -/// in-flight marker for the key, releases the cache lock, and runs the build -/// closure unsynchronized. Concurrent callers for the same key find the -/// in-flight marker, release the cache lock, and block in ``wait()`` on -/// `NSCondition`. The builder calls ``fulfill(_:)`` once the work is done, -/// `broadcast()` wakes every waiter at once, and `wait()` returns the same -/// value to all of them. -/// -/// `SwiftDeclaration`'s `DefinitionIndexing` uses it the same way for a -/// definition's one indexing pass, with a `Result` as the value so that -/// waiters share the pass's error too. -/// -/// `final class` because the same instance must be referenced from the cache -/// dictionary and from every waiter; `NSCondition` also requires a stable -/// memory address. `@unchecked Sendable` because the synchronization is -/// provided by `NSCondition`, not by Swift's data-race detector. -@_spi(Internals) -public final class SharedCacheBuildPromise: @unchecked Sendable { - private let condition = NSCondition() - /// The thread that installed this promise and runs the build it stands - /// for. `SharedCache.resolve` creates the promise on the very thread that - /// goes on to call the build closure, so the thread is captured here and - /// never assigned again. A build that hops to another thread (the symbol - /// index sweep moves onto a large-stack worker) is not covered by this: - /// only the builder's own thread can be told apart from a legitimate - /// waiter, which is the case ``isBuilderCurrentThread`` exists for. - private let builderThread: pthread_t = pthread_self() - /// Outer optional encodes "fulfilled yet?"; inner optional matches - /// `(MachO) -> Storage?` — a build that returned `nil` is a valid - /// terminal state, distinct from "still pending". - private var result: Value?? - - public init() {} - - /// `true` when the calling thread is the one running this promise's - /// build. A `wait()` from that thread can never return: the promise is - /// fulfilled only after the build closure returns, and the build closure - /// is what is waiting. `SharedCache.resolve` checks this before waiting - /// and traps with a message instead of hanging silently. - public var isBuilderCurrentThread: Bool { - pthread_equal(builderThread, pthread_self()) != 0 - } - - /// Blocks until ``fulfill(_:)`` is called and returns whatever the builder - /// produced. Safe to call from any thread. - public func wait() -> Value? { - condition.lock() - defer { condition.unlock() } - while result == nil { - condition.wait() - } - // `result` is `.some(.some(v))` or `.some(.none)`; flatten the outer - // optional we used as the "fulfilled" tag back to the inner Storage?. - return result.flatMap { $0 } - } - - /// Records the result and wakes every waiter. Idempotent — a second call - /// is silently ignored, which matters when memory pressure clears the - /// cache mid-build and a fresh builder installs a new promise: the old - /// builder's `fulfill` call still has to land for its already-blocked - /// waiters, but mustn't disturb the new promise. - public func fulfill(_ value: Value?) { - condition.lock() - defer { condition.unlock() } - if result != nil { return } - result = .some(value) - condition.broadcast() - } -} diff --git a/Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift b/Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift deleted file mode 100644 index 9bdd46d29..000000000 --- a/Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation - -/// The family a per-image cache belongs to, for eviction. -/// -/// An image's cached state is dropped per family rather than per cache: -/// the declaration indexer claims, when it prepares an image, every family -/// that has no finished entry for that image yet — those are the ones its -/// preparation is about to build — and the image's last live indexer evicts -/// what was claimed (``SharedCacheRegistry``). -/// -/// This module declares **no** families. The module that owns a cache -/// declares its family as a static constant in an extension, next to the -/// cache, and names it at the cache's creation: -/// -/// ```swift -/// extension SharedCacheEvictionGroup { -/// package static let symbolStore = SharedCacheEvictionGroup("symbolStore") -/// } -/// -/// private let cache = SharedCache(evictionGroup: .symbolStore) -/// ``` -/// -/// A cache whose entries point into another family's storage says so with -/// `follows:` — `SharedCache(evictionGroup: .symbolicMangling, follows: [.symbolStore])` -/// — and the registry evicts its family whenever the followed family is -/// claimed and evicted, so an eviction never leaves behind a reference that -/// pins what it just dropped. The relationship is declared by the cache that -/// holds the reference, where the fact is known; this module keeps only the -/// mechanism. -/// -/// Two families are the same family when their names are equal; a name is -/// therefore chosen once, by the module that owns it. -@_spi(Internals) -public struct SharedCacheEvictionGroup: Hashable, Sendable, CustomStringConvertible { - public let name: String - - public init(_ name: String) { - self.name = name - } - - public var description: String { - name - } -} diff --git a/Sources/MachO/MachOCaches/SharedCacheKey.swift b/Sources/MachO/MachOCaches/SharedCacheKey.swift deleted file mode 100644 index 55e0552f6..000000000 --- a/Sources/MachO/MachOCaches/SharedCacheKey.swift +++ /dev/null @@ -1,85 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions - -/// The key a ``SharedCache`` entry is filed under: a Mach-O reader's -/// identity, hashed on the cheapest part that already tells images apart. -/// -/// Every reader's `identifier` is a `MachOTargetIdentifier` today (the two -/// conformers are `MachOFile` and `MachOImage`). Boxing it into an -/// `AnyHashable` on each lookup allocated — the `uuidFile` payload, a path -/// plus a UUID, does not fit an existential's inline buffer — and hashed the -/// whole install path, on lookups that happen once per symbol and once per -/// mangled name. Here the `uuidFile` case hashes only its UUID (unique per -/// link, so it separates images by itself), the `dyldCacheImage` case only -/// its two UUIDs (the image's and its cache's — one build can sit in two -/// caches) and the `image` case only its base address; the path takes part -/// in equality, never in the hash. The two cases without a UUID, `file` and -/// `versionedFile`, still hash the path — they only occur for a binary that -/// carries no `LC_UUID`. -/// -/// An identifier of any other type is boxed the way it used to be, so a -/// future conformer keeps working, just without the cheaper hash. -@_spi(Internals) -public struct SharedCacheKey: Hashable, CustomStringConvertible, @unchecked Sendable { - private enum Representation: Hashable { - case target(MachOTargetIdentifier) - case opaque(AnyHashable) - } - - private let representation: Representation - - /// The key of `machO`'s cache entries. - public init(_ machO: some MachORepresentableWithCache) { - if let identifier = machO.identifier as? MachOTargetIdentifier { - self.init(identifier: identifier) - } else { - self.init(opaque: machO.identifier) - } - } - - /// The key for a reader whose identifier is `identifier`. - public init(identifier: MachOTargetIdentifier) { - representation = .target(identifier) - } - - /// A key for something that is not a Mach-O reader. The cache's own - /// process-scoped entry and its tests use this; a reader whose - /// identifier is not a `MachOTargetIdentifier` lands here as well. - public init(opaque value: some Hashable) { - representation = .opaque(AnyHashable(value)) - } - - public func hash(into hasher: inout Hasher) { - switch representation { - case .target(.uuidFile(_, let uuid)): - hasher.combine(0 as UInt8) - hasher.combine(uuid) - case .target(.dyldCacheImage(_, let uuid, let cacheUUID)): - hasher.combine(4 as UInt8) - hasher.combine(uuid) - hasher.combine(cacheUUID) - case .target(.image(let baseAddress)): - hasher.combine(1 as UInt8) - hasher.combine(baseAddress) - case .target(let identifier): - hasher.combine(2 as UInt8) - hasher.combine(identifier) - case .opaque(let value): - hasher.combine(3 as UInt8) - hasher.combine(value) - } - } - - // `==` is the synthesized one over `representation`: the full - // identifier, path included, decides equality. - - public var description: String { - switch representation { - case .target(let identifier): - return String(describing: identifier) - case .opaque(let value): - return String(describing: value.base) - } - } -} diff --git a/Sources/MachO/MachOCaches/SharedCacheRegistry.swift b/Sources/MachO/MachOCaches/SharedCacheRegistry.swift deleted file mode 100644 index d452038e0..000000000 --- a/Sources/MachO/MachOCaches/SharedCacheRegistry.swift +++ /dev/null @@ -1,236 +0,0 @@ -import Foundation - -/// A per-image cache the registry can inspect and evict by key. Every -/// ``SharedCache`` conforms; a store that keeps something other than a -/// built value per image (a host's weakly held provider) conforms by hand. -@_spi(Internals) -public protocol SharedCacheEvicting: AnyObject, Sendable { - /// Whether a finished entry exists for `key`. A build in flight does not - /// count. - func containsEntry(for key: SharedCacheKey) -> Bool - /// Drops the finished entry for `key`, if any. - func removeEntry(for key: SharedCacheKey) - /// The keys with a finished entry. - var entryKeys: [SharedCacheKey] { get } -} - -/// Process-wide coordination of per-image cache eviction. -/// -/// Every ``SharedCache`` registers itself here under its -/// ``SharedCacheEvictionGroup``, naming the groups it `follows` — the ones -/// whose storage its entries point into. An owner of an image's caches — the -/// declaration indexer — registers as a **live owner** when it prepares the -/// image and deregisters when it goes away. Registration claims, for that -/// image, every registered group that has no finished entry yet: those are -/// the groups the owner's preparation is about to build, and entries built -/// by non-owner callers before it are never claimed and never evicted here. -/// Deregistration of the image's **last** live owner evicts the claimed -/// groups together with every group that follows them, transitively. An -/// owner leaving earlier evicts nothing: the survivor's already-built names -/// would keep an orphaned store alive while new names land in a fresh one, -/// splitting the `store ===` fast paths for the rest of its lifetime -/// (PR #103 review, finding M6). -/// -/// The registry knows no group by name. The set it works over is the set -/// the caches registered, so a module adding a cache adds a group without -/// touching this module. -/// -/// The library does not react to memory pressure by itself. A host that -/// wants to shed cached state under pressure calls -/// ``evictImagesWithoutLiveOwners()`` at a moment of its choosing. -@_spi(Internals) -public final class SharedCacheRegistry: @unchecked Sendable { - public static let shared = SharedCacheRegistry() - - private struct WeakCache { - weak var cache: (any SharedCacheEvicting)? - } - - private struct ImageEntry { - /// Identity-keyed rather than counted: registration is idempotent - /// per owner, so a double `prepare()` cannot inflate the population - /// and strand the entry above zero forever. - var liveOwners: Set = [] - var claims: Set = [] - } - - private let lock = NSLock() - private var cachesByGroup: [SharedCacheEvictionGroup: [WeakCache]] = [:] - /// Followed group → the groups that follow it, as the caches declared. - private var followersByGroup: [SharedCacheEvictionGroup: Set] = [:] - private var entriesByImageKey: [SharedCacheKey: ImageEntry] = [:] - - /// `package` so a test can drive a registry of its own, with caches - /// created against it, instead of the process-wide one. - package init() {} - - /// Registers `cache` under `group`, following `follows`. Called by - /// ``SharedCache``'s initializer; held weakly. Declarations are unioned: - /// a group follows every group any of its caches named. - public func register(_ cache: any SharedCacheEvicting, group: SharedCacheEvictionGroup, follows: Set = []) { - lock.lock() - defer { lock.unlock() } - cachesByGroup[group, default: []].append(WeakCache(cache: cache)) - for followed in follows { - followersByGroup[followed, default: []].insert(group) - } - } - - /// Every group a cache registered under. - public var registeredGroups: Set { - lock.lock() - defer { lock.unlock() } - return Set(cachesByGroup.keys) - } - - /// The groups evicted along with `group` when it is claimed and evicted: - /// the ones that declared they follow it, transitively. - public func followers(of group: SharedCacheEvictionGroup) -> Set { - lock.lock() - defer { lock.unlock() } - var followers = expandingFollowers(of: [group]) - followers.remove(group) - return followers - } - - /// The groups with a finished entry for `key` in at least one of their - /// caches. - public func presentGroups(for key: SharedCacheKey) -> Set { - lock.lock() - defer { lock.unlock() } - return presentGroupsLocked(for: key) - } - - /// Registers `owner` as a live owner of `key`'s caches, claiming — in the - /// same critical section — every registered group with no finished entry - /// for `key`. - /// - /// Sampled under the lock on purpose: sampled before it, a sibling's - /// deregistration landing in between let an owner observe the caches as - /// present, claim nothing, register into an entry the sibling then - /// removed, rebuild everything and hold no claim to evict it — a symbol - /// store leaked for the process lifetime. - /// - /// Only a first registration contributes claims: an owner registering - /// again samples the caches its own earlier preparation just built and - /// would otherwise read "nobody had this, so I claim it" backwards. - public func registerLiveOwner(_ owner: ObjectIdentifier, for key: SharedCacheKey) { - lock.lock() - defer { lock.unlock() } - var entry = entriesByImageKey[key, default: ImageEntry()] - let isFirstRegistration = entry.liveOwners.insert(owner).inserted - if isFirstRegistration { - let present = presentGroupsLocked(for: key) - entry.claims.formUnion(cachesByGroup.keys.filter { !present.contains($0) }) - } - entriesByImageKey[key] = entry - } - - /// Deregisters `owner`, and — only if it was `key`'s LAST live owner, so - /// a shared entry never disappears under a live sibling — evicts the - /// claimed groups and their followers. - /// - /// The eviction runs under the lock, in the same critical section as the - /// deregistration: done afterwards, a sibling could sample the caches as - /// still present in between and claim nothing. Safe because no cache - /// calls back into the registry. - public func deregisterLiveOwner(_ owner: ObjectIdentifier, for key: SharedCacheKey) { - lock.lock() - defer { lock.unlock() } - guard var entry = entriesByImageKey[key] else { return } - entry.liveOwners.remove(owner) - guard entry.liveOwners.isEmpty else { - entriesByImageKey[key] = entry - return - } - entriesByImageKey.removeValue(forKey: key) - evictLocked(groups: expandingFollowers(of: entry.claims), for: key) - } - - /// Whether any live owner is registered for `key`. - public func hasLiveOwners(for key: SharedCacheKey) -> Bool { - lock.lock() - defer { lock.unlock() } - return !(entriesByImageKey[key]?.liveOwners.isEmpty ?? true) - } - - /// The claims currently held for `key`, for tests and diagnostics. - public func claims(for key: SharedCacheKey) -> Set { - lock.lock() - defer { lock.unlock() } - return entriesByImageKey[key]?.claims ?? [] - } - - /// Drops `key`'s entries from every cache in `groups` — exactly those - /// groups, no followers: an explicit eviction names what it wants gone. - public func evict(groups: Set, for key: SharedCacheKey) { - lock.lock() - defer { lock.unlock() } - evictLocked(groups: groups, for: key) - } - - /// Drops every cached entry of every image that has no live owner, in - /// every registered group. The host's memory-pressure hook: the library - /// never calls this by itself. An image populated only by non-owner - /// callers (a dump, a layout query) has no owner and is cleared too — - /// the caller decides when that is acceptable. - /// - /// - Returns: The number of images cleared. - @discardableResult - public func evictImagesWithoutLiveOwners() -> Int { - lock.lock() - defer { lock.unlock() } - var keys: Set = [] - for caches in cachesByGroup.values { - for weakCache in caches { - guard let cache = weakCache.cache else { continue } - keys.formUnion(cache.entryKeys) - } - } - let unownedKeys = keys.filter { entriesByImageKey[$0]?.liveOwners.isEmpty ?? true } - for key in unownedKeys { - evictLocked(groups: Set(cachesByGroup.keys), for: key) - } - return unownedKeys.count - } - - // MARK: - Under the lock - - private func presentGroupsLocked(for key: SharedCacheKey) -> Set { - var present: Set = [] - for (group, caches) in cachesByGroup { - for weakCache in caches { - guard let cache = weakCache.cache, cache.containsEntry(for: key) else { continue } - present.insert(group) - break - } - } - return present - } - - /// `groups` plus everything that follows them, transitively: a group - /// following a follower goes too. - private func expandingFollowers(of groups: Set) -> Set { - var expanded = groups - var pending = Array(groups) - while let group = pending.popLast() { - for follower in followersByGroup[group] ?? [] where expanded.insert(follower).inserted { - pending.append(follower) - } - } - return expanded - } - - private func evictLocked(groups: Set, for key: SharedCacheKey) { - for group in groups { - guard let caches = cachesByGroup[group] else { continue } - // Compact the dead references while here; a cache is a - // process-lifetime singleton in practice, a test's is not. - let liveCaches = caches.filter { $0.cache != nil } - cachesByGroup[group] = liveCaches - for weakCache in liveCaches { - weakCache.cache?.removeEntry(for: key) - } - } - } -} diff --git a/Sources/MachO/MachODependencies/DependencyClosure.swift b/Sources/MachO/MachODependencies/DependencyClosure.swift deleted file mode 100644 index f165df9a2..000000000 --- a/Sources/MachO/MachODependencies/DependencyClosure.swift +++ /dev/null @@ -1,146 +0,0 @@ -import Foundation -@_spi(Support) import MachOKit -import MachOKitExtensions - -/// How far a `DependencyClosure` follows the load commands. -public enum DependencyTraversal: Sendable, Hashable { - /// Only the root's own `LC_LOAD_DYLIB`-family entries. - case direct - /// The root's dependencies, their dependencies, and so on — breadth-first. - case transitive -} - -/// The dependency images of a root binary, resolved through a -/// `DependencyLocating` strategy. -/// -/// `images` is in **resolution order**: the load-command order for a direct -/// traversal, breadth-first for a transitive one (the root's direct -/// dependencies first, then theirs, …). The order is part of the contract, not -/// an implementation detail — a consumer that indexes dependencies lazily -/// (`SwiftLayout.ImageUniverse`) folds them in this order and stops at the -/// first hit, and depth-first would put Foundation's whole subtree ahead of the -/// root's own second Swift dependency. -/// -/// Images are deduplicated twice: by bare image name (`DependencyLoadName`), -/// never by load-name spelling, and by image identity -/// (`MachORepresentableWithCache.identifier`, `LC_UUID`-keyed for a file) — -/// the file locator registers an explicit file under its on-disk path, its -/// install name and its bare name, so a root that links the same binary under -/// two load names reaches one image twice, and it is collected once. The root -/// itself is excluded. A dependency the locator cannot find is not an error: -/// its load name is recorded in `unresolvedLoadNames` and traversal -/// continues, so the result degrades per dependency rather than failing -/// whole. -public struct DependencyClosure: Sendable { - public let root: MachO - public let traversal: DependencyTraversal - /// The resolved dependency images in resolution order (see the type - /// documentation), root excluded. - public let images: [MachO] - /// Load names no locator could resolve, in encounter order, deduplicated by - /// bare image name. - public let unresolvedLoadNames: [String] - /// Search paths the file locator could not open (always empty for a locator - /// that has no search paths, such as the in-process one). - public let searchPathLoadFailures: [DependencySearchPathLoadFailure] - - /// Resolves the closure of `root` through `locator`. The general entry - /// point; the reader-specific initializers below pick the locator. - public init(root: MachO, traversal: DependencyTraversal = .transitive, locator: some DependencyLocating) { - self.init(root: root, traversal: traversal, locator: locator, searchPathLoadFailures: []) - } - - init(root: MachO, traversal: DependencyTraversal, locator: some DependencyLocating, searchPathLoadFailures: [DependencySearchPathLoadFailure]) { - var visitedBareImageNames: Set = [DependencyLoadName.bareImageName(of: root.imagePath)] - var collectedImageIdentifiers: Set = [root.identifier] - var images: [MachO] = [] - var unresolvedLoadNames: [String] = [] - var frontier: [MachO] = [root] - - while !frontier.isEmpty { - var nextFrontier: [MachO] = [] - for image in frontier { - for loadName in image.dependencies.map(\.dylib.name) { - let bareImageName = DependencyLoadName.bareImageName(of: loadName) - guard !bareImageName.isEmpty, visitedBareImageNames.insert(bareImageName).inserted else { continue } - guard let dependencyImage = locator.locate(loadName: loadName) else { - unresolvedLoadNames.append(loadName) - continue - } - // Resolved, but to an image already collected under another - // spelling: nothing to add, and nothing to report. - guard collectedImageIdentifiers.insert(dependencyImage.identifier).inserted else { continue } - images.append(dependencyImage) - nextFrontier.append(dependencyImage) - } - } - frontier = traversal == .transitive ? nextFrontier : [] - } - - self.root = root - self.traversal = traversal - self.images = images - self.unresolvedLoadNames = unresolvedLoadNames - self.searchPathLoadFailures = searchPathLoadFailures - } -} - -// MARK: - In-process (MachOImage) - -extension DependencyClosure where MachO == MachOImage { - /// Resolves an in-process image's dependencies through the active dyld - /// (`InProcessDependencyLocator`). - public init(root: MachOImage, traversal: DependencyTraversal = .transitive) { - self.init(root: root, traversal: traversal, locator: InProcessDependencyLocator()) - } -} - -// MARK: - Offline (MachOFile) - -extension DependencyClosure where MachO == MachOFile { - /// Resolves a file-backed image's dependencies through `searchPaths` - /// (`FileDependencyLocator`). Fat explicit files contribute the slice - /// matching the root's architecture; cache images built for none of the - /// root's platforms are not candidates (`DependencyPlatforms`). - /// - /// A root read out of a dyld shared cache resolves in that cache before - /// any search path, as dyld resolves it. The search paths' default, the - /// running system's cache, would otherwise lay an image of an archived - /// cache out against the host's frameworks: macOS 15.5's `URL` is 24 bytes, - /// the host's 16 from macOS 26 on. - public init(root: MachOFile, searchPaths: [DependencySearchPath] = [.systemDyldSharedCache], traversal: DependencyTraversal = .transitive) { - // The cache instance the root was read from, when it came through a - // `FullDyldCache`, is searched as is; a root read from one cache file - // names that cache's main file instead. Never `root.fullCache`: it - // opens the cache on first use and stores it on the root, unguarded, - // and closures over one root are built from several threads. - let rootDyldCache = root._cachedFullCache - var rootCacheSearchPaths: [DependencySearchPath] = [] - if rootDyldCache == nil, root.isLoadedFromDyldCache, let mainCacheFileURL = Self.mainCacheFileURL(ofCacheFileAt: root.url) { - rootCacheSearchPaths.append(.dyldSharedCache(path: mainCacheFileURL.path)) - } - let locator = FileDependencyLocator( - searchPaths: rootCacheSearchPaths + searchPaths, - preferredCPU: root.header.cpu, - platforms: DependencyPlatforms.platforms(of: root), - rootDyldCache: rootDyldCache - ) - self.init(root: root, traversal: traversal, locator: locator, searchPathLoadFailures: locator.loadFailures) - } - - /// The main file of the cache a cache file belongs to: every other file - /// of a cache (`dyld_shared_cache_arm64e.01`, `.25.dylddata`, - /// `.26.dyldreadonly`, `.81.dyldlinkedit`) is named by it plus one or two - /// extensions, which is how MachOKit's `fullCache` derives it too. - static func mainCacheFileURL(ofCacheFileAt url: URL) -> URL? { - var candidate = url - for _ in 0 ... 2 { - if DependencySearchPath.isMainCacheFileName(candidate.lastPathComponent, architectureName: nil) { - return candidate - } - guard !candidate.pathExtension.isEmpty else { return nil } - candidate = candidate.deletingPathExtension() - } - return nil - } -} diff --git a/Sources/MachO/MachODependencies/DependencyLoadName.swift b/Sources/MachO/MachODependencies/DependencyLoadName.swift deleted file mode 100644 index 0424b34af..000000000 --- a/Sources/MachO/MachODependencies/DependencyLoadName.swift +++ /dev/null @@ -1,20 +0,0 @@ -/// Helpers over the dylib load names recorded in `LC_LOAD_DYLIB`-family load -/// commands (`@rpath/Foo.framework/Versions/A/Foo`, -/// `/usr/lib/swift/libswiftCore.dylib`, …). -public enum DependencyLoadName { - /// The bare image name a load name identifies: the last path component with - /// its first extension component stripped (`Foo`, `libswiftCore`). - /// - /// This is deliberately the same rule `MachOImage(name:)` applies to the - /// images dyld has mapped, so a load name normalized here can be handed - /// straight to the in-process lookup — passing the un-normalized load name - /// never matches, because dyld reports absolute paths and the lookup - /// compares bare names. It is also the key every dependency set is - /// deduplicated on: the same library is linked under different spellings - /// by different images (`@rpath/…` by a sibling, an absolute path by a - /// system framework), and only the bare name is stable across them. - public static func bareImageName(of loadName: String) -> String { - let lastPathComponent = loadName.components(separatedBy: "/").last ?? loadName - return lastPathComponent.components(separatedBy: ".").first ?? lastPathComponent - } -} diff --git a/Sources/MachO/MachODependencies/DependencyLocating.swift b/Sources/MachO/MachODependencies/DependencyLocating.swift deleted file mode 100644 index 76fef1f9a..000000000 --- a/Sources/MachO/MachODependencies/DependencyLocating.swift +++ /dev/null @@ -1,56 +0,0 @@ -#if canImport(Darwin) -import Darwin -#endif -import MachOKit -import MachOKitExtensions - -/// Turns a dependency load name into a concrete image of the root's reader -/// type — the one seam `DependencyClosure` needs, so the traversal is -/// independent of *where* images come from (the active dyld, a set of search -/// paths, or a test's hand-built table). -public protocol DependencyLocating { - associatedtype MachO: MachORepresentableWithCache - - /// The image `loadName` refers to, or `nil` when this locator cannot find - /// it. `loadName` is the raw load-command spelling; implementations - /// normalize it themselves (see `DependencyLoadName.bareImageName(of:)`). - func locate(loadName: String) -> MachO? -} - -/// Resolves dependencies through the active dyld: system frameworks resolve -/// from the shared cache automatically, and locally loaded frameworks resolve -/// as long as they are already mapped into this process. -/// -/// Answers from a table of the images dyld had mapped when the locator was -/// made: one pass over them, keeping the first image per bare name — the -/// image `MachOImage(name:)` picks, by the same naming rule — instead of that -/// initializer's own pass per lookup. A closure of a few hundred -/// dependencies, in a process with a thousand images mapped, split the same -/// paths hundreds of thousands of times and kept every other printing task -/// waiting on its catalog meanwhile (evolution proposal -/// `faster-lazy-definition-indexing`). An image mapped after the locator was -/// made is not found by it; a new locator sees it. -public struct InProcessDependencyLocator: DependencyLocating, Sendable { - /// Per bare name, the first mapped image carrying it — `nil` when dyld - /// had no header for that image, as `MachOImage(name:)` answers then. - private let imagesByBareName: [String: MachOImage?] - - public init() { - var imagesByBareName: [String: MachOImage?] = [:] - #if canImport(Darwin) - for index in 0 ..< _dyld_image_count() { - guard let pathC = _dyld_get_image_name(index) else { continue } - let bareImageName = DependencyLoadName.bareImageName(of: String(cString: pathC)) - guard imagesByBareName[bareImageName] == nil else { continue } - imagesByBareName.updateValue(_dyld_get_image_header(index).map { MachOImage(ptr: $0) }, forKey: bareImageName) - } - #endif - self.imagesByBareName = imagesByBareName - } - - public func locate(loadName: String) -> MachOImage? { - let bareImageName = DependencyLoadName.bareImageName(of: loadName) - guard !bareImageName.isEmpty, let image = imagesByBareName[bareImageName] else { return nil } - return image - } -} diff --git a/Sources/MachO/MachODependencies/DependencyPlatforms.swift b/Sources/MachO/MachODependencies/DependencyPlatforms.swift deleted file mode 100644 index 937c6a2ef..000000000 --- a/Sources/MachO/MachODependencies/DependencyPlatforms.swift +++ /dev/null @@ -1,43 +0,0 @@ -import MachOKit - -/// The platforms a Mach-O declares itself built for, as `FileDependencyLocator` -/// compares a root binary against a dyld shared cache's images (evolution -/// proposal `objc-ancestor-dependency-closure`). -/// -/// A cache is a per-platform artifact, but the running system's cache is the -/// default search path for every root, and a macOS cache carries the Mac -/// Catalyst builds of UIKit, SwiftUI and friends under `/System/iOSSupport` -/// wearing the same bare names an iOS root links. Ranking demotes them behind -/// a native build, but for an iOS root there is no native build to win, so -/// the bare-name fallback handed back a Catalyst UIKit — same class names, -/// different platform, different method tables — and every consumer reading -/// facts out of it (an ObjC ancestor's selectors, an instance size) read the -/// wrong platform's. The locator now skips a cache image whose platforms are -/// disjoint from the root's. -public enum DependencyPlatforms { - /// Every `LC_BUILD_VERSION` platform (a zippered macOS + Mac Catalyst - /// image carries two); with none, the platform an `LC_VERSION_MIN_*` - /// command implies; empty when the image declares nothing — an old or - /// unusual binary, which the guard then lets through rather than - /// refusing every candidate. - public static func platforms(of machO: some MachORepresentable) -> Set { - let loadCommands = machO.loadCommands - let declared = Set(loadCommands.infos(of: LoadCommand.buildVersion).map(\.platform)) - if !declared.isEmpty { return declared } - var implied: Set = [] - if loadCommands.info(of: LoadCommand.versionMinMacosx) != nil { implied.insert(.macOS) } - if loadCommands.info(of: LoadCommand.versionMinIphoneos) != nil { implied.insert(.iOS) } - if loadCommands.info(of: LoadCommand.versionMinTvos) != nil { implied.insert(.tvOS) } - if loadCommands.info(of: LoadCommand.versionMinWatchos) != nil { implied.insert(.watchOS) } - return implied - } - - /// Whether an image built for `candidatePlatforms` may stand in for a - /// dependency of a root built for `rootPlatforms`: the two share a - /// platform, or one side declares none. A simulator platform and its - /// device platform are distinct — an `iOSSimulator` root never takes an - /// `iOS` cache's image, nor a `macCatalyst` one. - public static func areCompatible(_ rootPlatforms: Set, _ candidatePlatforms: Set) -> Bool { - rootPlatforms.isEmpty || candidatePlatforms.isEmpty || !rootPlatforms.isDisjoint(with: candidatePlatforms) - } -} diff --git a/Sources/MachO/MachODependencies/DependencySearchPath.swift b/Sources/MachO/MachODependencies/DependencySearchPath.swift deleted file mode 100644 index 6ded87fc0..000000000 --- a/Sources/MachO/MachODependencies/DependencySearchPath.swift +++ /dev/null @@ -1,165 +0,0 @@ -import Foundation -import MachOKit - -/// Where an offline (`MachOFile`) dependency locator may look for a dependency -/// binary. Cache-resident system frameworks (the stdlib, Foundation, the rest -/// of the OS) resolve through a dyld shared cache; a system tree that still -/// ships them as files (an iOS 26 or earlier simulator runtime's -/// `RuntimeRoot`) resolves through a system root; anything else — a sibling -/// framework reached through `@rpath`, a test helper next to the root binary — -/// has to be handed over as an explicit file, because `@rpath` / -/// `@loader_path` / `@executable_path` are not expanded. -public enum DependencySearchPath: Sendable, Hashable, Codable, CustomStringConvertible { - /// An explicit on-disk path to a Mach-O (or fat) binary file. - case machOFile(path: String) - /// An explicit path to a dyld shared cache file. - case dyldSharedCache(path: String) - /// The running system's active dyld shared cache. - case systemDyldSharedCache - /// A directory an absolute load name is resolved under: the dependency - /// `/System/Library/Frameworks/Foo.framework/Foo` is looked for at - /// `/System/Library/Frameworks/Foo.framework/Foo`. What a simulator - /// runtime's `RuntimeRoot` is to its frameworks, before iOS 27 moved them - /// into a cache. Load names that are not absolute never match here. - case systemRoot(path: String) - - public var description: String { - switch self { - case .machOFile(let path): - return "machOFile(\(path))" - case .dyldSharedCache(let path): - return "dyldSharedCache(\(path))" - case .systemDyldSharedCache: - return "systemDyldSharedCache" - case .systemRoot(let path): - return "systemRoot(\(path))" - } - } -} - -extension DependencySearchPath { - /// The search path a user-supplied path most plausibly means, by its - /// shape: a directory is a ``systemRoot(path:)``, a file named like a - /// main dyld cache (`dyld_shared_cache_arm64e`, - /// `dyld_sim_shared_cache_arm64`) is a ``dyldSharedCache(path:)``, and - /// any other file is a ``machOFile(path:)``. For a command-line option - /// that takes all three without asking the user to spell the kind. - public init(classifyingPath path: String) { - var isDirectory: ObjCBool = false - if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue { - self = .systemRoot(path: path) - } else if Self.isMainCacheFileName(URL(fileURLWithPath: path).lastPathComponent, architectureName: nil) { - self = .dyldSharedCache(path: path) - } else { - self = .machOFile(path: path) - } - } - - /// The search paths a root binary's own location on disk implies. - /// - /// Two shapes are recognized, nearest ancestor first: - /// - /// 1. **A system tree carrying its own dyld cache** — an ancestor - /// directory with `System/Library/Caches/com.apple.dyld/` (iOS-family - /// and iOS 27+ simulator runtimes: `dyld_sim_shared_cache_arm64`) or - /// `System/Library/dyld/` (macOS) holding a main cache file for the - /// root's architecture. Each such cache becomes - /// ``dyldSharedCache(path:)``. - /// 2. **A system tree carrying its frameworks as files** — the root's - /// on-disk path ends with its own install name - /// (`…/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI` - /// for `/System/Library/Frameworks/SwiftUI.framework/SwiftUI`), so the - /// prefix is a ``systemRoot(path:)``. - /// - /// The filesystem root itself is never a candidate: the host's own cache - /// is ``systemDyldSharedCache``'s business. A binary that sits in neither - /// shape — a third-party app under `/Applications`, a build product — - /// infers nothing, and its caller adds the host cache or explicit paths. - public static func inferred(forRoot root: MachOFile) -> [DependencySearchPath] { - inferred(forRootFileAt: root.url, installName: root.imagePath, architectureName: architectureName(of: root.header.cpu)) - } - - /// ``inferred(forRoot:)`` over the three facts it reads off the file. - /// `architectureName` (`arm64`, `arm64e`, `x86_64`) selects among the - /// caches a directory carries; `nil` accepts every main cache file there. - public static func inferred(forRootFileAt url: URL, installName: String, architectureName: String?) -> [DependencySearchPath] { - let fileManager = FileManager.default - var ancestor = url.standardizedFileURL.deletingLastPathComponent() - while ancestor.path != "/", !ancestor.path.isEmpty { - var caches: [DependencySearchPath] = [] - for cacheDirectory in Self.cacheDirectoriesUnderSystemTree { - let directory = ancestor.appendingPathComponent(cacheDirectory) - guard let entries = try? fileManager.contentsOfDirectory(atPath: directory.path) else { continue } - for entry in entries.sorted() where Self.isMainCacheFileName(entry, architectureName: architectureName) { - caches.append(.dyldSharedCache(path: directory.appendingPathComponent(entry).path)) - } - } - if !caches.isEmpty { return caches } - let parent = ancestor.deletingLastPathComponent() - guard parent.path != ancestor.path else { break } - ancestor = parent - } - if installName.hasPrefix("/"), url.path.hasSuffix(installName) { - let systemRoot = String(url.path.dropLast(installName.count)) - if !systemRoot.isEmpty { return [.systemRoot(path: systemRoot)] } - } - return [] - } - - /// The directories, relative to a system tree's root, dyld caches live in. - private static let cacheDirectoriesUnderSystemTree = [ - "System/Library/Caches/com.apple.dyld", - "System/Library/dyld", - ] - - /// Whether `fileName` is a *main* cache file (`dyld_shared_cache_arm64e`, - /// `dyld_sim_shared_cache_arm64`) rather than a subcache (`.01`), a - /// `.map` / `.atlas` / `.symbols` companion, or another architecture's. - static func isMainCacheFileName(_ fileName: String, architectureName: String?) -> Bool { - for prefix in ["dyld_shared_cache_", "dyld_sim_shared_cache_"] where fileName.hasPrefix(prefix) { - let suffix = fileName.dropFirst(prefix.count) - guard !suffix.isEmpty, suffix.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" }) else { return false } - guard let architectureName else { return true } - return suffix == architectureName - } - return false - } - - /// The architecture spelling a cache file name carries, for the root's CPU. - static func architectureName(of cpu: CPU) -> String? { - switch cpu.type { - case .arm64: - if case .arm64(.arm64e) = cpu.subtype { return "arm64e" } - return "arm64" - case .x86_64: - return "x86_64" - default: - return nil - } - } -} - -/// Why a search path contributed nothing. Recorded on the closure rather than -/// thrown: one unusable search path must not fail the whole resolution, and -/// this module sits below the event layer, so the host decides where the -/// degradation is reported. -public enum DependencySearchPathError: Error, Sendable, Equatable { - /// The file loaded but yielded no Mach-O slice. - case noMachOSlice(path: String) - /// `FullDyldCache.cachedHost` returned `nil` — the platform exposes no shared - /// cache file to this process. - case systemDyldSharedCacheUnavailable - /// A ``DependencySearchPath/systemRoot(path:)`` that is not a directory. - case systemRootIsNotADirectory(path: String) -} - -/// A search path that could not be opened, paired with the reason. -public struct DependencySearchPathLoadFailure: Sendable { - public let searchPath: DependencySearchPath - public let error: any Error - - public init(searchPath: DependencySearchPath, error: any Error) { - self.searchPath = searchPath - self.error = error - } -} diff --git a/Sources/MachO/MachODependencies/FileDependencyLocator.swift b/Sources/MachO/MachODependencies/FileDependencyLocator.swift deleted file mode 100644 index 002f42d2c..000000000 --- a/Sources/MachO/MachODependencies/FileDependencyLocator.swift +++ /dev/null @@ -1,252 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions - -/// Locates dependency `MachOFile`s across a set of search paths, for a root -/// binary read from disk (no running process to ask). -/// -/// Two lookups, in order: -/// -/// 1. **Exact install path.** A system framework's load name is the absolute -/// path the cache image also reports as its `imagePath`, so this is the -/// compiler's own answer whenever it applies. -/// 2. **Bare name, ranked.** Load names that are not absolute (`@rpath/…`) or -/// that spell a path the cache does not use fall back to the bare image -/// name. Leaf names are not unique inside a shared cache — a macOS cache -/// carries the Mac Catalyst build of SwiftUI under `/System/iOSSupport` -/// next to the native one, and iOS caches ship an `.axbundle` wearing the -/// framework's name — so candidates are ranked with -/// `DyldCacheImageSearchMode.matchRank(forImagePath:)` (canonical framework -/// binary, then plain dylib, then bundle; support-root builds demoted) -/// instead of taking whichever image the cache enumerates first. -/// -/// The cache a root was read from, when it was, is searched before every -/// search path (`rootDyldCache`): dyld resolves a cache image's dependencies -/// in its own cache. -/// -/// A system root (``DependencySearchPath/systemRoot(path:)``) sits between the -/// two: an absolute load name is joined onto the root and opened if a file is -/// there — the tree's own layout is the index, so nothing is scanned up front -/// and each file is opened once, on the first lookup that names it. -/// -/// Explicit files are indexed eagerly at construction. Each dyld shared cache -/// is indexed **once**, lazily, on the first lookup that reaches the caches — -/// one pass over `machOFiles()` rather than a fresh per-lookup scan, which -/// would cost `O(dependencies × cache size)` (measured at 21 s over a -/// 551-image closure before this was made one-shot). -/// -/// A cache image is a candidate only when its platforms are compatible with -/// the root's (`DependencyPlatforms`): the running system's macOS cache is -/// the default search path for every root, and it carries the Mac Catalyst -/// builds of UIKit and SwiftUI under `/System/iOSSupport` — the only images -/// wearing those bare names, which an iOS root would otherwise resolve to. -/// Explicit files and system-root files are the caller's own choice and are -/// never filtered. A load name every candidate was rejected for lands in the -/// closure's `unresolvedLoadNames`, as any other miss does. -public final class FileDependencyLocator: DependencyLocating, @unchecked Sendable { - /// Search paths that could not be opened. Never thrown: one bad path must - /// not fail the whole resolution. - public let loadFailures: [DependencySearchPathLoadFailure] - - private let explicitFilesByInstallPath: [String: MachOFile] - private let explicitFilesByBareName: [String: MachOFile] - private let systemRoots: [String] - private let preferredCPU: CPU? - private let platforms: Set - private let caches: [FullDyldCache] - private let cacheIndexLock = NSLock() - private var cacheIndex: CacheImageIndex? - private let systemRootFilesLock = NSLock() - private var systemRootFilesByLoadName: [String: MachOFile?] = [:] - - /// - Parameters: - /// - searchPaths: Consulted in order; the first explicit file registered - /// under a name wins, and the first cache image with the best rank wins. - /// - preferredCPU: For a fat explicit file, the slice to pick — the root - /// binary's own architecture, so a universal dependency is laid out - /// for the same target as the root. Matched on CPU type plus subtype - /// (so arm64 and arm64e are told apart), then on type alone, then the - /// first slice. - /// - platforms: The root binary's platforms (`DependencyPlatforms.platforms(of:)`); - /// a cache image built for none of them is not a candidate. Empty - /// accepts every image. - /// - rootDyldCache: The dyld shared cache the root was read from, when - /// it was: searched before every search path, as the instance the root - /// came from. A search path naming the same cache does not open it a - /// second time. - public init(searchPaths: [DependencySearchPath], preferredCPU: CPU? = nil, platforms: Set = [], rootDyldCache: FullDyldCache? = nil) { - var explicitFilesByInstallPath: [String: MachOFile] = [:] - var explicitFilesByBareName: [String: MachOFile] = [:] - var systemRoots: [String] = [] - var caches: [FullDyldCache] = rootDyldCache.map { [$0] } ?? [] - var loadFailures: [DependencySearchPathLoadFailure] = [] - - for searchPath in searchPaths { - switch searchPath { - case .systemRoot(let path): - var isDirectory: ObjCBool = false - if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue { - systemRoots.append(path.hasSuffix("/") ? String(path.dropLast()) : path) - } else { - loadFailures.append(.init(searchPath: searchPath, error: DependencySearchPathError.systemRootIsNotADirectory(path: path))) - } - case .machOFile(let path): - do { - let slices = try File.loadFromFile(url: URL(fileURLWithPath: path)).machOFiles - guard let machOFile = Self.preferredSlice(among: slices, preferredCPU: preferredCPU) else { - throw DependencySearchPathError.noMachOSlice(path: path) - } - // A file's `imagePath` is its install name (`LC_ID_DYLIB`, - // typically `@rpath/…`), not its on-disk path, so both - // spellings are registered for the exact lookup, and the - // supplied path's bare name for the fallback. - for installPath in [path, machOFile.imagePath] where explicitFilesByInstallPath[installPath] == nil { - explicitFilesByInstallPath[installPath] = machOFile - } - let bareImageName = DependencyLoadName.bareImageName(of: path) - if !bareImageName.isEmpty, explicitFilesByBareName[bareImageName] == nil { - explicitFilesByBareName[bareImageName] = machOFile - } - } catch { - loadFailures.append(.init(searchPath: searchPath, error: error)) - } - case .dyldSharedCache(let path): - if let rootDyldCache, Self.isSameFile(rootDyldCache.url, URL(fileURLWithPath: path)) { - continue - } - do { - caches.append(try FullDyldCache(url: URL(fileURLWithPath: path))) - } catch { - loadFailures.append(.init(searchPath: searchPath, error: error)) - } - case .systemDyldSharedCache: - // Opened once per process: `host` opens and maps every file of - // the system's cache each time it is read, and a locator is - // built for every root. - if let hostCache = FullDyldCache.cachedHost { - if hostCache !== rootDyldCache { - caches.append(hostCache) - } - } else { - loadFailures.append(.init(searchPath: searchPath, error: DependencySearchPathError.systemDyldSharedCacheUnavailable)) - } - } - } - - self.explicitFilesByInstallPath = explicitFilesByInstallPath - self.explicitFilesByBareName = explicitFilesByBareName - self.systemRoots = systemRoots - self.preferredCPU = preferredCPU - self.platforms = platforms - self.caches = caches - self.loadFailures = loadFailures - } - - public func locate(loadName: String) -> MachOFile? { - if let explicitFile = explicitFilesByInstallPath[loadName] { - return explicitFile - } - let bareImageName = DependencyLoadName.bareImageName(of: loadName) - guard !bareImageName.isEmpty else { return nil } - if let explicitFile = explicitFilesByBareName[bareImageName] { - return explicitFile - } - if let systemRootFile = systemRootFile(forLoadName: loadName) { - return systemRootFile - } - guard !caches.isEmpty else { return nil } - let index = builtCacheIndex() - if let cacheImage = index.imagesByInstallPath[loadName] { - return cacheImage - } - return index.bestImagesByBareName[bareImageName]?.machOFile - } - - /// Compared on `CPU.type` and `CPU.subtype` rather than `CPU ==`: the - /// struct's synthesized equality includes the raw subtype's capability - /// bits (the arm64e pointer-authentication ABI version and versioned-ABI - /// flag under `CPU_SUBTYPE_MASK`), so a versioned-ABI arm64e slice would - /// compare unequal to a plain arm64e root and silently fall through to - /// the type-only match — the arm64 / arm64e confusion this exists to - /// avoid. `subtype` masks those bits. - private static func preferredSlice(among slices: [MachOFile], preferredCPU: CPU?) -> MachOFile? { - guard let preferredCPU else { return slices.first } - if let exactSlice = slices.first(where: { $0.header.cpu.type == preferredCPU.type && $0.header.cpu.subtype == preferredCPU.subtype }) { - return exactSlice - } - if let sameTypeSlice = slices.first(where: { $0.header.cpu.type == preferredCPU.type }) { - return sameTypeSlice - } - return slices.first - } - - /// Whether two file URLs name one file, through symbolic links and - /// `..` components alike. - private static func isSameFile(_ firstURL: URL, _ secondURL: URL) -> Bool { - firstURL.standardizedFileURL.resolvingSymlinksInPath().path == secondURL.standardizedFileURL.resolvingSymlinksInPath().path - } - - // MARK: - System roots - - /// The file an absolute load name names under the first system root that - /// has one. Opened once per load name; a path that exists but is not a - /// Mach-O counts as a miss, not a failure. - private func systemRootFile(forLoadName loadName: String) -> MachOFile? { - guard !systemRoots.isEmpty, loadName.hasPrefix("/") else { return nil } - systemRootFilesLock.lock() - defer { systemRootFilesLock.unlock() } - if let located = systemRootFilesByLoadName[loadName] { return located } - var located: MachOFile? - for systemRoot in systemRoots { - let path = systemRoot + loadName - guard FileManager.default.fileExists(atPath: path), - let slices = try? File.loadFromFile(url: URL(fileURLWithPath: path)).machOFiles, - let machOFile = Self.preferredSlice(among: slices, preferredCPU: preferredCPU) - else { continue } - located = machOFile - break - } - systemRootFilesByLoadName[loadName] = located - return located - } - - // MARK: - One-shot cache index - - private struct CacheImageIndex { - var imagesByInstallPath: [String: MachOFile] = [:] - var bestImagesByBareName: [String: (rank: Int, machOFile: MachOFile)] = [:] - } - - /// Rank given to a cache image whose path the `DyldCacheImageSearchMode` - /// name rule does not recognize under its bare name (a multi-dotted leaf - /// such as `libc++.1.dylib`, whose `deletingPathExtension` form is not the - /// bare name). It still resolves — every entry under a key legitimately - /// carries that bare name — it just loses to any recognized shape. - private static let unrankedShapeRank = Int.max - - private func builtCacheIndex() -> CacheImageIndex { - cacheIndexLock.lock() - defer { cacheIndexLock.unlock() } - if let cacheIndex { return cacheIndex } - - var index = CacheImageIndex() - for cache in caches { - for machOFile in cache.machOFiles() { - guard DependencyPlatforms.areCompatible(platforms, DependencyPlatforms.platforms(of: machOFile)) else { continue } - let installPath = machOFile.imagePath - if index.imagesByInstallPath[installPath] == nil { - index.imagesByInstallPath[installPath] = machOFile - } - let bareImageName = DependencyLoadName.bareImageName(of: installPath) - guard !bareImageName.isEmpty else { continue } - let rank = DyldCacheImageSearchMode.name(bareImageName).matchRank(forImagePath: installPath) ?? Self.unrankedShapeRank - if let existing = index.bestImagesByBareName[bareImageName], existing.rank <= rank { - continue - } - index.bestImagesByBareName[bareImageName] = (rank, machOFile) - } - } - cacheIndex = index - return index - } -} diff --git a/Sources/MachO/MachODependencies/SharedDependencyClosure.swift b/Sources/MachO/MachODependencies/SharedDependencyClosure.swift deleted file mode 100644 index 0ace2a493..000000000 --- a/Sources/MachO/MachODependencies/SharedDependencyClosure.swift +++ /dev/null @@ -1,38 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions - -/// A `DependencyClosure` resolved once, on first use, and shared by every -/// consumer of one root — the property-wrapper catalog and the ObjC ancestor -/// resolver both ask for a file's dependency images lazily, and resolving -/// the closure twice would index every search-path cache twice (one pass over -/// a cache's images each; see `FileDependencyLocator`). -public final class SharedDependencyClosure: @unchecked Sendable { - private let resolve: @Sendable () -> DependencyClosure - private let lock = NSLock() - private var resolved: DependencyClosure? - - /// - Parameter resolve: Resolves the closure; called at most once, on the - /// first read of ``closure``, outside any lock the caller holds. - public init(_ resolve: @escaping @Sendable () -> DependencyClosure) { - self.resolve = resolve - } - - /// The closure, resolved on first read. Concurrent first readers - /// serialize on the resolution; later reads are a lookup. - public var closure: DependencyClosure { - lock.lock() - defer { lock.unlock() } - if let resolved { return resolved } - let closure = resolve() - resolved = closure - return closure - } - - /// Whether ``closure`` has been read yet. - public var isResolved: Bool { - lock.lock() - defer { lock.unlock() } - return resolved != nil - } -} diff --git a/Sources/MachO/MachOFoundation/Exported.swift b/Sources/MachO/MachOFoundation/Exported.swift deleted file mode 100644 index 48103864f..000000000 --- a/Sources/MachO/MachOFoundation/Exported.swift +++ /dev/null @@ -1,3 +0,0 @@ -@_exported import MachOBase -@_exported import MachODependencies -@_exported import MachOSymbols diff --git a/Sources/MachO/MachOPointers/Bit.swift b/Sources/MachO/MachOPointers/Bit.swift deleted file mode 100644 index 95e6c9f86..000000000 --- a/Sources/MachO/MachOPointers/Bit.swift +++ /dev/null @@ -1,16 +0,0 @@ -/// A single-bit value extracted from a relative pointer int pair. -/// -/// Used as the `Value` generic parameter for `TargetRelativeIndirectablePointerIntPair` -/// instead of `Bool`, avoiding the need for a retroactive `Bool: RawRepresentable` -/// conformance that can fail to register in code injection contexts. -public struct Bit: RawRepresentable, Sendable, Equatable, Hashable { - public let rawValue: UInt8 - - public init?(rawValue: UInt8) { - self.rawValue = rawValue - } - - public var boolValue: Bool { - rawValue != 0 - } -} diff --git a/Sources/MachO/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift b/Sources/MachO/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift deleted file mode 100644 index 285721687..000000000 --- a/Sources/MachO/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift +++ /dev/null @@ -1,34 +0,0 @@ -import BinaryParseSupport -import MachOKitExtensions - -extension LocatableLayoutWrapper { - /// The file offset a relative direct pointer field resolves to, or `nil` - /// when the field is null. - /// - /// Every record holding a relative pointer resolves it the same three - /// ways — check for null, take the field's own location, add the stored - /// delta — so the key path is the only thing that differs. It also names - /// the field at the call site, which is what a per-field wrapper property - /// would have said and nothing more. - /// - /// Pure pointer arithmetic: no reader is involved, and the result is in - /// the same coordinate space as ``offset``. Attributing a symbol to that - /// offset belongs a layer up, in `SwiftInspection`. - /// - /// The key path must address a **stored** property of the concrete - /// `Layout`. One formed inside a generic context against a layout - /// *protocol* addresses a witness instead, and the offset lookup behind - /// this answers nil for it — so a shared implementation over a layout - /// protocol cannot use this; each conformer must call it itself. - /// - /// The field may be any relative pointer, but the offset is always the - /// **direct** reading. For a relative-*indirectable* field that is only - /// the target when the indirect bit is clear — when it is set, the offset - /// names the slot holding the pointer, not the pointee — so such a field's - /// caller must rule out `isIndirect` itself before trusting the result. - public func resolvedDirectOffset(from keyPath: KeyPath) -> Int? { - let pointer = layout[keyPath: keyPath] - guard pointer.isValid else { return nil } - return pointer.resolveDirectOffset(from: offset(of: keyPath)) - } -} diff --git a/Sources/MachO/MachOPointers/Pointer.swift b/Sources/MachO/MachOPointers/Pointer.swift deleted file mode 100644 index 1d9b7fe53..000000000 --- a/Sources/MachO/MachOPointers/Pointer.swift +++ /dev/null @@ -1,40 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public struct Pointer: RelativeIndirectType, PointerProtocol { - public typealias Resolved = Pointee - - public let address: UInt64 - - public init(address: UInt64) { - self.address = address - } - - /// Reads the pointer stored at `address`. In a file the stored bytes of a - /// rebased slot are a chained-fixup encoding, not an address; the rebase - /// table says what dyld writes there at load time. - public static func resolve(at address: Context.Address, in context: Context) throws -> Pointer where Context : ReadingContext { - if let resolver = context.bindRebaseResolver, let rebase = resolver.resolveRebase(fileOffset: try context.offsetFromAddress(address)) { - return .init(address: rebase) - } - return try context.readElement(at: address) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } -} - -public typealias RawPointer = Pointer - -public typealias MetadataPointer = Pointer - -public typealias ConstMetadataPointer = MetadataPointer diff --git a/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift deleted file mode 100644 index 9f4acb388..000000000 --- a/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift +++ /dev/null @@ -1,99 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public protocol PointerProtocol: Resolvable, Sendable, Equatable { - associatedtype Pointee: Resolvable - - var address: UInt64 { get } - - func resolve(in context: some ReadingContext) throws -> Pointee - func resolveAny(in context: some ReadingContext) throws -> T - func resolveAddress(in context: Context) throws -> Context.Address - - // The deprecated forms stay requirements, unlike everywhere else: `Pointer` - // conforms to this protocol and to `RelativeIndirectType`, which declares - // the same members, and two unrelated protocol extensions each providing - // them would make every call on a `Pointer` ambiguous. A requirement and - // its default deprecated together warn only at call sites. - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - func resolve() throws -> Pointee - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: .inProcess).") - func resolveAny() throws -> T - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: machO.context).") - func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T - @available(*, deprecated, message: "Pass a ReadingContext: resolveAddress(in: machO.context).") - func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int -} - -extension PointerProtocol { - public func resolve(in context: some ReadingContext) throws -> Pointee { - return try Pointee.resolve(at: resolveAddress(in: context), in: context) - } - - public func resolveAny(in context: some ReadingContext) throws -> T { - return try T.resolve(at: resolveAddress(in: context), in: context) - } - - public func resolveAddress(in context: Context) throws -> Context.Address { - return try context.addressFromVirtualAddress(address) - } -} - -// MARK: - Deprecated Mach-O and pointer forms - -extension PointerProtocol { - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - public func resolve() throws -> Pointee { - try resolve(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: .inProcess).") - public func resolveAny() throws -> T { - try resolveAny(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolve(in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: machO.context).") - public func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T { - try resolveAny(in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAddress(in: machO.context).") - public func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int { - // `MachOContext` converts addresses without failing; the requirement - // is declared `throws` only for the contexts that can. - try! resolveAddress(in: machO.context) - } -} - -extension PointerProtocol where Pointee: OptionalProtocol { - public func resolve(in context: some ReadingContext) throws -> Pointee { - try resolveUnlessNull(in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - public func resolve() throws -> Pointee { - try resolveUnlessNull(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolveUnlessNull(in: machO.context) - } - - /// A null pointer resolves to `nil`. The deprecated forms call this - /// rather than `resolve(in:)`, which from here binds to the protocol - /// requirement and skips the check. - private func resolveUnlessNull(in context: some ReadingContext) throws -> Pointee { - guard address != 0 else { return nil } - return try resolve(in: context) - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift deleted file mode 100644 index aaafaca3f..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift +++ /dev/null @@ -1,27 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -public protocol RelativeDirectPointerIntPairProtocol: RelativeDirectPointerProtocol { - typealias Integer = Value.RawValue - associatedtype Value: RawRepresentable where Value.RawValue: FixedWidthInteger - var relativeOffsetPlusInt: Offset { get } -} - -extension RelativeDirectPointerIntPairProtocol { - public var relativeOffset: Offset { - relativeOffsetPlusInt & ~mask - } - - public var mask: Offset { - Offset(MemoryLayout.alignment - 1) - } - - public var intValue: Integer { - numericCast(relativeOffsetPlusInt & mask) - } - - public var value: Value { - return Value(rawValue: intValue)! - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift deleted file mode 100644 index c163bd80e..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift +++ /dev/null @@ -1,62 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions -import MachOResolving - -public protocol RelativeDirectPointerProtocol: RelativePointerProtocol {} - -extension RelativeDirectPointerProtocol { - public func resolve( - at address: Context.Address, - in context: Context - ) throws -> Pointee { - return try resolveDirect(at: address, in: context) - } - - func resolveDirect( - at address: Context.Address, - in context: Context - ) throws -> Pointee { - return try Pointee.resolve(at: resolveDirectAddress(at: address, in: context), in: context) - } - - public func resolveAny( - at address: Context.Address, - in context: Context - ) throws -> T { - return try resolveDirectAny(at: address, in: context) - } - - func resolveDirectAny( - at address: Context.Address, - in context: Context - ) throws -> T { - return try T.resolve(at: resolveDirectAddress(at: address, in: context), in: context) - } -} - -extension RelativeDirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - try resolveUnlessNull(at: address, in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolveUnlessNull(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - try resolveUnlessNull(at: ptr, in: InProcessContext.shared) - } - - /// A null pointer resolves to `nil` instead of the bytes at its own - /// location. The deprecated forms call this rather than - /// `resolve(at:in:)`: from here that name binds to the protocol - /// requirement, whose witness is the unconstrained implementation - /// without this check. - private func resolveUnlessNull(at address: Context.Address, in context: Context) throws -> Pointee { - guard isValid else { return nil } - return try resolve(at: address, in: context) - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift deleted file mode 100644 index 557b5236c..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift +++ /dev/null @@ -1,77 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { - associatedtype IndirectType: RelativeIndirectType where IndirectType.Resolved == Pointee -} - -extension RelativeIndirectPointerProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - return try resolveIndirect(at: address, in: context) - } - - func resolveIndirect(at address: Context.Address, in context: Context) throws -> Pointee { - return try resolveIndirectType(at: address, in: context).resolve(in: context) - } - - public func resolveAny(at address: Context.Address, in context: Context) throws -> T { - return try resolveIndirectAny(at: address, in: context) - } - - func resolveIndirectAny(at address: Context.Address, in context: Context) throws -> T { - return try resolveIndirectType(at: address, in: context).resolveAny(in: context) - } - - public func resolveIndirectType(at address: Context.Address, in context: Context) throws -> IndirectType { - return try .resolve(at: resolveDirectAddress(at: address, in: context), in: context) - } - - public func resolveIndirectOffset(at address: Context.Address, in context: Context) throws -> Context.Address { - return try resolveIndirectType(at: address, in: context).resolveAddress(in: context) - } -} - -// MARK: - Deprecated Mach-O and pointer forms - -extension RelativeIndirectPointerProtocol { - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectType(at: offset, in: machO.context).") - public func resolveIndirectType(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> IndirectType { - try resolveIndirectType(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectOffset(at: offset, in: machO.context).") - public func resolveIndirectOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int { - try resolveIndirectOffset(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectType(at: pointer, in: .inProcess).") - public func resolveIndirectType(from ptr: UnsafeRawPointer) throws -> IndirectType { - try resolveIndirectType(at: ptr, in: InProcessContext.shared) - } -} - -extension RelativeIndirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - try resolveUnlessNull(at: address, in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolveUnlessNull(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - try resolveUnlessNull(at: ptr, in: InProcessContext.shared) - } - - /// A null pointer resolves to `nil`. The deprecated forms call this - /// rather than `resolve(at:in:)`, which from here binds to the protocol - /// requirement and skips the check. - private func resolveUnlessNull(at address: Context.Address, in context: Context) throws -> Pointee { - guard isValid else { return nil } - return try resolve(at: address, in: context) - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift deleted file mode 100644 index 896f09824..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift +++ /dev/null @@ -1,26 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public protocol RelativeIndirectType: Resolvable { - associatedtype Resolved: Resolvable - - func resolve(in context: some ReadingContext) throws -> Resolved - func resolveAny(in context: some ReadingContext) throws -> T - func resolveAddress(in context: Context) throws -> Context.Address - - // The deprecated forms stay requirements for the reason given in - // `PointerProtocol`: `Pointer` conforms to both protocols. - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Resolved - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: machO.context).") - func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T - @available(*, deprecated, message: "Pass a ReadingContext: resolveAddress(in: machO.context).") - func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - func resolve() throws -> Resolved - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: .inProcess).") - func resolveAny() throws -> T -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift deleted file mode 100644 index 1f5cf3428..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift +++ /dev/null @@ -1,60 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -public protocol RelativeIndirectablePointerIntPairProtocol: RelativeIndirectablePointerProtocol { - typealias Integer = Value.RawValue - associatedtype Value: RawRepresentable where Value.RawValue: FixedWidthInteger - var relativeOffsetPlusIndirectAndInt: Offset { get } - var isIndirect: Bool { get } -} - -extension RelativeIndirectablePointerIntPairProtocol { - public var relativeOffsetPlusIndirect: Offset { - relativeOffsetPlusIndirectAndInt & ~mask - } - - public var relativeOffset: Offset { - (relativeOffsetPlusIndirectAndInt & ~mask) & ~1 - } - - public var mask: Offset { - Offset(MemoryLayout.alignment - 1) & ~1 - } - - public var intValue: Integer { - numericCast((relativeOffsetPlusIndirectAndInt & mask) >> 1) - } - - public var isIndirect: Bool { - return relativeOffsetPlusIndirectAndInt & 1 == 1 - } - - public var value: Value { - return Value(rawValue: intValue)! - } -} - -extension RelativeIndirectablePointerIntPairProtocol where Pointee: OptionalProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - try resolveUnlessNull(at: address, in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolveUnlessNull(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - try resolveUnlessNull(at: ptr, in: InProcessContext.shared) - } - - /// A null pointer resolves to `nil`. The deprecated forms call this - /// rather than `resolve(at:in:)`, which from here binds to the protocol - /// requirement and skips the check. - private func resolveUnlessNull(at address: Context.Address, in context: Context) throws -> Pointee { - guard isValid else { return nil } - return try resolve(at: address, in: context) - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift deleted file mode 100644 index 9aac6de21..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift +++ /dev/null @@ -1,100 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { - var relativeOffsetPlusIndirect: Offset { get } - var isIndirect: Bool { get } -} - -extension RelativeIndirectablePointerProtocol { - public var relativeOffset: Offset { - relativeOffsetPlusIndirect & ~1 - } - - public var isIndirect: Bool { - return relativeOffsetPlusIndirect & 1 == 1 - } -} - -extension RelativeIndirectablePointerProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - return try resolveIndirectable(at: address, in: context) - } - - public func resolveAny(at address: Context.Address, in context: Context) throws -> T { - return try resolveIndirectableAny(at: address, in: context) - } - - func resolveIndirectable(at address: Context.Address, in context: Context) throws -> Pointee { - if isIndirect { - return try resolveIndirect(at: address, in: context) - } else { - return try resolveDirect(at: address, in: context) - } - } - - public func resolveIndirectableType(at address: Context.Address, in context: Context) throws -> IndirectType? { - guard isIndirect else { return nil } - return try resolveIndirectType(at: address, in: context) - } - - func resolveIndirectableAny(at address: Context.Address, in context: Context) throws -> T { - if isIndirect { - return try resolveIndirectAny(at: address, in: context) - } else { - return try resolveDirectAny(at: address, in: context) - } - } - - public func resolveIndirectableOffset(at address: Context.Address, in context: Context) throws -> Context.Address { - guard let indirectType = try resolveIndirectableType(at: address, in: context) else { - return try resolveDirectAddress(at: address, in: context) - } - return try indirectType.resolveAddress(in: context) - } -} - -// MARK: - Deprecated Mach-O and pointer forms - -extension RelativeIndirectablePointerProtocol { - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectableType(at: offset, in: machO.context).") - public func resolveIndirectableType(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> IndirectType? { - try resolveIndirectableType(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectableOffset(at: offset, in: machO.context).") - public func resolveIndirectableOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int { - try resolveIndirectableOffset(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveIndirectableType(at: pointer, in: .inProcess).") - public func resolveIndirectableType(from ptr: UnsafeRawPointer) throws -> IndirectType? { - try resolveIndirectableType(at: ptr, in: InProcessContext.shared) - } -} - -extension RelativeIndirectablePointerProtocol where Pointee: OptionalProtocol { - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { - try resolveUnlessNull(at: address, in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolveUnlessNull(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - try resolveUnlessNull(at: ptr, in: InProcessContext.shared) - } - - /// A null pointer resolves to `nil`. The deprecated forms call this - /// rather than `resolve(at:in:)`, which from here binds to the protocol - /// requirement and skips the check. - private func resolveUnlessNull(at address: Context.Address, in context: Context) throws -> Pointee { - guard isValid else { return nil } - return try resolve(at: address, in: context) - } -} diff --git a/Sources/MachO/MachOPointers/Protocol/RelativePointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativePointerProtocol.swift deleted file mode 100644 index f9ac42847..000000000 --- a/Sources/MachO/MachOPointers/Protocol/RelativePointerProtocol.swift +++ /dev/null @@ -1,66 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public protocol RelativePointerProtocol: Sendable, Equatable { - associatedtype Pointee: Resolvable - associatedtype Offset: FixedWidthInteger & SignedInteger - - var relativeOffset: Offset { get } - - func resolve(at address: Context.Address, in context: Context) throws -> Pointee - - func resolveAny(at address: Context.Address, in context: Context) throws -> T - - func resolveDirectOffset(from offset: Int) -> Int - func resolveDirectAddress(at address: Context.Address, in context: Context) throws -> Context.Address - -} - -extension RelativePointerProtocol { - public func resolveDirectOffset(from offset: Int) -> Int { - return Int(offset) + Int(relativeOffset) - } - - public func resolveDirectAddress(at address: Context.Address, in context: Context) throws -> Context.Address { - return context.advanceAddress(address, by: .init(relativeOffset)) - } - - public var isNull: Bool { - return relativeOffset == 0 - } - - public var isValid: Bool { - return relativeOffset != 0 - } -} - -// MARK: - Deprecated Mach-O and pointer forms - -extension RelativePointerProtocol { - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - try resolve(at: ptr, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(at: offset, in: machO.context).") - public func resolveAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - try resolveAny(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(at: pointer, in: .inProcess).") - public func resolveAny(from ptr: UnsafeRawPointer) throws -> T { - try resolveAny(at: ptr, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveDirectAddress(at: pointer, in: .inProcess).") - public func resolveDirectOffset(from ptr: UnsafeRawPointer) throws -> UnsafeRawPointer { - try resolveDirectAddress(at: ptr, in: InProcessContext.shared) - } -} diff --git a/Sources/MachO/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift b/Sources/MachO/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift deleted file mode 100644 index 69b8fdcab..000000000 --- a/Sources/MachO/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift +++ /dev/null @@ -1,3 +0,0 @@ -import MachOKitExtensions - -extension RelativeDirectPointer: LayoutProtocol {} diff --git a/Sources/MachO/MachOPointers/RelativePointers.swift b/Sources/MachO/MachOPointers/RelativePointers.swift deleted file mode 100644 index 3c6edf7b1..000000000 --- a/Sources/MachO/MachOPointers/RelativePointers.swift +++ /dev/null @@ -1,25 +0,0 @@ -import MachOReading -import MachOResolving -import MachOKitExtensions - -public typealias RelativeOffset = Int32 - -public typealias RelativeDirectPointer = TargetRelativeDirectPointer - -public typealias RelativeDirectRawPointer = TargetRelativeDirectPointer - -public typealias RelativeDirectPointerIntPair = TargetRelativeDirectPointerIntPair where Integer.RawValue: FixedWidthInteger - -public typealias RelativeDirectRawPointerIntPair = TargetRelativeDirectPointerIntPair where Integer.RawValue: FixedWidthInteger - -public typealias RelativeIndirectPointer = TargetRelativeIndirectPointer where Pointee == IndirectType.Resolved - -public typealias RelativeIndirectRawPointer = TargetRelativeIndirectPointer> - -public typealias RelativeIndirectablePointer = TargetRelativeIndirectablePointer where Pointee == IndirectType.Resolved - -public typealias RelativeIndirectableRawPointer = TargetRelativeIndirectablePointer> - -public typealias RelativeIndirectablePointerIntPair = TargetRelativeIndirectablePointerIntPair where Pointee == IndirectType.Resolved, Integer.RawValue: FixedWidthInteger - -public typealias RelativeIndirectableRawPointerIntPair = TargetRelativeIndirectablePointerIntPair> where Integer.RawValue: FixedWidthInteger diff --git a/Sources/MachO/MachOPointers/SymbolOrElementPointer.swift b/Sources/MachO/MachOPointers/SymbolOrElementPointer.swift deleted file mode 100644 index 1ee2619d5..000000000 --- a/Sources/MachO/MachOPointers/SymbolOrElementPointer.swift +++ /dev/null @@ -1,115 +0,0 @@ -import MachOKit -import MachOReading -import MachOResolving -import MachOKitExtensions - -public typealias RelativeSymbolOrElementPointer = RelativeIndirectablePointer, SymbolOrElementPointer> - -public typealias RelativeIndirectSymbolOrElementPointer = RelativeIndirectPointer, SymbolOrElementPointer> - -public typealias RelativeSymbolOrElementPointerIntPair = RelativeIndirectablePointerIntPair, Value, SymbolOrElementPointer> where Value.RawValue: FixedWidthInteger - -public enum SymbolOrElementPointer: RelativeIndirectType { - public typealias Resolved = SymbolOrElement - - case symbol(Symbol) - case address(UInt64) - - public func resolve(in context: some ReadingContext) throws -> Resolved { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .address: - return try .element(Element.resolve(at: resolveAddress(in: context), in: context)) - } - } - - public func resolveAddress(in context: Context) throws -> Context.Address { - switch self { - case .symbol(let symbol): - return try context.addressFromOffset(symbol.offset) - case .address(let address): - return try context.addressFromVirtualAddress(address) - } - } - - public func resolveAny(in context: some ReadingContext) throws -> T { - fatalError("resolveAny is not supported for SymbolOrElementPointer with ReadingContext") - } - - /// Reads the pointer stored at `address`: the symbol dyld binds there when - /// the element lives in another image, otherwise the rebased target or - /// the stored address. - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - if let resolver = context.bindRebaseResolver { - let offset = try context.offsetFromAddress(address) - if let symbol = resolver.resolveBind(fileOffset: offset) { - return .symbol(.init(offset: offset, name: symbol)) - } - if let rebase = resolver.resolveRebase(fileOffset: offset) { - return .address(rebase) - } - } - return try .address(context.readElement(at: address)) - } -} - -// MARK: - Deprecated Mach-O and pointer forms - -extension SymbolOrElementPointer { - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - public func resolve() throws -> Resolved { - try resolve(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Resolved { - try resolve(in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAddress(in: machO.context).") - public func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int { - // `MachOContext` converts addresses without failing; the requirement - // is declared `throws` only for the contexts that can. - try! resolveAddress(in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: .inProcess).") - public func resolveAny() throws -> T where T: Resolvable { - try resolveAny(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolveAny(in: machO.context).") - public func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T { - try resolveAny(in: machO.context) - } -} - -extension SymbolOrElementPointer where Element: OptionalProtocol { - public func resolve(in context: some ReadingContext) throws -> Resolved { - try resolveUnlessNull(in: context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") - public func resolve() throws -> Resolved { - try resolveUnlessNull(in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: machO.context).") - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Resolved { - try resolveUnlessNull(in: machO.context) - } - - /// A stored address that is null once its tag bits are stripped - /// resolves to a `nil` element. - private func resolveUnlessNull(in context: some ReadingContext) throws -> Resolved { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .address(let address) where stripPointerTags(of: address) == 0: - return .element(.none) - case .address: - return try .element(Element.resolve(at: resolveAddress(in: context), in: context)) - } - } -} diff --git a/Sources/MachO/MachOPointers/TargetRelativeDirectPointer.swift b/Sources/MachO/MachOPointers/TargetRelativeDirectPointer.swift deleted file mode 100644 index 254247d3f..000000000 --- a/Sources/MachO/MachOPointers/TargetRelativeDirectPointer.swift +++ /dev/null @@ -1,11 +0,0 @@ -import MachOReading -import MachOResolving -import MachOKitExtensions - -public struct TargetRelativeDirectPointer: RelativeDirectPointerProtocol { - public typealias Element = Pointee - public let relativeOffset: Offset - public init(relativeOffset: Offset) { - self.relativeOffset = relativeOffset - } -} diff --git a/Sources/MachO/MachOPointers/TargetRelativeDirectPointerIntPair.swift b/Sources/MachO/MachOPointers/TargetRelativeDirectPointerIntPair.swift deleted file mode 100644 index 6403f2413..000000000 --- a/Sources/MachO/MachOPointers/TargetRelativeDirectPointerIntPair.swift +++ /dev/null @@ -1,11 +0,0 @@ -import MachOReading -import MachOResolving -import MachOKitExtensions - -public struct TargetRelativeDirectPointerIntPair: RelativeDirectPointerIntPairProtocol where Value.RawValue: FixedWidthInteger { - public let relativeOffsetPlusInt: Offset - - public init(relativeOffsetPlusInt: Offset) { - self.relativeOffsetPlusInt = relativeOffsetPlusInt - } -} diff --git a/Sources/MachO/MachOPointers/TargetRelativeIndirectPointer.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectPointer.swift deleted file mode 100644 index fb47e838f..000000000 --- a/Sources/MachO/MachOPointers/TargetRelativeIndirectPointer.swift +++ /dev/null @@ -1,12 +0,0 @@ -import MachOReading -import MachOResolving -import MachOKitExtensions - -public struct TargetRelativeIndirectPointer: RelativeIndirectPointerProtocol where Pointee == IndirectType.Resolved { - public typealias Element = Pointee - public let relativeOffset: Offset - - public init(relativeOffset: Offset) { - self.relativeOffset = relativeOffset - } -} diff --git a/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointer.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointer.swift deleted file mode 100644 index 487182892..000000000 --- a/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointer.swift +++ /dev/null @@ -1,15 +0,0 @@ -import MachOReading -import MachOResolving -import MachOKitExtensions - -public struct TargetRelativeIndirectablePointer: RelativeIndirectablePointerProtocol where Pointee == IndirectType.Resolved { - public let relativeOffsetPlusIndirect: Offset - - public init(relativeOffsetPlusIndirect: Offset) { - self.relativeOffsetPlusIndirect = relativeOffsetPlusIndirect - } - - public func withIntPairPointer(_ integer: Integer.Type = Integer.self) -> TargetRelativeIndirectablePointerIntPair { - return .init(relativeOffsetPlusIndirectAndInt: relativeOffsetPlusIndirect) - } -} diff --git a/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift deleted file mode 100644 index b003feb74..000000000 --- a/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift +++ /dev/null @@ -1,10 +0,0 @@ -import MachOReading -import MachOKitExtensions - -public struct TargetRelativeIndirectablePointerIntPair: RelativeIndirectablePointerIntPairProtocol where Value.RawValue: FixedWidthInteger, Pointee == IndirectType.Resolved { - public let relativeOffsetPlusIndirectAndInt: Offset - - public init(relativeOffsetPlusIndirectAndInt: Offset) { - self.relativeOffsetPlusIndirectAndInt = relativeOffsetPlusIndirectAndInt - } -} diff --git a/Sources/MachO/MachOReading/Extensions/DyldCache+.swift b/Sources/MachO/MachOReading/Extensions/DyldCache+.swift deleted file mode 100644 index ce9b7e327..000000000 --- a/Sources/MachO/MachOReading/Extensions/DyldCache+.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Foundation -import MachOKit -import FileIO -import AssociatedObject -import FoundationToolbox - -extension DyldCache { - /// The lock a cache file's handle and mapping are created under. One - /// `DyldCache` is read by many readers at once: a `FullDyldCache` hands - /// the same sub-cache instances to every image read from it, and the - /// host's cache (`FullDyldCache.cachedHost`) is opened once per process — - /// so `diff` and `evolution`, preparing their inputs concurrently, make - /// the first read of a sub-cache from several roots together. Created - /// unlocked, each racing reader mapped the file again and stored its own - /// mapping over the others', and a reader holding a replaced one - /// unretained (the association is non-atomic) could read through a file - /// already unmapped. Created under this lock, each is stored once and - /// never replaced, so every later read takes it without the lock. - @Mutex - private static var fileAccessCreation: Void = () - - @AssociatedObject(.retain(.nonatomic)) - private var _fileHandle: FileHandle? - - var fileHandle: FileHandle { - if let _fileHandle { - return _fileHandle - } - return Self._fileAccessCreation.withLockUnchecked { _ in - if let _fileHandle { - return _fileHandle - } - let fileHandle = try! FileHandle(forReadingFrom: url) - _fileHandle = fileHandle - return fileHandle - } - } - - @AssociatedObject(.retain(.nonatomic)) - private var _fileIO: MemoryMappedFile? - - var fileIO: MemoryMappedFile { - if let _fileIO { - return _fileIO - } - return Self._fileAccessCreation.withLockUnchecked { _ in - if let _fileIO { - return _fileIO - } - let fileIO = try! MemoryMappedFile.open(url: url, isWritable: false) - _fileIO = fileIO - return fileIO - } - } -} diff --git a/Sources/MachO/MachOReading/Extensions/FileHandle+.swift b/Sources/MachO/MachOReading/Extensions/FileHandle+.swift deleted file mode 100644 index 77d636294..000000000 --- a/Sources/MachO/MachOReading/Extensions/FileHandle+.swift +++ /dev/null @@ -1,200 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions - -extension FileHandle: @retroactive MachONamespacing {} - -extension MachONamespace where Base: FileHandle { - func readDataSequence( - offset: UInt64, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence where Element: LayoutWrapper { - base.seek(toFileOffset: offset) - let size = Element.layoutSize * numberOfElements - var data = base.readData( - ofLength: size - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - numberOfElements: numberOfElements - ) - } - - @_disfavoredOverload - func readDataSequence( - offset: UInt64, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence { - base.seek(toFileOffset: offset) - let size = MemoryLayout.size * numberOfElements - var data = base.readData( - ofLength: size - ) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - numberOfElements: numberOfElements - ) - } - - func readDataSequence( - offset: UInt64, - entrySize: Int, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence where Element: LayoutWrapper { - base.seek(toFileOffset: offset) - let size = entrySize * numberOfElements - var data = base.readData( - ofLength: size - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - entrySize: entrySize - ) - } - - @_disfavoredOverload - func readDataSequence( - offset: UInt64, - entrySize: Int, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence { - base.seek(toFileOffset: offset) - let size = entrySize * numberOfElements - var data = base.readData( - ofLength: size - ) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - entrySize: entrySize - ) - } -} - -extension MachONamespace where Base: FileHandle { - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element? where Element: LayoutWrapper { - base.seek(toFileOffset: offset) - var data = base.readData( - ofLength: Element.layoutSize - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - try throwIfInvalid(data.count >= Element.layoutSize, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element? { - base.seek(toFileOffset: offset) - var data = base.readData( - ofLength: MemoryLayout.size - ) - try throwIfInvalid(data.count >= MemoryLayout.size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element where Element: LayoutWrapper { - base.seek(toFileOffset: offset) - var data = base.readData( - ofLength: Element.layoutSize - ) - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - try throwIfInvalid(data.count >= Element.layoutSize, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element { - base.seek(toFileOffset: offset) - var data = base.readData( - ofLength: MemoryLayout.size - ) - try throwIfInvalid(data.count >= MemoryLayout.size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } -} - -extension MachONamespace where Base: FileHandle { - func readString( - offset: UInt64, - size: Int - ) -> String { - let data = readData( - offset: offset, - size: size - ) - return String(cString: data) ?? "" - } - - func readString( - offset: UInt64, - step: UInt64 = 10 - ) -> String { - var data = Data() - var offset = offset - while true { - let new = readData(offset: offset, size: Int(step)) - if new.isEmpty { break } - data.append(new) - if new.contains(0) { break } - offset += UInt64(new.count) - } - - return String(cString: data) ?? "" - } - - func readData( - offset: UInt64, - size: Int - ) -> Data { - base.seek(toFileOffset: offset) - return base.readData( - ofLength: size - ) - } -} diff --git a/Sources/MachO/MachOReading/Extensions/FileIO+.swift b/Sources/MachO/MachOReading/Extensions/FileIO+.swift deleted file mode 100644 index f718a9f56..000000000 --- a/Sources/MachO/MachOReading/Extensions/FileIO+.swift +++ /dev/null @@ -1,227 +0,0 @@ -import Foundation -import FileIO -import MachOKit -import MachOKitExtensions - -extension MemoryMappedFile: @retroactive MachONamespacing {} - -extension MachONamespace where Base: _FileIOProtocol { - func readDataSequence( - offset: UInt64, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence where Element: LayoutWrapper { - let size = Element.layoutSize * numberOfElements - var data = try base.readData( - offset: numericCast(offset), - length: size - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - numberOfElements: numberOfElements - ) - } - - @_disfavoredOverload - func readDataSequence( - offset: UInt64, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence { - let size = MemoryLayout.size * numberOfElements - var data = try base.readData( - offset: numericCast(offset), - length: size - ) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - numberOfElements: numberOfElements - ) - } - - func readDataSequence( - offset: UInt64, - entrySize: Int, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence where Element: LayoutWrapper { - let size = entrySize * numberOfElements - var data = try base.readData( - offset: numericCast(offset), - length: size - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - entrySize: entrySize - ) - } - - @_disfavoredOverload - func readDataSequence( - offset: UInt64, - entrySize: Int, - numberOfElements: Int, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> DataSequence { - let size = entrySize * numberOfElements - var data = try base.readData( - offset: numericCast(offset), - length: size - ) - - try throwIfInvalid(data.count >= size, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return .init( - data: data, - entrySize: entrySize - ) - } -} - -extension MachONamespace where Base: _FileIOProtocol { - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element? where Element: LayoutWrapper { - var data = try base.readData( - offset: numericCast(offset), - length: Element.layoutSize - ) - - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - try throwIfInvalid(data.count >= Element.layoutSize, error: .invalidDataSize) - - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element? { - var data = try base.readData( - offset: numericCast(offset), - length: MemoryLayout.size - ) - try throwIfInvalid(data.count >= MemoryLayout.size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element where Element: LayoutWrapper { - var data = try base.readData( - offset: numericCast(offset), - length: Element.layoutSize - ) - try throwIfInvalid(Element.layoutSize == MemoryLayout.size, error: .invalidLayoutSize) - try throwIfInvalid(data.count >= Element.layoutSize, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } - - func read( - offset: UInt64, - swapHandler: ((inout Data) -> Void)? = nil - ) throws -> Element { - var data = try base.readData( - offset: numericCast(offset), - length: MemoryLayout.size - ) - try throwIfInvalid(data.count >= MemoryLayout.size, error: .invalidDataSize) - if let swapHandler { swapHandler(&data) } - return data.withUnsafeBytes { - $0.load(as: Element.self) - } - } -} - -extension MachONamespace where Base: _FileIOProtocol { - @_disfavoredOverload - @inline(__always) - func readString( - offset: UInt64, - size: Int - ) -> String? { - let data = try! base.readData( - offset: numericCast(offset), - length: size - ) - return String(cString: data) - } - - @_disfavoredOverload - @inline(__always) - func readString( - offset: UInt64, - step: Int = 10 - ) -> String? { - var data = Data() - var offset = offset - while true { - guard let new = try? base.readData( - offset: numericCast(offset), - upToCount: step - ) else { break } - if new.isEmpty { break } - data.append(new) - if new.contains(0) { break } - offset += UInt64(new.count) - } - - return String(cString: data) - } -} - -extension MachONamespace where Base == MemoryMappedFile { - @inline(__always) - func readString( - offset: UInt64 - ) -> String { - String( - cString: base.ptr - .advanced(by: numericCast(offset)) - .assumingMemoryBound(to: CChar.self) - ) - } - - @inline(__always) - func readString( - offset: UInt64, - size: Int // ignored - ) -> String { - readString(offset: offset) - } - - @inline(__always) - func readString( - offset: UInt64, - step: Int = 10 // ignored - ) -> String { - readString(offset: offset) - } -} diff --git a/Sources/MachO/MachOReading/Extensions/MachOFile+.swift b/Sources/MachO/MachOReading/Extensions/MachOFile+.swift deleted file mode 100644 index c1f1539fe..000000000 --- a/Sources/MachO/MachOReading/Extensions/MachOFile+.swift +++ /dev/null @@ -1,52 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions -import FileIO -import AssociatedObject -import FoundationToolbox - -extension MachOFile { - /// The lock a file's handle and mapping are created under, the way - /// `DyldCache`'s are. Created unlocked, readers racing to make a file's - /// first read each opened it again and stored their own over the others', - /// and a reader holding a replaced one unretained (the association is - /// non-atomic) could read through a file already unmapped. Created under - /// it, each is stored once and never replaced, so every later read takes - /// it without the lock. - @Mutex - private static var fileAccessCreation: Void = () - - @AssociatedObject(.retain(.nonatomic)) - private var _fileHandle: FileHandle? - - var fileHandle: FileHandle { - if let _fileHandle { - return _fileHandle - } - return Self._fileAccessCreation.withLockUnchecked { _ in - if let _fileHandle { - return _fileHandle - } - let fileHandle = try! FileHandle(forReadingFrom: url) - _fileHandle = fileHandle - return fileHandle - } - } - - @AssociatedObject(.retain(.nonatomic)) - private var _fileIO: MemoryMappedFile? - - var fileIO: MemoryMappedFile { - if let _fileIO { - return _fileIO - } - return Self._fileAccessCreation.withLockUnchecked { _ in - if let _fileIO { - return _fileIO - } - let fileIO = try! MemoryMappedFile.open(url: url, isWritable: false) - _fileIO = fileIO - return fileIO - } - } -} diff --git a/Sources/MachO/MachOReading/Extensions/ReadingError.swift b/Sources/MachO/MachOReading/Extensions/ReadingError.swift deleted file mode 100644 index 7c1ad542d..000000000 --- a/Sources/MachO/MachOReading/Extensions/ReadingError.swift +++ /dev/null @@ -1,21 +0,0 @@ -import MachOKitExtensions - -/// Errors that can occur when reading data from MachO files or memory. -public enum ReadingError: Error { - /// The data size is smaller than expected for the requested read operation. - case invalidDataSize - - /// The layout size does not match the memory layout size. - case invalidLayoutSize - - /// The address is invalid or cannot be converted (e.g., null pointer). - case invalidAddress(Int) -} - -extension MachONamespace { - func throwIfInvalid(_ isValid: Bool, error: ReadingError) throws { - if !isValid { - throw error - } - } -} diff --git a/Sources/MachO/MachOReading/Models/DataSequence.swift b/Sources/MachO/MachOReading/Models/DataSequence.swift deleted file mode 100644 index 230e9dfe2..000000000 --- a/Sources/MachO/MachOReading/Models/DataSequence.swift +++ /dev/null @@ -1,100 +0,0 @@ -import Foundation - -package struct DataSequence: Sequence { - package typealias Element = T - - private let data: Data - private let entrySize: Int - private let numberOfElements: Int - - init( - data: Data, - numberOfElements: Int - ) { - self.data = data - self.entrySize = MemoryLayout.size - self.numberOfElements = numberOfElements - } - - init( - data: Data, - entrySize: Int - ) { - self.data = data - self.entrySize = entrySize - self.numberOfElements = data.count / entrySize - } - - package func makeIterator() -> Iterator { - Iterator( - data: data, - entrySize: entrySize, - numberOfElements: numberOfElements - ) - } -} - -extension DataSequence { - package struct Iterator: IteratorProtocol { - public typealias Element = T - - private let data: Data - private let entrySize: Int - private let numberOfElements: Int - - private var nextIndex: Int = 0 - private var nextOffset: Int = 0 - - init( - data: Data, - entrySize: Int, - numberOfElements: Int - ) { - self.data = data - self.entrySize = entrySize - self.numberOfElements = numberOfElements - } - - public mutating func next() -> Element? { - guard nextIndex < numberOfElements else { return nil } - guard nextOffset + entrySize <= data.count else { return nil } - - defer { - nextIndex += 1 - nextOffset += entrySize - } - - return data.withUnsafeBytes { - guard let baseAddress = $0.baseAddress else { return nil } - return baseAddress.advanced(by: nextOffset).load(as: Element.self) - } - } - } -} - -extension DataSequence: Collection { - package typealias Index = Int - - package var startIndex: Index { 0 } - package var endIndex: Index { numberOfElements } - - package func index(after i: Int) -> Int { - i + 1 - } - - package subscript(position: Int) -> Element { - precondition(position >= 0) - precondition(position < endIndex) - precondition(data.count >= (position + 1) * entrySize) - return data.withUnsafeBytes { - guard let baseAddress = $0.baseAddress else { - fatalError("data is empty") - } - return baseAddress - .advanced(by: position * entrySize) - .load(as: Element.self) - } - } -} - -extension DataSequence: RandomAccessCollection {} diff --git a/Sources/MachO/MachOReading/Models/MemorySequence.swift b/Sources/MachO/MachOReading/Models/MemorySequence.swift deleted file mode 100644 index d3d4c9996..000000000 --- a/Sources/MachO/MachOReading/Models/MemorySequence.swift +++ /dev/null @@ -1,85 +0,0 @@ -package struct MemorySequence: Sequence { - public typealias Element = T - - private let basePointer: UnsafeRawPointer - private let entrySize: Int - private let numberOfElements: Int - - package init( - basePointer: UnsafePointer, - numberOfElements: Int - ) { - self.basePointer = .init(basePointer) - self.entrySize = MemoryLayout.size - self.numberOfElements = numberOfElements - } - - package init( - basePointer: UnsafePointer, - entrySize: Int, - numberOfElements: Int - ) { - self.basePointer = .init(basePointer) - self.entrySize = entrySize - self.numberOfElements = numberOfElements - } - - package func makeIterator() -> Iterator { - Iterator( - basePointer: basePointer, - entrySize: entrySize, - numberOfElements: numberOfElements - ) - } -} - -extension MemorySequence { - package struct Iterator: IteratorProtocol { - public typealias Element = T - - private let basePointer: UnsafeRawPointer - private let entrySize: Int - private let numberOfElements: Int - - private var nextIndex: Int = 0 - - init( - basePointer: UnsafeRawPointer, - entrySize: Int, - numberOfElements: Int - ) { - self.basePointer = basePointer - self.entrySize = entrySize - self.numberOfElements = numberOfElements - } - - public mutating func next() -> Element? { - guard nextIndex < numberOfElements else { return nil } - defer { nextIndex += 1 } - return basePointer - .advanced(by: nextIndex * entrySize) - .load(as: Element.self) - } - } -} - -extension MemorySequence: Collection { - package typealias Index = Int - - package var startIndex: Index { 0 } - package var endIndex: Index { numberOfElements } - - package func index(after i: Int) -> Int { - i + 1 - } - - package subscript(position: Int) -> Element { - precondition(position >= 0) - precondition(position < endIndex) - return basePointer - .advanced(by: position * entrySize) - .load(as: Element.self) - } -} - -extension MemorySequence: RandomAccessCollection {} diff --git a/Sources/MachO/MachOReading/Readable/MachOFile+Readable.swift b/Sources/MachO/MachOReading/Readable/MachOFile+Readable.swift deleted file mode 100644 index c0baf026b..000000000 --- a/Sources/MachO/MachOReading/Readable/MachOFile+Readable.swift +++ /dev/null @@ -1,117 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions -import FileIO -import AssociatedObject - -/// Extends `MachOFile` to conform to `Readable`, enabling file-based reading. -/// -/// This extension provides file I/O based reading operations for MachO files. -/// It handles the complexity of: -/// - dyld shared cache support (resolving cross-file references) -/// - Header offset adjustments -/// - File handle management -/// -/// ## dyld Shared Cache Support -/// -/// When reading from a MachO file that is part of a dyld shared cache, -/// offsets may need to be resolved to different cache files. This extension -/// automatically handles this resolution. -/// -/// ## Example -/// -/// ```swift -/// let machOFile: MachOFile = ... -/// -/// // Read a raw element -/// let header: mach_header_64 = try machOFile.readElement(offset: 0) -/// -/// // Read with wrapper (preserves offset for relative pointer resolution) -/// let descriptor: ProtocolDescriptor = try machOFile.readWrapperElement(offset: offset) -/// ``` -extension MachOFile: Readable { - public func readElement( - offset: Int - ) throws -> Element { - let originalOffset = offset - var offset = originalOffset - var fileIO = fileIO - if let cacheAndFileOffset = cacheAndFileOffset(fromStart: offset.cast()) { - offset = cacheAndFileOffset.1.cast() - fileIO = cacheAndFileOffset.0.fileIO - } - return try fileIO.machO.read(offset: numericCast(offset + headerStartOffset)) - } - - public func readElement( - offset: Int - ) throws -> Element where Element: LocatableLayoutWrapper { - return try readWrapperElement(offset: offset) - } - - public func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { - let originalOffset = offset - var offset = originalOffset - var fileIO = fileIO - if let cacheAndFileOffset = cacheAndFileOffset(fromStart: offset.cast()) { - offset = cacheAndFileOffset.1.cast() - fileIO = cacheAndFileOffset.0.fileIO - } - let layout: Element.Layout = try fileIO.machO.read(offset: numericCast(offset + headerStartOffset)) - return .init(layout: layout, offset: originalOffset) - } - - public func readElements( - offset: Int, - numberOfElements: Int - ) throws -> [Element] { - let originalOffset = offset - var offset = originalOffset - var fileIO = fileIO - if let cacheAndFileOffset = cacheAndFileOffset(fromStart: offset.cast()) { - offset = cacheAndFileOffset.1.cast() - fileIO = cacheAndFileOffset.0.fileIO - } - var currentOffset = offset - let elements = try fileIO.machO.readDataSequence(offset: numericCast(offset + headerStartOffset), numberOfElements: numberOfElements).map { (element: Element) -> Element in - currentOffset += MemoryLayout.size - return element - } - return elements - } - - public func readElements( - offset: Int, - numberOfElements: Int - ) throws -> [Element] where Element: LocatableLayoutWrapper { - return try readWrapperElements(offset: offset, numberOfElements: numberOfElements) - } - - public func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { - let originalOffset = offset - var offset = originalOffset - var fileIO = fileIO - if let cacheAndFileOffset = cacheAndFileOffset(fromStart: offset.cast()) { - offset = cacheAndFileOffset.1.cast() - fileIO = cacheAndFileOffset.0.fileIO - } - var currentOffset = originalOffset - let elements = try fileIO.machO.readDataSequence(offset: numericCast(offset + headerStartOffset), numberOfElements: numberOfElements).map { (layout: Element.Layout) -> Element in - let element = Element(layout: layout, offset: currentOffset) - currentOffset += Element.layoutSize - return element - } - return elements - } - - public func readString(offset: Int) throws -> String { - let originalOffset = offset - var offset = originalOffset - var fileIO = fileIO - if let cacheAndFileOffset = cacheAndFileOffset(fromStart: offset.cast()) { - offset = cacheAndFileOffset.1.cast() - fileIO = cacheAndFileOffset.0.fileIO - } - return fileIO.machO.readString(offset: numericCast(offset + headerStartOffset)) - } -} diff --git a/Sources/MachO/MachOReading/Readable/MachOImage+Readable.swift b/Sources/MachO/MachOReading/Readable/MachOImage+Readable.swift deleted file mode 100644 index 70e11950e..000000000 --- a/Sources/MachO/MachOReading/Readable/MachOImage+Readable.swift +++ /dev/null @@ -1,76 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// Extends `MachOImage` to conform to `Readable`, enabling memory-based reading. -/// -/// This extension provides direct memory access for MachO images that are -/// already loaded in memory (e.g., via `dlopen` or the dyld image list). -/// -/// ## Performance -/// -/// Since `MachOImage` operates on memory-mapped data, reads are essentially -/// pointer dereferences with no additional I/O overhead. -/// -/// ## Example -/// -/// ```swift -/// let machOImage: MachOImage = ... -/// -/// // Read a raw element from memory -/// let header: mach_header_64 = try machOImage.readElement(offset: 0) -/// -/// // Read with wrapper (preserves offset for relative pointer resolution) -/// let descriptor: ProtocolDescriptor = try machOImage.readWrapperElement(offset: offset) -/// ``` -extension MachOImage: Readable { - public func readElement( - offset: Int - ) throws -> Element { - let pointer = ptr + offset - return pointer.assumingMemoryBound(to: Element.self).pointee - } - - public func readElement( - offset: Int - ) throws -> Element where Element: LocatableLayoutWrapper { - return try readWrapperElement(offset: offset) - } - - public func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { - let pointer = ptr + offset - let layout: Element.Layout = pointer.assumingMemoryBound(to: Element.Layout.self).pointee - return .init(layout: layout, offset: offset) - } - - public func readElements( - offset: Int, - numberOfElements: Int - ) throws -> [Element] { - let pointer = ptr + offset - return MemorySequence(basePointer: pointer.assumingMemoryBound(to: Element.self), numberOfElements: numberOfElements).map { $0 } - } - - public func readElements( - offset: Int, - numberOfElements: Int - ) throws -> [Element] where Element: LocatableLayoutWrapper { - return try readWrapperElements(offset: offset, numberOfElements: numberOfElements) - } - - public func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { - let pointer = ptr + offset - var currentOffset = offset - let elements = MemorySequence(basePointer: pointer.assumingMemoryBound(to: Element.Layout.self), numberOfElements: numberOfElements).map { (layout: Element.Layout) -> Element in - let element = Element(layout: layout, offset: currentOffset) - currentOffset += Element.layoutSize - return element - } - return elements - } - - public func readString(offset: Int) throws -> String { - let pointer = ptr + offset - return .init(cString: pointer.assumingMemoryBound(to: CChar.self)) - } -} - diff --git a/Sources/MachO/MachOReading/Readable/Readable.swift b/Sources/MachO/MachOReading/Readable/Readable.swift deleted file mode 100644 index 9ec972a95..000000000 --- a/Sources/MachO/MachOReading/Readable/Readable.swift +++ /dev/null @@ -1,81 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// A protocol for types that can read binary data from a backing store. -/// -/// `Readable` provides a unified interface for reading elements, arrays, and strings -/// from different sources (files, memory, etc.) using byte offsets. -/// -/// ## Overview -/// -/// This protocol abstracts the reading operations needed to parse MachO data structures. -/// Conforming types include: -/// - `MachOFile`: Reads from disk via file I/O -/// - `MachOImage`: Reads from memory-mapped images -/// - `UnsafeRawPointer`: Reads directly from memory -/// -/// ## Reading Elements -/// -/// There are two variants for reading elements: -/// - `readElement`: Reads raw bytes and interprets them as the target type -/// - `readWrapperElement`: Reads a layout and wraps it with location information -/// -/// ## Example -/// -/// ```swift -/// // Read a raw struct from a MachO file -/// let header: mach_header_64 = try machOFile.readElement(offset: 0) -/// -/// // Read a descriptor that remembers its location -/// let descriptor: ProtocolDescriptor = try machOFile.readWrapperElement(offset: offset) -/// print(descriptor.offset) // The offset where this was read from -/// ``` -public protocol Readable { - /// Reads a single element from the given offset. - /// - /// - Parameter offset: The byte offset to read from - /// - Returns: The element read and interpreted as type `Element` - /// - Throws: If reading fails - func readElement(offset: Int) throws -> Element - - /// Reads a layout wrapper element from the given offset. - /// - /// This method reads the layout bytes and creates a wrapper that remembers - /// its location (offset), enabling relative pointer resolution. - /// - /// - Parameter offset: The byte offset to read from - /// - Returns: The wrapper element with location information - /// - Throws: If reading fails - func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper - - /// Reads multiple elements starting from the given offset. - /// - /// Elements are read sequentially with each element's size determining - /// the offset for the next element. - /// - /// - Parameters: - /// - offset: The byte offset to start reading from - /// - numberOfElements: The number of elements to read - /// - Returns: An array of elements read sequentially - /// - Throws: If reading fails - func readElements(offset: Int, numberOfElements: Int) throws -> [Element] - - /// Reads multiple layout wrapper elements starting from the given offset. - /// - /// Each wrapper element remembers its individual offset, enabling - /// relative pointer resolution for each element. - /// - /// - Parameters: - /// - offset: The byte offset to start reading from - /// - numberOfElements: The number of elements to read - /// - Returns: An array of wrapper elements with location information - /// - Throws: If reading fails - func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper - - /// Reads a null-terminated C string from the given offset. - /// - /// - Parameter offset: The byte offset to read from - /// - Returns: The string read from the data - /// - Throws: If reading fails or the string is not valid UTF-8 - func readString(offset: Int) throws -> String -} diff --git a/Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift b/Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift deleted file mode 100644 index 147159f01..000000000 --- a/Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift +++ /dev/null @@ -1,86 +0,0 @@ -import MachOKit -import MachOKitExtensions -// `box` used to arrive implicitly through the in-package MachOKitExtensions target. -// MachOKitExtensions is now a separate package that deliberately avoids the -// Apple-only FrameworkToolbox, so this import has to be spelled out here. -import FoundationToolbox - -/// Extends `UnsafeRawPointer` to conform to `Readable`, enabling direct memory reading. -/// -/// This extension allows reading data directly from memory addresses, which is -/// useful for in-process Swift runtime introspection where metadata is already -/// loaded in the current process's address space. -/// -/// ## Offset vs Direct Reading -/// -/// This extension provides two sets of methods: -/// - **Offset-based**: `readElement(offset:)` - reads relative to the pointer -/// - **Direct**: `readElement()` - reads at the pointer's current location -/// -/// ## Pointer Tags -/// -/// The implementation handles ARM64 pointer authentication tags by stripping -/// them before reading. This ensures compatibility with PAC-enabled systems. -/// -/// ## Example -/// -/// ```swift -/// let ptr: UnsafeRawPointer = ... -/// -/// // Read at the pointer location -/// let flags: ContextDescriptorFlags = try ptr.readElement() -/// -/// // Read at an offset from the pointer -/// let name: String = try ptr.readString(offset: 4) -/// -/// // Read with wrapper (uses bit pattern as offset for InProcess context) -/// let descriptor: ProtocolDescriptor = try ptr.readWrapperElement() -/// ``` -extension UnsafeRawPointer: Readable { - public func readElement(offset: Int) throws -> Element { - try advanced(by: offset).readElement() - } - - public func readWrapperElement(offset: Int) throws -> Element where Element: MachOKitExtensions.LocatableLayoutWrapper { - try advanced(by: offset).readWrapperElement() - } - - public func readElements(offset: Int, numberOfElements: Int) throws -> [Element] { - try advanced(by: offset).readElements(numberOfElements: numberOfElements) - } - - public func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: MachOKitExtensions.LocatableLayoutWrapper { - try advanced(by: offset).readWrapperElements(numberOfElements: numberOfElements) - } - - public func readString(offset: Int) throws -> String { - try advanced(by: offset).readString() - } - - public func readElement() throws -> Element { - return assumingMemoryBound(to: Element.self).pointee - } - - public func readWrapperElement() throws -> Element where Element: LocatableLayoutWrapper { - let layout: Element.Layout = assumingMemoryBound(to: Element.Layout.self).pointee - return .init(layout: layout, offset: box.bitPattern.int) - } - - public func readElements(to: Element.Type = Element.self, numberOfElements: Int) throws -> [Element] { - return MemorySequence(basePointer: assumingMemoryBound(to: Element.self), numberOfElements: numberOfElements).map { $0 } - } - - public func readWrapperElements(to: Element.Type = Element.self, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { - var currentOffset = box.bitPattern.int - let elements = MemorySequence(basePointer: assumingMemoryBound(to: Element.Layout.self), numberOfElements: numberOfElements).map { (layout: Element.Layout) -> Element in - let element = Element(layout: layout, offset: currentOffset) - currentOffset += Element.layoutSize - return element - } - return elements - } - - public func readString() throws -> String { - return .init(cString: assumingMemoryBound(to: CChar.self)) - } -} diff --git a/Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift b/Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift deleted file mode 100644 index 289d894b4..000000000 --- a/Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift +++ /dev/null @@ -1,128 +0,0 @@ -import MachOKit -import MachOKitExtensions -import Utilities - -/// A reading context for direct in-process memory access. -/// -/// `InProcessContext` provides zero-copy memory access using `UnsafeRawPointer` -/// as addresses. This is the most efficient way to read data when working with -/// memory that's already loaded in the current process. -/// -/// ## Usage -/// -/// ```swift -/// let ptr: UnsafeRawPointer = ... -/// let context = InProcessContext.shared -/// -/// // Read data directly from memory -/// let descriptor: ProtocolDescriptor = try context.readWrapperElement(at: ptr) -/// ``` -/// -/// ## Address Type -/// -/// `InProcessContext` uses `UnsafeRawPointer` as its address type, allowing -/// direct memory operations without any copying or offset calculations. -/// -/// ## Thread Safety -/// -/// `InProcessContext` is stateless and can be safely shared across threads. -/// The `shared` singleton is recommended for most use cases. -/// -/// Note: This type is marked as `@unchecked Sendable` because `UnsafeRawPointer` -/// is not `Sendable`. Thread safety must be ensured by the caller when using -/// addresses across thread boundaries. -public struct InProcessContext: ReadingContext, Sendable { - /// The runtime target for in-process access. - public typealias Runtime = InProcess - - /// Addresses are raw memory pointers. - public typealias Address = UnsafeRawPointer - - /// A shared singleton instance. - /// - /// Since `InProcessContext` is stateless, using a shared instance - /// avoids unnecessary allocations. - public static let shared = InProcessContext() - - /// Creates a new in-process reading context. - public init() {} - - /// The bits of an address in this process that are the address itself, - /// without pointer authentication or tag bits. - /// - /// Every image in a process shares one architecture and platform, so the - /// mask is computed once. `UnsafeRawPointer.stripPointerTags()` computes - /// it again on every call — it looks up the current image and walks its - /// load commands — which is a cost paid once per read here. - private static let addressMask = UInt(truncatingIfNeeded: MachOImage.current().vmaddrMask ?? .max) - - /// `address` without its tag bits; throws for an address that is only tag - /// bits, the way a null pointer throws. - private func strippingTags(from address: Address) throws -> Address { - try UnsafeRawPointer(bitPattern: UInt(bitPattern: address) & Self.addressMask) - } - - public func readElement(at ptr: Address) throws -> T { - try strippingTags(from: ptr).readElement() - } - - public func readElements(at ptr: Address, numberOfElements: Int) throws -> [T] { - try strippingTags(from: ptr).readElements(numberOfElements: numberOfElements) - } - - public func readWrapperElement(at ptr: Address) throws -> T { - try strippingTags(from: ptr).readWrapperElement() - } - - public func readWrapperElements(at ptr: Address, numberOfElements: Int) throws -> [T] where T : LocatableLayoutWrapper { - try strippingTags(from: ptr).readWrapperElements(numberOfElements: numberOfElements) - } - - public func readString(at ptr: Address) throws -> String { - try strippingTags(from: ptr).readString() - } - - /// Advances from the untagged address: a tagged base plus a delta is not - /// an address the process can use, signed or not. - public func advanceAddress(_ address: Address, by delta: Int) -> Address { - ((try? strippingTags(from: address)) ?? address).advanced(by: delta) - } - - public func advanceAddress(_ address: Address, of type: T.Type) -> Address { - advanceAddress(address, by: MemoryLayout.size) - } - - public func addressFromOffset(_ offset: Int) throws -> Address { - // For InProcess context, the offset is a pointer bit pattern - try UnsafeRawPointer(bitPattern: offset) - } - - public func addressFromVirtualAddress(_ virtualAddress: UInt64) throws -> Address { - // For InProcess context, the virtual address is a pointer bit pattern. - try UnsafeRawPointer(bitPattern: UInt(truncatingIfNeeded: virtualAddress) & Self.addressMask) - } - - public func offsetFromAddress(_ address: Address) throws -> Int { - Int(bitPattern: address) - } -} - -// MARK: - Runtime Pointer Support - -extension InProcessContext { - /// In-process addresses are already runtime pointers, so this returns - /// the address unchanged. - public func runtimePointer(at address: UnsafeRawPointer) throws -> UnsafeRawPointer? { - address - } - - /// Addresses are absolute in this process, so memo entries are - /// process-wide. - public var cacheScope: ReadingContextCacheScope { - .process - } -} - -extension ReadingContext where Self == InProcessContext { - public static var inProcess: Self { .shared } -} diff --git a/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift b/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift deleted file mode 100644 index 72db86837..000000000 --- a/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift +++ /dev/null @@ -1,153 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// A reading context for MachO files and images. -/// -/// `MachOContext` wraps a MachO file or image and provides a unified -/// interface for reading data using file offsets as addresses. -/// -/// ## Usage -/// -/// ```swift -/// let machO: MachOFile = ... -/// let context = MachOContext(machO) -/// -/// // Or use the convenience property -/// let context = machO.context -/// -/// // Read data using the context -/// let descriptor: ProtocolDescriptor = try context.readWrapperElement(at: offset) -/// ``` -/// -/// ## Address Type -/// -/// `MachOContext` uses `Int` as its address type, representing file offsets. -/// This allows relative pointer resolution to work correctly with file-based -/// data. -public struct MachOContext: ReadingContext, Sendable { - /// The runtime target is always 64-bit for MachO contexts. - /// TODO: Support 32-bit MachO files by checking the header. - public typealias Runtime = RuntimeTarget64 - - /// Addresses are file offsets. - public typealias Address = Int - - /// The underlying MachO file or image. - public let machO: MachO - - /// Creates a new MachO reading context. - /// - /// - Parameter machO: The MachO file or image to read from - public init(_ machO: MachO) { - self.machO = machO - } - - public func readElement(at offset: Int) throws -> T { - try machO.readElement(offset: offset) - } - - public func readElements(at address: Int, numberOfElements: Int) throws -> [T] { - try machO.readElements(offset: address, numberOfElements: numberOfElements) - } - - public func readWrapperElement(at offset: Int) throws -> T { - try machO.readWrapperElement(offset: offset) - } - - public func readWrapperElements(at address: Int, numberOfElements: Int) throws -> [T] where T: LocatableLayoutWrapper { - try machO.readWrapperElements(offset: address, numberOfElements: numberOfElements) - } - - public func readString(at offset: Int) throws -> String { - try machO.readString(offset: offset) - } - - public func advanceAddress(_ offset: Int, by delta: Int) -> Int { - offset + delta - } - - public func advanceAddress(_ address: Int, of type: T.Type) -> Int { - address.offseting(of: type) - } - - public func addressFromOffset(_ offset: Int) -> Int { - offset - } - - /// Never throws: every reader resolves any virtual address to some - /// offset. The reader strips pointer tags itself — `MachOFile` inside - /// `fileOffset(of:)`, `MachOImage` in `resolveOffset(at:)` — so they are - /// not stripped a second time here. - public func addressFromVirtualAddress(_ virtualAddress: UInt64) -> Int { - machO.resolveOffset(at: virtualAddress) - } - - public func offsetFromAddress(_ address: Int) -> Int { - address - } - - /// 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.underlyingReader as? any MachOBindRebaseResolving) - } - - /// Offsets are per image, so memo entries belong to this image: keyed on - /// the reader's identifier, the key its other per-image caches use. - /// - /// Every reader identifies its image by a `MachOTargetIdentifier`. One - /// that did not would be read unmemoized — slower, never wrong, since an - /// identity the scope cannot name must not share another image's entries. - public var cacheScope: ReadingContextCacheScope { - guard let identifier = machO.identifier as? MachOTargetIdentifier else { return .uncached } - return .image(identifier: identifier) - } -} - -// MARK: - Convenience Extensions - -extension MachORepresentableWithCache where Self: Readable { - /// Returns a reading context for this MachO file or image. - /// - /// This is a convenience property that wraps `self` in a `MachOContext`. - /// - /// ```swift - /// let machO: MachOFile = ... - /// let name = try descriptor.layout.name.resolve( - /// from: descriptor.offset(of: \.name), - /// in: machO.context - /// ) - /// ``` - public var context: MachOContext { - MachOContext(self) - } -} - -// MARK: - Runtime Pointer Support - -extension MachOContext { - /// 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? { - guard let machOImage = machO.asMachOImage else { return nil } - return machOImage.ptr + UnsafeRawPointer.Stride(address) - } -} - -extension ReadingContext where Self == MachOContext { - public static func machOFile(_ machO: MachOFile) -> Self { - .init(machO) - } -} - -extension ReadingContext where Self == MachOContext { - public static func machOImage(_ machO: MachOImage) -> Self { - .init(machO) - } -} diff --git a/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift b/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift deleted file mode 100644 index 0a46b2b79..000000000 --- a/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift +++ /dev/null @@ -1,319 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// A protocol for address types that support arithmetic operations. -/// -/// This enables generic code to perform pointer arithmetic without -/// knowing the concrete address type (Int for file offsets, UnsafeRawPointer for memory). -/// -/// ## Conforming Types -/// -/// - `Int`: Used for file offsets in external MachO reading -/// - `UnsafeRawPointer`: Used for direct memory access in in-process reading -/// -/// ## Example -/// -/// ```swift -/// func computeOffset( -/// from base: Address, -/// to current: Address -/// ) -> Int { -/// current - base // Returns the byte distance -/// } -/// -/// func advance( -/// _ address: Address, -/// by offset: Int -/// ) -> Address { -/// address + offset // Returns a new address -/// } -/// ``` -public protocol AddressArithmetic { - /// Returns a new address by adding an offset to the base address. - /// - /// - Parameters: - /// - lhs: The base address - /// - rhs: The byte offset to add - /// - Returns: A new address offset by the given amount - static func + (lhs: Self, rhs: Int) -> Self - - /// Returns a new address by adding an offset to the base address (reversed operands). - /// - /// - Parameters: - /// - lhs: The byte offset to add - /// - rhs: The base address - /// - Returns: A new address offset by the given amount - static func + (lhs: Int, rhs: Self) -> Self - - /// Returns a new address by subtracting an offset from the base address. - /// - /// - Parameters: - /// - lhs: The base address - /// - rhs: The byte offset to subtract - /// - Returns: A new address offset by the given amount - static func - (lhs: Self, rhs: Int) -> Self - - /// Computes the byte distance between two addresses. - /// - /// - Parameters: - /// - lhs: The end address - /// - rhs: The start address - /// - Returns: The number of bytes from `rhs` to `lhs` (can be negative) - static func - (lhs: Self, rhs: Self) -> Int - - /// Advances the address in place by adding an offset. - /// - /// - Parameters: - /// - lhs: The address to modify - /// - rhs: The byte offset to add - static func += (lhs: inout Self, rhs: Int) - - /// Moves the address backward in place by subtracting an offset. - /// - /// - Parameters: - /// - lhs: The address to modify - /// - rhs: The byte offset to subtract - static func -= (lhs: inout Self, rhs: Int) -} - -// MARK: - AddressArithmetic Conformances - -extension Int: AddressArithmetic {} -extension UnsafeRawPointer: AddressArithmetic {} - -/// A unified protocol for reading data from different sources. -/// -/// `ReadingContext` abstracts the differences between: -/// - **External reading**: Reading from MachO files via file I/O (using offsets) -/// - **InProcess reading**: Direct memory access via pointers -/// -/// This design is inspired by Swift Runtime's `MemoryReader` abstraction -/// (see `swift/include/swift/Remote/MemoryReader.h`). -/// -/// ## Overview -/// -/// The key insight is that both reading modes share the same operations: -/// - Read an element at an address -/// - Read a string at an address -/// - Advance an address by a relative offset -/// -/// The difference is in the `Address` type: -/// - MachO: `Address = Int` (file offset) -/// - InProcess: `Address = UnsafeRawPointer` (memory pointer) -/// -/// ## Example -/// -/// ```swift -/// // Generic function that works with any ReadingContext -/// func readDescriptor( -/// at address: Context.Address, -/// in context: Context -/// ) throws -> ProtocolDescriptor { -/// try ProtocolDescriptor.resolve(at: address, in: context) -/// } -/// -/// // Use with MachO file -/// let desc1 = try readDescriptor(at: offset, in: machO.context) -/// -/// // Use with in-process memory -/// let desc2 = try readDescriptor(at: ptr, in: InProcessContext.shared) -/// ``` -public protocol ReadingContext: Sendable { - /// The runtime target this context operates on. - associatedtype Runtime: RuntimeProtocol - - /// The address type used by this context. - /// - MachO contexts use `Int` (file offset) - /// - InProcess contexts use `UnsafeRawPointer` - /// - /// Note: `Address` does not require `Sendable` because `UnsafeRawPointer` - /// is not `Sendable` in Swift's concurrency model. Thread safety must be - /// ensured by the caller when using `InProcessContext`. - associatedtype Address: AddressArithmetic - - /// Reads a raw element from the given address. - /// - /// - Parameter address: The address to read from - /// - Returns: The element read from memory/file - /// - Throws: If reading fails - func readElement(at address: Address) throws -> T - - /// Reads multiple elements starting from the given address. - /// - /// Elements are read sequentially, with each element's size determining - /// the address for the next element. - /// - /// - Parameters: - /// - address: The address to start reading from - /// - numberOfElements: The number of elements to read - /// - Returns: An array of elements read sequentially - /// - Throws: If reading fails - func readElements(at address: Address, numberOfElements: Int) throws -> [T] - - /// Reads a layout wrapper element from the given address. - /// - /// This method reads the layout and creates a wrapper that remembers - /// its location (offset or pointer). - /// - /// - Parameter address: The address to read from - /// - Returns: The wrapper element with location information - /// - Throws: If reading fails - func readWrapperElement(at address: Address) throws -> T - - /// Reads multiple layout wrapper elements starting from the given address. - /// - /// Each wrapper element remembers its individual address/offset, enabling - /// relative pointer resolution for each element. - /// - /// - Parameters: - /// - address: The address to start reading from - /// - numberOfElements: The number of elements to read - /// - Returns: An array of wrapper elements with location information - /// - Throws: If reading fails - func readWrapperElements(at address: Address, numberOfElements: Int) throws -> [T] - - /// Reads a null-terminated C string from the given address. - /// - /// - Parameter address: The address to read from - /// - Returns: The string read from memory/file - /// - Throws: If reading fails - func readString(at address: Address) throws -> String - - /// Computes a new address by applying a relative offset. - /// - /// This is used for resolving relative pointers: - /// `newAddress = baseAddress + relativeOffset` - /// - /// - Parameters: - /// - address: The base address - /// - offset: The relative offset to add - /// - Returns: The computed address - func advanceAddress(_ address: Address, by offset: Int) -> Address - - /// Advances an address by the size of the given type. - /// - /// This is equivalent to `advanceAddress(address, by: MemoryLayout.size)` - /// and is useful when iterating through arrays of elements. - /// - /// - Parameters: - /// - address: The base address - /// - type: The type whose size determines the advancement - /// - Returns: The address advanced by the type's size - func advanceAddress(_ address: Address, of type: T.Type) -> Address - - /// Converts an integer offset (typically a pointer bit pattern) to this context's address type. - /// - /// This is used when working with `MangledName` lookup elements, which store - /// offsets as integers regardless of the context type. - /// - /// - For `MachOContext`: Returns the offset as-is (since `Address = Int`) - /// - For `InProcessContext`: Converts to `UnsafeRawPointer` - /// - /// - Parameter offset: The integer offset to convert - /// - Returns: The address in this context's address type - /// - Throws: If the offset cannot be converted to a valid address - func addressFromOffset(_ offset: Int) throws -> Address - - /// Converts a virtual address (UInt64) to this context's address type. - /// - /// This is used when working with pointer types that store absolute virtual - /// addresses, such as `SymbolOrElementPointer`. - /// - /// - For `MachOContext`: Converts virtual address to file offset - /// - For `InProcessContext`: Converts to `UnsafeRawPointer` via bit pattern - /// - /// - Parameter virtualAddress: The virtual address to convert - /// - Returns: The address in this context's address type - /// - Throws: If the address cannot be converted - func addressFromVirtualAddress(_ virtualAddress: UInt64) throws -> Address - - /// Converts this context's address to an integer offset. - /// - /// This is the inverse operation of `addressFromOffset` and is used when - /// an integer offset is needed (e.g., for symbol binding lookups). - /// - /// - For `MachOContext`: Returns the address as-is (since `Address = Int`) - /// - For `InProcessContext`: Returns the pointer's bit pattern as `Int` - /// - /// - Parameter address: The address to convert - /// - Returns: The integer offset representation - /// - Throws: If the address cannot be converted - func offsetFromAddress(_ address: Address) throws -> Int - - /// Optional bridge to dyld bind / rebase resolution. - /// - /// Indirect symbolic references encoded in Swift mangled names point at - /// relocation sites whose bytes are still chained-fixup encoded on disk. - /// Readers must consult bind / rebase tables before treating those bytes - /// as a real address. Contexts that wrap a `MachOFile` return the - /// underlying file (or any `MachOBindRebaseResolving` adapter) here; - /// contexts that read already-relocated memory (in-process images, etc.) - /// return `nil` and the caller falls back to a direct read. - var bindRebaseResolver: (any MachOBindRebaseResolving)? { get } - - /// Converts a context-specific address to a runtime `UnsafeRawPointer`, - /// when this context is mapped into the current process. - /// - /// - `InProcessContext`: returns the address itself (already a pointer). - /// - `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 - /// in the extension below) so existential `any ReadingContext` calls - /// dynamic-dispatch to the concrete context's override. The default keeps - /// adding new conformers non-breaking. - func runtimePointer(at address: Address) throws -> UnsafeRawPointer? - - /// Where a memo cache built on top of reading — demangling, node - /// interning — may file what it computes from this context. - /// - /// A cache keys its entries by address, so the scope says which - /// addresses cannot collide: the offsets of one image, or the absolute - /// addresses of this process. The default is ``ReadingContextCacheScope/uncached``, - /// so a context that declares nothing is never memoized at all rather - /// than sharing entries with another image's offsets. - var cacheScope: ReadingContextCacheScope { get } -} - -/// The scope a memo cache files its entries under for a ``ReadingContext``. -/// -/// `@unchecked Sendable` for the same reason `SharedCacheKey` is: an image -/// identifier can hold the image's base address, an `UnsafeRawPointer` that -/// is only ever hashed and compared, never dereferenced. -public enum ReadingContextCacheScope: @unchecked Sendable { - /// The context reads one image by offset: entries belong to that image - /// and are evicted with it. `identifier` is the reader's own - /// `identifier`, the same identity per-image caches already key on. - /// - /// Carried unboxed: the scope is asked for on every memo lookup, and - /// boxing a file's identifier — a path plus a UUID, too large for an - /// existential's inline buffer — would allocate each time. - case image(identifier: MachOTargetIdentifier) - - /// The context reads this process's memory by absolute address, so two - /// images can never collide: entries are process-wide. - case process - - /// The context gives no identity; nothing computed from it is memoized. - case uncached -} - -extension ReadingContext { - /// Default: no bind/rebase support. Concrete contexts override when they - /// can vend a resolver (see `MachOContext`'s implementation). - public var bindRebaseResolver: (any MachOBindRebaseResolving)? { nil } - - /// Default: no identity, so nothing is memoized. - public var cacheScope: ReadingContextCacheScope { .uncached } -} - -extension ReadingContext { - /// Default: contexts that aren't mapped into the current process can't - /// vend a runtime pointer. Concrete contexts override this in their own - /// files (`InProcessContext`, `MachOContext`). - public func runtimePointer(at address: Address) throws -> UnsafeRawPointer? { - nil - } -} diff --git a/Sources/MachO/MachOResolving/AnyResolvable.swift b/Sources/MachO/MachOResolving/AnyResolvable.swift deleted file mode 100644 index 51b7b9ae8..000000000 --- a/Sources/MachO/MachOResolving/AnyResolvable.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -public struct AnyResolvable: Resolvable { - public let wrappedValue: UInt8 -} diff --git a/Sources/MachO/MachOResolving/AsyncResolvable.swift b/Sources/MachO/MachOResolving/AsyncResolvable.swift deleted file mode 100644 index 22174934e..000000000 --- a/Sources/MachO/MachOResolving/AsyncResolvable.swift +++ /dev/null @@ -1,65 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -/// An asynchronous spelling of the Mach-O form of ``Resolvable``. Nothing in -/// the package calls it, and reading never suspends; resolve synchronously -/// through a `ReadingContext` instead. -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -public protocol AsyncResolvable: Resolvable { - static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self - static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self? -} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension AsyncResolvable { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self { - try resolve(at: offset, in: machO.context) - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self? { - try resolve(at: offset, in: machO.context) - } -} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Optional: AsyncResolvable where Wrapped: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension String: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Int: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension UInt: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Int8: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension UInt8: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Int16: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension UInt16: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Int32: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension UInt32: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Int64: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension UInt64: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Float: AsyncResolvable {} - -@available(*, deprecated, message: "Resolve synchronously through a ReadingContext: resolve(at: offset, in: machO.context).") -extension Double: AsyncResolvable {} diff --git a/Sources/MachO/MachOResolving/Resolvable.swift b/Sources/MachO/MachOResolving/Resolvable.swift deleted file mode 100644 index 6fa41fde7..000000000 --- a/Sources/MachO/MachOResolving/Resolvable.swift +++ /dev/null @@ -1,133 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -public protocol Resolvable: Sendable { - static func resolve(at address: Context.Address, in context: Context) throws -> Self - static func resolve(at address: Context.Address, in context: Context) throws -> Self? -} - -extension Resolvable { - public static func resolve( - at address: Context.Address, - in context: Context - ) throws -> Self { - try context.readElement(at: address) - } - - public static func resolve( - at address: Context.Address, - in context: Context - ) throws -> Self? { - let result: Self = try resolve(at: address, in: context) - return .some(result) - } -} - -// MARK: - Deprecated Mach-O and pointer forms -// -// Each deprecated form sits where its implementation used to — the protocol -// extension, a constrained extension, a concrete conformer — so overload -// resolution picks the same form it always did, notably the `Self` form over -// the `Self?` form for a wrapper or a `String`. - -extension Resolvable { - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self? { - try resolve(at: ptr, in: InProcessContext.shared) - } -} - -extension Optional: Resolvable where Wrapped: Resolvable { - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - let result: Wrapped? = try Wrapped.resolve(at: address, in: context) - if let result { - return .some(result) - } else { - return .none - } - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } -} - -extension String: Resolvable { - public static func resolve(at address: Context.Address, in context: Context) throws -> String { - try context.readString(at: address) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } -} - -extension Resolvable where Self: LocatableLayoutWrapper { - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - try context.readWrapperElement(at: address) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } -} - -extension Int: Resolvable {} -extension UInt: Resolvable {} - -extension Int8: Resolvable {} -extension UInt8: Resolvable {} - -extension Int16: Resolvable {} -extension UInt16: Resolvable {} - -extension Int32: Resolvable {} -extension UInt32: Resolvable {} - -extension Int64: Resolvable {} -extension UInt64: Resolvable {} - -extension Float: Resolvable {} -extension Double: Resolvable {} - - -extension LocatableLayoutWrapper where Self: Resolvable { - package func asMachOWrapper(in machO: MachOImage) throws -> Self { - let offset = Int(bitPattern: UInt(bitPattern: offset) - machO.ptr.bitPattern.uint) - return try .resolve(at: offset, in: machO.context) - } -} diff --git a/Sources/MachO/MachOResolving/Symbol.swift b/Sources/MachO/MachOResolving/Symbol.swift deleted file mode 100644 index d5d2de771..000000000 --- a/Sources/MachO/MachOResolving/Symbol.swift +++ /dev/null @@ -1,51 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// A symbol as the resolution layer knows it: the offset it sits at, its -/// name, and whether the symbol-table entry was an undefined external -/// import. -/// -/// This is a plain value — a bind-table entry read back through -/// `SymbolOrElementPointer`, or a row a symbol index vends — and it carries -/// no lookup behavior of its own. Looking a symbol *up* by offset is the -/// job of `MachOSymbols` (`symbols(offset:)`), deliberately one layer above -/// the ABI model (evolution proposal `self-contained-abi-layer`). -public struct Symbol: Hashable, Sendable { - public let offset: Int - - public let name: String - - /// Whether the symbol-table entry was flagged as an undefined external - /// import (`N_EXT` with `N_UNDF` type). Extracted from the `nlist` entry - /// at collection time; the entry itself is not retained. - public let isExternal: Bool - - public init(offset: Int, name: String, isExternal: Bool = false) { - self.offset = offset - self.name = name - self.isExternal = isExternal - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(offset) - hasher.combine(name) - } - - public static func == (lhs: Self, rhs: Self) -> Bool { - return lhs.offset == rhs.offset && lhs.name == rhs.name - } - - public enum AddressFormat { - case hex - case decimal - } - - public func addressString(format: AddressFormat, in machO: some MachORepresentableWithCache) -> String { - switch format { - case .hex: - return "0x" + String(machO.address(forOffset: offset), radix: 16, uppercase: true) - case .decimal: - return String(machO.address(forOffset: offset), radix: 10) - } - } -} diff --git a/Sources/MachO/MachOResolving/SymbolOrElement.swift b/Sources/MachO/MachOResolving/SymbolOrElement.swift deleted file mode 100644 index 5fae66c88..000000000 --- a/Sources/MachO/MachOResolving/SymbolOrElement.swift +++ /dev/null @@ -1,126 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -public enum SymbolOrElement: Resolvable { - case symbol(Symbol) - case element(Element) - - public var isResolved: Bool { - switch self { - case .symbol: - return false - case .element: - return true - } - } - - public var symbol: Symbol? { - switch self { - case .symbol(let unsolvedSymbol): - return unsolvedSymbol - case .element: - return nil - } - } - - public var resolved: Element? { - switch self { - case .symbol: - return nil - case .element(let element): - return element - } - } - - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - if let symbol = boundSymbol(at: address, in: context) { - return .symbol(symbol) - } else { - return .element(try Element.resolve(at: address, in: context)) - } - } - - public static func resolve(at address: Context.Address, in context: Context) throws -> Self? { - if let symbol = boundSymbol(at: address, in: context) { - return .symbol(symbol) - } else { - return try Element.resolve(at: address, in: context).map { .element($0) } - } - } - - /// The symbol dyld binds at `address`, when the context reads a file whose - /// bind table names one there: the element lives in another image, so - /// there is nothing at `address` to read. - private static func boundSymbol(at address: Context.Address, in context: Context) -> Symbol? { - guard let resolver = context.bindRebaseResolver, let offset = try? context.offsetFromAddress(address), let name = resolver.resolveBind(fileOffset: offset) else { - return nil - } - return Symbol(offset: offset, name: name) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - try resolve(at: offset, in: machO.context) - } - - @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try resolve(at: ptr, in: InProcessContext.shared) - } - - public func map(_ transform: (Element) throws(E) -> T) throws(E) -> SymbolOrElement { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .element(let context): - return try .element(transform(context)) - } - } - - public func mapOptional(_ transform: (Element) throws(E) -> T?) throws(E) -> SymbolOrElement? { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .element(let context): - if let transformed = try transform(context) { - return .element(transformed) - } else { - return nil - } - } - } - - public func flatMap(_ transform: (Element) throws(E) -> SymbolOrElement) throws(E) -> SymbolOrElement { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .element(let context): - return try transform(context) - } - } -} - -extension SymbolOrElement where Element: OptionalProtocol, Element.Wrapped: Resolvable { - public var asOptional: SymbolOrElement? { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .element(let optionalContext): - if let context = optionalContext.flatMap({ $0 }) { - return .element(context) - } else { - return nil - } - } - } -} - -extension SymbolOrElement: Equatable where Element: Equatable {} - -extension SymbolOrElement: Hashable where Element: Hashable {} diff --git a/Sources/MachO/MachOResolving/Symbols.swift b/Sources/MachO/MachOResolving/Symbols.swift deleted file mode 100644 index 0a6b19b34..000000000 --- a/Sources/MachO/MachOResolving/Symbols.swift +++ /dev/null @@ -1,51 +0,0 @@ -/// Every symbol found at one offset. -/// -/// Identical code folding leaves several names at one address, so a -/// symbol lookup answers with a collection rather than a single `Symbol`. -/// The resolution layer only defines the collection; `MachOSymbols` -/// populates it from its per-image index. -public struct Symbols: Sendable { - public let offset: Int - - private var _storage: [Symbol] = [] - - package init(offset: Int, symbols: [Symbol]) { - self.offset = offset - self._storage = symbols - } -} - -extension Symbols: RandomAccessCollection { - public typealias Element = Symbol - - public var startIndex: Int { _storage.startIndex } - - public var endIndex: Int { _storage.endIndex } - - public func index(after i: Int) -> Int { - _storage.index(after: i) - } -} - -extension Symbols: MutableCollection { - public subscript(position: Int) -> Symbol { - get { - _storage[position] - } - set { - _storage[position] = newValue - } - } - - public mutating func append(_ newElement: Symbol) { - _storage.append(newElement) - } - - public mutating func remove(at index: Int) { - _storage.remove(at: index) - } - - public mutating func removeAll() { - _storage.removeAll() - } -} diff --git a/Sources/MachO/MachOSymbols/SymbolRowBucket.swift b/Sources/MachO/MachOSymbols/SymbolRowBucket.swift deleted file mode 100644 index 681f75b02..000000000 --- a/Sources/MachO/MachOSymbols/SymbolRowBucket.swift +++ /dev/null @@ -1,59 +0,0 @@ -/// Row-index bucket for `SymbolIndexStore`'s offset and member indexes -/// (evolution proposal 0003): almost every offset / member key maps to -/// exactly one symbol-table row, so the single-row form stays inline in the -/// dictionary slot and only a bucket that actually collects a second row -/// pays a heap allocation. The former `[UInt32]` buckets paid an array -/// allocation per key — one per hundreds of thousands of keys in a -/// framework-scale image. -/// -/// Iteration order is insertion order in both forms (`multiple` preserves -/// the array's append order, `single` is trivially ordered), so query -/// output is byte-identical to the `[UInt32]` representation it replaces. -enum SymbolRowBucket: Equatable, Sendable { - case single(UInt32) - case multiple([UInt32]) - - /// Starting value for the `dictionary[key, default: .empty].append(row)` - /// accumulation idiom. `.multiple([])` allocates nothing (an empty - /// `Array` shares the global empty storage singleton) and the first - /// `append` rewrites it to the inline `single` form. - static var empty: SymbolRowBucket { .multiple([]) } - - mutating func append(_ row: UInt32) { - switch self { - case .multiple(let rows) where rows.isEmpty: - self = .single(row) - case .single(let existingRow): - self = .multiple([existingRow, row]) - case .multiple(var rows): - // Drop the payload's array reference before mutating so the - // append never triggers a copy-on-write of the whole bucket. - self = .empty - rows.append(row) - self = .multiple(rows) - } - } -} - -extension SymbolRowBucket: RandomAccessCollection { - var startIndex: Int { 0 } - - var endIndex: Int { - switch self { - case .single: - return 1 - case .multiple(let rows): - return rows.count - } - } - - subscript(position: Int) -> UInt32 { - switch self { - case .single(let row): - precondition(position == 0, "single-row bucket only has index 0") - return row - case .multiple(let rows): - return rows[position] - } - } -} diff --git a/Sources/MachO/MachOSymbols/SymbolTable.swift b/Sources/MachO/MachOSymbols/SymbolTable.swift deleted file mode 100644 index fedf4c745..000000000 --- a/Sources/MachO/MachOSymbols/SymbolTable.swift +++ /dev/null @@ -1,402 +0,0 @@ -import MachOResolving -import Foundation -import MachOKit - -/// One retained symbol row: 16 bytes. The row holds the canonical -/// (cache-adjusted) offset plus a packed reference to the name's bytes; -/// the name itself is materialized on demand from the table's name source -/// (evolution proposal 0001 — the previous representation retained a -/// 32-byte `Symbol` with an interned `String` per row). -struct SymbolRow { - var canonicalOffset: Int64 - - var packedNameReference: PackedNameReference -} - -/// Packed location of a symbol name's bytes within a `SymbolTable`'s name -/// source. Layout (most significant bit first): 1 bit name source -/// (0 = mapped string table, 1 = private name buffer), 1 bit `isExternal`, -/// 22 bits byte length, 40 bits byte offset into the source. -struct PackedNameReference { - let rawValue: UInt64 - - private static let byteOffsetBitCount: UInt64 = 40 - private static let byteLengthBitCount: UInt64 = 22 - private static let byteOffsetMask: UInt64 = (1 << byteOffsetBitCount) - 1 - private static let byteLengthMask: UInt64 = (1 << byteLengthBitCount) - 1 - private static let privateNameBufferFlag: UInt64 = 1 << 63 - private static let isExternalFlag: UInt64 = 1 << 62 - - /// The widest name byte length / source byte offset the packed layout - /// can represent. Values beyond these arrive only from malformed or - /// hostile input — no legitimate mangled name approaches the 4 MB - /// length budget — so the initializer refuses them instead of trapping: - /// these components are binary-supplied (strlen over a string table, - /// accumulated buffer offsets), and a `precondition` would let the - /// analyzed binary decide whether the host process lives. - static var maximumByteLength: Int { Int(byteLengthMask) } - static var maximumByteOffset: Int { Int(byteOffsetMask) } - - private init(rawValue: UInt64) { - self.rawValue = rawValue - } - - init?(usesPrivateNameBuffer: Bool, isExternal: Bool, byteOffset: Int, byteLength: Int) { - guard byteOffset >= 0, UInt64(byteOffset) <= Self.byteOffsetMask, - byteLength >= 0, UInt64(byteLength) <= Self.byteLengthMask else { return nil } - var packed = UInt64(byteOffset) | (UInt64(byteLength) << Self.byteOffsetBitCount) - if isExternal { - packed |= Self.isExternalFlag - } - if usesPrivateNameBuffer { - packed |= Self.privateNameBufferFlag - } - self.rawValue = packed - } - - /// The same reference with only the external bit replaced — raw bit - /// surgery, no re-validation, for updating an already-packed row in - /// place. - func replacingIsExternal(_ isExternal: Bool) -> PackedNameReference { - var packed = rawValue & ~Self.isExternalFlag - if isExternal { - packed |= Self.isExternalFlag - } - return PackedNameReference(rawValue: packed) - } - - var usesPrivateNameBuffer: Bool { - rawValue & Self.privateNameBufferFlag != 0 - } - - var isExternal: Bool { - rawValue & Self.isExternalFlag != 0 - } - - var byteOffset: Int { - Int(rawValue & Self.byteOffsetMask) - } - - var byteLength: Int { - Int((rawValue >> Self.byteOffsetBitCount) & Self.byteLengthMask) - } -} - -/// The frozen per-image symbol table: compact rows plus the bytes their -/// names point into. Replaces the former bare `[Symbol]` (whose every row -/// retained a name `String`) and the name-keyed row dictionary. -/// -/// Names come from one of two sources per row: -/// - the image's mmap'd LINKEDIT string table (`MachOImage` rows) — clean -/// pages the kernel can reclaim, read zero-copy at materialization; -/// - the table's own private contiguous byte buffer (`MachOFile` rows and -/// export-trie names, whose decoded strings exist nowhere in mapped -/// memory). -/// -/// Lifetime constraint (accepted in proposal 0001): `mappedStringTableBase` -/// points into the loaded image and dangles if the image is ever unloaded. -/// Name materialization therefore requires the image to stay loaded — the -/// same requirement every other in-process read path already has, but now -/// extending to vended values' `symbol` accessor. Empirically the unload -/// cannot happen on Darwin (probed 2026-08-09, macOS 26): dyld pins every -/// image carrying Swift/ObjC content as never-unload — `dlclose` leaves -/// even a class-less Swift dylib mapped — and the only images that DO -/// unmap (pure C, no ObjC/Swift) contain no Swift-mangling-prefixed names, -/// so they never mint mapped rows in the first place. See -/// `Documentations/Internal/ReviewAdjudications.md` (A4). -/// -/// The byte access layer uses `UnsafeBufferPointer` rather than -/// `Span`/`UTF8Span`: the Span family is only available at runtime on -/// macOS 26 / iOS 26 and newer, above this package's deployment floor. -/// -/// `@unchecked Sendable`: every stored property is immutable after `init`. -final class SymbolTable: @unchecked Sendable { - /// Base of the image's mmap'd string table; `nil` for tables whose rows - /// all live in `privateNameBuffer`. - let mappedStringTableBase: UnsafeRawPointer? - - /// Name bytes for rows outside the mapped string table — one contiguous - /// allocation appended during the build sweep, exact-capacity at freeze. - let privateNameBuffer: [UInt8] - - let rows: [SymbolRow] - - /// Name-order permutation over `rows`: binary search over it replaces - /// the former `[String: UInt32]` row dictionary. Ordering and equality - /// are exact byte comparisons — mangled names are ASCII by construction, - /// and byte equality is precisely the identity a mangled name needs. - let rowsSortedByName: [UInt32] - - init(mappedStringTableBase: UnsafeRawPointer?, privateNameBuffer: [UInt8], rows: [SymbolRow], rowsSortedByName: [UInt32]) { - self.mappedStringTableBase = mappedStringTableBase - self.privateNameBuffer = privateNameBuffer - self.rows = rows - self.rowsSortedByName = rowsSortedByName - } - - /// A one-row table for a standalone value (`DemangledSymbol(symbol:demangledNode:)` - /// and `detachedFromSharedTable()`): the name is copied into a private - /// buffer so the detached value retains nothing image-scoped. - convenience init(standaloneSymbol symbol: Symbol) { - // Clamped, not trapped: the packed reference cannot represent a name - // beyond `PackedNameReference.maximumByteLength` (4 MB — far past - // any legitimate mangled name), and this initializer backs the - // public `DemangledSymbol(symbol:demangledNode:)`, so absurd caller - // input degrades to a truncated materialized name instead of - // killing the process. Rows minted by the build sweep are - // budget-checked there and never reach the clamp. - let nameBytes = Array(symbol.name.utf8.prefix(PackedNameReference.maximumByteLength)) - // Never nil: byteOffset is 0 and the clamp above bounds the length. - let packedNameReference = PackedNameReference(usesPrivateNameBuffer: true, isExternal: symbol.isExternal, byteOffset: 0, byteLength: nameBytes.count)! - self.init( - mappedStringTableBase: nil, - privateNameBuffer: nameBytes, - rows: [SymbolRow(canonicalOffset: Int64(symbol.offset), packedNameReference: packedNameReference)], - rowsSortedByName: [0] - ) - } - - var rowCount: Int { - rows.count - } - - func canonicalOffset(atRow row: UInt32) -> Int { - Int(rows[Int(row)].canonicalOffset) - } - - func isExternal(atRow row: UInt32) -> Bool { - rows[Int(row)].packedNameReference.isExternal - } - - /// Scoped access to a row's raw name bytes (no terminator). The buffer - /// is only valid inside `body` — for mapped rows it points straight into - /// the image's string table. - func withNameBytes(atRow row: UInt32, _ body: (UnsafeBufferPointer) throws -> Result) rethrows -> Result { - let nameReference = rows[Int(row)].packedNameReference - if nameReference.usesPrivateNameBuffer { - return try privateNameBuffer.withUnsafeBufferPointer { buffer in - try body(UnsafeBufferPointer(rebasing: buffer[nameReference.byteOffset ..< nameReference.byteOffset + nameReference.byteLength])) - } - } else { - let baseAddress = mappedStringTableBase.unsafelyUnwrapped.advanced(by: nameReference.byteOffset).assumingMemoryBound(to: UInt8.self) - return try body(UnsafeBufferPointer(start: baseAddress, count: nameReference.byteLength)) - } - } - - /// Builds the row's name `String` on demand. `String(decoding:)` repairs - /// invalid UTF-8 exactly like the `String(cString:)` the eager - /// representation used, so materialized names match it byte for byte. - func materializedName(atRow row: UInt32) -> String { - withNameBytes(atRow: row) { String(decoding: $0, as: UTF8.self) } - } - - /// The row's `Symbol` with its canonical (cache-adjusted) offset. - func symbol(atRow row: UInt32) -> Symbol { - let symbolRow = rows[Int(row)] - return Symbol(offset: Int(symbolRow.canonicalOffset), name: materializedName(atRow: row), isExternal: symbolRow.packedNameReference.isExternal) - } - - /// The table row holding `name`, via binary search over the name-order - /// permutation. Comparison is on raw bytes, so a hit means exact byte - /// equality with the queried string's UTF-8. - func row(forName name: String) -> UInt32? { - var mutableName = name - return mutableName.withUTF8 { nameBytes -> UInt32? in - var lowerBound = 0 - var upperBound = rowsSortedByName.count - while lowerBound < upperBound { - let middle = (lowerBound + upperBound) / 2 - let candidateRow = rowsSortedByName[middle] - let ordering = withNameBytes(atRow: candidateRow) { compareSymbolNameBytes($0, nameBytes) } - if ordering == 0 { - return candidateRow - } else if ordering < 0 { - lowerBound = middle + 1 - } else { - upperBound = middle - } - } - return nil - } - } -} - -/// Build-time accumulator for `SymbolTable`. Holds a name-keyed dedup -/// dictionary that exists only until `freeze()` — the frozen table answers -/// name lookups by binary search instead. -struct SymbolTableBuilder { - private let mappedStringTableBase: UnsafeRawPointer? - - private var rows: [SymbolRow] = [] - - private var privateNameBuffer: [UInt8] = [] - - /// Build-time dedup only; discarded at freeze. Keys are transient - /// `String`s materialized per Swift-flagged symbol. - private var tableRowByName: [String: UInt32] = [:] - - init(mappedStringTableBase: UnsafeRawPointer?) { - self.mappedStringTableBase = mappedStringTableBase - } - - var rowCount: Int { - rows.count - } - - func existingRow(forName name: String) -> UInt32? { - tableRowByName[name] - } - - /// The table row for a symbol whose name lives in the mapped string - /// table, plus whether this call created it. A duplicate name updates - /// the existing row's offset and external bit in place (last-wins, like - /// the former name-keyed collection pass) and keeps the first - /// occurrence's name reference — the bytes are equal by definition. - mutating func canonicalRow(forName name: String, mappedNameByteOffset: Int, nameByteLength: Int, canonicalOffset: Int, isExternal: Bool) -> (row: UInt32, isNewRow: Bool)? { - precondition(mappedStringTableBase != nil, "mapped name references require a mapped string table base") - // The offset and length are binary-supplied (a pointer difference - // into the mapped string table, and strlen over it): a name whose - // geometry cannot pack is malformed input, and its row is refused — - // the caller skips the symbol — rather than trapping the process. - guard let nameReference = PackedNameReference(usesPrivateNameBuffer: false, isExternal: isExternal, byteOffset: mappedNameByteOffset, byteLength: nameByteLength) else { - return nil - } - return canonicalRow( - forName: name, - nameReference: nameReference, - canonicalOffset: canonicalOffset - ) - } - - /// The table row for a symbol whose name has no mapped-memory home - /// (`MachOFile` rows, export-trie names): a new row appends the name's - /// bytes to the private buffer. Refuses (returns `nil` for) a name - /// whose geometry cannot pack — same budget rule as the mapped - /// overload, validated BEFORE appending so a refused name leaves no - /// orphan bytes in the buffer. - mutating func canonicalRow(forName name: String, canonicalOffset: Int, isExternal: Bool) -> (row: UInt32, isNewRow: Bool)? { - if let existingRow = tableRowByName[name] { - updateRowInPlace(existingRow, canonicalOffset: canonicalOffset, isExternal: isExternal) - return (existingRow, false) - } - let byteOffset = privateNameBuffer.count - guard name.utf8.count <= PackedNameReference.maximumByteLength, - byteOffset <= PackedNameReference.maximumByteOffset else { - return nil - } - privateNameBuffer.append(contentsOf: name.utf8) - // Never nil: both components were bounds-checked above. - let nameReference = PackedNameReference(usesPrivateNameBuffer: true, isExternal: isExternal, byteOffset: byteOffset, byteLength: privateNameBuffer.count - byteOffset)! - return appendRow(forName: name, nameReference: nameReference, canonicalOffset: canonicalOffset) - } - - /// Opens the row of a debug-map (STABS) entry's name, and never touches - /// an existing one. The entry may fix where the name sits in the table — - /// rows then keep the debug map's order, which is the source's, and the - /// printers list members in row order — but its value never becomes the - /// row's offset: the symbol it describes overwrites it when listed after - /// the entry, and is left alone when listed before it. An `N_GSYM` - /// entry's value is 0. - mutating func reserveRow(forName name: String, canonicalOffset: Int) { - guard tableRowByName[name] == nil else { return } - _ = canonicalRow(forName: name, canonicalOffset: canonicalOffset, isExternal: false) - } - - /// ``reserveRow(forName:canonicalOffset:)`` for a name that lives in the - /// mapped string table. - mutating func reserveRow(forName name: String, mappedNameByteOffset: Int, nameByteLength: Int, canonicalOffset: Int) { - guard tableRowByName[name] == nil else { return } - _ = canonicalRow(forName: name, mappedNameByteOffset: mappedNameByteOffset, nameByteLength: nameByteLength, canonicalOffset: canonicalOffset, isExternal: false) - } - - private mutating func canonicalRow(forName name: String, nameReference: PackedNameReference, canonicalOffset: Int) -> (row: UInt32, isNewRow: Bool) { - if let existingRow = tableRowByName[name] { - updateRowInPlace(existingRow, canonicalOffset: canonicalOffset, isExternal: nameReference.isExternal) - return (existingRow, false) - } - return appendRow(forName: name, nameReference: nameReference, canonicalOffset: canonicalOffset) - } - - private mutating func updateRowInPlace(_ row: UInt32, canonicalOffset: Int, isExternal: Bool) { - rows[Int(row)] = SymbolRow( - canonicalOffset: Int64(canonicalOffset), - packedNameReference: rows[Int(row)].packedNameReference.replacingIsExternal(isExternal) - ) - } - - private mutating func appendRow(forName name: String, nameReference: PackedNameReference, canonicalOffset: Int) -> (row: UInt32, isNewRow: Bool) { - let newRow = UInt32(rows.count) - rows.append(SymbolRow(canonicalOffset: Int64(canonicalOffset), packedNameReference: nameReference)) - tableRowByName[name] = newRow - return (newRow, true) - } - - /// Freezes into the immutable table: exact-capacity copies drop the - /// append-time growth slack, the dedup dictionary is discarded, and the - /// name-order permutation is sorted for binary search. - consuming func freeze() -> SymbolTable { - let frozenRows = exactCapacityCopy(rows) - let frozenNameBuffer = exactCapacityCopy(privateNameBuffer) - var permutation = Array(UInt32(0) ..< UInt32(frozenRows.count)) - let frozenMappedStringTableBase = mappedStringTableBase - frozenNameBuffer.withUnsafeBufferPointer { privateBuffer in - func nameBytes(ofRow row: UInt32) -> UnsafeBufferPointer { - let nameReference = frozenRows[Int(row)].packedNameReference - if nameReference.usesPrivateNameBuffer { - return UnsafeBufferPointer(rebasing: privateBuffer[nameReference.byteOffset ..< nameReference.byteOffset + nameReference.byteLength]) - } else { - let baseAddress = frozenMappedStringTableBase.unsafelyUnwrapped.advanced(by: nameReference.byteOffset).assumingMemoryBound(to: UInt8.self) - return UnsafeBufferPointer(start: baseAddress, count: nameReference.byteLength) - } - } - permutation.sort { compareSymbolNameBytes(nameBytes(ofRow: $0), nameBytes(ofRow: $1)) < 0 } - } - return SymbolTable( - mappedStringTableBase: frozenMappedStringTableBase, - privateNameBuffer: frozenNameBuffer, - rows: frozenRows, - rowsSortedByName: permutation - ) - } - - private func exactCapacityCopy(_ elements: [Element]) -> [Element] { - guard elements.capacity > elements.count else { return elements } - var copy: [Element] = [] - copy.reserveCapacity(elements.count) - copy.append(contentsOf: elements) - return copy - } -} - -/// Three-way byte comparison (`memcmp` order with length tiebreak) — the -/// ordering `rowsSortedByName` is sorted by and searched with. -func compareSymbolNameBytes(_ left: UnsafeBufferPointer, _ right: UnsafeBufferPointer) -> Int { - let commonByteCount = min(left.count, right.count) - if commonByteCount > 0 { - let ordering = Int(memcmp(left.baseAddress.unsafelyUnwrapped, right.baseAddress.unsafelyUnwrapped, commonByteCount)) - if ordering != 0 { - return ordering - } - } - return left.count - right.count -} - -/// Byte-level `isSwiftSymbol` over a C string: mirrors -/// `Demangling.getManglingPrefixLength`'s prefix set exactly (`_T0`, `_$S`, -/// `_$s`, `_$e`, `$S`, `$s`, `$e`, `@__swiftmacro_`) so the build sweep can -/// reject a non-Swift symbol without materializing its name. `strncmp` -/// stops at the terminator, so short names are safe. Pinned equal to -/// `String.isSwiftSymbol` over a full real symbol table by -/// `SymbolTableEquivalenceTests`. -func nameBytesHaveSwiftManglingPrefix(_ nameC: UnsafePointer) -> Bool { - switch nameC.pointee { - case 0x5F: // "_" - return strncmp(nameC, "_T0", 3) == 0 || strncmp(nameC, "_$S", 3) == 0 || strncmp(nameC, "_$s", 3) == 0 || strncmp(nameC, "_$e", 3) == 0 - case 0x24: // "$" - return strncmp(nameC, "$S", 2) == 0 || strncmp(nameC, "$s", 2) == 0 || strncmp(nameC, "$e", 2) == 0 - case 0x40: // "@" - return strncmp(nameC, "@__swiftmacro_", 14) == 0 - default: - return false - } -} diff --git a/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift b/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift deleted file mode 100644 index f623d6838..000000000 --- a/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift +++ /dev/null @@ -1,73 +0,0 @@ -import MachOKit -import MachOKitExtensions - -/// Converts a symbol table entry's value into the offset the symbol index -/// files it under — the accounting every descriptor-derived offset (a vtable -/// slot's implementation, a witness, a relative pointer's target) asks with. -/// -/// `MachOKit` hands a `MachOFile` symbol over with its raw `n_value`, which is -/// a virtual address, whatever its documentation says: -/// -/// | Image | Symbol value | Index offset | -/// |---|---|---| -/// | `MachOImage` (in-process) | already an offset from the mach header | unchanged | -/// | `MachOFile` in a dyld shared cache | unslid address | the value minus `sharedRegionStart` | -/// | standalone `MachOFile` | address | the file offset its segment maps it to | -/// -/// A dylib links `__TEXT` at 0, where a standalone file's addresses and file -/// offsets coincide — which hid the standalone case until a main executable -/// (`__TEXT` at 0x100000000) had every symbol filed 0x100000000 too high: its -/// member addresses printed doubled, and no vtable slot found its name. -struct SymbolValueOffsetConverter { - private struct SegmentMapping { - let virtualMemoryAddress: UInt64 - let virtualMemorySize: UInt64 - let fileOffset: Int - } - - private enum Accounting { - case unchanged - case sharedRegion(start: Int) - case segments([SegmentMapping]) - } - - private let accounting: Accounting - - init(for machO: some MachORepresentableWithCache) { - guard let machOFile = machO.asMachOFile else { - accounting = .unchanged - return - } - if let cache = machOFile.cache { - accounting = .sharedRegion(start: cache.mainCacheHeader.sharedRegionStart.cast()) - } else { - // Read once: `segments` walks the load commands on every access. - accounting = .segments(machOFile.segments.map { - SegmentMapping( - virtualMemoryAddress: UInt64($0.virtualMemoryAddress), - virtualMemorySize: UInt64($0.virtualMemorySize), - fileOffset: $0.fileOffset - ) - }) - } - } - - /// The index offset for `value`. A value that is no address in the image - /// — negative (bit 63 set) or outside every segment, as an absolute - /// symbol's constant can be — is returned unchanged. - func offset(forSymbolValue value: Int) -> Int { - switch accounting { - case .unchanged: - return value - case .sharedRegion(let sharedRegionStart): - return value >= 0 ? value - sharedRegionStart : value - case .segments(let segments): - guard value >= 0 else { return value } - let address = UInt64(value) - for segment in segments where address >= segment.virtualMemoryAddress && address - segment.virtualMemoryAddress < segment.virtualMemorySize { - return segment.fileOffset + Int(address - segment.virtualMemoryAddress) - } - return value - } - } -} diff --git a/Sources/Output/SwiftDeclarationRendering/AnnotationRegionKind+SwiftComments.swift b/Sources/Output/SwiftDeclarationRendering/AnnotationRegionKind+SwiftComments.swift new file mode 100644 index 000000000..6cb58b771 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/AnnotationRegionKind+SwiftComments.swift @@ -0,0 +1,103 @@ +import Semantic + +// The kinds of the comments the interface prints (evolution proposal +// `comment-structure`): the region a print with +// `SwiftDeclarationPrintConfiguration.marksCommentStructure` puts each comment +// in. Every other explanatory comment is a `note`, which swift-semantic-string +// defines itself. A host that meets a kind it does not know draws it as a +// note: kinds are added as the printers add comments. + +extension AnnotationRegion.Kind { + /// `// Address: 0x135DC`, `// Address (getter): 0x135DC`: where a member's + /// implementation — or one accessor's, or a class's destructor — lives. + public static let memberAddress = Self("memberAddress") + + /// `// VTable offset: 12`, `// VTable offset (setter): 13`. + public static let vtableOffset = Self("vtableOffset") + + /// `// PWT offset: 0x18`: a protocol requirement's offset in the witness + /// table. + public static let pwtOffset = Self("pwtOffset") + + /// `// Field offset: 0x8`, and below it, when the expanded offsets print, + /// the tree of the field's own fields: one `fieldLayoutNode` for each row. + public static let fieldOffset = Self("fieldOffset") + + /// `// Field offset: unknown (generic parameter not substituted)`. + public static let fieldOffsetUnknown = Self("fieldOffsetUnknown") + + /// `// │ ├── _countAndFlagsBits (Swift.UInt64): 0x8`: one row of the + /// expanded field-offset tree and the rows nested under it, each a + /// `fieldLayoutNode` of its own. + public static let fieldLayoutNode = Self("fieldLayoutNode") + + /// `// Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 0)`; + /// for a tuple read in process, the whole block of its elements' layouts + /// and its own. + public static let typeLayout = Self("typeLayout") + + /// One element of a tuple's type layout block: its `// Type: Swift.Int` + /// and `// Layout: (…)` lines. + public static let typeLayoutElement = Self("typeLayoutElement") + + /// `/* Tagged Multi-Payload (tag bytes after the payload area) — cases: 3 + /// (2 payload + 1 empty); … */`: an enum's layout strategy and its facts. + public static let enumLayoutSummary = Self("enumLayoutSummary") + + /// `/* Enum Layout */` and the block of lines below it that describes one + /// case, each line a region of one of the five kinds that follow. + public static let enumLayoutCase = Self("enumLayoutCase") + + /// ``// Case 1 (0x01) `withPair` — payload case #1``. + public static let enumLayoutCaseHeader = Self("enumLayoutCaseHeader") + + /// `// encoding: tag byte(s) after the payload area = 1; …`. + public static let enumLayoutCaseEncoding = Self("enumLayoutCaseEncoding") + + /// `// note: the exact bytes depend on …`. + public static let enumLayoutCaseNote = Self("enumLayoutCaseNote") + + /// `// fixed bytes: byte[0x18] = 0x1 (0b00000001)`. + public static let enumLayoutCaseFixedBytes = Self("enumLayoutCaseFixedBytes") + + /// `// offset 0x18 = 0x01 (0b00000001)`: one fixed byte. + public static let enumLayoutCaseByte = Self("enumLayoutCaseByte") + + /// `// not exported`. + public static let exportStatus = Self("exportStatus") + + /// `// protocol-extension default`. + public static let protocolExtensionDefault = Self("protocolExtensionDefault") + + /// `// init accessor: the binary does not record which stored properties it initializes`: + /// above a property whose SE-0400 init accessor initializes fields + /// nothing in the image names. The dump puts it, or + /// `// init accessor: initializes _value (inferred from the stored property's name and type)`, + /// above every init accessor's symbol. + public static let initAccessorFields = Self("initAccessorFields") + + /// `// EnabledKey is declared in Enabled.swift of module SwiftUICore`. + public static let privateDeclarationSource = Self("privateDeclarationSource") + + /// `// Body is picked at run time by an availability check (SE-0360):` + /// and the lines below it, each a `conditionalWitnessBranch`. + public static let conditionalWitness = Self("conditionalWitness") + + /// `// macOS 26.0 or later: some SwiftUI.View`. + public static let conditionalWitnessBranch = Self("conditionalWitnessBranch") + + /// `// Kind: Method, isAsync: false, isInstance: true`: what a protocol + /// requirement whose symbol was stripped still records. + public static let strippedSymbolicRequirement = Self("strippedSymbolicRequirement") + + /// `// NS_REFINED_FOR_SWIFT: var __settings: __C.SHScenePresentationSettings! { get set }`: + /// in the Swift view of an Objective-C class, a member the header refines + /// for Swift whose Swift declaration the image keeps no symbol of. + public static let refinedForSwiftMember = Self("refinedForSwiftMember") + + // Comments only the dump prints, and the dump marks none. + + package static let deletedMethodSlot = Self("deletedMethodSlot") + package static let ambiguousAttribution = Self("ambiguousAttribution") + package static let spareBits = Self("spareBits") +} diff --git a/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift b/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift index 770bd3f4e..fc5333e87 100644 --- a/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift +++ b/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift @@ -63,14 +63,31 @@ public enum ConditionalWitnessComment { /// more than one branch, because a single answer is already the /// `typealias` line. public static func lines(associatedTypeName: String, branches: [Branch]) -> [String] { + lineBodies(associatedTypeName: associatedTypeName, branches: branches).map(\.text) + } + + /// `lines(associatedTypeName:branches:)` as segments: the associated + /// type's name, and each branch's condition and type (evolution proposal + /// `comment-structure`). + package static func lineBodies(associatedTypeName: String, branches: [Branch]) -> [[StructuredComment.Segment]] { guard branches.count >= 2 else { return [] } - let labels = branches.map { branch in (branch.availability?.phrase ?? "always") + ":" } - let labelWidth = labels.map(\.count).max() ?? 0 - var lines = ["\(associatedTypeName) is picked at run time by an availability check (SE-0360):"] - for (label, branch) in zip(labels, branches) { - lines.append(" " + label.padding(toLength: labelWidth, withPad: " ", startingAt: 0) + " " + branch.typeText) + let phrases = branches.map { branch in branch.availability?.phrase ?? "always" } + let labelWidth = phrases.map { ($0 + ":").count }.max() ?? 0 + var lineBodies: [[StructuredComment.Segment]] = [[ + .name(associatedTypeName), .separator(" "), + .text("is picked at run time by an availability check (SE-0360)"), .separator(":"), + ]] + for (phrase, branch) in zip(phrases, branches) { + // The padding lines the types up, so it goes with the colon. + let paddedLabel = (phrase + ":").padding(toLength: labelWidth, withPad: " ", startingAt: 0) + let condition: [StructuredComment.Segment] = if paddedLabel.hasPrefix(phrase) { + [.qualifier(phrase), .separator(String(paddedLabel.dropFirst(phrase.count)) + " ")] + } else { + [.qualifier(paddedLabel), .separator(" ")] + } + lineBodies.append([.marker(" ")] + condition + [.type(branch.typeText)]) } - return lines + return lineBodies } } @@ -79,13 +96,22 @@ extension Node.OpaqueTypeResolution { /// this resolution's branches, each printed through `resolver` so the /// comment spells types exactly as the `typealias` line does. package func conditionalWitnessCommentLines(associatedTypeName: String, resolvedBy resolver: DemangleResolver) async throws -> [String] { + try await conditionalWitnessCommentLineBodies(associatedTypeName: associatedTypeName, resolvedBy: resolver).map(\.text) + } + + /// The same lines as the comments the printers emit. + package func conditionalWitnessComments(associatedTypeName: String, resolvedBy resolver: DemangleResolver) async throws -> [StructuredComment] { + try await conditionalWitnessCommentLineBodies(associatedTypeName: associatedTypeName, resolvedBy: resolver).map(StructuredComment.line) + } + + private func conditionalWitnessCommentLineBodies(associatedTypeName: String, resolvedBy resolver: DemangleResolver) async throws -> [[StructuredComment.Segment]] { guard conditionalCandidates.count >= 2 else { return [] } var branches: [ConditionalWitnessComment.Branch] = [] for candidate in conditionalCandidates { let typeText = try await resolver.resolve(for: candidate.substitutedNode).string branches.append(ConditionalWitnessComment.Branch(availability: candidate.availability, typeText: typeText)) } - return ConditionalWitnessComment.lines(associatedTypeName: associatedTypeName, branches: branches) + return ConditionalWitnessComment.lineBodies(associatedTypeName: associatedTypeName, branches: branches) } /// The comment the dump puts above a witness whose member of an expanded diff --git a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift index 1205b28dc..78d6a5d1e 100644 --- a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift +++ b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift @@ -26,8 +26,8 @@ public struct IdentifiableClosure: Sendable { } extension IdentifiableClosure: Equatable { - public static func == (lhs: Self, rhs: Self) -> Bool { - lhs.id == rhs.id + public static func == (left: Self, right: Self) -> Bool { + left.id == right.id } } @@ -96,6 +96,13 @@ public struct DeclarationRenderConfiguration: Sendable { /// option with a `VisibilityRegion`, whatever the `print…` flags say. public var marksOptionalContent: Bool = false + /// Set by a printer that marks comment structure + /// (`SwiftDeclarationPrintConfiguration.marksCommentStructure`): every + /// comment goes in an `AnnotationRegion` of its kind, its parts in + /// segments of their roles. The dump never sets it. + @Init(.ignore) + package var marksCommentStructure: 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 @@ -123,7 +130,7 @@ extension DeclarationRenderConfiguration { case .printVTableOffset: printVTableOffset case .printTypeLayout: printTypeLayout case .printEnumLayout: printEnumLayout - case .printStrippedSymbolicItem, .printPWTOffset, .infersObjCOverridesFromSelectorNames, .opaqueTypeResolution: false + case .printStrippedSymbolicItem, .printPWTOffset, .infersObjCOverridesFromSelectorNames, .printExportedDeclarationsOnly, .opaqueTypeResolution, .expandsMacros: false } } @@ -154,6 +161,47 @@ extension DeclarationRenderConfiguration { } } + /// This configuration, marking comment structure or not. + package func markingCommentStructure(_ marksCommentStructure: Bool) -> Self { + var configuration = self + configuration.marksCommentStructure = marksCommentStructure + return configuration + } + + /// `content`; when marking comment structure, in a region of `kind` — + /// one spanning several comments: a field offset and its tree, a tree + /// row and the rows under it, a case's layout block. + @SemanticStringBuilder + package func commentRegion(_ kind: AnnotationRegion.Kind, @SemanticStringBuilder content: () -> SemanticString) -> SemanticString { + if marksCommentStructure { + AnnotationRegion(kind, content: content()) + } else { + content() + } + } + + /// The async form of `commentRegion(_:content:)`. + @SemanticStringBuilder + package func commentRegion(_ kind: AnnotationRegion.Kind, @SemanticStringBuilder content: () async throws -> SemanticString) async rethrows -> SemanticString { + if marksCommentStructure { + try await AnnotationRegion(kind, content: content) + } else { + try await content() + } + } + + /// `comment` as printed, marked as a comment of `kind` when marking + /// comment structure (see `StructuredComment.printed(markingStructure:as:)`). + package func comment(_ comment: StructuredComment, as kind: AnnotationRegion.Kind?) -> SemanticString { + comment.printed(markingStructure: marksCommentStructure, as: kind) + } + + /// What a transformer printed in place of a comment of `kind` (see + /// `StructuredComment.printedTemplate(_:markingStructure:as:)`). + package func templatedComment(_ output: SemanticString, as kind: AnnotationRegion.Kind?) -> SemanticString { + StructuredComment.printedTemplate(output, markingStructure: marksCommentStructure, as: kind) + } + /// Builds a member address comment line for the given symbol offset. /// /// The returned ``SemanticString`` includes indentation and a trailing line break. @@ -161,11 +209,9 @@ extension DeclarationRenderConfiguration { package func memberAddressComment(offset: Int, addressString: String, label: String? = nil) -> SemanticString { indentString if let memberAddressTransformer { - memberAddressTransformer(offset) - } else if let label { - Comment("Address (\(label)): 0x\(addressString)") + templatedComment(memberAddressTransformer(offset), as: .memberAddress) } else { - Comment("Address: 0x\(addressString)") + comment(.memberAddress(addressString: addressString, qualifier: label), as: .memberAddress) } BreakLine() } @@ -186,9 +232,9 @@ extension DeclarationRenderConfiguration { indentationLevel: Int ) -> SemanticString { if let privateDeclarationSourceFileProvider { - for line in PrivateDeclarationSourceFileComments.lines(for: nodes(), enclosedBy: enclosingNodes(), provider: privateDeclarationSourceFileProvider) { + for sourceFileComment in PrivateDeclarationSourceFileComments.comments(for: nodes(), enclosedBy: enclosingNodes(), provider: privateDeclarationSourceFileProvider) { Indent(level: indentationLevel) - Comment(line) + comment(sourceFileComment, as: .privateDeclarationSource) BreakLine() } } @@ -202,20 +248,38 @@ extension DeclarationRenderConfiguration { @SemanticStringBuilder package func exportStatusComment() -> SemanticString { indentString - Comment("not exported") + comment(.exportStatus, as: .exportStatus) + BreakLine() + } + + /// Builds the line the dumpers emit above a SE-0400 init accessor's + /// symbol (evolution proposal `init-accessor-recovery`): the fields it + /// is inferred to initialize, or that the binary does not record them. + /// + /// The returned ``SemanticString`` includes indentation and a trailing line break. + @SemanticStringBuilder + package func initAccessorFieldsComment(initializedFieldNames: [String]?) -> SemanticString { + indentString + if let initializedFieldNames { + comment(.initAccessorInitializedFields(initializedFieldNames), as: .initAccessorFields) + } else { + comment(.initAccessorFieldsNotRecorded, as: .initAccessorFields) + } BreakLine() } /// Builds a field offset comment line for the given start and end offsets. /// /// The returned ``SemanticString`` includes indentation and a trailing line break. + /// Marking comment structure, it is not a region of its own: the caller + /// puts it in a `fieldOffset` region with the expanded tree under it. @SemanticStringBuilder package func fieldOffsetComment(startOffset: Int, endOffset: Int?) -> SemanticString { indentString if let fieldOffsetTransformer { - fieldOffsetTransformer((startOffset, endOffset)) + templatedComment(fieldOffsetTransformer((startOffset, endOffset)), as: nil) } else { - Comment("Field offset: 0x\(String(startOffset, radix: 16))") + comment(.fieldOffset(startOffset), as: nil) } BreakLine() } @@ -228,23 +292,23 @@ extension DeclarationRenderConfiguration { @SemanticStringBuilder package func unknownFieldOffsetComment(reasonDescription: String) -> SemanticString { indentString - Comment("Field offset: unknown (\(reasonDescription))") + comment(.unknownFieldOffset(reasonDescription: reasonDescription), as: .fieldOffsetUnknown) BreakLine() } /// Builds an expanded field offset comment line for a nested struct sub-field. /// /// The returned ``SemanticString`` includes indentation and a trailing line break. + /// Marking comment structure, it is not a region of its own: the walk puts + /// it in a `fieldLayoutNode` region with the rows nested under it. @SemanticStringBuilder package func expandedFieldOffsetComment(fieldName: String, typeName: String, offset: Int, baseIndentation: Int, ancestors: [Bool], isLast: Bool) -> SemanticString { let treePrefix = Self.buildTreePrefix(ancestors: ancestors, isLast: isLast) Indent(level: baseIndentation) if let expandedFieldOffsetTransformer { - expandedFieldOffsetTransformer((fieldName, typeName, offset, treePrefix)) - } else if typeName.isEmpty { - Comment("\(treePrefix)\(fieldName): 0x\(String(offset, radix: 16))") + templatedComment(expandedFieldOffsetTransformer((fieldName, typeName, offset, treePrefix)), as: nil) } else { - Comment("\(treePrefix)\(fieldName) (\(typeName)): 0x\(String(offset, radix: 16))") + comment(.fieldLayoutNode(treePrefix: treePrefix, fieldName: fieldName, typeName: typeName, offset: offset), as: nil) } BreakLine() } @@ -266,11 +330,9 @@ extension DeclarationRenderConfiguration { package func vtableOffsetComment(slotOffset: Int, label: String? = nil) -> SemanticString { indentString if let vtableOffsetTransformer { - vtableOffsetTransformer((slotOffset, label)) - } else if let label { - Comment("VTable offset (\(label)): \(slotOffset)") + templatedComment(vtableOffsetTransformer((slotOffset, label)), as: .vtableOffset) } else { - Comment("VTable offset: \(slotOffset)") + comment(.vtableOffset(slotOffset, qualifier: label), as: .vtableOffset) } BreakLine() } @@ -286,7 +348,7 @@ extension DeclarationRenderConfiguration { @SemanticStringBuilder package func deletedMethodSlotComment() -> SemanticString { indentString - Comment("No implementation in this image (deleted method — slot retained for ABI)") + comment(.deletedMethodSlot, as: .deletedMethodSlot) BreakLine() } @@ -299,17 +361,23 @@ extension DeclarationRenderConfiguration { @SemanticStringBuilder package func ambiguousAttributionComment(foldedSymbolCount: Int) -> SemanticString { indentString - Comment("Attribution: ambiguous — \(foldedSymbolCount) symbols folded at this address") + comment(.ambiguousAttribution(foldedSymbolCount: foldedSymbolCount), as: .ambiguousAttribution) BreakLine() } /// Builds an enum layout per-case comment block for the given case projection. + /// + /// Marking comment structure, it is not a region of its own: the caller + /// puts it in an `enumLayoutCase` region with the `/* Enum Layout */` line + /// above it. Each line of the built-in block is a region of its own kind. @SemanticStringBuilder package func enumLayoutCaseComment(caseProjection: EnumLayoutCalculator.EnumCaseProjection) -> SemanticString { if let enumLayoutCaseTransformer { - enumLayoutCaseTransformer((caseProjection: caseProjection, indentation: indentation)) + templatedComment(enumLayoutCaseTransformer((caseProjection: caseProjection, indentation: indentation)), as: nil) + } else if marksCommentStructure { + StructuredComment.annotatedEnumLayoutCaseBlock(caseProjection, indentation: indentation) } else { - AtomicComponent(string: caseProjection.description(indent: indentation, prefix: "//"), type: .comment) + StructuredComment.enumLayoutCaseBlock(caseProjection.description(indent: indentation, prefix: "//")) } } @@ -318,9 +386,9 @@ extension DeclarationRenderConfiguration { package func spareBitAnalysisComment(analysis: SpareBitAnalyzer.Analysis) -> SemanticString { indentString if let spareBitAnalysisTransformer { - spareBitAnalysisTransformer((analysis: analysis, indentation: indentation)) + templatedComment(spareBitAnalysisTransformer((analysis: analysis, indentation: indentation)), as: .spareBits) } else { - InlineComment("Spare Bits: \(analysis.totalSpareBits) total") + comment(.spareBits(totalSpareBits: analysis.totalSpareBits), as: .spareBits) } BreakLine() } @@ -332,9 +400,9 @@ extension DeclarationRenderConfiguration { package func enumLayoutComment(layoutResult: EnumLayoutCalculator.LayoutResult) -> SemanticString { indentString if let enumLayoutTransformer { - enumLayoutTransformer(layoutResult) + templatedComment(enumLayoutTransformer(layoutResult), as: .enumLayoutSummary) } else { - InlineComment(layoutResult.summaryDescription) + comment(.enumLayoutSummary(layoutResult), as: .enumLayoutSummary) } BreakLine() } @@ -351,7 +419,15 @@ extension DeclarationRenderConfiguration { @SemanticStringBuilder package func staticTypeLayoutComment(_ staticTypeLayout: StaticTypeLayout) -> SemanticString { indentString - Comment("Type Layout: (size: \(staticTypeLayout.size), stride: \(staticTypeLayout.stride), alignment: \(staticTypeLayout.alignment), extraInhabitantCount: \(staticTypeLayout.extraInhabitantCount))") + comment( + .typeLayout( + size: staticTypeLayout.size, + stride: staticTypeLayout.stride, + alignment: staticTypeLayout.alignment, + extraInhabitantCount: staticTypeLayout.extraInhabitantCount + ), + as: .typeLayout + ) BreakLine() } } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift index 31bee8a37..5c71367e8 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift @@ -1,5 +1,6 @@ import Semantic import SwiftInspection +import SwiftObjCInterop extension CustomObjCClassName.Attribute { /// The keyword a renamed class's attribute prints with (evolution proposal diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift index 38d03fc02..d4f9c65c2 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift @@ -18,6 +18,7 @@ extension Keyword { case `override` case `static` case `dynamic` + case `optional` case `func` case `case` case `let` @@ -29,7 +30,9 @@ extension Keyword { case `Self` case `each` case `repeat` + case convenience case atObjc = "@objc" + case atNSCopying = "@NSCopying" case atObjCRuntimeName = "@_objcRuntimeName" case atImplementation = "@implementation" case atNonobjc = "@nonobjc" diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift index 09065e8dd..e22a80864 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift @@ -5,54 +5,64 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection extension MetadataWrapper { + /// The type layout comment, or for a tuple the block of its elements' + /// layouts and its own. Marking comment structure, the whole of it is one + /// `typeLayout` region, each element a `typeLayoutElement` inside it. @SemanticStringBuilder package func dumpTypeLayout(using configuration: DumperConfiguration) async throws -> SemanticString { + try await configuration.commentRegion(.typeLayout) { + try await typeLayoutLines(using: configuration) + } + } + + @SemanticStringBuilder + private func typeLayoutLines(using configuration: DumperConfiguration) async throws -> SemanticString { var isTuple = false if let tupleMetadata = tuple { configuration.indentString - InlineComment("Type Layout") + configuration.comment(.tupleTypeLayoutHeading, as: nil) BreakLine() for (_, element) in try tupleMetadata.elements(in: .inProcess).enumerated() { let tupleElementMetadata = try element.type.resolve(in: .inProcess) if let descriptor = try tupleElementMetadata.typeContextDescriptorWrapper(in: .inProcess)?.asContextDescriptorWrapper { - configuration.indentString - try await Comment("Type: " + configuration.demangleResolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptor, in: .inProcess)).string) - BreakLine() - configuration.indentString + let elementTypeName = try await configuration.demangleResolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptor, in: .inProcess)).string let elementLayout = try tupleElementMetadata.asFullMetadata(in: .inProcess).valueWitnesses.resolve(in: .inProcess).typeLayout - if let transformer = configuration.typeLayoutTransformer { - transformer(elementLayout) - } else { - Comment(elementLayout.dumpTupleDescription) + configuration.commentRegion(.typeLayoutElement) { + configuration.indentString + configuration.comment(.tupleElementType(elementTypeName), as: nil) + BreakLine() + configuration.indentString + if let transformer = configuration.typeLayoutTransformer { + configuration.templatedComment(transformer(elementLayout), as: nil) + } else { + configuration.comment(elementLayout.structuredComment(labeled: "Layout"), as: nil) + } + BreakLine() } - BreakLine() } } configuration.indentString - Comment("Total: ") + configuration.comment(.tupleTypeLayoutTotal, as: nil) BreakLine() isTuple = true } let typeLayout = try valueWitnessTable(in: .inProcess).typeLayout configuration.indentString if let transformer = configuration.typeLayoutTransformer { - transformer(typeLayout) + configuration.templatedComment(transformer(typeLayout), as: nil) } else if isTuple { - Comment(typeLayout.dumpTupleDescription) + configuration.comment(typeLayout.structuredComment(labeled: "Layout"), as: nil) } else { - Comment(typeLayout.dumpDescription) + configuration.comment(typeLayout.structuredComment(labeled: "Type Layout"), as: nil) } BreakLine() } } extension TypeLayout { - fileprivate var dumpDescription: String { - "Type Layout: (size: \(size), stride: \(stride), alignment: \(flags.alignment), extraInhabitantCount: \(extraInhabitantCount))" - } - - fileprivate var dumpTupleDescription: String { - "Layout: (size: \(size), stride: \(stride), alignment: \(flags.alignment), extraInhabitantCount: \(extraInhabitantCount))" + /// `// Type Layout: (size: …)`, or under `Layout` in a tuple's block. + fileprivate func structuredComment(labeled label: String) -> StructuredComment { + StructuredComment.typeLayout(labeled: label, size: size, stride: stride, alignment: flags.alignment, extraInhabitantCount: extraInhabitantCount) } fileprivate var dumpDebugDescription: String { diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift index 263794aa1..ce3cbbd53 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift @@ -89,7 +89,7 @@ extension DemanglingNode { /// before it, the printer recursed unguarded and a deeply nested generic /// really did overflow a 512KB worker. It is paid down at a *batch* /// boundary, never here — a `withLargeStack` around this single call would - /// save exactly the one hop it adds. `SymbolIndexStore.buildStorageImpl` + /// save exactly the one hop it adds. `SwiftSymbolIndexStore.Storage.demangledIndex` /// does that for the synchronous sweep, because it owns a loop; the /// printer's loop lives in `SwiftDeclarationPrinter` and is `async`, which /// a synchronous wrapper cannot enclose. The async side's batch boundary diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift index 1b9753da6..ccf880db6 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift @@ -1,13 +1,14 @@ import Foundation import FoundationToolbox import MachOKit +@_spi(Internals) import MachOAddressResolution import MachOSwiftSection import Demangling import OrderedCollections @_spi(Internals) import SwiftInspection import SwiftThunkAnalysis import MachODependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// Carries the logging floor onto the rewriter. /// @@ -370,7 +371,7 @@ extension Node { return try ReadOpaqueType(OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: offset, in: machO.context), in: machO.context), in: machO.context) } if reference.isKind(of: .opaqueReturnTypeOf), let memberNode = reference.firstChild, - let descriptorSymbol = SymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: memberNode, in: machO) { + let descriptorSymbol = SwiftSymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: memberNode, in: machO) { return try ReadOpaqueType(OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorSymbol.offset, in: machO.context), in: machO.context), in: machO.context) } return nil @@ -406,7 +407,7 @@ extension Node { #log(.info, "no search path located an image exporting \(descriptorSymbolName, privacy: .public)") return nil } - let imageAddressSpace = ThunkAddressSpace(of: location.image) + let imageAddressSpace = ImageAddressSpace(of: location.image) guard let descriptorAddress = imageAddressSpace.address(forExportedSymbolOffset: location.exportedSymbolOffset), let descriptorOffset = imageAddressSpace.offset(forAddress: descriptorAddress) else { return nil } @@ -723,14 +724,17 @@ fileprivate struct ReadOpaqueType { let ownerLayout: AccessorThunkOwnerLayout /// How the descriptor's parameters split into depths: what regroups the /// argument lists of a reference to it (`opaqueTypeGenericArgumentsByDepth`). - /// `nil` for a descriptor with no generic context. + /// `nil` for a descriptor with no generic context, or one whose depths + /// cannot be told (`GenericParameterDepthLayout.make(forOpaqueType:genericContext:in:)`), + /// which leaves the lists keyed by position. let depthLayout: GenericParameterDepthLayout? init(_ opaqueType: OpaqueType, in context: some ReadingContext) { self.opaqueType = opaqueType if let genericContext = opaqueType.genericContext { - let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .opaqueType(opaqueType.descriptor), in: context) - self.ownerLayout = AccessorThunkOwnerLayout(genericContext: genericContext, depthLayout: depthLayout) + let depthLayout = GenericParameterDepthLayout.make(forOpaqueType: opaqueType.descriptor, genericContext: genericContext, in: context) + self.ownerLayout = depthLayout.map { AccessorThunkOwnerLayout(genericContext: genericContext, depthLayout: $0) } + ?? AccessorThunkOwnerLayout(genericContext: genericContext) self.depthLayout = depthLayout } else { self.ownerLayout = AccessorThunkOwnerLayout(genericContext: nil as GenericContext?) diff --git a/Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift b/Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift index 5b2d7dac3..4f0610e72 100644 --- a/Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift +++ b/Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift @@ -34,6 +34,15 @@ public enum FieldRecordRendering { "synthesized from the backing storage `\(backingFieldName)`; the property's own accessors are stripped" } + /// The comment the interface prints above a property an `@Observable` + /// class tracks when it had to synthesize the declaration from the + /// property's storage because the property's own accessors are stripped + /// (`ObservableMacroExpansion.TrackedProperty.Origin.synthesized`, + /// evolution proposal `observable-macro-folding`). + public static func synthesizedTrackedPropertyComment(backingFieldName: String) -> String { + "synthesized from the storage `\(backingFieldName)` that @Observable generated; the property's own accessors are stripped" + } + /// The line printed in place of an enum element whose record carries no /// name: the element is unavailable at run time (Swift 6.4 emits neither /// its name nor its payload type) but keeps its tag, so the case count diff --git a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift index f519433af..20a0e6cb7 100644 --- a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift +++ b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import MachOFoundation +import SwiftSymbols import MachOSwiftSection @_spi(Internals) import Demangling @_spi(Internals) import SwiftInspection diff --git a/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift b/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift index 5502625a7..2179fde7f 100644 --- a/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift +++ b/Sources/Output/SwiftDeclarationRendering/PrivateDeclarationSourceFiles.swift @@ -56,6 +56,23 @@ package enum PrivateDeclarationSourceFileComments { enclosedBy enclosingNodes: [any DemanglingNode], provider: any PrivateDeclarationSourceFileProviding ) -> [String] { + lineBodies(for: nodes, enclosedBy: enclosingNodes, provider: provider).map(\.text) + } + + /// `lines(for:enclosedBy:provider:)` as the comments the printers emit. + package static func comments( + for nodes: [any DemanglingNode], + enclosedBy enclosingNodes: [any DemanglingNode], + provider: any PrivateDeclarationSourceFileProviding + ) -> [StructuredComment] { + lineBodies(for: nodes, enclosedBy: enclosingNodes, provider: provider).map(StructuredComment.line) + } + + private static func lineBodies( + for nodes: [any DemanglingNode], + enclosedBy enclosingNodes: [any DemanglingNode], + provider: any PrivateDeclarationSourceFileProviding + ) -> [[StructuredComment.Segment]] { let enclosingDiscriminators = Set(enclosingNodes.flatMap { $0.privateDeclarations.map(\.discriminator) }) var discriminators: [String] = [] var lastDeclarationByDiscriminator: [String: (declaration: PrivateDeclaration, moduleName: String?)] = [:] @@ -69,7 +86,7 @@ package enum PrivateDeclarationSourceFileComments { } } return discriminators.compactMap { discriminator in - lastDeclarationByDiscriminator[discriminator].map { line(for: $0.declaration, sourceFile: provider.sourceFile(forPrivateDiscriminator: discriminator), printedModuleName: $0.moduleName) } + lastDeclarationByDiscriminator[discriminator].map { lineBody(for: $0.declaration, sourceFile: provider.sourceFile(forPrivateDiscriminator: discriminator), printedModuleName: $0.moduleName) } } } @@ -79,13 +96,36 @@ package enum PrivateDeclarationSourceFileComments { /// 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" + lineBody(for: privateDeclaration, sourceFile: sourceFile, printedModuleName: printedModuleName).text + } + + /// `line(for:sourceFile:printedModuleName:)` as segments: the + /// declaration's name, the file's and the module's (evolution proposal + /// `comment-structure`). + package static func lineBody(for privateDeclaration: PrivateDeclaration, sourceFile: PrivateDeclarationSourceFile?, printedModuleName: String?) -> [StructuredComment.Segment] { + var body: [StructuredComment.Segment] = [] + let predicate: String + if let name = privateDeclaration.name { + body += [.name(name), .separator(" ")] + predicate = "is declared in" + } else { + predicate = "Declared in" + } guard let sourceFile else { - return "\(subject) a source file whose name could not be recovered (private discriminator \(privateDeclaration.discriminator))" + return body + [ + .text("\(predicate) a source file whose name could not be recovered"), .separator(" ("), + .key("private discriminator"), .separator(" "), .value(privateDeclaration.discriminator), .separator(")"), + ] + } + if sourceFile.isSynthesized { + body += [.text("\(predicate) the file the compiler synthesized for"), .separator(" "), .value(sourceFile.fileName)] + } else { + body += [.text(predicate), .separator(" "), .value(sourceFile.fileName)] + } + if sourceFile.moduleName != printedModuleName { + body += [.separator(" "), .text("of module"), .separator(" "), .name(sourceFile.moduleName)] } - 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)" + return body } /// The module a name is declared in: the end of its chain of contexts, diff --git a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift index c072b7c5e..c5bf1f65d 100644 --- a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift +++ b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift @@ -2,6 +2,7 @@ import Foundation @_spi(Internals) import Demangling import MachOKit import MachOFoundation +import SwiftSymbols @_spi(Internals) import MachOCaches /// What a wrapper type's `wrappedValue` accessor symbols say about it. @@ -178,7 +179,7 @@ public final class PropertyWrapperTypeCatalog: @unchecked Sendable { return winner } // `updateValue` stores a `nil` verdict unambiguously, as - // `SymbolIndexStore`'s late-demangle cache does. + // `SwiftSymbolIndexStore`'s late-demangle cache does. memoizedEvidenceByPrefix.updateValue(evidence, forKey: prefix) return evidence } diff --git a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift index 3810f26b2..0773d8513 100644 --- a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift @@ -122,18 +122,22 @@ struct RuntimeFieldLayoutBackend { endOffset = nil } configuration.optionalContent(.printFieldOffset) { - configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) - // Expanded offsets hang off the field offset: printed only - // when both are on. A field whose specialized resolution - // failed may still resolve by its bare name, so the expansion - // keeps that second try. - configuration.optionalContent(.printExpandedFieldOffsets) { - expandedFieldOffsets( - of: fieldMetatype ?? (try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, in: machO)), - baseOffset: startOffset, - baseIndentation: configuration.indentation, - ancestors: [] - ) + // The tree belongs to the field offset's region, so a host + // folds it under that line. + configuration.commentRegion(.fieldOffset) { + configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) + // Expanded offsets hang off the field offset: printed only + // when both are on. A field whose specialized resolution + // failed may still resolve by its bare name, so the expansion + // keeps that second try. + configuration.optionalContent(.printExpandedFieldOffsets) { + expandedFieldOffsets( + of: fieldMetatype ?? (try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, in: machO)), + baseOffset: startOffset, + baseIndentation: configuration.indentation, + ancestors: [] + ) + } } } } @@ -175,10 +179,12 @@ struct RuntimeFieldLayoutBackend { BreakLine() } } - configuration.indentString - InlineComment("Enum Layout") - BreakLine() - configuration.enumLayoutCaseComment(caseProjection: caseProjection) + configuration.commentRegion(.enumLayoutCase) { + configuration.indentString + configuration.comment(.enumLayoutCaseHeading, as: nil) + BreakLine() + configuration.enumLayoutCaseComment(caseProjection: caseProjection) + } } } } @@ -255,19 +261,25 @@ struct RuntimeFieldLayoutBackend { } else { let nestedEnclosingMetatypes = enclosingMetatypes.union([ObjectIdentifier(metatype)]) switch nestedFieldOffsetLevel(of: metatype) { + // A row's region holds the rows nested under it: the tree is the + // regions' nesting. case .structFields(let fields): for field in fields { let absoluteOffset = baseOffset + field.relativeOffset - configuration.expandedFieldOffsetComment(fieldName: field.fieldName, typeName: field.typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: field.isLast) - if let childMetatype = field.childMetatype { - walkNestedExpandedFieldOffsets(of: childMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [field.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: field.fieldName, typeName: field.typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: field.isLast) + if let childMetatype = field.childMetatype { + walkNestedExpandedFieldOffsets(of: childMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [field.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + } } } case .enumPayloads(let payloads): for payload in payloads { - configuration.expandedFieldOffsetComment(fieldName: payload.caseName, typeName: payload.typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: payload.isLast) - if payload.descends { - walkNestedExpandedFieldOffsets(of: payload.payloadMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [payload.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: payload.caseName, typeName: payload.typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: payload.isLast) + if payload.descends { + walkNestedExpandedFieldOffsets(of: payload.payloadMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [payload.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + } } } case .notExpanded: diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift index fe7cae1c5..5f70e6ba6 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift @@ -108,11 +108,15 @@ struct StaticFieldLayoutBackend { endOffset = nil } configuration.optionalContent(.printFieldOffset) { - configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) - // Expanded offsets hang off the field offset: printed only - // when both are on. - configuration.optionalContent(.printExpandedFieldOffsets) { - expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset) + // The tree belongs to the field offset's region, so a host + // folds it under that line. + configuration.commentRegion(.fieldOffset) { + configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) + // Expanded offsets hang off the field offset: printed only + // when both are on. + configuration.optionalContent(.printExpandedFieldOffsets) { + expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset) + } } } } else if @@ -189,8 +193,12 @@ struct StaticFieldLayoutBackend { private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors: [Bool]) -> SemanticString { for (index, node) in nodes.enumerated() { let isLast = index == nodes.count - 1 - configuration.expandedFieldOffsetComment(fieldName: node.fieldName, typeName: node.typeName, offset: node.offset, baseIndentation: configuration.indentation, ancestors: ancestors, isLast: isLast) - renderNestedFieldOffsetTree(node.children, ancestors: ancestors + [isLast]) + // A row's region holds the rows nested under it: the tree is the + // regions' nesting. + configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: node.fieldName, typeName: node.typeName, offset: node.offset, baseIndentation: configuration.indentation, ancestors: ancestors, isLast: isLast) + renderNestedFieldOffsetTree(node.children, ancestors: ancestors + [isLast]) + } } } @@ -222,10 +230,12 @@ struct StaticFieldLayoutBackend { BreakLine() } } - configuration.indentString - InlineComment("Enum Layout") - BreakLine() - configuration.enumLayoutCaseComment(caseProjection: caseProjection) + configuration.commentRegion(.enumLayoutCase) { + configuration.indentString + configuration.comment(.enumLayoutCaseHeading, as: nil) + BreakLine() + configuration.enumLayoutCaseComment(caseProjection: caseProjection) + } } } } diff --git a/Sources/Output/SwiftDeclarationRendering/StructuredComment+EnumLayoutCase.swift b/Sources/Output/SwiftDeclarationRendering/StructuredComment+EnumLayoutCase.swift new file mode 100644 index 000000000..01154d158 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/StructuredComment+EnumLayoutCase.swift @@ -0,0 +1,122 @@ +import Foundation +import Semantic +import OutputTransformer +import SwiftOutputTransformer +@_spi(Internals) import SwiftInspection + +// One enum case's layout block, marked line by line (evolution proposal +// `comment-structure`). Unmarked, the block prints through +// `EnumCaseProjection.description(indent:prefix:)` — the `.detailed` template +// the dump and the template engine share — so this spells the same lines a +// second time, one segment at a time. `StructuredCommentTests` holds the two +// to the same text for every wording, and the contract tests for every enum +// of the fixture. + +extension StructuredComment { + /// The layout block of one case as `description(indent: indentation, + /// prefix: "//")` prints it — one annotated atom, each line a region: + /// the header, the encoding, the note, the fixed bytes, then one region + /// for each fixed byte. A line's code indentation and its line break lie + /// outside its region. + package static func annotatedEnumLayoutCaseBlock(_ caseProjection: EnumLayoutCalculator.EnumCaseProjection, indentation: Int) -> AnnotatedAtom { + let caseInput = Transformer.SwiftEnumLayout.CaseInput(caseProjection) + var lines: [(kind: AnnotationRegion.Kind, body: [Segment])] = [(.enumLayoutCaseHeader, enumLayoutCaseHeaderBody(caseInput))] + if !caseInput.encoding.isEmpty { + lines.append((.enumLayoutCaseEncoding, [.label("encoding"), .separator(": "), .text(caseInput.encoding)])) + } + if !caseInput.patternNote.isEmpty { + lines.append((.enumLayoutCaseNote, [.label("note"), .separator(": "), .text(caseInput.patternNote)])) + } + lines.append((.enumLayoutCaseFixedBytes, enumLayoutCaseFixedBytesBody(caseProjection, caseInput: caseInput))) + for (offset, value) in caseProjection.memoryChanges.sorted(by: { $0.key < $1.key }) { + // The detail lines sit four spaces further in than the others. + let body = enumLayoutCaseByteBody(offset: offset, value: value, fixedBitMask: caseProjection.fixedBitMask(atByteOffset: offset)) + lines.append((.enumLayoutCaseByte, [.marker(" ")] + body)) + } + + let codeIndentation = String(repeating: " ", count: indentation) + var blockPieces = SemanticString() + for (lineIndex, line) in lines.enumerated() { + // Every line after the first is a continuation, two spaces in. + let marker: [Segment] = lineIndex == 0 ? [.marker("// ")] : [.marker("// "), .marker(" ")] + blockPieces.append(Standard(codeIndentation)) + blockPieces.append(AnnotationRegion(line.kind, content: Self.pieces(of: marker + line.body))) + blockPieces.append(Standard("\n")) + } + return AnnotatedAtom(type: .comment, content: blockPieces) + } + + /// ``Case 1 (0x01) `withPair` — payload case #1``: the case's index, in + /// decimal and in hexadecimal, its declared name when the records keep + /// one, and its structural label. + private static func enumLayoutCaseHeaderBody(_ caseInput: Transformer.SwiftEnumLayout.CaseInput) -> [Segment] { + var body: [Segment] = [ + .label("Case"), .separator(" "), .value(String(caseInput.caseIndex)), + .separator(" ("), .value(String(format: "0x%02X", caseInput.caseIndex)), + ] + if let declaredName = caseInput.declaredName { + body += [.separator(") `"), .name(declaredName), .separator("` — ")] + } else { + body.append(.separator(") — ")) + } + return body + structuralCaseNameBody(caseInput.caseName) + } + + /// `payload case #1` as the kind of case and its number among the cases + /// of that kind; a label of any other shape, whole. + private static func structuralCaseNameBody(_ caseName: String) -> [Segment] { + guard let numberSeparator = caseName.range(of: " #", options: .backwards) else { + return [.key(caseName)] + } + let number = caseName[numberSeparator.upperBound...] + guard !number.isEmpty, number.allSatisfy({ $0.isASCII && $0.isNumber }) else { + return [.key(caseName)] + } + return [.key(String(caseName[.. [Segment] { + let labelText = "fixed bytes: " + guard !caseProjection.memoryChanges.isEmpty else { + let line = caseInput.fixedBytesLine + guard line.hasPrefix(labelText) else { + return [.text(line)] + } + return [.label("fixed bytes"), .separator(": "), .text(String(line.dropFirst(labelText.count)))] + } + var body: [Segment] = [.label("fixed bytes"), .separator(": ")] + for (runIndex, run) in caseProjection.formattedFixedByteRuns().enumerated() { + if runIndex > 0 { + body.append(.separator(", ")) + } + body.append(.value(run)) + } + return body + } + + /// `offset 0x18 = 0x01 (0b00000001)`, or for a byte only some of whose + /// bits are fixed, `offset 0x00: fixed bits 0b11000000 = 0b10000000 (the + /// other bits hold payload storage)` — `builtInOffsetDescription`'s + /// wordings. + private static func enumLayoutCaseByteBody(offset: Int, value: UInt8, fixedBitMask: UInt8) -> [Segment] { + let offsetText = String(format: "0x%02X", offset) + if fixedBitMask == 0xFF { + return [ + .label("offset"), .separator(" "), .key(offsetText), .separator(" = "), + .value(String(format: "0x%02X", value)), .separator(" ("), .value("0b" + paddedBinary(value)), .separator(")"), + ] + } + return [ + .label("offset"), .separator(" "), .key(offsetText), .separator(": "), + .label("fixed bits"), .separator(" "), .value("0b" + paddedBinary(fixedBitMask)), .separator(" = "), + .value("0b" + paddedBinary(value)), .separator(" ("), .text("the other bits hold payload storage"), .separator(")"), + ] + } + + private static func paddedBinary(_ byteValue: UInt8) -> String { + let binaryDigits = String(byteValue, radix: 2) + return String(repeating: "0", count: 8 - binaryDigits.count) + binaryDigits + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/StructuredComment+Factories.swift b/Sources/Output/SwiftDeclarationRendering/StructuredComment+Factories.swift new file mode 100644 index 000000000..3c03928d3 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/StructuredComment+Factories.swift @@ -0,0 +1,204 @@ +@_spi(Internals) import SwiftInspection + +// The comments the dump and the interface print, each spelled out once +// (evolution proposal `comment-structure`). A doc comment shows the text a +// factory prints; the segments it is made of follow the proposal's table. + +// MARK: - Addresses and Offsets + +extension StructuredComment { + /// `// Address: 0x135DC`, or `// Address (getter): 0x135DC` with the + /// accessor — or `destructor` — it is the address of. + package static func memberAddress(addressString: String, qualifier: String? = nil) -> Self { + labeledValue("Address", qualifier: qualifier, value: "0x" + addressString) + } + + /// `// VTable offset: 12`, or `// VTable offset (setter): 13` with the + /// accessor owning the slot. + package static func vtableOffset(_ slotOffset: Int, qualifier: String? = nil) -> Self { + labeledValue("VTable offset", qualifier: qualifier, value: String(slotOffset)) + } + + /// `// Field offset: 0x8`. + package static func fieldOffset(_ offset: Int) -> Self { + Self.offset(labeled: "Field offset", offset) + } + + /// `// PWT offset: 0x18`. + package static func pwtOffset(_ offset: Int) -> Self { + Self.offset(labeled: "PWT offset", offset) + } + + /// `// ` — three concrete fields /// (`field1: Double`, `field2: A`, `field3: Int`). Exercises the @@ -45,6 +50,7 @@ package enum FieldDescriptorBaselineGenerator { // entries under the scanner's name-based deduplication. // `init(layout:offset:)` is filtered as memberwise-synthesized. let registered = [ + "actualSize", "kind", "layout", "mangledTypeName", @@ -69,8 +75,11 @@ package enum FieldDescriptorBaselineGenerator { enum FieldDescriptorBaseline { static let registeredTestMethodNames: Set = \(literal: registered) + static let descriptorCount = \(literal: try BaselineFixturePicker.fieldDescriptors(in: machO).count) + struct Entry { let offset: Int + let actualSize: Int let kindRawValue: UInt16 let layoutNumFields: Int let layoutFieldRecordSize: Int @@ -94,6 +103,7 @@ package enum FieldDescriptorBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { let offset = descriptor.offset + let actualSize = descriptor.actualSize let kindRawValue = descriptor.layout.kind let layoutNumFields = Int(descriptor.layout.numFields) let layoutFieldRecordSize = Int(descriptor.layout.fieldRecordSize) @@ -104,6 +114,7 @@ package enum FieldDescriptorBaselineGenerator { let expr: ExprSyntax = """ Entry( offset: \(raw: BaselineEmitter.hex(offset)), + actualSize: \(literal: actualSize), kindRawValue: \(raw: BaselineEmitter.hex(kindRawValue)), layoutNumFields: \(literal: layoutNumFields), layoutFieldRecordSize: \(literal: layoutFieldRecordSize), diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift similarity index 96% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift index 428a1a16a..1bd2bb7af 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift @@ -62,10 +62,7 @@ package enum GenericContextBaselineGenerator { let invertibleExpr = emitEntryExpr(for: invertibleContext) // Public members declared directly in GenericContext.swift on - // `TargetGenericContext`. The three `init(contextDescriptor:in:)` - // overloads (MachO + InProcess + ReadingContext) collapse to one - // MethodKey under PublicMemberScanner's name-based deduplication; - // `init(contextDescriptor:)` is the InProcess variant. + // `TargetGenericContext`. let registered = [ "allParameters", "allRequirements", @@ -81,7 +78,6 @@ package enum GenericContextBaselineGenerator { "currentValues", "depth", "header", - "init(contextDescriptor:)", "init(contextDescriptor:in:)", "offset", "parameters", @@ -94,7 +90,6 @@ package enum GenericContextBaselineGenerator { "typePackHeader", "typePacks", "uniqueCurrentRequirements", - "uniqueCurrentRequirementsInProcess", "valueHeader", "values", ] diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift similarity index 94% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift index e56f5449f..9540eebfb 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift @@ -47,13 +47,9 @@ package enum GenericRequirementBaselineGenerator { let sameTypeExpr = emitEntryExpr(for: sameTypeReq) // Public members declared directly in GenericRequirement.swift. - // The three `init(descriptor:in:)` overloads (MachO + InProcess + - // ReadingContext) collapse to one MethodKey under PublicMemberScanner's - // name-based deduplication; `init(descriptor:)` is the InProcess form. let registered = [ "content", "descriptor", - "init(descriptor:)", "init(descriptor:in:)", "paramManagledName", ] diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift similarity index 98% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift index 09376569a..249d09464 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift @@ -113,7 +113,7 @@ package enum GenericRequirementDescriptorBaselineGenerator { private static func emitEntryExpr(for requirement: GenericRequirementDescriptor) -> String { let offset = requirement.offset let flagsRawValue = requirement.layout.flags.rawValue - let kindRawValue = requirement.layout.flags.kind.rawValue + let kindRawValue = requirement.layout.flags.kind!.rawValue let contentKindCase = describeContentKind(requirement.content) let expr: ExprSyntax = """ diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift similarity index 98% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift index d0b12e9da..c1ee1d8cc 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift @@ -83,7 +83,7 @@ package enum GenericRequirementFlagsBaselineGenerator { private static func emitEntryExpr(rawValue: UInt32) -> String { let flags = GenericRequirementFlags(rawValue: rawValue) - let kindRawValue = flags.kind.rawValue + let kindRawValue = flags.kind!.rawValue let isPackRequirement = flags.contains(.isPackRequirement) let hasKeyArgument = flags.contains(.hasKeyArgument) let isValueRequirement = flags.contains(.isValueRequirement) diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift similarity index 87% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift index e78765276..5e4eae3d7 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift @@ -9,19 +9,18 @@ import SwiftSyntaxBuilder /// kind. PublicMemberScanner sees only the source-declared members /// (macro-injected case-presence helpers and associated-value extractors /// are out of scope per `GenericRequirementContentBaseline`'s pattern): -/// - `anyMetadata`, `metadata` (computed properties) -/// - `valueWitnessTable` (3 overloads collapsing to one MethodKey) -/// - `resolve` (3 overloads collapsing to one MethodKey) +/// - `anyMetadata` (computed property) +/// - `valueWitnessTable` +/// - `resolve` /// /// Live wrappers are materialised only via MachOImage's accessor /// (`StructTest`'s `MetadataResponse.value.resolve(in:)`). The Suite asserts /// the wrapper enum's `case` discriminant matches `.struct` and the -/// projected `metadata`/`anyMetadata` round-trip the offset. +/// projected `anyMetadata` round-trips the offset. package enum MetadataWrapperBaselineGenerator { package static func generate(outputDirectory: URL) throws { let registered = [ "anyMetadata", - "metadata", "resolve", "valueWitnessTable", ] diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift similarity index 91% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift index 62905b112..6dbd54ff0 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift @@ -22,12 +22,8 @@ package enum ModuleContextBaselineGenerator { let entryExpr = emitEntryExpr(for: context) // Public members declared directly in ModuleContext.swift. - // Both `init(descriptor:in:)` overloads (MachO + ReadingContext) - // collapse to a single MethodKey under PublicMemberScanner's - // name-based deduplication. let registered = [ "descriptor", - "init(descriptor:)", "init(descriptor:in:)", "name", ] diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift similarity index 98% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift index 2a634fd03..35d4574d4 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift @@ -27,7 +27,6 @@ package enum OpaqueTypeBaselineGenerator { let registered = [ "descriptor", "genericContext", - "init(descriptor:)", "init(descriptor:in:)", "invertedProtocols", "underlyingTypeArgumentMangledNames", diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift similarity index 91% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift index 70b968116..850202eb4 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift @@ -23,16 +23,13 @@ package enum InvertibleProtocolSetBaselineGenerator { let bothEntry = emitEntryExpr(rawValue: 0x3) // Public members declared directly in InvertibleProtocolSet.swift. - // `init(rawValue:)` and `rawValue` come from the OptionSet conformance. - // The static `.copyable` / `.escapable` OptionSet values surface as - // declared static vars. + // `@FlagSet` generates `rawValue`, `init(rawValue:)` and the + // `.copyable` / `.escapable` statics, which the source-scanning + // coverage check cannot see, so only the two declared properties are + // registered; the Suite still exercises the generated members. let registered = [ - "copyable", - "escapable", "hasCopyable", "hasEscapable", - "init(rawValue:)", - "rawValue", ] let header = """ diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift similarity index 93% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift index 15ef07b1b..834c67985 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift @@ -31,14 +31,9 @@ package enum ProtocolBaselineGenerator { // Public members declared directly in Protocol.swift (across the main // body and two same-file extensions, both in the ReadingContext block). - // Stored properties (descriptor/protocolFlags/name/baseRequirement/ - // requirementInSignatures/requirements) collapse with the two - // `init(descriptor:in:)` overloads under PublicMemberScanner's name- - // based deduplication. let registered = [ "baseRequirement", "descriptor", - "init(descriptor:)", "init(descriptor:in:)", "name", "numberOfRequirements", diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift similarity index 99% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift index ffb5750ae..56f06c684 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift @@ -64,7 +64,7 @@ package enum ProtocolContextDescriptorFlagsBaselineGenerator { let rawValue = flags.rawValue let isResilient = flags.isResilient let classConstraintRawValue = flags.classConstraint.rawValue - let specialProtocolKindRawValue = flags.specialProtocolKind.rawValue + let specialProtocolKindRawValue = flags.specialProtocolKind!.rawValue let expr: ExprSyntax = """ Entry( diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift similarity index 97% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift index f6bfa2fc5..ed1b2133c 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift @@ -82,8 +82,8 @@ package enum ProtocolDescriptorFlagsBaselineGenerator { let isSwift = flags.isSwift let isResilient = flags.isResilient let classConstraintRawValue = flags.classConstraint.rawValue - let dispatchStrategyRawValue = flags.dispatchStrategy.rawValue - let specialProtocolKindRawValue = flags.specialProtocolKind.rawValue + let dispatchStrategyRawValue = flags.dispatchStrategy!.rawValue + let specialProtocolKindRawValue = flags.specialProtocolKind!.rawValue let needsProtocolWitnessTable = flags.needsProtocolWitnessTable let expr: ExprSyntax = """ diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift similarity index 98% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift index 48f438dc7..6f1a38f1f 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift @@ -86,7 +86,7 @@ package enum ProtocolRequirementFlagsBaselineGenerator { private static func emitEntryExpr(rawValue: UInt32) -> String { let flags = ProtocolRequirementFlags(rawValue: rawValue) - let kindRawValue = flags.kind.rawValue + let kindRawValue = flags.kind!.rawValue let isCoroutine = flags.isCoroutine let isAsync = flags.isAsync let isInstance = flags.isInstance diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift similarity index 95% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift index 51f2d6a92..8748700d2 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift @@ -49,10 +49,7 @@ package enum ProtocolConformanceBaselineGenerator { // Public members declared directly in ProtocolConformance.swift // (across the body and the same-file ReadingContext extension). - // The `init(descriptor:in:)` MachO and ReadingContext overloads - // collapse to a single MethodKey under PublicMemberScanner's - // name-based deduplication. `flags` is a derived computed - // property over `descriptor.flags`. + // `flags` is a derived computed property over `descriptor.flags`. let registered = [ "conditionalPackShapeDescriptors", "conditionalRequirements", @@ -60,7 +57,6 @@ package enum ProtocolConformanceBaselineGenerator { "flags", "genericWitnessTable", "globalActorReference", - "init(descriptor:)", "init(descriptor:in:)", "protocol", "resilientWitnesses", diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift index 9c13a17b5..c45724376 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift @@ -79,7 +79,7 @@ package enum ProtocolConformanceDescriptorBaselineGenerator { ) throws -> String { let offset = descriptor.offset let layoutFlagsRawValue = descriptor.layout.flags.rawValue - let typeReferenceKindRawValue = descriptor.layout.flags.typeReferenceKind.rawValue + let typeReferenceKindRawValue = descriptor.layout.flags.typeReferenceKind!.rawValue let hasProtocolDescriptor = (try descriptor.protocolDescriptor(in: machO.context)) != nil let hasWitnessTablePattern = (try descriptor.witnessTablePattern(in: machO.context)) != nil let resolvedTypeReference = try descriptor.resolvedTypeReference(in: machO.context) diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift similarity index 99% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift index a8a03187b..957bb48d8 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift @@ -103,7 +103,7 @@ package enum ProtocolConformanceFlagsBaselineGenerator { let expr: ExprSyntax = """ Entry( rawValue: \(raw: BaselineEmitter.hex(rawValue)), - typeReferenceKindRawValue: \(raw: BaselineEmitter.hex(flags.typeReferenceKind.rawValue)), + typeReferenceKindRawValue: \(raw: BaselineEmitter.hex(flags.typeReferenceKind!.rawValue)), isRetroactive: \(literal: flags.isRetroactive), isSynthesizedNonUnique: \(literal: flags.isSynthesizedNonUnique), isConformanceOfProtocol: \(literal: flags.isConformanceOfProtocol), diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift similarity index 96% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift index 43edcf2ec..0a56c36e1 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift @@ -42,8 +42,6 @@ package enum StructBaselineGenerator { let genericStructExpr = emitEntryExpr(for: genericStructStruct) // Public members declared directly in Struct.swift, per scanner output. - // Two `init(descriptor:in:)` overloads (MachO + Context) collapse to one - // MethodKey under PublicMemberScanner's name-based deduplication. let registered = [ "canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", @@ -51,7 +49,6 @@ package enum StructBaselineGenerator { "descriptor", "foreignMetadataInitialization", "genericContext", - "init(descriptor:)", "init(descriptor:in:)", "invertibleProtocolSet", "singletonMetadataInitialization", diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift similarity index 99% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift index 71d6e4365..7bae57581 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift @@ -110,7 +110,7 @@ package enum TypeContextDescriptorFlagsBaselineGenerator { let classHasDefaultOverrideTable = flags.classHasDefaultOverrideTable let classIsActor = flags.classIsActor let classIsDefaultActor = flags.classIsDefaultActor - let classResilientSuperclassReferenceKindRawValue = flags.classResilientSuperclassReferenceKind.rawValue + let classResilientSuperclassReferenceKindRawValue = flags.classResilientSuperclassReferenceKind!.rawValue let classAreImmdiateMembersNegative = flags.classAreImmdiateMembersNegative let classHasResilientSuperclass = flags.classHasResilientSuperclass let classHasOverrideTable = flags.classHasOverrideTable diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Coverage/CoverageAllowlist.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/CoverageAllowlist.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Coverage/CoverageAllowlist.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/CoverageAllowlist.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Coverage/FixtureSuite.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/FixtureSuite.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Coverage/FixtureSuite.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/FixtureSuite.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Coverage/MethodKey.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/MethodKey.swift similarity index 65% rename from Sources/TestSupport/MachOFixtureSupport/Coverage/MethodKey.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/MethodKey.swift index 5f7624439..ae7c261f8 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Coverage/MethodKey.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/MethodKey.swift @@ -9,9 +9,9 @@ package struct MethodKey: Hashable, Comparable, CustomStringConvertible { self.memberName = memberName } - package static func < (lhs: MethodKey, rhs: MethodKey) -> Bool { - if lhs.typeName != rhs.typeName { return lhs.typeName < rhs.typeName } - return lhs.memberName < rhs.memberName + package static func < (left: MethodKey, right: MethodKey) -> Bool { + if left.typeName != right.typeName { return left.typeName < right.typeName } + return left.memberName < right.memberName } package var description: String { diff --git a/Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/PublicMemberScanner.swift similarity index 95% rename from Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/PublicMemberScanner.swift index 041b25438..86a01c3ca 100644 --- a/Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/PublicMemberScanner.swift @@ -18,7 +18,7 @@ import SwiftParser /// (handled via allowlist if they slip through) /// /// Added back: -/// - `layout` / `offset` on a struct carrying `@LocatableLayoutWrapping`. This +/// - `layout` / `offset` on a struct carrying `@ResolvableLocatableLayoutWrapper`. This /// scanner reads source, not macro expansions, and those two properties were /// spelled out by hand in every wrapper until the macro absorbed them — so /// they are re-added here to keep the coverage contract (and the 96 baseline @@ -82,7 +82,7 @@ private final class PublicMemberVisitor: SyntaxVisitor { override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { typeStack.append(stripBackticks(node.name.text)) spiStack.append(hasSPI(attributes: node.attributes)) - collectLocatableLayoutWrappingMembers(of: node) + collectResolvableLocatableLayoutWrapperMembers(of: node) return .visitChildren } override func visitPost(_ node: StructDeclSyntax) { @@ -197,15 +197,15 @@ private final class PublicMemberVisitor: SyntaxVisitor { return false } - /// `@LocatableLayoutWrapping` generates `layout`, `offset` and + /// `@ResolvableLocatableLayoutWrapper` generates `layout`, `offset` and /// `init(layout:offset:)` at the host's own access level. Only the two /// properties are recorded — the initializer is skipped for macro-generated /// and hand-written wrappers alike (`isMemberwiseSynthesizedInit`). /// /// Called after the host has been pushed onto the scopes, so an enclosing /// `@_spi` still disqualifies it. - private func collectLocatableLayoutWrappingMembers(of node: StructDeclSyntax) { - guard hasAttribute(named: "LocatableLayoutWrapping", attributes: node.attributes) else { return } + private func collectResolvableLocatableLayoutWrapperMembers(of node: StructDeclSyntax) { + guard hasAttribute(named: "ResolvableLocatableLayoutWrapper", attributes: node.attributes) else { return } guard isPublicLike(node.modifiers, attributes: node.attributes) else { return } guard let typeName = currentTypeName(), !shouldSkip(typeName: typeName) else { return } collected.append(MethodKey(typeName: typeName, memberName: "layout")) @@ -234,7 +234,7 @@ private final class PublicMemberVisitor: SyntaxVisitor { private func isMemberwiseSynthesizedInit(_ node: InitializerDeclSyntax) -> Bool { // The LocatableLayoutWrapper initializer, whether hand-written or - // generated by @LocatableLayoutWrapping. Exercised through every + // generated by @ResolvableLocatableLayoutWrapper. Exercised through every // wrapper's own reads, never as a standalone member. let names = node.signature.parameterClause.parameters.map { $0.firstName.text } return names == ["layout", "offset"] || names == ["offset", "layout"] diff --git a/Sources/TestSupport/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/DemangleOptions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift similarity index 63% rename from Sources/TestSupport/MachOFixtureSupport/DemangleOptions.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift index 94d022f0c..4e4249306 100644 --- a/Sources/TestSupport/MachOFixtureSupport/DemangleOptions.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift @@ -8,6 +8,8 @@ extension DemangleOptions { /// `.synthesizeSugarOnTypes`, which `.default` does not). Keep this on /// `.interface` so the recorded `SwiftDumpTests` snapshots stay sugared and /// idiomatic — switching to `.default` desugars every optional/array in the - /// output and breaks the snapshot suite. - package static let test: DemangleOptions = .interface + /// output and breaks the snapshot suite. Existentials are spelled with + /// `any`, as the dump prints them by default (evolution proposal + /// `existential-any`). + package static let test: DemangleOptions = DemangleOptions.interface.union(.useExistentialAny) } diff --git a/Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift similarity index 98% rename from Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift index 11dcb298f..97f223e57 100644 --- a/Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift @@ -5,7 +5,7 @@ import MachOSwiftSection import SwiftDump import SwiftDeclarationRendering import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection @MainActor @@ -103,7 +103,7 @@ extension DumpableTests { } package func dumpOpaqueTypes(for machO: some MachOFieldLayoutRenderable) async throws { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore let symbols = symbolIndexStore.symbols(of: .opaqueTypeDescriptor, in: machO) for symbol in symbols where symbol.offset != 0 { diff --git a/Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/Extensions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/Extensions.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/FixtureLoadError.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/FixtureLoadError.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/FixtureLoadError.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/FixtureLoadError.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift similarity index 94% rename from Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift index 2cf560d9b..3cf8bb1cc 100644 --- a/Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift @@ -78,19 +78,14 @@ package enum InProcessMetadataPicker { /// `Any.self` — covers `ExistentialTypeMetadata` for the maximally-general /// existential. /// - /// Note: `Any.self` has flags `0x80000000` (bit 31 set → - /// `classConstraint == .any`). Calling `flags.classConstraint` traps - /// because the source's accessor does `UInt8(rawValue & 0x80000000)`, - /// which overflows for any value ≥ 256. Tests that exercise - /// `classConstraint` / `isClassBounded` / `isObjC` / `representation` - /// must therefore use `stdlibAnyObjectExistential` instead. + /// `Any.self` has flags `0x80000000`: bit 31 is set because it is not + /// class-constrained, so `classConstraint == .any`. package nonisolated(unsafe) static let stdlibAnyExistential: UnsafeRawPointer = { unsafeBitCast(Any.self, to: UnsafeRawPointer.self) }() /// `AnyObject.self` — class-bounded existential with zero witness tables - /// (flags `0x0`). Safe substitute for `stdlibAnyExistential` when a test - /// needs to call `flags.classConstraint`. + /// (flags `0x0`), so `classConstraint == .class`. package nonisolated(unsafe) static let stdlibAnyObjectExistential: UnsafeRawPointer = { unsafeBitCast(AnyObject.self, to: UnsafeRawPointer.self) }() @@ -245,8 +240,8 @@ extension InProcessMetadataPicker { /// Caveat: `MachOImageName.SymbolTestsCore.rawValue` is rooted as if the /// caller lives in `Sources///Foo.swift`, i.e. exactly three /// `../` hops to reach the package root. This file lives one level deeper - /// in `Sources/TestSupport/MachOFixtureSupport/InProcess/`, so we anchor - /// against `Sources/TestSupport/MachOFixtureSupport/` (one path component up + /// in `Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/`, so we anchor + /// against `Sources/TestSupport/SwiftSectionFixtureSupport/` (one path component up /// from `#filePath`'s parent) to make the existing `../../../...` rawValue /// resolve correctly. private static func resolveFixturePath(_ relativePath: String) -> String { diff --git a/Sources/TestSupport/MachOFixtureSupport/MachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/MachOFileName.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift similarity index 91% rename from Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift index 2641f86f2..b7a94897f 100644 --- a/Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift @@ -1,5 +1,8 @@ package enum MachOImageName: String { case AppKit + case UIFoundation + case CollectionViewCore + case CoreAutoLayout case SwiftUI case SwiftUICore case AttributeGraph @@ -20,7 +23,6 @@ package enum MachOImageName: String { case SnippetUI case SiriOntology - case SymbolTests = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTests.framework/Versions/A/SymbolTests" case SymbolTestsCore = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore" diff --git a/Sources/TestSupport/MachOFixtureSupport/SnapshotDumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/SnapshotDumpableTests.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/SnapshotInterfaceTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/SnapshotInterfaceTests.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/SwiftStdlibDemangle.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SwiftStdlibDemangle.swift similarity index 97% rename from Sources/TestSupport/MachOFixtureSupport/SwiftStdlibDemangle.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/SwiftStdlibDemangle.swift index 80cf73e1d..69785623a 100644 --- a/Sources/TestSupport/MachOFixtureSupport/SwiftStdlibDemangle.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/SwiftStdlibDemangle.swift @@ -1,5 +1,5 @@ import Foundation -import MachOTestingSupportC +import SwiftSectionTestingSupportC @_silgen_name("swift_demangle") private func _stdlib_demangleImpl( diff --git a/Sources/TestSupport/MachOFixtureSupport/URL+.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/URL+.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/URL+.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/URL+.swift diff --git a/Sources/TestSupport/MachOFixtureSupport/XcodeMachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift similarity index 100% rename from Sources/TestSupport/MachOFixtureSupport/XcodeMachOFileName.swift rename to Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift new file mode 100644 index 000000000..cffffc7ea --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift @@ -0,0 +1,244 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for the Swift classes an image keeps no class +/// object for (evolution proposal `objc-classes-without-class-objects`): one +/// of each metadata strategy that leaves a class out of `__objc_classlist` — +/// generic classes, a class whose superclass lives in another resilience +/// domain, a class with generic ancestry — beside a class with a class +/// object, the negative control. +/// +/// Two same-named private generic classes, one in each of the client's two +/// source files, are what no name the index gives tells apart. +/// +/// Two images: the Swift kit `libClassesWithoutClassObjectsFixtureKit` +/// (library evolution, so its `ResilientBase` is resilient to the client) +/// and the client itself, in two variants: +/// - `.full`: every symbol present, the `To` thunks and the class stubs' +/// `…CMs` / `…CMt` symbols included. +/// - `.strippedLocals` (`strip -x`): as in every OS framework, the thunks +/// and the non-public stub of the class with generic ancestry are gone. +package enum ClassesWithoutClassObjectsFixture { + package enum Variant: String, CaseIterable, Sendable { + case full + case strippedLocals + } + + package static let moduleName = "ClassesWithoutClassObjectsFixture" + + package static let kitModuleName = "ClassesWithoutClassObjectsFixtureKit" + + package static let kitSource = """ + import Foundation + + open class ResilientBase: NSObject { + public override init() { super.init() } + } + + open class ResilientGenericBase: NSObject { + public override init() { super.init() } + } + """ + + package static let swiftSource = """ + import Foundation + import \(kitModuleName) + + // Generic: the `class_ro_t` template sits in the generic metadata + // pattern, its name a null pointer. + public class GenericWidget: NSObject { + public override var description: String { "GenericWidget" } + @objc public func poke() {} + @objc public class func classPoke() {} + } + + public enum Namespace { + // Two parameters at one depth. + public class NestedGenericWidget: NSObject { + @objc public func nestedPoke() {} + } + } + + // Generic on the native object model: the runtime gives it `SwiftObject` + // for a superclass. + public class GenericNativeRoot { + public init() {} + } + + // A superclass in another resilience domain: the metadata is allocated + // from a pattern at runtime, and the descriptor records the class stub. + public class ResilientChild: ResilientBase { + public override var description: String { "ResilientChild" } + @objc public func resilientPoke() {} + } + + // The same with a generic superclass, the shape of a subclass of + // SwiftUI's `NSHostingView`: the superclass's name keeps its + // generic arguments. + public class ResilientGenericChild: ResilientGenericBase { + @objc public func resilientGenericPoke() {} + } + + // Generic ancestry: statically emitted metadata the runtime initializes + // first, registered through a stub only its local `…CMt` symbol names. + public class ConcreteSubclass: GenericWidget { + public override var description: String { "ConcreteSubclass" } + @objc public func concretePoke() {} + } + + // Generic ancestry on the native object model: no stub at all, and + // nothing `__objc_stublist` registers. + public class NativeConcreteSubclass: GenericNativeRoot {} + + // A class object in the class list: the negative control. + public class PlainWidget: NSObject { + @objc public func plainPoke() {} + } + + // Same-named as the one in `SecondFile.swift`: both private and generic, + // so the index names both `SameNamedPrivateGeneric`. + private class SameNamedPrivateGeneric: NSObject { + @objc func firstFilePoke() {} + } + + public func makeFirstFilePrivateGeneric() -> NSObject { + SameNamedPrivateGeneric() + } + """ + + /// The client's second source file. + package static let secondSwiftSource = """ + import Foundation + + private class SameNamedPrivateGeneric: NSObject { + @objc func secondFilePoke() {} + } + + public func makeSecondFilePrivateGeneric() -> NSObject { + SameNamedPrivateGeneric() + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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) + } + } + }() + } + + package struct CompiledLibraries: Sendable { + package let clientLibrariesByVariant: [Variant: URL] + package let kitLibrary: URL + } + + /// Compiled once per process; every variant shares one working directory. + private static let compilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let kitSourceURL = workingDirectory.appendingPathComponent("Kit.swift") + let kitLibraryURL = workingDirectory.appendingPathComponent("lib\(kitModuleName).dylib") + let swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + let secondSwiftSourceURL = workingDirectory.appendingPathComponent("SecondFile.swift") + try kitSource.write(to: kitSourceURL, atomically: true, encoding: .utf8) + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + try secondSwiftSource.write(to: secondSwiftSourceURL, atomically: true, encoding: .utf8) + + // Install names are the absolute output paths, which is what the + // client's load commands then spell — so the in-process leg loads + // with no rpath, and a resolver finds them by path. + try run(step: "swiftc (kit)", [ + // 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", "-enable-library-evolution", + "-emit-module", "-emit-module-path", workingDirectory.appendingPathComponent("\(kitModuleName).swiftmodule").path, + "-module-name", kitModuleName, + "-Xlinker", "-install_name", "-Xlinker", kitLibraryURL.path, + kitSourceURL.path, "-o", kitLibraryURL.path, + ]) + + var clientLibraries: [Variant: URL] = [:] + for variant in Variant.allCases { + let clientLibraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(variant.rawValue).dylib") + try run(step: "swiftc (\(variant.rawValue))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", moduleName, + "-I", workingDirectory.path, + swiftSourceURL.path, secondSwiftSourceURL.path, kitLibraryURL.path, "-framework", "Foundation", + "-o", clientLibraryURL.path, + ]) + if variant == .strippedLocals { + try run(step: "strip (\(variant.rawValue))", ["strip", "-x", clientLibraryURL.path]) + } + clientLibraries[variant] = clientLibraryURL + } + return CompiledLibraries(clientLibrariesByVariant: clientLibraries, kitLibrary: kitLibraryURL) + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) throws -> URL { + let libraries = try compilationResult.get() + guard let libraryURL = libraries.clientLibrariesByVariant[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + /// The search paths under which the client's whole world is reachable: + /// the kit as an explicit file, the OS's classes through the running + /// system's dyld shared cache. + package static func dependencySearchPaths() throws -> [DependencySearchPath] { + let libraries = try compilationResult.get() + return [.machOFile(path: libraries.kitLibrary.path), .systemDyldSharedCache] + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + let libraryURL = try libraryURL(variant) + 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") + } + } + + /// The `.full` client loaded into the test process — only that variant: + /// both define the same ObjC classes, and the runtime keeps one of each. + package static func loadedImage() throws -> MachOImage { + let libraryURL = try libraryURL(.full) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/CommentStructureContract.swift b/Sources/TestSupport/SwiftSectionTestingSupport/CommentStructureContract.swift new file mode 100644 index 000000000..41a2e7bfa --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/CommentStructureContract.swift @@ -0,0 +1,86 @@ +import Semantic + +/// The contract of a print marking comment structure (evolution proposal +/// `comment-structure`), checked against the same print with it off: +/// separated, the marked print is exactly the unmarked one — text, spans and +/// identifiers — and every comment in it lies in a region. +package enum CommentStructureContract { + /// Why `marked` breaks the contract against `unmarked`; `nil` when it + /// keeps it. + package static func violation(marked: FrozenSemanticString, unmarked: FrozenSemanticString) -> String? { + let (separatedText, annotations) = marked.separatingAnnotationRegions() + if separatedText != unmarked { + return "separated, the marked print differs from the unmarked one: \(firstDifference(between: separatedText, and: unmarked))" + } + if !unmarked.separatingAnnotationRegions().annotations.isEmpty { + return "the unmarked print carries annotation regions" + } + let uncoveredComments = commentsOutsideEveryRegion(in: unmarked, annotations: annotations) + if !uncoveredComments.isEmpty { + return "comments in no region: \(uncoveredComments.prefix(5).map { "\"\($0)\"" }.joined(separator: ", "))" + } + return nil + } + + /// The text of every `.comment` atom in `text` with a byte other than + /// whitespace that no region of `annotations` covers. A region leaves out + /// the whitespace at its ends, so a comment's own line break or leading + /// indentation may lie outside one. + package static func commentsOutsideEveryRegion(in text: FrozenSemanticString, annotations: AnnotationRegionTable) -> [String] { + // The regions' union as disjoint ranges in text order, swept once + // alongside the atoms, which come in text order too. + var coveredRanges: [Range] = [] + for range in annotations.regions.map({ Int($0.utf8Offset) ..< Int($0.utf8Offset) + Int($0.utf8Length) }).sorted(by: { $0.lowerBound < $1.lowerBound }) { + if let last = coveredRanges.last, range.lowerBound <= last.upperBound { + coveredRanges[coveredRanges.count - 1] = last.lowerBound ..< max(last.upperBound, range.upperBound) + } else { + coveredRanges.append(range) + } + } + var uncoveredComments: [String] = [] + var rangeIndex = 0 + var atomStart = 0 + for atom in text.components { + let atomBytes = Array(atom.string.utf8) + defer { atomStart += atomBytes.count } + guard atom.type == .comment else { continue } + for (byteIndex, byte) in atomBytes.enumerated() where !isWhitespace(byte) { + let position = atomStart + byteIndex + while rangeIndex < coveredRanges.count, coveredRanges[rangeIndex].upperBound <= position { + rangeIndex += 1 + } + if rangeIndex == coveredRanges.count || !coveredRanges[rangeIndex].contains(position) { + uncoveredComments.append(atom.string) + break + } + } + } + return uncoveredComments + } + + private static func isWhitespace(_ byte: UInt8) -> Bool { + byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\n") || byte == UInt8(ascii: "\r") + } + + /// Where two frozen strings first differ, for a readable failure. + package static func firstDifference(between left: FrozenSemanticString, and right: FrozenSemanticString) -> String { + if left.string != right.string { + let leftLines = left.string.split(separator: "\n", omittingEmptySubsequences: false) + let rightLines = right.string.split(separator: "\n", omittingEmptySubsequences: false) + let lineIndex = (0 ..< max(leftLines.count, rightLines.count)).first { index in + index >= leftLines.count || index >= rightLines.count || leftLines[index] != rightLines[index] + } ?? 0 + let leftLine = lineIndex < leftLines.count ? String(leftLines[lineIndex]) : "" + let rightLine = lineIndex < rightLines.count ? String(rightLines[lineIndex]) : "" + return "text differs at line \(lineIndex + 1):\n marked: \(leftLine)\n plain: \(rightLine)" + } + let leftComponents = left.components + let rightComponents = right.components + let componentIndex = (0 ..< max(leftComponents.count, rightComponents.count)).first { index in + index >= leftComponents.count || index >= rightComponents.count || leftComponents[index] != rightComponents[index] + } ?? 0 + let leftComponent = componentIndex < leftComponents.count ? "\(leftComponents[componentIndex])" : "" + let rightComponent = componentIndex < rightComponents.count ? "\(rightComponents[componentIndex])" : "" + return "same text, span \(componentIndex) differs:\n marked: \(leftComponent)\n plain: \(rightComponent)" + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift b/Sources/TestSupport/SwiftSectionTestingSupport/DefinitionName+DeclaredNameForTesting.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/DefinitionName+DeclaredNameForTesting.swift diff --git a/Sources/TestSupport/MachOTestingSupport/DyldCacheTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift similarity index 97% rename from Sources/TestSupport/MachOTestingSupport/DyldCacheTests.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift index 9d568c4ed..70810e2a0 100644 --- a/Sources/TestSupport/MachOTestingSupport/DyldCacheTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOFoundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport @MainActor package class DyldCacheTests: Sendable { diff --git a/Sources/TestSupport/MachOTestingSupport/ExclusiveImageAccess.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift similarity index 99% rename from Sources/TestSupport/MachOTestingSupport/ExclusiveImageAccess.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift index 17ab130b0..194ea0340 100644 --- a/Sources/TestSupport/MachOTestingSupport/ExclusiveImageAccess.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift @@ -1,5 +1,5 @@ import Foundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Testing /// Serializes every test that declares the same fixture image — **across diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift new file mode 100644 index 000000000..6df9396e4 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift @@ -0,0 +1,152 @@ +import Foundation +import MachOKit +import MachOFoundation +import Testing + +/// An on-the-fly fixture for spelling existential types with the `any` +/// keyword (evolution proposal `existential-any`): one stored property or +/// parameter of every shape the keyword, or the parentheses it needs, treats +/// differently. +/// +/// - `any Marker`, `any Marker & SecondMarker`, `any Marker & AnyObject`, +/// `any Base & Marker`: a protocol, a composition, a class-bound and a +/// superclass-bound existential, each with one keyword. +/// - `Any` and `AnyObject`: bare, as the compiler leaves them. +/// - `any Collection`: a protocol with associated types, which the compiler +/// warns must be written with `any`. +/// - `(any Marker)?`, `(any Error)?`, `Any?`: an optional parenthesizes the +/// existential written with the keyword, and only that one. +/// - `any Marker.Type`, `any (Marker & SecondMarker).Type`, `Any.Type`, +/// `AnyObject.Type`, `(any Marker.Type)?`: existential metatypes, every one +/// with the keyword — the compiler writes `any Any.Type`. +/// - `(any Marker).Type`: the metatype of the existential itself, which the +/// bare spelling writes as `Marker.Protocol`. +/// - `any Boxed`, `(any Boxed)?`, `any Boxed.Type`, +/// `(any Boxed.Type)?`: a constrained existential, which a field record +/// spells as an extended existential shape plus its arguments, and which +/// takes the keyword — and the parentheses an optional needs — whether or +/// not the other existentials do. +/// - an array of existentials, a closure taking and returning one, a variadic +/// and an `inout` parameter, a parameterized existential parameter, and an +/// opaque type constrained by an existential argument. +/// +/// Nothing here needs a recent toolchain, so the fixture compiles with the +/// selected one — CI's included. +package enum ExistentialAnyFixture { + package static let moduleName = "ExistentialAnyFixture" + + /// The `Anchor` class is ballast for the reader: a struct-only module + /// compiles to a dylib with no `__DATA` segment (see + /// `ExportedOnlyLibraryEvolutionFixtureTests`). + package static let source = """ + public protocol Marker {} + + public protocol SecondMarker {} + + public protocol Boxed { + associatedtype Wrapped + var wrapped: Wrapped { get } + } + + public class Base {} + + public struct Shapes { + public var single: any Marker + public var composition: any Marker & SecondMarker + public var classBound: any Marker & AnyObject + public var superclassBound: any Base & Marker + public var anything: Any + public var anyObject: AnyObject + public var collection: any Collection + public var optional: (any Marker)? + public var optionalComposition: (any Marker & SecondMarker)? + public var optionalError: (any Error)? + public var optionalAnything: Any? + public var existentialMetatype: any Marker.Type + public var compositionMetatype: any (Marker & SecondMarker).Type + public var anythingMetatype: Any.Type + public var anyObjectMetatype: AnyObject.Type + public var optionalExistentialMetatype: (any Marker.Type)? + public var protocolMetatype: (any Marker).Type + public var constrained: any Boxed + public var optionalConstrained: (any Boxed)? + public var constrainedMetatype: any Boxed.Type + public var optionalConstrainedMetatype: (any Boxed.Type)? + public var existentialArray: [any Marker] + public var existentialFunction: (any Marker) -> any SecondMarker + + public func accept(_ value: any Marker, _ values: any Marker...) {} + + public func acceptInout(_ value: inout any Marker) {} + + public func acceptConstrained(_ value: any Boxed) {} + + public func opaqueSequence() -> some Sequence { [any Marker]() } + } + + public class Anchor { + public func run() {} + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + 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 { + 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", "-enable-library-evolution", + "-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 + } + }() + + 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/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift new file mode 100644 index 000000000..2f8131b44 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift @@ -0,0 +1,204 @@ +import Foundation +import MachOKit +import MachOFoundation +import Testing + +/// An on-the-fly fixture for the exported-only filter (evolution proposals +/// `exported-only-interface` and `exported-only-marking-mode`) over +/// `internal` declarations — the shape `SymbolTestsCore` cannot pin, because +/// that fixture is built with `ENABLE_TESTABILITY` and exports its +/// internals. This module is compiled with `-enable-library-evolution` and +/// WITHOUT `-enable-testing`, so every `internal` declaration is a local +/// symbol and the filter has a definitive negative to act on for: a type, a +/// nested type, a protocol and its default implementation, a method, a +/// stored property, a global, a conformance to an internal protocol, and a +/// constrained extension whose members are all internal. It also extends a +/// C-imported type (`CGPoint`), whose descriptor the module emits as a copy +/// of its own and never exports. +/// +/// The last group is for a marked print: definitions whose body keeps its +/// nested types but nothing after them once the filter is on — a type +/// (`Holder`), a type whose stored property is internal (`FieldHolder`), a +/// caseless enum (`Namespace`) and an extension of another module's type +/// (`Int`) — and one that keeps nothing at all (`Hidden`). +/// +/// `UnexportedParent` is public in the source, but the link leaves its type +/// symbols out of the export trie (`unexportedSymbolNames`) while its nested +/// `ExportedNested` keeps them: an exported type nested in one that is not, +/// the shape an export list gives an OS framework — Foundation's +/// `LocalePreferences.ICUSymbolsAndStrings`, `package` in the source like its +/// parent, is exported while `LocalePreferences` is not. +package enum ExportedOnlyFixture { + package static let moduleName = "ExportedOnlyFixture" + + /// The symbols the link leaves out of the export trie: the type + /// descriptor, metadata accessor and type metadata of `UnexportedParent`. + package static let unexportedSymbolNames = [ + "_$s19ExportedOnlyFixture16UnexportedParentVMn", + "_$s19ExportedOnlyFixture16UnexportedParentVMa", + "_$s19ExportedOnlyFixture16UnexportedParentVN", + ] + + /// The `Anchor` class is load-bearing fixture ballast: a struct-only + /// module compiles to a dylib with no `__DATA` segment, whose + /// chained-fixup pages MachOKit releases before 0.52.103 mis-walked (see + /// `DiffMemberIndentationTests`). `@inline(never)` keeps the internal + /// members' symbols from being folded away. + package static let source = """ + import CoreGraphics + public struct PublicShape { + public var title: String + var internalNote: String + public init(title: String, internalNote: String) { + self.title = title + self.internalNote = internalNote + } + public func publicMethod() {} + @inline(never) func internalMethod() {} + public struct PublicNested {} + struct InternalNested {} + } + struct InternalShape { + var value: Int + } + extension InternalShape { + @inline(never) func orphanMethod() {} + } + public protocol PublicContract { + func requirement() + } + protocol InternalContract { + func hidden() + } + extension InternalContract { + @inline(never) func hiddenDefault() {} + } + extension PublicShape: PublicContract { + public func requirement() {} + } + extension PublicShape: InternalContract { + @inline(never) func hidden() {} + } + public struct PublicBox { + public var element: Element + public init(element: Element) { self.element = element } + } + extension PublicBox where Element == Int { + @inline(never) func internalConstrainedMember() {} + } + extension PublicBox where Element == String { + public func publicConstrainedMember() {} + } + public struct PublicPair { + public var first: Element + public var second: Element + public init(first: Element, second: Element) { + self.first = first + self.second = second + } + } + extension PublicPair where Element == Int { + @inline(never) func internalOnlyConstrainedMember() {} + } + public enum PublicEnum { + case alpha + case beta + } + public class Anchor { + public func run() {} + } + public func publicGlobal() {} + @inline(never) func internalGlobal() {} + extension CGPoint: PublicContract { + public func requirement() {} + } + extension CGPoint { + public func publicCImportedTypeMember() {} + } + public struct Holder { + public struct Nested {} + @inline(never) func internalHelper() {} + } + public struct FieldHolder { + public struct Nested {} + var internalStorage: Int = 0 + } + public enum Namespace { + public struct Member {} + @inline(never) static func internalHelper() {} + } + extension Int { + public struct ExportedOnlyFixtureNested {} + @inline(never) func exportedOnlyFixtureInternalHelper() {} + } + public struct Hidden { + struct InternalNested {} + @inline(never) func internalHelper() {} + } + public struct UnexportedParent { + public struct ExportedNested { + public init() {} + } + public init() {} + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + 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 { + 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("\(moduleName).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 = [ + "swiftc", "-emit-library", "-enable-library-evolution", + "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ] + unexportedSymbolNames.flatMap { ["-Xlinker", "-unexported_symbol", "-Xlinker", $0] } + 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 + } + }() + + 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/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift new file mode 100644 index 000000000..640b2b079 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift @@ -0,0 +1,231 @@ +import Foundation +import MachOKit +import Testing + +/// An on-the-fly fixture for the export verdict of types declared in +/// extensions of another module's types, in images that keep no symbol at a +/// non-exported descriptor (evolution proposal +/// `export-verdict-without-local-symbols`). +/// +/// Every type nested in such an extension runs through an extension context +/// — the shape every Swift type nested in an Objective-C class has +/// (`(extension in AppKit):__C.NSView`). Without a symbol at the descriptor, +/// its verdict comes from remangling its name, which the remangling leg used +/// to refuse for any extension context. The module declares, in an +/// unconstrained extension of `Int` and of `NSObject` and in a constrained +/// extension of its own generic type, one public, one internal and one +/// private type each, plus a type nested in a private one, a protocol and a +/// local type. It also declares a public and a private `@objc` protocol, +/// which have no descriptor at all, and two categories of Foundation +/// classes: one adopting only the private protocol, one adopting both. It is +/// compiled without `-enable-testing`, so every internal and private +/// descriptor is a local symbol, in three variants: +/// +/// - `.unstripped`: every symbol — leg 1 rules on every descriptor, which +/// makes it the reference the other two are compared with. +/// - `.symbolicReferencesOnly`: the exported and imported symbols plus the +/// `_symbolic` ones — the shape of AppKit in the macOS 27.2 dyld shared +/// cache, where private discriminators are still recovered but no +/// non-exported descriptor carries a symbol. +/// - `.stripped` (`strip -x`): the exported and imported symbols only — a +/// stripped app, where private types are named by position. +/// +/// `strip -s ` cuts the middle variant: no strip option +/// removes chosen local symbols, and `strip -s` keeps a local symbol only +/// when it was a private external before linking, as the `_symbolic` ones +/// are. Stripping invalidates the linker's ad-hoc signature, so every +/// variant is re-signed. Each variant is compiled on its own, under a module +/// name of its own: the per-image caches key a file by its `LC_UUID`, which +/// copies of one build share, so a stripped copy would be answered from the +/// unstripped one's symbol index. +package enum ExtensionContextExportFixture { + package enum Variant: String, CaseIterable, Sendable, CustomTestStringConvertible { + case unstripped + case symbolicReferencesOnly + case stripped + + /// The variants that keep no symbol at a non-exported descriptor. + package static let withoutLocalDescriptorSymbols: [Variant] = [.symbolicReferencesOnly, .stripped] + + package var testDescription: String { rawValue } + + package var moduleName: String { + switch self { + case .unstripped: "ExtensionContextExportFixtureUnstripped" + case .symbolicReferencesOnly: "ExtensionContextExportFixtureSymbolicReferencesOnly" + case .stripped: "ExtensionContextExportFixtureStripped" + } + } + } + + /// The `ExclusiveImageAccess` key every suite touching these images + /// declares. + package static let exclusiveAccessName = "ExtensionContextExportFixture" + + package static let source = """ + import Foundation + + extension Int { + public struct PublicNestedInExtension { + public init() {} + } + struct InternalNestedInExtension {} + private struct PrivateNestedInExtension { + struct NestedInPrivateType {} + } + protocol InternalProtocolNestedInExtension {} + @inline(never) func makeLocalTypeValue() -> Any { + struct LocalTypeInExtension {} + return LocalTypeInExtension() + } + } + + extension NSObject { + public struct PublicNestedInObjCClassExtension { + public init() {} + } + struct InternalNestedInObjCClassExtension {} + private final class PrivateNestedInObjCClassExtension {} + } + + public struct GenericBox { + public var element: Element + public init(element: Element) { self.element = element } + } + + extension GenericBox where Element == Int { + public struct PublicNestedInConstrainedExtension { + public init() {} + } + struct InternalNestedInConstrainedExtension {} + private struct PrivateNestedInConstrainedExtension {} + } + + @objc public protocol PublicObjCProtocol { + func publicObjCRequirement() + } + + @objc private protocol PrivateObjCProtocol { + func privateObjCRequirement() + } + + extension NumberFormatter: PrivateObjCProtocol { + func privateObjCRequirement() {} + } + + extension ByteCountFormatter: PrivateObjCProtocol, PublicObjCProtocol { + func privateObjCRequirement() {} + public func publicObjCRequirement() {} + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "ExtensionContextExportFixture step \(step) failed:\n\(diagnostics)" } + } + + 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; every variant shares one working directory. + private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("ExtensionContextExportFixture-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + + var libraries: [Variant: URL] = [:] + for variant in Variant.allCases { + let libraryURL = workingDirectory.appendingPathComponent("lib\(variant.moduleName).dylib") + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + try run(step: "swiftc (\(variant.rawValue))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", variant.moduleName, + sourceURL.path, "-o", libraryURL.path, + ]) + switch variant { + case .unstripped: + break + case .symbolicReferencesOnly: + try strip(libraryURL, keepingLocalSymbolsWhere: { $0.hasPrefix("_symbolic") }, in: workingDirectory, variant: variant) + case .stripped: + try run(step: "strip (\(variant.rawValue))", ["strip", "-x", libraryURL.path]) + } + try run(step: "codesign (\(variant.rawValue))", ["codesign", "--force", "--sign", "-", libraryURL.path]) + libraries[variant] = libraryURL + } + return libraries + } + }() + + /// Strips every local symbol but those `isKept` selects. The global ones + /// stay: `-g` lists the imported symbols too, which the indirect symbol + /// table refers to and `strip -s` refuses to drop. + private static func strip(_ libraryURL: URL, keepingLocalSymbolsWhere isKept: (String) -> Bool, in directory: URL, variant: Variant) throws { + let globalSymbolNames = try symbolNames(of: libraryURL, globalOnly: true, step: "nm -g (\(variant.rawValue))") + let keptLocalSymbolNames = try symbolNames(of: libraryURL, globalOnly: false, step: "nm (\(variant.rawValue))").filter(isKept) + let keepListURL = directory.appendingPathComponent("keep-\(variant.rawValue).txt") + try ((globalSymbolNames + keptLocalSymbolNames).joined(separator: "\n") + "\n").write(to: keepListURL, atomically: true, encoding: .utf8) + try run(step: "strip -s (\(variant.rawValue))", ["strip", "-s", keepListURL.path, libraryURL.path]) + } + + private static func symbolNames(of libraryURL: URL, globalOnly: Bool, step: String) throws -> [String] { + let output = try run(step: step, ["nm", globalOnly ? "-gj" : "-j", libraryURL.path]) + return output.split(separator: "\n").map(String.init).filter { !$0.isEmpty } + } + + /// Runs `xcrun ` and returns its standard output. Standard + /// error goes to a file rather than a pipe, so neither stream can fill + /// while the other is drained. + @discardableResult + private static func run(step: String, _ arguments: [String]) throws -> String { + let diagnosticsURL = FileManager.default.temporaryDirectory + .appendingPathComponent("ExtensionContextExportFixture-diagnostics-\(UUID().uuidString).txt") + FileManager.default.createFile(atPath: diagnosticsURL.path, contents: nil) + defer { try? FileManager.default.removeItem(at: diagnosticsURL) } + let diagnosticsHandle = try FileHandle(forWritingTo: diagnosticsURL) + defer { try? diagnosticsHandle.close() } + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + let standardOutputPipe = Pipe() + process.standardOutput = standardOutputPipe + process.standardError = diagnosticsHandle + try process.run() + // Drain BEFORE waitUntilExit, or a long output deadlocks both sides. + let outputData = standardOutputPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + let diagnostics = (try? String(contentsOf: diagnosticsURL, encoding: .utf8)) ?? "" + throw CompilationError(step: step, diagnostics: diagnostics) + } + return String(decoding: outputData, as: UTF8.self) + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + let libraries = try compilationResult.get() + let libraryURL = try #require(libraries[variant], "no library for variant \(variant.rawValue)") + 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") + } + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift diff --git a/Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/ForwardingMachOReader.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift similarity index 99% rename from Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift index 452d5d822..265a6b964 100644 --- a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift @@ -1,7 +1,7 @@ import Foundation import MachOKit import MachOFoundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport import MachOSwiftSection import Testing diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationTestingEnvironment.swift similarity index 98% rename from Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationTestingEnvironment.swift index fc7822dc1..72c4ffd48 100644 --- a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationTestingEnvironment.swift @@ -4,7 +4,7 @@ import Foundation import Testing import MachOKit -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import MachOSwiftSection @_spi(Support) import SwiftInterface @@ -64,7 +64,7 @@ private actor SharedSpecializationIndexerCache { /// `machO` and an async `indexer` for free, plus descriptor-lookup helpers, /// all backed by a single per-process cache. /// -/// Lives in `MachOTestingSupport` so any test target depending on it can +/// Lives in `SwiftSectionTestingSupport` so any test target depending on it can /// adopt the protocol without copy-pasting the boilerplate or reaching into /// another test file's nested namespace. package protocol GenericSpecializationTestingEnvironment { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift new file mode 100644 index 000000000..e9f3b37a9 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift @@ -0,0 +1,311 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for an evolution whose versions are groups of +/// images (evolution proposal `image-group-evolution`): one module split +/// across two images from 2.0 on, the way SwiftUI split into SwiftUI and +/// SwiftUICore in macOS 15. +/// +/// 1.0 is the module alone, `ImageGroupFixture`. From 2.0 on a second image, +/// `ImageGroupFixtureCore`, defines `Gauge` under +/// `@_originallyDefinedIn(module: "ImageGroupFixture", …)`, so its mangled +/// name — and every member's — keeps the module name it had in 1.0. The +/// stories the versions tell: +/// +/// - `Gauge` moves into the core image in 2.0; `reading()`, `value` and +/// `init(value:)` move with it. +/// - `Gauge.calibrated()` stays in `ImageGroupFixture` in 2.0, declared in an +/// extension of a type that now lives in another image — mangled with no +/// extension context, as SwiftUI declares members of SwiftUICore's types — +/// and moves into the core image's `Gauge` in 3.0. +/// - `Gauge.standard` stays in `ImageGroupFixture` throughout. +/// - `Needle` arrives in the core image in 2.0; `ImageGroupFixture` extends +/// it from 2.0 on with `sweep()`, an ordinary cross-module extension whose +/// mangling names the extension. +/// - `Dial` stays in `ImageGroupFixture` and never changes. +/// - `comparison(_:)` calls the importer's `ComparisonResult.init?(rawValue:)` +/// in every version, which the compiler emits into the image: members of +/// another module's type the image carries without declaring them. +package enum ImageGroupFixture { + /// The module every version declares, and the image it lives in. + package static let moduleName = "ImageGroupFixture" + + /// The module, and image, the split moves declarations into from 2.0 on. + package static let coreModuleName = "ImageGroupFixtureCore" + + /// The version-axis labels, oldest first. + package static let labels = ["1.0", "2.0", "3.0"] + + /// One image of a version: its name and its reader. + package struct Image { + package let name: String + package let machOFile: MachOFile + } + + /// Per version, oldest first: the core image's source (`nil` before the + /// split) and the module's. + package static let sources: [(core: String?, module: String)] = [ + // 1.0 + ( + core: nil, + module: """ + import Foundation + + public struct Gauge { + public var value: Int + + public init(value: Int) { + self.value = value + } + + public func reading() -> Int { + value + } + + public func calibrated() -> Int { + value + 1 + } + + public static var standard: Gauge { + Gauge(value: 0) + } + } + + public struct Dial { + public init() {} + + public func turn() -> Int { + 1 + } + } + + public func comparison(_ value: Int) -> Int { + ComparisonResult(rawValue: value)?.rawValue ?? 0 + } + """ + ), + // 2.0 + ( + core: """ + @_originallyDefinedIn(module: "ImageGroupFixture", macOS 14.0) + @available(macOS 10.15, *) + public struct Gauge { + public var value: Int + + public init(value: Int) { + self.value = value + } + + public func reading() -> Int { + value + } + } + + public struct Needle { + public init() {} + } + """, + module: """ + @_exported import ImageGroupFixtureCore + import Foundation + + @available(macOS 10.15, *) + extension Gauge { + public func calibrated() -> Int { + value + 1 + } + + public static var standard: Gauge { + Gauge(value: 0) + } + } + + extension Needle { + public func sweep() -> Int { + 2 + } + } + + public struct Dial { + public init() {} + + public func turn() -> Int { + 1 + } + } + + public func comparison(_ value: Int) -> Int { + ComparisonResult(rawValue: value)?.rawValue ?? 0 + } + """ + ), + // 3.0 + ( + core: """ + @_originallyDefinedIn(module: "ImageGroupFixture", macOS 14.0) + @available(macOS 10.15, *) + public struct Gauge { + public var value: Int + + public init(value: Int) { + self.value = value + } + + public func reading() -> Int { + value + } + + public func calibrated() -> Int { + value + 1 + } + } + + public struct Needle { + public init() {} + } + """, + module: """ + @_exported import ImageGroupFixtureCore + import Foundation + + @available(macOS 10.15, *) + extension Gauge { + public static var standard: Gauge { + Gauge(value: 0) + } + } + + extension Needle { + public func sweep() -> Int { + 2 + } + } + + public struct Dial { + public init() {} + + public func turn() -> Int { + 1 + } + } + + public func comparison(_ value: Int) -> Int { + ComparisonResult(rawValue: value)?.rawValue ?? 0 + } + """ + ), + ] + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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) + } + } + }() + } + + /// The deployment target every image is built for: one + /// `@_originallyDefinedIn` can name, and any host running the tests has. + private static let target = "arm64-apple-macos14.0" + + /// Compiled once per process, each version in a directory of its own, + /// since every version reuses the two module names. Per version the + /// libraries' URLs, the core image's first when there is one. + private static let compilationResult: Result<[[(name: String, libraryURL: URL)]], Swift.Error> = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + var librariesPerVersion: [[(name: String, libraryURL: URL)]] = [] + for (versionIndex, versionSources) in sources.enumerated() { + let versionName = "V\(versionIndex + 1)" + let versionDirectory = workingDirectory.appendingPathComponent(versionName) + try FileManager.default.createDirectory(at: versionDirectory, withIntermediateDirectories: true) + var libraries: [(name: String, libraryURL: URL)] = [] + var linkArguments: [String] = [] + if let coreSource = versionSources.core { + let coreSourceURL = versionDirectory.appendingPathComponent("\(coreModuleName).swift") + let coreLibraryURL = versionDirectory.appendingPathComponent("lib\(coreModuleName).dylib") + try coreSource.write(to: coreSourceURL, atomically: true, encoding: .utf8) + // The language mode pinned, so CI's toolchain and a newer + // local one compile the source the same way. + try run(step: "swiftc \(coreModuleName) (\(versionName))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-target", target, + "-module-name", coreModuleName, + "-emit-module", "-emit-module-path", versionDirectory.appendingPathComponent("\(coreModuleName).swiftmodule").path, + coreSourceURL.path, "-o", coreLibraryURL.path, + ]) + libraries.append((coreModuleName, coreLibraryURL)) + linkArguments = ["-I", versionDirectory.path, "-L", versionDirectory.path, "-l\(coreModuleName)"] + } + let moduleSourceURL = versionDirectory.appendingPathComponent("\(moduleName).swift") + let moduleLibraryURL = versionDirectory.appendingPathComponent("lib\(moduleName).dylib") + try versionSources.module.write(to: moduleSourceURL, atomically: true, encoding: .utf8) + try run(step: "swiftc \(moduleName) (\(versionName))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-target", target, + "-module-name", moduleName, + ] + linkArguments + [ + moduleSourceURL.path, "-o", moduleLibraryURL.path, + ]) + libraries.insert((moduleName, moduleLibraryURL), at: 0) + librariesPerVersion.append(libraries) + } + return librariesPerVersion + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + /// Each version's images, oldest version first; within a version the + /// module's own image first, then the core image when there is one. + package static func imageGroups() throws -> [[Image]] { + try compilationResult.get().map { libraries in + try libraries.map { library in + try Image(name: library.name, machOFile: machOFile(at: library.libraryURL)) + } + } + } + + /// The image named `imageName` in the version at `versionIndex`. + package static func image(named imageName: String, atVersion versionIndex: Int) throws -> MachOFile { + let image = try imageGroups()[versionIndex].first { $0.name == imageName } + return try #require(image, "\(imageName) is not part of version \(labels[versionIndex])").machOFile + } + + private static func machOFile(at libraryURL: URL) throws -> MachOFile { + 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") + } + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift new file mode 100644 index 000000000..2686b5b1e --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift @@ -0,0 +1,384 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for SE-0400 init accessors (evolution proposal +/// `init-accessor-recovery`): computed properties whose init accessor +/// initializes a stored property named after them, one named otherwise, two +/// at once, or only accesses one; SwiftUICore's two shapes — a frozen struct +/// whose `@usableFromInline` init accessor is exported, and a stored property +/// with a function under its init accessor's name, kept for the clients that +/// inlined a call to it — and SwiftData's, a `_name` of another type. +/// +/// One module, built with library evolution as SwiftUICore is, in four +/// variants: +/// - `.debug` (`-Onone`): every init accessor, each called by its +/// initializer. +/// - `.release` (`-O`): every init accessor, as local symbols: the +/// initializers inlined them, but nothing removes them. +/// - `.releaseDeadStripped` (`-O`, linked with `-dead_strip`): as SwiftUI — +/// the local symbols kept, but every function nothing references dropped, +/// which is every init accessor the image does not export. +/// - `.releaseStripped` (`-O`, then `strip -x`): as an OS framework or a +/// shipped app — only the exported init accessors. +package enum InitAccessorFixture { + package enum Variant: String, CaseIterable, Sendable { + case debug + case release + case releaseDeadStripped + case releaseStripped + } + + package static let moduleName = "InitAccessorFixture" + + package static let swiftSource = """ + // Initializes a stored property named otherwise: nothing in the image + // tells which. + public struct Angle { + public var degrees: Double + public var radians: Double { + @storageRestrictions(initializes: degrees) + init(initialValue) { degrees = initialValue * 180 / .pi } + get { degrees * .pi / 180 } + set { degrees = newValue * 180 / .pi } + } + public init(radians: Double) { self.radians = radians } + } + + // Accesses a stored property, and initializes none. + public struct Titled { + private var dictionary: [String: String] + public var title: String { + @storageRestrictions(accesses: dictionary) + init(newValue) { dictionary["title"] = newValue } + get { dictionary["title"] ?? "" } + set { dictionary["title"] = newValue } + } + public init(title: String) { + dictionary = [:] + self.title = title + } + } + + // Initializes two stored properties at once. + public struct Pair { + private var _x: Int + private var _y: Int + public var point: (x: Int, y: Int) { + @storageRestrictions(initializes: _x, _y) + init(initialValue) { (_x, _y) = initialValue } + get { (_x, _y) } + set { (_x, _y) = newValue } + } + public init(point: (x: Int, y: Int)) { self.point = point } + } + + // Both lists, and the default parameter name. + public struct Mixed { + private var _a: String + private var b: Int + public var a: String { + @storageRestrictions(initializes: _a, accesses: b) + init { _a = newValue + String(b) } + get { _a } + set { _a = newValue } + } + public init(a: String, b: Int) { + self.b = b + self.a = a + } + } + + // SwiftUICore's `_GeometryActionModifier2.value`: an inlinable + // initializer a client may inline calls the init accessor, so it is + // exported. + @frozen + public struct FrozenBox { + @usableFromInline var _value: Value + public var value: Value { + @usableFromInline + @storageRestrictions(initializes: _value) + init(initialValue) { _value = initialValue } + get { _value } + set { _value = newValue } + } + @inlinable public init(value: Value) { self.value = value } + } + + // SwiftUICore's `_GeometryActionModifier2.value` again: the getter and + // setter keep the mangling from before the type became `@Sendable`, so + // only the init accessor spells the property's type as its field has it. + public struct SendableUpgrade { + private var _value: @Sendable (Int) -> Int + public var value: @Sendable (Int) -> Int { + @storageRestrictions(initializes: _value) + init(initialValue) { _value = initialValue } + @_silgen_name("$s19InitAccessorFixture15SendableUpgradeV5valueyS2icvg") + get { _value } + @_silgen_name("$s19InitAccessorFixture15SendableUpgradeV5valueyS2icvs") + set { _value = newValue } + } + public init(value: @escaping @Sendable (Int) -> Int) { self.value = value } + } + + // A function type with a `sending` result: the field record spells + // `sending`, while every accessor symbol, the init accessor's too, + // leaves it out of the property's own type. + public struct SendingResult { + private var _make: () -> sending Value + public var make: () -> sending Value { + @storageRestrictions(initializes: _make) + init(initialValue) { _make = initialValue } + get { _make } + set { _make = newValue } + } + public init(make: @escaping () -> sending Value) { self.make = make } + } + + // A class, and a storage whose field type is `weak Swift.AnyObject?`. + public final class Model { + private var _name: String + private weak var _delegate: AnyObject? + public var name: String { + @storageRestrictions(initializes: _name) + init(initialValue) { _name = initialValue } + get { _name } + set { _name = newValue } + } + public var delegate: AnyObject? { + @storageRestrictions(initializes: _delegate) + init(initialValue) { _delegate = initialValue } + get { _delegate } + set { _delegate = newValue } + } + public init(name: String, delegate: AnyObject?) { + self.name = name + self.delegate = delegate + } + } + + // SwiftData's `@Model` shape: `_name` holds a placeholder of another + // type, and the value lives in the storage the accessor accesses. + public struct Placeholder { + public init() {} + } + + public struct PersistedLookalike { + private var _name: Placeholder + private var storage: [String: String] + public var name: String { + @storageRestrictions(initializes: _name, accesses: storage) + init(initialValue) { + storage["name"] = initialValue + _name = Placeholder() + } + get { storage["name"] ?? "" } + set { storage["name"] = newValue } + } + public init(name: String) { + storage = [:] + self.name = name + } + } + + // SwiftUICore's `_GeometryActionModifier.value`: computed with an init + // accessor once, stored now, and a function keeps the init accessor's + // symbol for the clients that inlined a call to it. + @frozen + public struct ShimmedBox { + public var value: Int + @_silgen_name("$s19InitAccessorFixture10ShimmedBoxV5valueSivi") + @usableFromInline + internal mutating func valueInitAccessorABIShim(value: Int) { + self.value = value + } + @inlinable public init(value: Int) { self.value = value } + } + """ + + /// A computed property with an init accessor, by its type's and its own + /// name. + package struct Property: Hashable, Sendable, CustomStringConvertible { + package let typeName: String + package let name: String + + package init(_ typeName: String, _ name: String) { + self.typeName = typeName + self.name = name + } + + package var description: String { "\(typeName).\(name)" } + } + + /// Every computed property the source gives an init accessor. + package static let propertiesWithInitAccessors: [Property] = [ + Property("Angle", "radians"), + Property("Titled", "title"), + Property("Pair", "point"), + Property("Mixed", "a"), + Property("FrozenBox", "value"), + Property("SendableUpgrade", "value"), + Property("SendingResult", "make"), + Property("Model", "name"), + Property("Model", "delegate"), + Property("PersistedLookalike", "name"), + ] + + /// The init accessors the image exports, which every variant keeps. + package static let propertiesWithExportedInitAccessors: Set = [ + Property("FrozenBox", "value"), + ] + + /// What `@storageRestrictions(initializes:)` is inferred to list: a + /// stored property named `_` with the property's type — the type + /// the init accessor names, which `SendableUpgrade.value`'s getter does + /// not, and with `sending` left out the way a declaration's own mangling + /// leaves it out. `Mixed.a` also accesses `b`, which nothing infers. + package static let inferredInitializedFieldNames: [Property: [String]] = [ + Property("Mixed", "a"): ["_a"], + Property("FrozenBox", "value"): ["_value"], + Property("SendableUpgrade", "value"): ["_value"], + Property("SendingResult", "make"): ["_make"], + Property("Model", "name"): ["_name"], + Property("Model", "delegate"): ["_delegate"], + ] + + /// The stored property a function keeps an init accessor's symbol for. + package static let storedPropertyWithInitAccessorSymbol = Property("ShimmedBox", "value") + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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, on a thread of its own, as + /// `ObservableMacroFixture` is: a test that needs the fixture suspends + /// until it is built instead of holding a cooperative thread through + /// four compiles. + private static let compilation = OneTimeCompilation() + + private final class OneTimeCompilation: @unchecked Sendable { + private let lock = NSLock() + private var result: Result<[Variant: URL], Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var hasStarted = false + + func libraries() async throws -> [Variant: URL] { + try await withCheckedThrowingContinuation { continuation in + lock.lock() + if let result { + lock.unlock() + continuation.resume(with: result) + return + } + waiters.append(continuation) + let startsCompilation = !hasStarted + hasStarted = true + lock.unlock() + guard startsCompilation else { return } + Thread { + let result = Result { try InitAccessorFixture.compileLibraries() } + self.lock.lock() + self.result = result + let waiters = self.waiters + self.waiters = [] + self.lock.unlock() + for waiter in waiters { + waiter.resume(with: result) + } + }.start() + } + } + } + + /// Every variant, in one working directory. + private static func compileLibraries() throws -> [Variant: 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 swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + + var libraries: [Variant: URL] = [:] + for variant in Variant.allCases { + // Each variant its own install name: the in-process leg loads + // one by path, and its image is told from the others by name. + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(variant.rawValue).dylib") + let optimization = variant == .debug ? "-Onone" : "-O" + let deadStripping = variant == .releaseDeadStripped ? ["-Xlinker", "-dead_strip"] : [] + try run(step: "swiftc (\(variant.rawValue))", [ + // The language mode pinned: CI's toolchain and a newer + // local one must compile the same source the same way. + "swiftc", "-swift-version", "5", "-enable-library-evolution", "-emit-library", optimization, "-module-name", moduleName, + "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, + ] + deadStripping + [ + swiftSourceURL.path, "-o", libraryURL.path, + ]) + if variant == .releaseStripped { + try run(step: "strip (\(variant.rawValue))", ["strip", "-x", libraryURL.path]) + } + libraries[variant] = libraryURL + } + return libraries + } + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) async throws -> URL { + let libraries = try await compilation.libraries() + guard let libraryURL = libraries[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + package static func machOFile(_ variant: Variant) async throws -> MachOFile { + let libraryURL = try await libraryURL(variant) + 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") + } + } + + /// The `.release` variant loaded into the test process — only that one: + /// the variants define the same class, and the Objective-C runtime keeps + /// one of each. + package static func loadedImage() async throws -> MachOImage { + let libraryURL = try await libraryURL(.release) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift diff --git a/Sources/TestSupport/MachOTestingSupport/MachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift similarity index 95% rename from Sources/TestSupport/MachOTestingSupport/MachOFileTests.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift index e5c4ce4d1..063cd74e6 100644 --- a/Sources/TestSupport/MachOTestingSupport/MachOFileTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOFoundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport @MainActor package class MachOFileTests: Sendable { diff --git a/Sources/TestSupport/MachOTestingSupport/MachOImageTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift similarity index 91% rename from Sources/TestSupport/MachOTestingSupport/MachOImageTests.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift index 83ca25f27..28e4f9550 100644 --- a/Sources/TestSupport/MachOTestingSupport/MachOImageTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOFoundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport @MainActor package class MachOImageTests: Sendable { diff --git a/Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift similarity index 98% rename from Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift index 6ee5f3680..007637af5 100644 --- a/Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import MachOReading import MachOResolving -import MachOFixtureSupport +import SwiftSectionFixtureSupport @MainActor package class MachOSwiftSectionFixtureTests: Sendable { @@ -78,7 +78,7 @@ package class MachOSwiftSectionFixtureTests: Sendable { /// Resolve a relative MachOImageName path (rooted at the package-relative `../../../Tests/...` /// convention) to an absolute filesystem path. Uses the same anchor strategy as /// `loadFromFile` for parity: relative paths resolve against the directory containing - /// this source file (i.e. `Sources/TestSupport/MachOTestingSupport/`). + /// this source file (i.e. `Sources/TestSupport/SwiftSectionTestingSupport/`). private static func resolveFixturePath(_ relativePath: String) -> String { if relativePath.hasPrefix("/") { return relativePath } let url = URL(fileURLWithPath: relativePath, relativeTo: URL(fileURLWithPath: #filePath)) diff --git a/Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift diff --git a/Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift similarity index 85% rename from Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift index f1d6914bd..453a7a151 100644 --- a/Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift @@ -111,6 +111,32 @@ package enum ObjCImplementationFixture { - (void)drawInRect:(NSRect)rect; @end + // Shaped after SceneHosting's `SHScenePresentation` on macOS 27.2 + // (evolution proposal `swift-first-imported-declarations`): an + // `@objc @implementation` class shipped optimized and stripped, whose + // header refines two properties for Swift. `isHostingSceneLayer:` takes + // the Swift name `NS_SWIFT_NAME` gives it, as SceneHosting's does: the + // importer alone keeps `isHostingSceneLayer(_:)`. + @interface FXSceneLayer : NSObject + @end + + @interface PresentationFilter : NSObject + @end + + @interface PresentationSettings : NSObject + @end + + @interface ScenePresentationWidget : NSObject + @property (nonatomic, strong) id observers; + @property (nonatomic, weak, nullable) NSObject *scene; + @property (nonatomic) NSInteger priority; + @property (nonatomic, readonly) BOOL isActive; + @property (nonatomic, strong) PresentationFilter *layerFilter NS_REFINED_FOR_SWIFT; + @property (nonatomic, strong) PresentationSettings *settings NS_REFINED_FOR_SWIFT; + - (BOOL)isHostingSceneLayer:(FXSceneLayer *)sceneLayer NS_SWIFT_NAME(isHosting(sceneLayer:)); + - (void)activate; + @end + NS_ASSUME_NONNULL_END """ @@ -122,6 +148,15 @@ package enum ObjCImplementationFixture { - (void)ping { self.tally += 2; } + (NSInteger)pingCount { return 1; } @end + + @implementation FXSceneLayer + @end + + @implementation PresentationFilter + @end + + @implementation PresentationSettings + @end """ package static let categoryObjectiveCSource = """ @@ -260,6 +295,54 @@ package enum ObjCImplementationFixture { public override func dynamicHook() { super.dynamicHook() } public func widgetWillPing() {} } + + // Shaped after SceneHosting's `SHScenePresentation` (evolution proposal + // `swift-first-imported-declarations`). `public` members keep their + // symbols through `strip -x`, as an OS framework's exports do, and under + // `-O` the thunks inline the bodies and call none of them. A refined + // property's implementation takes the `__` name Swift imports it under and + // spells the selector out. `__settings` is internal, so the optimized + // stripped image keeps no symbol of the member implementing the header's + // `settings`, nor `observers` of its storage; `scene`'s setter is + // internal, so its getter and field offset survive alone. + public struct PresentationFilterValue { + public var isEnabled = true + } + + public struct PresentationSettingsValue { + public var level = 0 + } + + @objc @implementation extension ScenePresentationWidget { + var observers: Any = NSNull() + public internal(set) weak var scene: NSObject? + public var priority: Int = 0 + public var isActive: Bool { priority > 0 } + @objc(layerFilter) public var __layerFilter: PresentationFilter { + get { PresentationFilter() } + set { priority += newValue.hash & 1 } + } + public final var layerFilter: PresentationFilterValue { + get { PresentationFilterValue(isEnabled: priority > 0) } + set { priority = newValue.isEnabled ? 1 : 0 } + } + @objc(settings) var __settings: PresentationSettings { + get { PresentationSettings() } + set { priority += newValue.hash & 1 } + } + public final var settings: PresentationSettingsValue { + get { PresentationSettingsValue(level: priority) } + set { priority = newValue.level } + } + // The compiler derives `isHostingWithSceneLayer:` from the Swift name, + // so the body spells the header's selector, as for `draw(in:)`. + @objc(isHostingSceneLayer:) public func isHosting(sceneLayer: FXSceneLayer) -> Bool { + sceneLayer.hash == priority + } + public func activate() { + priority += 1 + } + } """ package struct CompilationError: Swift.Error, CustomStringConvertible { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift new file mode 100644 index 000000000..05e278b38 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift @@ -0,0 +1,299 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for classes the Observation module's `@Observable` +/// macro expanded (evolution proposal `observable-macro-folding`), beside the +/// look-alikes the recognition must turn down: a class conforming to +/// `Observable` by hand, a stand-in for what SwiftData's `@Model` leaves (a +/// registrar of the same name and type beside `_$backingData`), and a +/// registrar field of another type. +/// +/// One module, four variants: +/// - `.debug` (`-Onone`): every symbol, and the private backing storage's +/// accessors in the vtable. +/// - `.release` (`-O`): every symbol the optimizer leaves; the private +/// generated `shouldNotifyObservers(_:_:)` overloads of a final class are +/// gone. +/// - `.releaseDeadStripped` (`-O`, linked with `-dead_strip`): as SwiftUI — +/// the local symbols kept, but every function nothing references dropped: +/// most init accessors, and every accessor of a final class's internal +/// properties. +/// - `.releaseStripped` (`-O`, then `strip -x`): as an OS framework or a +/// shipped app — an internal class keeps no symbol at all, a public one +/// only its exports, among them the initial-value expressions of its stored +/// properties. +package enum ObservableMacroFixture { + package enum Variant: String, CaseIterable, Sendable { + case debug + case release + case releaseDeadStripped + case releaseStripped + } + + package static let moduleName = "ObservableMacroFixture" + + package static let swiftSource = """ + import Observation + + @propertyWrapper + public struct Clamped { + var storage: Int = 0 + public var wrappedValue: Int { + get { storage } + set { storage = min(newValue, 10) } + } + public init() {} + } + + // Tracked properties with and without an initial value, and stored + // properties the macro leaves alone: one whose name starts with an + // underscore, a lazy one and a `let`. + @Observable + public final class FinalModel { + public var name: String = "" + var count: Int = 0 + var uninitialized: Double + @ObservationIgnored var ignored: Double = 0 + @ObservationIgnored private var _cache: [Int] = [] + @ObservationIgnored lazy var lazyValue: Int = 1 + let constant: Int = 1 + public init() { uninitialized = 0 } + } + + @Observable + open class OpenModel { + public var title: String = "" + var items: [String] = [] + public init() {} + } + + // Internal: a stripped image keeps no symbol of it. + @Observable + class InternalModel { + var value: Int = 0 + var optionalText: String? = nil + weak var delegate: AnyObject? + @ObservationIgnored var _underscored: Int = 0 + } + + // Inherits the conformance: the macro generates no conformance record. + @Observable + class SubModel: OpenModel { + var extra: Int = 0 + } + + @Observable + final class GenericModel { + var elements: [Element] = [] + } + + @Observable + final class WrapperModel { + @ObservationIgnored @Clamped var clamped: Int + var tracked: Int = 0 + init() {} + } + + // Nested in another `@Observable` class, so one print holds both + // attributes. + @Observable + final class ContainerModel { + var title: String = "" + + @Observable + final class NestedModel { + var flag: Bool = false + } + } + + // Properties of a function type with `sending` on its result or a + // parameter: the storage's field record spells `sending`, the accessor + // symbols do not — the mangler leaves it out of a declaration's own + // function type. Public, so every variant keeps the accessors. + public final class Coordinator { + public init() {} + } + + @Observable + public final class SendingModel { + public var makeCoordinator: @Sendable () -> sending Coordinator = { Coordinator() } + public var takeCoordinator: (sending Coordinator) -> Void = { _ in } + public init() {} + } + + // Methods the source declares under the names of those the macro + // generates, in shapes the macro does not generate: it adds its own + // beside them, and these stay the source's. Public, so every variant + // keeps them. + @Observable + public final class HandwrittenNamesModel { + public var value: Int = 0 + public init() {} + public func shouldNotifyObservers() -> Bool { true } + public func access(keyPath: String) {} + } + + final class ManualObservable: Observable { + var plain: Int = 0 + } + + // What SwiftData's `@Model` leaves beside its registrar. + final class PersistentModelStandIn { + private var _$backingData: Int = 0 + private let _$observationRegistrar = ObservationRegistrar() + } + + final class LookalikeRegistrar { + private let _$observationRegistrar: Int = 0 + } + """ + + /// The classes `@Observable` expanded, by the name the source declares. + package static let observableClassNames: Set = [ + "FinalModel", "OpenModel", "InternalModel", "SubModel", "GenericModel", "WrapperModel", "ContainerModel", "NestedModel", + "SendingModel", "HandwrittenNamesModel", + ] + + /// The classes and types the recognition must turn down. + package static let lookalikeTypeNames: Set = [ + "ManualObservable", "PersistentModelStandIn", "LookalikeRegistrar", "Clamped", + ] + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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, on a thread of its own: a test that needs + /// the fixture suspends until it is built instead of holding a + /// cooperative thread through four compiles. Several suites ask for it at + /// once, and a pool whose threads all wait on `swiftc` stalls every other + /// test in the process — a timed one fails. + private static let compilation = OneTimeCompilation() + + private final class OneTimeCompilation: @unchecked Sendable { + private let lock = NSLock() + private var result: Result<[Variant: URL], Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var hasStarted = false + + func libraries() async throws -> [Variant: URL] { + try await withCheckedThrowingContinuation { continuation in + lock.lock() + if let result { + lock.unlock() + continuation.resume(with: result) + return + } + waiters.append(continuation) + let startsCompilation = !hasStarted + hasStarted = true + lock.unlock() + guard startsCompilation else { return } + Thread { + let result = Result { try ObservableMacroFixture.compileLibraries() } + self.lock.lock() + self.result = result + let waiters = self.waiters + self.waiters = [] + self.lock.unlock() + for waiter in waiters { + waiter.resume(with: result) + } + }.start() + } + } + } + + /// Every variant, in one working directory. + private static func compileLibraries() throws -> [Variant: 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 swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + + var libraries: [Variant: URL] = [:] + for variant in Variant.allCases { + // Each variant its own install name: the in-process leg loads + // one by path, and its image is told from the others by name. + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(variant.rawValue).dylib") + let optimization = variant == .debug ? "-Onone" : "-O" + let deadStripping = variant == .releaseDeadStripped ? ["-Xlinker", "-dead_strip"] : [] + try run(step: "swiftc (\(variant.rawValue))", [ + // 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", optimization, "-module-name", moduleName, + "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, + ] + deadStripping + [ + swiftSourceURL.path, "-o", libraryURL.path, + ]) + if variant == .releaseStripped { + try run(step: "strip (\(variant.rawValue))", ["strip", "-x", libraryURL.path]) + } + libraries[variant] = libraryURL + } + return libraries + } + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) async throws -> URL { + let libraries = try await compilation.libraries() + guard let libraryURL = libraries[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + package static func machOFile(_ variant: Variant) async throws -> MachOFile { + let libraryURL = try await libraryURL(variant) + 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") + } + } + + /// The `.release` variant loaded into the test process — only that one: + /// the variants define the same classes, and the Objective-C runtime keeps + /// one of each. + package static func loadedImage() async throws -> MachOImage { + let libraryURL = try await libraryURL(.release) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/ProcessMemory.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/ProcessMemory.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift diff --git a/Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/ProtocolRequirementPlacementFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift diff --git a/Sources/TestSupport/MachOTestingSupport/RenamedObjCClassFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/RenamedObjCClassFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift diff --git a/Sources/TestSupport/MachOTestingSupport/SpecializedMangledNameFixtures.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SpecializedMangledNameFixtures.swift similarity index 98% rename from Sources/TestSupport/MachOTestingSupport/SpecializedMangledNameFixtures.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/SpecializedMangledNameFixtures.swift index e58f7c8e3..2b36657fd 100644 --- a/Sources/TestSupport/MachOTestingSupport/SpecializedMangledNameFixtures.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/SpecializedMangledNameFixtures.swift @@ -3,7 +3,7 @@ import Foundation /// Shared generic fixtures for tests that exercise the specialized /// mangled-name resolution helpers in `RuntimeFunctions`. /// -/// Lives in `MachOTestingSupport` so any test target that links it gets the +/// Lives in `SwiftSectionTestingSupport` so any test target that links it gets the /// type context descriptors compiled into the test executable's /// `__swift5_types` section. Tests look the descriptors up by substring on /// `MachOImage.current()` and force per-instantiation metadata emission by diff --git a/Sources/TestSupport/MachOTestingSupport/Swift64DeclarationShapesFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/Swift64DeclarationShapesFixture.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift new file mode 100644 index 000000000..7dec3ae05 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift @@ -0,0 +1,306 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for the `@objc` protocols a Swift module declares +/// (evolution proposal `swift-declared-objc-protocols`): the compiler emits +/// no Swift protocol descriptor for them and no Swift symbol for any of their +/// requirements, only an Objective-C protocol record and a field descriptor +/// of kind `ObjCProtocol`. +/// +/// Two images. The kit `libSwiftDeclaredObjCProtocolsFixtureKit` declares +/// three `@objc` protocols — one renamed to its own Swift name, one to +/// another name — that the client adopts, so the client holds Swift-emitted +/// copies of records it does not define. The client declares one protocol of +/// each shape (selectors the compiler derives, renamed to its own Swift name, +/// renamed to another name, refining another, internal, declared in a type), +/// the classes that adopt them, and an extension of a Foundation class that +/// adopts one — a category — in three variants: +/// - `.full`: reflection metadata and every symbol present. +/// - `.withoutReflectionMetadata` (`-disable-reflection-metadata`): no +/// `__swift5_fieldmd`, so only the records' runtime names say which +/// protocols are the client's. +/// - `.strippedLocals` (`strip -x`): as every OS framework ships. +package enum SwiftDeclaredObjCProtocolsFixture { + package enum Variant: String, CaseIterable, Sendable { + case full + case withoutReflectionMetadata + case strippedLocals + } + + package static let moduleName = "SwiftDeclaredObjCProtocolsFixture" + + package static let kitModuleName = "SwiftDeclaredObjCProtocolsFixtureKit" + + package static let kitSource = """ + import Foundation + + @objc public protocol KitObserver { + func observe() + } + + @objc(KITRenamedObserver) public protocol RenamedKitObserver { + func renamedObserve() + } + + @objc(KitSameName) public protocol KitSameName { + func sameNameObserve() + } + + // A Swift class the client extends to adopt one of its own protocols. + open class KitWidget: NSObject { + public override init() { super.init() } + } + """ + + package static let swiftSource = """ + import Foundation + import \(kitModuleName) + + // Swift names only: the compiler derives every selector. + @objc public protocol DerivedSelectors: NSObjectProtocol { + init(identifier: String) + func name(for object: Any) -> String + func teamName(for teamIdentifier: String) throws -> String + func hangPoints(input: NSObject) throws -> [String] + func perform(_ action: String, with object: Any?) + func download(identifier: String, completion: @escaping (URL?, Error?) -> Void) + func token() throws -> String + func reload() + var title: String { get } + var isEnabled: Bool { get set } + subscript(index: Int) -> Any { get set } + static func makeDefault() -> NSObject + static var shared: NSObject { get } + @objc optional func scroll(to index: Int, animated: Bool) + @objc optional var optionalCount: Int { get } + } + + // Renamed to its own Swift name, Apple's usual shape. + @objc(SameNameRenamed) public protocol SameNameRenamed { + func ping() + } + + // Renamed to another name: nothing pairs the record with the declaration. + @objc(PRBDifferentlyNamed) public protocol DifferentlyNamed { + @objc(nameForObject:) func name(for object: Any) -> String + @objc(isEnabled) var enabled: Bool { get } + } + + @objc public protocol RefinedProtocol: SameNameRenamed { + func refine() + } + + @objc protocol InternalProtocol { + func internalRequirement() + } + + // File-private: its Swift name carries a private discriminator. + @objc private protocol PrivateProtocol { + func privateRequirement() + } + + // Declared in a type (SE-0404): `_TtPC…` names it, with its parent. + public class Outer: NSObject { + @objc public protocol NestedProtocol { + func nestedRequirement() + } + } + + extension DerivedSelectors { + public func describe() -> String { title } + } + + // Adopted in the class declaration: `class_ro_t` lists the protocols, + // an imported one among them. + public class Conformer: NSObject, SameNameRenamed, NSCopying { + public func ping() {} + public func copy(with zone: NSZone? = nil) -> Any { self } + } + + // Adopted in an extension of its own module: the compiler folds the + // extension into the class's own data, so no category lists it. + public class ExtensionConformer: NSObject {} + + extension ExtensionConformer: RefinedProtocol { + public func ping() {} + public func refine() {} + } + + // Adopts the kit's protocols: the client holds copies of their records. + public class KitObserverConformer: NSObject, KitObserver, RenamedKitObserver, KitSameName { + public func observe() {} + public func renamedObserve() {} + public func sameNameObserve() {} + } + + // An extension of another module's class: a category lists the protocol. + extension DateFormatter: SameNameRenamed { + public func ping() {} + } + + // The same for another module's Swift class: the category names it by + // its `_TtC` runtime name. + @objc public protocol KitWidgetAdopted { + func adoptedPoke() + } + + extension KitWidget: KitWidgetAdopted { + public func adoptedPoke() {} + } + + final class InternalConformer: NSObject, InternalProtocol { + func internalRequirement() {} + } + + public class NestedConformer: NSObject, Outer.NestedProtocol { + public func nestedRequirement() {} + } + + // Existentials of protocols only their field descriptors name: renamed, + // and declared in a type. Class-bound, with no witness table. + public struct RenamedProtocolExistentialHolder { + public var leading: Int + public var renamed: any SameNameRenamed + public var nested: any Outer.NestedProtocol + public var optionalRenamed: (any SameNameRenamed)? + public var trailing: Int8 + } + + // Not @objc, refining an Objective-C protocol: the class data of a class + // conforming to it lists `NSCopying` as well. + public protocol CopyingRefinement: NSCopying {} + + public class ImpliedConformer: NSObject, CopyingRefinement { + public func copy(with zone: NSZone? = nil) -> Any { self } + } + + public func makeInternalConformer() -> AnyObject { + InternalConformer() + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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) + } + } + }() + } + + package struct CompiledLibraries: Sendable { + package let clientLibrariesByVariant: [Variant: URL] + package let kitLibrary: URL + } + + /// Compiled once per process; every variant shares one working directory. + private static let compilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let kitSourceURL = workingDirectory.appendingPathComponent("Kit.swift") + let kitLibraryURL = workingDirectory.appendingPathComponent("lib\(kitModuleName).dylib") + let swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try kitSource.write(to: kitSourceURL, atomically: true, encoding: .utf8) + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + + // Install names are the absolute output paths, so the in-process + // leg loads with no rpath. + try run(step: "swiftc (kit)", [ + // 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", + "-emit-module", "-emit-module-path", workingDirectory.appendingPathComponent("\(kitModuleName).swiftmodule").path, + "-module-name", kitModuleName, + "-Xlinker", "-install_name", "-Xlinker", kitLibraryURL.path, + kitSourceURL.path, "-o", kitLibraryURL.path, + ]) + + var clientLibraries: [Variant: URL] = [:] + for variant in Variant.allCases { + let clientLibraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(variant.rawValue).dylib") + var arguments = [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", moduleName, + "-I", workingDirectory.path, + swiftSourceURL.path, kitLibraryURL.path, "-framework", "Foundation", + "-o", clientLibraryURL.path, + ] + if variant == .withoutReflectionMetadata { + arguments += ["-Xfrontend", "-disable-reflection-metadata"] + } + try run(step: "swiftc (\(variant.rawValue))", arguments) + if variant == .strippedLocals { + try run(step: "strip (\(variant.rawValue))", ["strip", "-x", clientLibraryURL.path]) + } + clientLibraries[variant] = clientLibraryURL + } + return CompiledLibraries(clientLibrariesByVariant: clientLibraries, kitLibrary: kitLibraryURL) + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) throws -> URL { + let libraries = try compilationResult.get() + guard let libraryURL = libraries.clientLibrariesByVariant[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + /// The search paths under which the client's whole world is reachable: + /// the kit as an explicit file, the OS through the running system's dyld + /// shared cache. + package static func dependencySearchPaths() throws -> [DependencySearchPath] { + let libraries = try compilationResult.get() + return [.machOFile(path: libraries.kitLibrary.path), .systemDyldSharedCache] + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + let libraryURL = try libraryURL(variant) + 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") + } + } + + /// The `.full` client loaded into the test process — only that variant: + /// every variant defines the same Objective-C classes, and the runtime + /// keeps one of each. + package static func loadedImage() throws -> MachOImage { + let libraryURL = try libraryURL(.full) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/SwiftIndexEventCollector.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftIndexEventCollector.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/SwiftIndexEventCollector.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/SwiftIndexEventCollector.swift diff --git a/Sources/TestSupport/MachOTestingSupport/TestActor.swift b/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift similarity index 100% rename from Sources/TestSupport/MachOTestingSupport/TestActor.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift new file mode 100644 index 000000000..9bddb5894 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift @@ -0,0 +1,203 @@ +import Foundation +import MachOKit +import Testing + +/// An on-the-fly fixture for members whose implementation symbol the +/// optimizer deleted while another entry point of theirs survived (evolution +/// proposal `thunk-only-objc-members`), compiled twice from one source: +/// - `.unoptimized` (`-Onone`): every entry point keeps its symbol — the +/// independent truth of what the classes declare. +/// - `.wholeModuleOptimized` (`-O -wmo`): the shape of an app's release +/// build. Whole-module optimization lets the optimizer see every use of an +/// internal member, so once those uses are inlined it deletes the entry +/// point. The small `@objc` members are inlined into their Objective-C +/// thunks, which leaves each thunk (`$s…To`) as the member's only symbol; +/// the allocating entry point of `InitializingEntryOnlyHolder.init(values:)` +/// is inlined into both of its callers, while the initializing entry point +/// is too large to inline and stays (`…fc` without `…fC`); so do +/// `ThunkOnlyWidget.init(tags:)`'s, a Swift-only initializer beside the +/// class's `@objc` `init()`; and the synthesized `init()` of the generic +/// class keeps only its initializing entry point and its thunk. +/// +/// Xcode 27.2's `Xcode Service` executable has the same shapes in the wild: +/// `MenuBarPanelWindow.canBecomeKey` and `XcodeServiceAppDelegate`'s +/// `NSApplicationDelegate` methods as thunks alone, nine class initializers +/// as initializing entry points alone. +package enum ThunkOnlyMemberFixture { + package enum Variant: String, CaseIterable, Sendable { + case unoptimized + case wholeModuleOptimized + } + + package static let moduleName = "ThunkOnlyMemberFixture" + + package static let source = """ + import Foundation + + // Internal on purpose: only an internal member's every use is visible to + // whole-module optimization, so only its entry points can be deleted. + class ThunkOnlyWidget: NSObject { + let normalizedTagCount: Int + + override var description: String { "ThunkOnlyWidget" } + override func isEqual(_ object: Any?) -> Bool { object is ThunkOnlyWidget } + @objc func handleTick(_ sender: Any?) {} + // A Swift-only overload of the `@objc` method above, kept out of line + // so both builds have it. + @inline(never) func handleTick(count: Int) -> Int { count * 2 + normalizedTagCount } + @objc class func classTick() -> Int { 1 } + override init() { + normalizedTagCount = 0 + super.init() + } + + // Swift-only beside the `@objc` `init()`: it has no thunk of its own. + init(tags: [String]) { + var normalizedTags: [String] = [] + for tag in tags { + normalizedTags.append(tag.trimmingCharacters(in: .whitespaces).lowercased()) + } + normalizedTagCount = Set(normalizedTags).count + super.init() + } + } + + // Declared in the class's own module, so filed as a member of the class. + extension ThunkOnlyWidget { + @objc func handleExtensionTick(_ sender: Any?) {} + } + + // Another module's class: filed as an extension member. + extension NSObject { + @objc func thunkOnlyFixtureHook() {} + } + + // A generic class has no static class object: its ObjC method table is + // the template its generic metadata pattern carries. + class GenericThunkOnlyWidget: NSObject { + override var description: String { "GenericThunkOnlyWidget" } + @objc func handleTick(_ sender: Any?) {} + } + + class InitializingEntryOnlyHolder { + var values: [String] + var total: Int + var lookup: [String: Int] + + init(values: [String]) { + var lookup: [String: Int] = [:] + var total = 0 + for (index, value) in values.enumerated() { + let normalized = value.trimmingCharacters(in: .whitespaces).lowercased() + lookup[normalized, default: 0] += index + total += normalized.count * (index + 1) + } + self.values = values.sorted() + self.total = total + self.lookup = lookup + } + } + + public func makeFixtureObjects() -> [AnyObject] { + [ThunkOnlyWidget(), ThunkOnlyWidget(tags: ["a", " B "]), GenericThunkOnlyWidget(), InitializingEntryOnlyHolder(values: ["a", " B "])] + } + + public func makeMoreFixtureObjects() -> [AnyObject] { + [ThunkOnlyWidget(tags: ["c"]), InitializingEntryOnlyHolder(values: ["c"])] + } + + public func countTicks(_ count: Int) -> Int { + ThunkOnlyWidget(tags: ["d"]).handleTick(count: count) + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(ThunkOnlyMemberFixture.moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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; both variants share one working directory. + private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + Result { + 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") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + var libraries: [Variant: URL] = [:] + for variant in Variant.allCases { + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(variant.rawValue).dylib") + let optimizationArguments = switch variant { + case .unoptimized: ["-Onone"] + case .wholeModuleOptimized: ["-O", "-wmo"] + } + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + try run(step: "swiftc (\(variant.rawValue))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, + ] + optimizationArguments + [ + sourceURL.path, "-framework", "Foundation", "-o", libraryURL.path, + ]) + libraries[variant] = libraryURL + } + return libraries + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) throws -> URL { + let libraries = try compilationResult.get() + guard let libraryURL = libraries[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + switch try MachOKit.loadFromFile(url: try libraryURL(variant)) { + 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") + } + } + + /// The `.wholeModuleOptimized` build loaded into the test process — only + /// that one: both builds define the same Objective-C classes. + package static func loadedOptimizedImage() throws -> MachOImage { + let libraryURL = try libraryURL(.wholeModuleOptimized) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the optimized fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift new file mode 100644 index 000000000..cb3188450 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift @@ -0,0 +1,232 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for telling a declaration a version cannot show from +/// one that is gone (evolution proposal `evolution-unobservable-presence`): +/// three versions of one module, the middle one stripped of its local symbols +/// (`strip -x`) — the shape of SwiftUI in the macOS 13.0–14.8 dyld shared +/// caches, between the symbol-rich 12.x and 15.0 builds. +/// +/// The public surface is the same in every version except `retiredRender()`, +/// removed in 2.0: it is public, so the stripped version still names its +/// absence through the export trie and the removal is exact. The internal +/// members tell the other stories: +/// +/// - `Panel.layout()` is in every version: invisible in 2.0, inferred present +/// there. +/// - `Panel.legacyLayout()` is in 1.0 and 2.0 and gone from 3.0: removed +/// somewhere between 1.0 and 3.0. +/// - `Panel.freshLayout()` arrives in 3.0: added somewhere between 1.0 and +/// 3.0. +/// - `Int.panelScale()` is in every version, and its extension declares +/// nothing else, so in 2.0 the whole extension is invisible. +/// +/// `Anchor` is `__DATA`-segment ballast: a module without a class compiles to +/// a dylib without one, a layout MachOKit releases before 0.52.103 mis-walked. +package enum UnobservablePresenceFixture { + package static let moduleName = "UnobservablePresenceFixture" + + /// The version-axis labels, oldest first. + package static let labels = ["1.0", "2.0", "3.0"] + + /// The index of the version stripped of its local symbols. + package static let strippedVersionIndex = 1 + + package static let sources: [String] = [ + // 1.0 + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + legacyLayout() + } + + public func retiredRender() -> Int { + 0 + } + + func layout() -> Int { + 1 + } + + func legacyLayout() -> Int { + 2 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + // 2.0, stripped of its local symbols after linking + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + legacyLayout() + } + + func layout() -> Int { + 1 + } + + func legacyLayout() -> Int { + 2 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + // 3.0 + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + freshLayout() + } + + func layout() -> Int { + 1 + } + + func freshLayout() -> Int { + 4 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + ] + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + 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; the versions share one working directory. + private static let compilationResult: Result<[URL], Swift.Error> = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + var libraryURLs: [URL] = [] + for (versionIndex, source) in sources.enumerated() { + let versionName = "V\(versionIndex + 1)" + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName)\(versionName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)\(versionName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + // One module name across every version, so declarations key + // identically; the language mode pinned, so CI's toolchain and + // a newer local one compile the source the same way. + try run(step: "swiftc (\(versionName))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ]) + if versionIndex == strippedVersionIndex { + try run(step: "strip (\(versionName))", ["strip", "-x", libraryURL.path]) + } + libraryURLs.append(libraryURL) + } + return libraryURLs + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + 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(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + /// The compiled versions, oldest first. + package static func libraryURLs() throws -> [URL] { + try compilationResult.get() + } + + /// The compiled versions as readers, oldest first. + package static func machOFiles() throws -> [MachOFile] { + try libraryURLs().map { libraryURL in + 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") + } + } + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/XcodeMachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift similarity index 95% rename from Sources/TestSupport/MachOTestingSupport/XcodeMachOFileTests.swift rename to Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift index 3d889a288..520cef0ae 100644 --- a/Sources/TestSupport/MachOTestingSupport/XcodeMachOFileTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOFoundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport package class XcodeMachOFileTests { package let machOFile: MachOFile diff --git a/Sources/TestSupport/MachOTestingSupportC/CDemangleTree.cpp b/Sources/TestSupport/SwiftSectionTestingSupportC/CDemangleTree.cpp similarity index 100% rename from Sources/TestSupport/MachOTestingSupportC/CDemangleTree.cpp rename to Sources/TestSupport/SwiftSectionTestingSupportC/CDemangleTree.cpp diff --git a/Sources/TestSupport/MachOTestingSupportC/include/CDemangleTree.h b/Sources/TestSupport/SwiftSectionTestingSupportC/include/CDemangleTree.h similarity index 100% rename from Sources/TestSupport/MachOTestingSupportC/include/CDemangleTree.h rename to Sources/TestSupport/SwiftSectionTestingSupportC/include/CDemangleTree.h diff --git a/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift b/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift index 9c1e2e028..12553de67 100644 --- a/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ARM64InstructionDecodingTests.swift @@ -1,7 +1,9 @@ import Foundation import Testing import Capstone -import ARM64InstructionDecoding +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding @Suite struct ARM64InstructionWordTests { @@ -27,6 +29,26 @@ struct ARM64InstructionWordTests { #expect(ARM64InstructionWord.addressMaterialization(backward, at: address)?.address == 0x1_2000_0000) } + /// What ld64 makes of an `adrp` / `add` or `adrp` / `ldr` pair whose + /// address lies within a megabyte (`LinkerOptimizationHintTests`). + @Test func linkerRewrittenAddressesAndLoads() throws { + for target in [address + 0x10_0000 - 4, address - 0x10_0000, address + 0x2B4] { + let whole = try #require(ARM64InstructionWord.addressMaterialization(InstructionEncoding.adr(3, at: address, target: target), at: address)) + #expect(whole.destination == 3 && whole.address == target && !whole.isPageAddress) + } + let page = try #require(ARM64InstructionWord.addressMaterialization(InstructionEncoding.adrp(3, at: address, page: 0x1_E20F_A000), at: address)) + #expect(page.isPageAddress) + + let slot = address + 0x4_2A8 + let literal = try #require(ARM64InstructionWord.loadLiteral(InstructionEncoding.loadLiteral(1, at: address, slot: slot), at: address)) + #expect(literal.destination == 1 && literal.slotAddress == slot) + #expect(ARM64InstructionWord.loadLiteral(InstructionEncoding.loadLiteral(16, at: address, slot: address - 0x8_0000), at: address)?.slotAddress == address - 0x8_0000) + // A 32-bit literal load and an ordinary load are not this one. + #expect(ARM64InstructionWord.loadLiteral(0x1800_0048, at: address) == nil) + #expect(ARM64InstructionWord.loadLiteral(InstructionEncoding.loadUnsignedOffset(1, base: 8, byteOffset: 0x2A8), at: address) == nil) + #expect(ARM64InstructionWord.load(InstructionEncoding.loadLiteral(1, at: address, slot: slot)) == nil) + } + @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) @@ -41,6 +63,38 @@ struct ARM64InstructionWordTests { #expect(negative.displacement == -0x20) } + /// How code reads an Objective-C instance variable's offset variable: + /// `adrp` / `ldrsw`, or the literal `ldrsw` ld64 makes of a pair within a + /// megabyte. A 64-bit load is none of them, and none of them a 64-bit + /// load. + @Test func decoderDecodesThirtyTwoBitLoadAndLoadSignedWord() throws { + let word = try #require(ARM64InstructionWord.wordLoad(InstructionEncoding.loadWordUnsignedOffset(3, base: 8, byteOffset: 0x1F4))) + #expect(word.destination == 3 && word.base == 8 && word.displacement == 0x1F4) + let signedWord = try #require(ARM64InstructionWord.wordLoad(InstructionEncoding.loadSignedWordUnsignedOffset(8, base: 8, byteOffset: 0x3FFC))) + #expect(signedWord.destination == 8 && signedWord.base == 8 && signedWord.displacement == 0x3FFC) + #expect(ARM64InstructionWord.wordLoad(InstructionEncoding.loadUnsignedOffset(8, base: 8, byteOffset: 0x10)) == nil) + #expect(ARM64InstructionWord.load(InstructionEncoding.loadSignedWordUnsignedOffset(8, base: 8, byteOffset: 0x10)) == nil) + + let slot = address + 0x2_0004 + let literal = try #require(ARM64InstructionWord.wordLoadLiteral(InstructionEncoding.loadSignedWordLiteral(9, at: address, slot: slot), at: address)) + #expect(literal.destination == 9 && literal.slotAddress == slot) + // A 64-bit literal load is the other reader's. + #expect(ARM64InstructionWord.wordLoadLiteral(InstructionEncoding.loadLiteral(9, at: address, slot: slot), at: address) == nil) + #expect(ARM64InstructionWord.loadLiteral(InstructionEncoding.loadSignedWordLiteral(9, at: address, slot: slot), at: address) == nil) + + let instructions = try Disassembler().decode( + InstructionEncoding.bytes(of: [ + InstructionEncoding.loadWordUnsignedOffset(3, base: 8, byteOffset: 0x1F4), + InstructionEncoding.loadSignedWordUnsignedOffset(8, base: 8, byteOffset: 0x3FFC), + InstructionEncoding.loadSignedWordLiteral(9, at: address + 8, slot: address + 8 + 0x2_0004), + ]), + address: address + ) + #expect(instructions.map(\.mnemonic) == ["ldr", "ldrsw", "ldrsw"]) + #expect(instructions[0].operands[1].memory?.displacement == 0x1F4) + #expect(instructions[1].operands[1].memory?.displacement == 0x3FFC) + } + @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)) @@ -72,11 +126,17 @@ struct ARM64InstructionWordTests { InstructionEncoding.moveKeep(16, immediate: 0x18B8, shift: 48), InstructionEncoding.callRegisterAuthenticated(9, modifier: 16), InstructionEncoding.branchWithLink(at: address + 28, to: address - 0x1_0000), + InstructionEncoding.adr(3, at: address + 32, target: address + 32 + 0x2B4), + InstructionEncoding.loadLiteral(1, at: address + 36, slot: address + 36 + 0x4_2A8), ] 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.map(\.mnemonic) == ["adrp", "add", "ldr", "braa", "ldr", "movk", "blraa", "bl", "adr", "ldr"]) #expect(instructions[0].operands[1].immediateValue == 0x1_E20F_A000) #expect(instructions[7].operands[0].immediateValue == Int64(address - 0x1_0000)) + #expect(instructions[8].operands[1].immediateValue == Int64(address + 32 + 0x2B4)) + // Capstone gives a literal load's label as memory with no base. + #expect(instructions[9].operands[1].memory?.base == AArch64Reg.invalid) + #expect(instructions[9].operands[1].memory?.displacement == Int64(address + 36 + 0x4_2A8)) } } @@ -106,6 +166,18 @@ struct ARM64TrampolineTests { #expect(ARM64Trampoline(words: words, at: address) == .slotLoad(slotAddress: 0x1_0000_8018)) } + /// ld64 rewrites a lazily bound stub whose slot lies within a megabyte + /// into a load straight from the slot (`LinkerOptimizationHintTests`). + @Test func linkerRewrittenSlotStub() { + let slot = address + 0x4_0008 + let words = [ + ARM64InstructionWord.noOperation, + InstructionEncoding.loadLiteral(16, at: address + 4, slot: slot), + InstructionEncoding.branchToRegister(16), + ] + #expect(ARM64Trampoline(words: words, at: address) == .slotLoad(slotAddress: slot)) + } + @Test func stubIsland() { let words = [ InstructionEncoding.adrp(16, at: address, page: 0x1_8A4E_B000), @@ -130,6 +202,38 @@ struct ARM64TrampolineTests { #expect(ARM64Trampoline(words: words, at: stubAddress) == .selectorStub(selectorAddress: 0x1_F57F_7F98, messageSendAddress: messageSend)) } + /// A function that starts by loading a global — a Swift field offset + /// here — begins the way a GOT stub does; what it does with the loaded + /// value tells the two apart. UIKitCore's `UIHostingViewBase.viewGraph` + /// getter in the iOS 26.3.1 device cache, which a stub island leads to, + /// read as a stub loading its target from the offset variable. + @Test func aFunctionLoadingAGlobalIsNoSlotStub() { + // adrp x8, 0x1e9949000 / ldr x8, [x8, #0xb10] / ldr x0, [x20, x8] / b + let getter: [UInt32] = [0xB030_47C8, 0xF945_8908, 0xF868_6A80, 0x1503_490D] + #expect(ARM64Trampoline(words: getter, at: 0x1_8905_01B0) == nil) + // A jump through another register leaves the loaded value unused. + let otherRegister = [ + InstructionEncoding.adrp(16, at: address, page: 0x1_0000_8000), + InstructionEncoding.loadUnsignedOffset(16, base: 16, byteOffset: 0x18), + InstructionEncoding.branchToRegister(17), + ] + #expect(ARM64Trampoline(words: otherRegister, at: address) == nil) + // A call through the loaded register returns; a stub's jump does not. + let call = [ + InstructionEncoding.adrp(16, at: address, page: 0x1_0000_8000), + InstructionEncoding.loadUnsignedOffset(16, base: 16, byteOffset: 0x18), + InstructionEncoding.callRegisterAuthenticated(16, modifier: 17), + ] + #expect(ARM64Trampoline(words: call, at: address) == nil) + // A literal load the stub's jump does not follow. + let literal = [ + ARM64InstructionWord.noOperation, + InstructionEncoding.loadLiteral(8, at: address + 4, slot: address + 0x4_0008), + ARM64InstructionWord.noOperation, + ] + #expect(ARM64Trampoline(words: literal, at: address) == nil) + } + @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) diff --git a/Tests/CrossReferenceAnalysisTests/AbbreviatedIdentifierScanTests.swift b/Tests/CrossReferenceAnalysisTests/AbbreviatedIdentifierScanTests.swift new file mode 100644 index 000000000..76baee7c5 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/AbbreviatedIdentifierScanTests.swift @@ -0,0 +1,72 @@ +import Foundation +import Testing + +/// Identifiers are spelled out: `instructionAddress`, not `pc`; `left` and +/// `right`, not `lhs` and `rhs`. The names here are the ones a review found +/// spread through the package; the fixture sources under `Tests/Projects` +/// are left out, since their names are what the tests read from the +/// binaries built from them. +@Suite +struct AbbreviatedIdentifierScanTests { + private static let abbreviations = ["pc", "lhs", "rhs"] + + @Test("no source names anything with an abbreviation the package spelled out") + func sourcesSpellNamesOut() throws { + var offendingLines: [String] = [] + for fileURL in try Self.packageSourceFiles() { + let contents = try String(contentsOf: fileURL, encoding: .utf8) + for (lineNumber, line) in contents.components(separatedBy: .newlines).enumerated() where Self.namesAnAbbreviation(line) { + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(line.trimmingCharacters(in: .whitespaces))") + } + } + #expect(offendingLines.isEmpty, "spell these names out:\n\(offendingLines.joined(separator: "\n"))") + } + + /// The scan must be able to see an abbreviation, and must not invent one + /// — its silence proves nothing otherwise. + @Test("the scan sees an abbreviated name and nothing else") + func theScanDiscriminates() { + #expect(Self.namesAnAbbreviation("let pc = start &+ UInt64(instructionIndex * 4)")) + #expect(Self.namesAnAbbreviation("public static func == (lhs: Self, rhs: Self) -> Bool {")) + #expect(Self.namesAnAbbreviation("namedAddresses.sort { lhs, rhs in")) + + #expect(!Self.namesAnAbbreviation("let instructionAddress = start &+ UInt64(instructionIndex * 4)")) + #expect(!Self.namesAnAbbreviation("/// the instruction's own address, `pc`")) + #expect(!Self.namesAnAbbreviation("let pcRelative = true // pc")) + #expect(!Self.namesAnAbbreviation("print(\"lhs\")")) + } + + private static let abbreviationExpression = try! NSRegularExpression(pattern: #"\b(\#(abbreviations.joined(separator: "|")))\b"#) + private static let stringLiteralExpression = try! NSRegularExpression(pattern: #""(?:[^"\\]|\\.)*""#) + + /// Whether the code of `line` — its comment and string literals left out + /// — uses one of the abbreviations as a whole word. + private static func namesAnAbbreviation(_ line: String) -> Bool { + var code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//") else { return false } + code = stringLiteralExpression.stringByReplacingMatches(in: code, range: NSRange(code.startIndex..., in: code), withTemplate: "\"\"") + if let commentStart = code.range(of: "//") { code = String(code[.. [URL] { + let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // CrossReferenceAnalysisTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + var files: [URL] = [] + for directoryName in ["Sources", "Tests"] { + let directory = packageRoot.appendingPathComponent(directoryName) + let enumerator = try #require(FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil)) + for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" { + let components = fileURL.pathComponents.drop(while: { $0 != directoryName }) + if components.dropFirst().first == "Projects" { continue } + files.append(fileURL) + } + } + #expect(files.count > 200, "found only \(files.count) sources under \(packageRoot.path)") + return files + } +} diff --git a/Tests/CrossReferenceAnalysisTests/AddressMaskScanTests.swift b/Tests/CrossReferenceAnalysisTests/AddressMaskScanTests.swift new file mode 100644 index 000000000..b50e59692 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/AddressMaskScanTests.swift @@ -0,0 +1,81 @@ +import Foundation +import Testing + +/// A pointer read out of the process's memory is stripped with the running +/// platform's mask, `InProcessContext.addressMask` — never a constant. A +/// Mac's user addresses fit in 47 bits and an iPhone's in 36, with an arm64e +/// signature starting right above them, at bit 39 on an iPhone: the 47-bit +/// constant the cross-reference scan used left bits 39–46 of every signed +/// slot it read there, and every call through one led nowhere. +@Suite +struct AddressMaskScanTests { + @Test("no library module strips pointers with an address mask of its own") + func libraryModulesUseThePlatformMask() throws { + var offendingLines: [String] = [] + for fileURL in try Self.librarySourceFiles() { + let contents = try String(contentsOf: fileURL, encoding: .utf8) + let allowedFields = Self.fixupFormatFields[fileURL.lastPathComponent] ?? [] + for (lineNumber, line) in contents.components(separatedBy: .newlines).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//"), Self.containsAnAddressMask(code), !allowedFields.contains(where: code.contains) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect(offendingLines.isEmpty, "strip with `InProcessContext.addressMask`:\n\(offendingLines.joined(separator: "\n"))") + } + + /// The scan must be able to see a mask, and must not invent one — its + /// silence proves nothing otherwise. + @Test("the scan sees an address mask and nothing else") + func theScanDiscriminates() { + #expect(Self.containsAnAddressMask("let target = UInt(value & 0x0000_7FFF_FFFF_FFFF)")) + #expect(Self.containsAnAddressMask("static let addressMask: UInt64 = 0x7FFFFFFFFFFF")) + #expect(Self.containsAnAddressMask("value & 0x0000_000F_FFFF_FFFF")) + #expect(Self.containsAnAddressMask("value & 0x7F_FFFF_FFFF")) + + // 32-bit addresses, `Int64.max`, and bits that are no run from bit 0. + #expect(!Self.containsAnAddressMask("value & 0x7FFF_FFFF")) + #expect(!Self.containsAnAddressMask("value & 0xFFFF_FFFF")) + #expect(!Self.containsAnAddressMask("value == 0x7FFF_FFFF_FFFF_FFFF")) + #expect(!Self.containsAnAddressMask("value & 0x0000_7FFF_FFFF_F000")) + #expect(!Self.containsAnAddressMask("let shift = 47")) + } + + /// Fields of a fixup format that look like an address mask and are none: + /// decoding a file reads them, and no process pointer is stripped with + /// them. Shrink-only; each entry says which field it is. Empty since the + /// file readers moved to MachOKitExtensions, whose scan keeps its own. + private static let fixupFormatFields: [String: [String]] = [:] + + private static let hexadecimalLiteral = try! NSRegularExpression(pattern: #"\b0x[0-9A-Fa-f_]+\b"#) + + /// A hexadecimal literal that is a run of 33 to 62 one bits from bit 0: + /// the width of a user address on some platform. + private static func containsAnAddressMask(_ code: String) -> Bool { + hexadecimalLiteral.matches(in: code, range: NSRange(code.startIndex..., in: code)).contains { match in + guard let range = Range(match.range, in: code), + let value = UInt64(code[range].dropFirst(2).filter { $0 != "_" }, radix: 16) + else { return false } + return value & (value &+ 1) == 0 && (33 ... 62).contains(value.nonzeroBitCount) + } + } + + /// Every Swift file of a library module: `Sources///…`, the + /// `TestSupport` group left out. + private static func librarySourceFiles() throws -> [URL] { + let sourcesDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // CrossReferenceAnalysisTests + .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) + } + #expect(files.count > 100, "found only \(files.count) library sources under \(sourcesDirectory.path)") + return files + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift new file mode 100644 index 000000000..3f60219c6 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift @@ -0,0 +1,79 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// `[self class]` compiles to `objc_opt_class(self)`, which returns the class +/// of what it is handed: a class object itself, an instance's class +/// otherwise. In an instance method the send that follows goes to the +/// receiver's class, not to the receiver — a class method of it — so `x0` no +/// longer names the method's receiver; in a class method, and for a class +/// literal, it still names what it named. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct ClassOfReceiverSendTests { + private struct Fixture { + let analyzer: CrossReferenceAnalyzer + let imageIndex: Int + } + + /// The library is loaded before the analyzer that reads it is made. + private static let fixture = Result { + // Without ARC, so no call the compiler adds stands among them. + try CompiledFixture.load( + libraryName: "libCrossReferenceClassOfReceiver.dylib", + sources: [ + "ClassOfReceiver.m": """ + #import + + @interface CrossReferenceClassOfReceiverProbe : NSObject + + (void)classSideProbe; + - (void)sendsToItsClass; + + (void)classSendsToItsClass; + @end + + @implementation CrossReferenceClassOfReceiverProbe + + (void)classSideProbe {} + + - (void)sendsToItsClass { + [[self class] classSideProbe]; + } + + + (void)classSendsToItsClass { + [[self class] classSideProbe]; + } + @end + + void crossReferenceSendsToALiteralsClass(void) { + [[CrossReferenceClassOfReceiverProbe class] classSideProbe]; + } + """, + ], + compilerArguments: ["-O1", "-mmacosx-version-min=12.0", "-fno-objc-arc", "-framework", "Foundation"] + ) + guard let analyzer = CrossReferenceAnalyzer(), + let imageIndex = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix("/libCrossReferenceClassOfReceiver.dylib") }) + else { throw CompiledFixture.Failure(description: "the analyzer does not see the fixture") } + return Fixture(analyzer: analyzer, imageIndex: imageIndex) + } + + static let probe = ReceiverClassHint.classLiteral("CrossReferenceClassOfReceiverProbe") + + @Test(arguments: [ + // The instance's class is not the instance. + ("-[CrossReferenceClassOfReceiverProbe sendsToItsClass]", [ClassOfReceiverSendTests.send("class", to: .methodReceiver), ClassOfReceiverSendTests.send("classSideProbe", to: .unknown)]), + // A class object's class is the class object. + ("+[CrossReferenceClassOfReceiverProbe classSendsToItsClass]", [ClassOfReceiverSendTests.send("class", to: .methodReceiver), ClassOfReceiverSendTests.send("classSideProbe", to: .methodReceiver)]), + ("_crossReferenceSendsToALiteralsClass", [ClassOfReceiverSendTests.send("class", to: ClassOfReceiverSendTests.probe), ClassOfReceiverSendTests.send("classSideProbe", to: ClassOfReceiverSendTests.probe)]), + ]) + func aSendAfterAskingForTheClassGoesToTheClassOfTheReceiver(functionName: String, expectedSends: [CodeReferenceTarget]) throws { + let fixture = try Self.fixture.get() + let function = try #require(fixture.analyzer.functions(inImageAt: fixture.imageIndex).first { $0.name == .symbol(functionName) }, "no function \(functionName)") + let sends = fixture.analyzer.references(madeBy: function).filter { if case .messageSend = $0.target { true } else { false } } + #expect(sends.map(\.target) == expectedSends) + } + + static func send(_ selector: String, to receiver: ReceiverClassHint) -> CodeReferenceTarget { + .messageSend(selector: selector, receiver: receiver) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift b/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift index f6ee72dff..5089e3fab 100644 --- a/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift +++ b/Tests/CrossReferenceAnalysisTests/CodeReferenceIndexTests.swift @@ -1,6 +1,8 @@ import Foundation import Testing @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// Foundation's index, built once for the suite: a Debug build scans an image /// of its size in seconds. diff --git a/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift new file mode 100644 index 000000000..310217b5f --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift @@ -0,0 +1,98 @@ +import Foundation +import MachOKit +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// A dynamic library compiled from source for one suite, rewritten after +/// linking when the suite asks, and loaded into the test process. +enum CompiledFixture { + struct Failure: Error, CustomStringConvertible { + let description: String + } + + /// Compiles `sources` — file names and their contents — into the arm64 + /// library `libraryName`, hands the linked bytes to `rewrite` and signs + /// the result again when there is one, and loads it. The library stays + /// loaded after its directory is removed; the analyzers made from then on + /// see it under the path this returns. + @discardableResult + static func load( + libraryName: String, + sources: KeyValuePairs, + compilerArguments: [String], + rewrite: ((inout Data, MachOFile) throws -> Void)? = nil + ) throws -> String { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + var sourcePaths: [String] = [] + for (fileName, contents) in sources { + let sourceURL = directory.appendingPathComponent(fileName) + try contents.write(to: sourceURL, atomically: true, encoding: .utf8) + sourcePaths.append(sourceURL.path) + } + let library = directory.appendingPathComponent(libraryName) + try run("/usr/bin/xcrun", arguments: ["clang", "-dynamiclib", "-arch", "arm64"] + compilerArguments + ["-o", library.path] + sourcePaths) + if let rewrite { + var bytes = try Data(contentsOf: library) + try rewrite(&bytes, try MachOFile(url: library)) + try bytes.write(to: library) + // Rewritten code no longer matches the signature's page hashes. + try run("/usr/bin/codesign", arguments: ["--force", "--sign", "-", library.path]) + } + guard dlopen(library.path, RTLD_NOW | RTLD_LOCAL) != nil else { + throw Failure(description: "could not load \(libraryName): \(dlerror().map { String(cString: $0) } ?? "")") + } + return library.path + } + + /// Compiles `sources` into the arm64 library `libraryName` and leaves it + /// on disk, unloaded, for a suite that reads it as a file. The caller + /// removes `directory`. + static func build( + libraryName: String, + sources: KeyValuePairs, + compilerArguments: [String], + architecture: String = "arm64", + isExecutable: Bool = false + ) throws -> (directory: URL, library: URL) { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var sourcePaths: [String] = [] + for (fileName, contents) in sources { + let sourceURL = directory.appendingPathComponent(fileName) + try contents.write(to: sourceURL, atomically: true, encoding: .utf8) + sourcePaths.append(sourceURL.path) + } + let library = directory.appendingPathComponent(libraryName) + try run("/usr/bin/xcrun", arguments: ["clang"] + (isExecutable ? [] : ["-dynamiclib"]) + ["-arch", architecture] + compilerArguments + ["-o", library.path] + sourcePaths) + return (directory, library) + } + + /// Compiles one Swift source into the arm64 library `libraryName`, + /// optimized, and leaves it on disk. The caller removes `directory`. + static func buildSwift(libraryName: String, source: String) throws -> (directory: URL, library: URL) { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let sourceURL = directory.appendingPathComponent("Fixture.swift") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + let library = directory.appendingPathComponent(libraryName) + try run("/usr/bin/xcrun", arguments: ["swiftc", "-O", "-emit-library", "-target", "arm64-apple-macos14", "-module-name", "Fixture", "-o", library.path, sourceURL.path]) + return (directory, library) + } + + private static func run(_ executablePath: String, arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + let output = Pipe() + process.standardOutput = output + process.standardError = output + try process.run() + let printed = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw Failure(description: "\(([executablePath] + arguments).joined(separator: " ")) exited with \(process.terminationStatus): \(String(decoding: printed, as: UTF8.self))") + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift index 28c69b93b..a131cb419 100644 --- a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift +++ b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift @@ -3,6 +3,8 @@ import Testing import Capstone import MachOKit @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// One analyzer for the whole suite: building it reads every image of the /// shared cache. @@ -29,7 +31,7 @@ struct CrossReferenceAnalyzerTests { #expect(analyzer.images.count > 1000) #expect(analyzer.imagePaths.contains { $0.hasSuffix("/libobjc.A.dylib") }) #expect(!analyzer.messageSendLocations.isEmpty) - #expect(!analyzer.runtimeHelperLocations.isEmpty) + #expect(!analyzer.imageSet.runtimeHelperLocations.isEmpty) } /// The three messages this method sends — through the image's own @@ -190,7 +192,9 @@ struct CrossReferenceAnalyzerTests { /// /// The dropped images are sampled, every sixteenth: a Debug build scans /// the whole cache in minutes, not seconds. - @Test(arguments: ["orderWindow:relativeTo:", "description", "count"]) + /// `isKindOfClass:` is sent through `objc_opt_isKindOfClass` alone, which + /// no selector reference shows (`RuntimeSendEntryPointTests`). + @Test(arguments: ["orderWindow:relativeTo:", "description", "count", "isKindOfClass:"]) func selectorPrefilterKeepsEverySender(selector: String) throws { let everyImage = Array(analyzer.images.indices) let kept = analyzer.imageIndices(referencingSelector: selector, among: everyImage) diff --git a/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift b/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift index 942d16b96..f1d576956 100644 --- a/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FallbackNamingTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOSwiftSection import Demangling @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// 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 @@ -49,7 +51,7 @@ struct FallbackNamingTests { @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() + let methods = ObjCMethodNames.of(table).methodsByAddress #expect(methods.count > 50000) var compared = 0 var agreeing = 0 @@ -90,7 +92,7 @@ struct FallbackNamingTests { 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]) + let rebuilt = SwiftMetadataNames.of(table).name(at: table.starts[index]) else { continue } compared += 1 let symbol = String(cString: name) diff --git a/Tests/CrossReferenceAnalysisTests/FileModeTests.swift b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift new file mode 100644 index 000000000..3a54295ad --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift @@ -0,0 +1,339 @@ +import Foundation +import Testing +import MachOKit +import MachOKitExtensions +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding +@testable import CrossReferenceAnalysis + +/// The analyzer made from the running system's dyld shared cache file: +/// the same images the process maps, read where they lie on disk. +enum RunningCacheFileAnalyzer { + static let analyzer: CrossReferenceAnalyzer? = FullDyldCache.cachedHost.flatMap { try? CrossReferenceAnalyzer(dyldCache: $0) } +} + +/// The analyzer made from files reads what the in-process analyzer reads, +/// and reaches what the process cannot: archived caches, another device's +/// cache, an app on disk (evolution proposal +/// `offline-cross-references-and-symbolication`, step 4). +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil && RunningCacheFileAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct FileModeTests { + /// Every reference of a large image, read from the cache file, is the + /// one the process reads from memory: the same functions, the same + /// sites, the same targets — a class object a GOT slot rebases to, a + /// selector a stub sets, a Swift type an accessor names. + @Test(arguments: ReferenceTableDigestTests.imageSuffixes) + func fileModeMatchesInProcessReferencesOnTheRunningSystemCache(imageSuffix: String) throws { + let inProcess = try #require(SharedAnalyzer.analyzer) + let fromFile = try #require(RunningCacheFileAnalyzer.analyzer) + let inProcessIndex = try #require(inProcess.imagePaths.firstIndex { $0.hasSuffix(imageSuffix) }) + let fileIndex = try #require(fromFile.imagePaths.firstIndex { $0.hasSuffix(imageSuffix) }) + let inProcessLines = inProcess.referenceTable(ofImageAt: inProcessIndex).references.map { Self.spelling(of: $0, imagePaths: inProcess.imagePaths) } + let fileLines = fromFile.referenceTable(ofImageAt: fileIndex).references.map { Self.spelling(of: $0, imagePaths: fromFile.imagePaths) } + #expect(fileLines.count == inProcessLines.count, "\(imageSuffix): \(fileLines.count) references from the file, \(inProcessLines.count) in the process") + let differences = zip(inProcessLines, fileLines).filter { $0 != $1 }.prefix(5) + #expect(differences.isEmpty, "\(imageSuffix), first differences (process, file):\n\(differences.map { "\($0)\n\($1)" }.joined(separator: "\n\n"))") + #expect(inProcessLines.count > 100_000) + } + + /// Every function of an image is named from the file as the process + /// names it: from its symbols and export trie, and — where those leave + /// it unnamed — from the Objective-C method lists and the Swift + /// metadata, which read through each reader's own API. + @Test(arguments: ReferenceTableDigestTests.imageSuffixes + ["/Matter.framework/Versions/A/Matter"]) + func fileModeNamesFunctionsAsTheProcessDoes(imageSuffix: String) throws { + let inProcess = try #require(SharedAnalyzer.analyzer) + let fromFile = try #require(RunningCacheFileAnalyzer.analyzer) + let inProcessIndex = try #require(inProcess.imagePaths.firstIndex { $0.hasSuffix(imageSuffix) }) + let fileIndex = try #require(fromFile.imagePaths.firstIndex { $0.hasSuffix(imageSuffix) }) + func spelling(of function: CodeFunction) -> String { + "\(function.location.address) \(function.size) \(Self.describe(function.name)) \(function.foldedSymbolNames) \(function.isRuntimeHelper)" + } + let inProcessFunctions = inProcess.functions(inImageAt: inProcessIndex) + let inProcessLines = inProcessFunctions.map(spelling(of:)) + let fileLines = fromFile.functions(inImageAt: fileIndex).map(spelling(of:)) + #expect(fileLines.count == inProcessLines.count) + let differences = zip(inProcessLines, fileLines).filter { $0 != $1 }.prefix(5) + #expect(differences.isEmpty, "\(imageSuffix), first differences (process, file):\n\(differences.map { "\($0)\n\($1)" }.joined(separator: "\n\n"))") + #expect(inProcessFunctions.count > 1000) + } + + /// The two fallback sources read every name from the file that they + /// read from memory: the Objective-C method lists of AppKit (whose + /// classes the runtime has realized in the process) and of Matter, and + /// the Swift metadata of SwiftUICore — each through its reader's own + /// API, in which a method's `imp` and a descriptor's offset count + /// differently. + @Test func fileModeReadsTheFallbackNameSourcesAsTheProcessDoes() throws { + let inProcess = try #require(SharedAnalyzer.analyzer) + let fromFile = try #require(RunningCacheFileAnalyzer.analyzer) + func tables(_ suffix: String) throws -> (ImageFunctionTable, ImageFunctionTable) { + let inProcessIndex = try #require(inProcess.imagePaths.firstIndex { $0.hasSuffix(suffix) }) + let fileIndex = try #require(fromFile.imagePaths.firstIndex { $0.hasSuffix(suffix) }) + return (inProcess.imageSet.transientFunctionTable(ofImageAt: inProcessIndex), fromFile.imageSet.transientFunctionTable(ofImageAt: fileIndex)) + } + for suffix in ["/AppKit.framework/Versions/C/AppKit", "/Matter.framework/Versions/A/Matter"] { + let (inProcessTable, fileTable) = try tables(suffix) + func spelled(_ names: ObjCMethodNames) -> [UInt64: String] { + names.methodsByAddress.mapValues { "\($0.isClassMethod ? "+" : "-")[\($0.className) \($0.selector)]" } + } + let inProcessMethods = spelled(ObjCMethodNames.of(inProcessTable)) + let fileMethods = spelled(ObjCMethodNames.of(fileTable)) + #expect(inProcessMethods.count > 100, "\(suffix): \(inProcessMethods.count) methods in the process") + let differing = inProcessMethods.filter { fileMethods[$0.key] != $0.value }.prefix(5) + #expect(fileMethods.count == inProcessMethods.count && differing.isEmpty, "\(suffix): \(fileMethods.count) methods from the file, \(inProcessMethods.count) in the process; differing: \(Array(differing))") + } + let (inProcessTable, fileTable) = try tables("/SwiftUICore.framework/Versions/A/SwiftUICore") + let inProcessNames = SwiftMetadataNames.of(inProcessTable) + let fileNames = SwiftMetadataNames.of(fileTable) + var named = 0 + var differing: [String] = [] + for start in inProcessTable.starts { + let inProcessName = inProcessNames.name(at: start) + if inProcessName != nil { named += 1 } + if fileNames.name(at: start) != inProcessName, differing.count < 5 { differing.append("\(String(start, radix: 16)): \(inProcessName ?? "nil") / \(fileNames.name(at: start) ?? "nil")") } + } + #expect(named > 1000, "the metadata names only \(named) functions of SwiftUICore") + #expect(differing.isEmpty, "process / file: \(differing)") + } + + /// The prefilters read the same slots and symbols from the file: the + /// images that may send a selector are the process's, less the images + /// it loaded outside the cache. + @Test(arguments: ["makeKeyAndOrderFront:", "init"]) + func fileModePrefiltersSelectorsAsTheProcessDoes(selector: String) throws { + let inProcess = try #require(SharedAnalyzer.analyzer) + let fromFile = try #require(RunningCacheFileAnalyzer.analyzer) + let cachePaths = Set(fromFile.imagePaths) + let inProcessPaths = Set(inProcess.imageIndices(referencingSelector: selector, among: inProcess.imagePaths.indices).map { inProcess.imagePaths[$0] }).intersection(cachePaths) + let filePaths = Set(fromFile.imageIndices(referencingSelector: selector, among: fromFile.imagePaths.indices).map { fromFile.imagePaths[$0] }) + #expect(filePaths == inProcessPaths, "only in the process: \(inProcessPaths.subtracting(filePaths).sorted().prefix(5)); only in the file: \(filePaths.subtracting(inProcessPaths).sorted().prefix(5))") + #expect(filePaths.count > 10) + } + + /// A reference spelled with its images by path rather than by position, + /// which differs between the two analyzers: the process lists the images + /// loaded outside the cache too. + private static func spelling(of reference: CodeReference, imagePaths: [String]) -> String { + let spelling = ReferenceTableDigestTests.spelling(of: reference) + let range = NSRange(location: 0, length: spelling.utf16.count) + var result = "" + var last = spelling.startIndex + for match in imageIndexPattern.matches(in: spelling, range: range) { + guard let whole = Range(match.range, in: spelling), let number = Range(match.range(at: 1), in: spelling), let imageIndex = Int(spelling[number]) else { continue } + result += spelling[last ..< whole.lowerBound] + result += "image: \(imageIndex < imagePaths.count ? imagePaths[imageIndex] : "?")" + last = whole.upperBound + } + return result + spelling[last...] + } + + private static let imageIndexPattern = try! NSRegularExpression(pattern: #"imageIndex: (\d+)"#) + + /// The two callers of `UINSPasteboardWritingItemProvider` in macOS 27.0 + /// and 27.2 load UIKitMacHelper's own class object from a GOT slot, + /// which no disassembler names: the slot holds a cache-relative rebase + /// of the class's address. + @Test(.enabled(if: FileManager.default.fileExists(atPath: "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e"), "needs the archived macOS caches"), arguments: ["27.0", "27.2"]) + func archivedCacheFindsBothCallersOfPasteboardWritingItemProvider(version: String) throws { + let cachePath = "/Volumes/DyldSharedCaches/macOS/\(version)/dyld_shared_cache_arm64e" + try #require(FileManager.default.fileExists(atPath: cachePath), "no archived macOS \(version) cache") + let analyzer = try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: URL(fileURLWithPath: cachePath))) + let macHelper = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/UIKitMacHelper.framework/Versions/A/UIKitMacHelper") }) + let className = "UINSPasteboardWritingItemProvider" + #expect(analyzer.objectiveCClassLocations(named: className, inImageAt: macHelper).count == 1) + let references = analyzer.references(to: [.objectiveCClass(className)], inImageAt: macHelper) + let callerNames = Set(analyzer.functions(containing: references.map(\.function)).values.map { Self.describe($0.name) }) + #expect(callerNames == [ + "-[UINSInputView writeSelectionToPasteboard:types:]", + "-[UINSSceneWindowController window:shouldDragDocumentWithEvent:from:withPasteboard:]", + ], "macOS \(version): \(references)") + } + + private static func describe(_ name: CodeFunction.Name?) -> String { + switch name { + case .symbol(let symbol)?: + return symbol + case .objectiveCMethod(let className, let selector, let isClassMethod)?: + return "\(isClassMethod ? "+" : "-")[\(className) \(selector)]" + case .swiftMetadata(let mangledName)?: + return mangledName + case nil: + return "" + } + } + + /// An iOS device cache is too large for a `bl` to reach across its + /// subcaches: a call to another image goes through stub islands between + /// the images. A send through one is still a send. + @Test(.enabled(if: FileManager.default.fileExists(atPath: "/Volumes/DyldSharedCaches/iOS/26.3.1/dyld_shared_cache_arm64e"), "needs the archived iOS 26.3.1 device cache")) + func archivedCacheFollowsStubIslandsForSelectorSends() throws { + let analyzer = try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: URL(fileURLWithPath: "/Volumes/DyldSharedCaches/iOS/26.3.1/dyld_shared_cache_arm64e"))) + let swiftUI = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/SwiftUI.framework/SwiftUI") }) + let table = analyzer.referenceTable(ofImageAt: swiftUI) + var sendsThroughIslands = 0 + for reference in table.references { + guard case .messageSend = reference.target, + let word = analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: swiftUI, address: reference.instructionAddress))), + let branchTarget = ARM64InstructionWord.callTarget(word, at: reference.instructionAddress) ?? ARM64InstructionWord.branchTarget(word, at: reference.instructionAddress) + else { continue } + // The `bl` lands between the images: on an island. + if analyzer.imageSet.imageIndex(containingRuntimeAddress: UInt(branchTarget)) == nil { + sendsThroughIslands += 1 + #expect(reference.route == .stubIsland, "\(String(reference.instructionAddress, radix: 16)): \(reference.route)") + } + } + #expect(sendsThroughIslands > 100, "only \(sendsThroughIslands) sends of SwiftUI go through stub islands") + } + + /// A standalone library linked `-interposable` calls its own exported + /// function the way it calls another library's: through a stub whose + /// slot binds by name, to itself. The bind leads to the function; a call + /// into a library the analyzer does not cover stays an imported name. + @Test func standaloneAppResolvesImportedAndSelfBoundSymbols() throws { + let (directory, library) = try CompiledFixture.build( + libraryName: "libSelfBound.dylib", + sources: ["SelfBound.c": """ + #include + __attribute__((noinline)) int selfBoundCallee(int value) { return value * 3; } + int selfBoundCaller(int value) { puts("called"); return selfBoundCallee(value) + 1; } + """], + compilerArguments: ["-O1", "-Wl,-interposable"] + ) + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + #expect(analyzer.imageCount == 1) + #expect(analyzer.images.isEmpty) + let functions = analyzer.functions(inImageAt: 0) + let caller = try #require(functions.first { $0.name == .symbol("_selfBoundCaller") }) + let callee = try #require(functions.first { $0.name == .symbol("_selfBoundCallee") }) + let targets = analyzer.references(madeBy: caller).map(\.target) + #expect(targets.contains(.function(callee.location)), "\(targets)") + #expect(targets.contains(.importedSymbol(name: "_puts")), "\(targets)") + #expect(!targets.contains(.importedSymbol(name: "_selfBoundCallee"))) + } + + /// A C++ function's exception cleanup — the landing pad that runs a + /// destructor and resumes unwinding — lies after its `retab`, where no + /// function start marks it. The scan runs past a return to the next + /// start, so the cleanup's calls are found: `_Unwind_Resume` is called + /// nowhere else. + @Test func fileModeScansExceptionCleanupCodeAfterReturn() throws { + let (directory, library) = try CompiledFixture.build( + libraryName: "libCleanup.dylib", + sources: ["Cleanup.cpp": """ + #include + extern "C" __attribute__((noinline)) void cleanupCallee(void) { asm volatile(""); } + struct Guard { ~Guard() { cleanupCallee(); } }; + __attribute__((noinline)) void mayThrow(int value) { if (value > 3) throw std::runtime_error("too large"); } + extern "C" int withCleanup(int value) { Guard guard; mayThrow(value); return value + 1; } + """], + compilerArguments: ["-O1", "-lc++"], + architecture: "arm64e" + ) + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + let withCleanup = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_withCleanup") }) + let references = analyzer.references(madeBy: withCleanup) + let resume = try #require(references.first { $0.target == .importedSymbol(name: "__Unwind_Resume") }, "\(references.map(\.target))") + // The resume call comes after a return of the function's own. + var returnAddress: UInt64? + var address = withCleanup.location.address + while address < resume.instructionAddress { + if let word = analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: 0, address: address))), + ARM64InstructionWord.isReturn(word) { + returnAddress = address + } + address += 4 + } + #expect(returnAddress != nil, "no return before the cleanup's call at \(String(resume.instructionAddress, radix: 16))") + } + + /// The memory decodes a shared cache's slots itself, from slide info + /// taken once per mapping: every pointer slot of the first images of the + /// running system's cache (slide info version 5, decoded by the memory + /// itself) and of an iOS simulator runtime's (no slide info: MachOKit + /// decodes them) holds what MachOKit decodes it to. + @Test(arguments: [ + "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e", + "/Volumes/DyldSharedCaches/iOS-Simulator/27.0/dyld_sim_shared_cache_arm64", + ]) + func fileMemoryDecodesSlotsAsMachOKitDoes(cachePath: String) throws { + guard FileManager.default.fileExists(atPath: cachePath) else { + withKnownIssue("\(cachePath) is not on this machine") { throw CompiledFixture.Failure(description: "missing cache") } + return + } + let cache = try FullDyldCache(url: URL(fileURLWithPath: cachePath)) + let storage = FileCrossReferenceMemory.storage(cache: cache) + defer { withExtendedLifetime(storage) {} } + let memory = FileCrossReferenceMemory(storage: storage) + let pointerSections: Set = ["__got", "__auth_got", "__objc_selrefs", "__objc_classrefs", "__objc_superrefs", "__objc_classlist", "__objc_protolist"] + var compared = 0 + var differences: [String] = [] + for file in cache.machOFiles().prefix(60) { + for section in file.sections64 where pointerSections.contains(section.sectionName) { + for slot in stride(from: UInt64(section.address), to: UInt64(section.address) + UInt64(section.size), by: 8) { + guard let (subcache, fileOffset) = cache.cacheAndFileOffset(for: slot) else { continue } + let decodedByMachOKit = subcache.resolveOptionalRebase(at: fileOffset).map { UInt(truncatingIfNeeded: $0) & memory.addressMask } ?? 0 + let decoded = memory.slotContent(at: UInt(slot)) + if decoded != .address(decodedByMachOKit), differences.count < 5 { + differences.append("\(file.imagePath) \(section.sectionName) \(String(slot, radix: 16)): \(String(describing: decoded)) / MachOKit \(String(decodedByMachOKit, radix: 16))") + } + compared += 1 + } + } + } + #expect(compared > 10000, "only \(compared) slots compared") + #expect(differences.isEmpty, "\(differences)") + } + + /// A main executable's `__TEXT` lies at 0x100000000, not at 0 as a + /// dylib's does, so a rebase's target read as an offset from the image + /// rather than as an address points 4 GiB below where it should: the + /// selector references of `__objc_stubs` then lead nowhere, and every + /// send through one reads as an unrecognized call. + @Test func standaloneExecutableResolvesRebasesAndObjectiveCStubs() throws { + let (directory, executable) = try CompiledFixture.build( + libraryName: "ObjectiveCExecutable", + sources: ["Main.m": """ + #import + __attribute__((noinline)) static void target(void) { asm volatile(""); } + void (*volatile functionPointer)(void) = target; + int main(void) { + @autoreleasepool { + NSMutableArray *array = [NSMutableArray array]; + [array addObject:@"element"]; + functionPointer(); + return (int)[array count]; + } + } + """], + compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"], + isExecutable: true + ) + defer { try? FileManager.default.removeItem(at: directory) } + let file = try MachOFile(url: executable) + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) + let main = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_main") }) + let targets = analyzer.references(madeBy: main).map(\.target) + #expect(targets.contains { if case .messageSend("addObject:", _) = $0 { true } else { false } }, "\(targets)") + #expect(targets.contains { if case .messageSend("count", _) = $0 { true } else { false } }, "\(targets)") + #expect(!targets.contains { if case .unrecognized = $0 { true } else { false } }, "\(targets)") + // A data slot rebased to a function holds the function's address. + let dataSection = try #require(file.sections64.first { $0.segmentName == "__DATA" && $0.sectionName == "__data" }) + let slot = analyzer.memory.pointer(at: UInt(dataSection.address)) + let targetFunction = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_target") }) + #expect(slot == UInt(targetFunction.location.address), "the slot holds \(slot.map { String($0, radix: 16) } ?? "nothing")") + } + + /// Images read from files are no `MachOImage`s; the count says how many + /// there are. + @Test func fileModeListsImagesByPathAndCount() throws { + let fromFile = try #require(RunningCacheFileAnalyzer.analyzer) + #expect(fromFile.images.isEmpty) + #expect(fromFile.imageCount == fromFile.imagePaths.count) + #expect(fromFile.imageCount > 1000) + #expect(fromFile.imageIndex(forPath: "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit") != nil) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift new file mode 100644 index 000000000..cb5e7a734 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift @@ -0,0 +1,39 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// Some images' symbol tables put a function start of `__text` below the +/// section's own start. The scan reads such a function where it lies, as it +/// always did; reading it at an offset from `__text` underflowed and trapped +/// the first scan of every image of the macOS 27.2 cache (the throughput +/// benchmark of the layer split, 2026-11-19). +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct FunctionStartOutsideTextTests { + private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } + + /// The images whose function table holds a start outside `__text`. + private func imagesWithAStartOutsideText() -> [Int] { + let imageCount = analyzer.imagePaths.count + let flags = UnsafeMutableBufferPointer.allocate(capacity: imageCount) + flags.initialize(repeating: false) + defer { flags.deallocate() } + nonisolated(unsafe) let flagsBase = flags.baseAddress! + let analyzer = self.analyzer + DispatchQueue.concurrentPerform(iterations: imageCount) { imageIndex in + let table = analyzer.imageSet.transientFunctionTable(ofImageAt: imageIndex) + (flagsBase + imageIndex).pointee = table.starts.contains { $0 < table.textStart || $0 >= table.textEnd } + } + return (0 ..< imageCount).filter { flags[$0] } + } + + @Test func aFunctionStartingOutsideTextScansWhereItLies() throws { + let images = imagesWithAStartOutsideText() + try #require(!images.isEmpty, "no image of this system's cache has a function start outside __text") + for imageIndex in images.prefix(3) { + let table = analyzer.referenceTable(ofImageAt: imageIndex) + #expect(table.imageIndex == imageIndex, "\(analyzer.imagePaths[imageIndex])") + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/InstructionEncoding.swift b/Tests/CrossReferenceAnalysisTests/InstructionEncoding.swift index 28061097f..75c007162 100644 --- a/Tests/CrossReferenceAnalysisTests/InstructionEncoding.swift +++ b/Tests/CrossReferenceAnalysisTests/InstructionEncoding.swift @@ -1,4 +1,6 @@ import Foundation +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// Encoders for the A64 instructions the decoding tests build by hand, /// written straight from the architecture's encoding tables so the readers @@ -10,6 +12,20 @@ enum InstructionEncoding { return 0x9000_0000 | ((immediate & 0x3) << 29) | ((immediate >> 2) << 5) | UInt32(destination) } + /// `adr xd, label`: an address within a megabyte, from the instruction's + /// own address. + static func adr(_ destination: Int, at address: UInt64, target: UInt64) -> UInt32 { + let immediate = UInt32(truncatingIfNeeded: Int64(bitPattern: target &- address)) & 0x1F_FFFF + return 0x1000_0000 | ((immediate & 0x3) << 29) | ((immediate >> 2) << 5) | UInt32(destination) + } + + /// `ldr xt, label`: a 64-bit load from a slot within a megabyte of the + /// instruction. + static func loadLiteral(_ destination: Int, at address: UInt64, slot: UInt64) -> UInt32 { + let wordDelta = UInt32(truncatingIfNeeded: Int64(bitPattern: slot &- address) >> 2) & 0x7FFFF + return 0x5800_0000 | (wordDelta << 5) | UInt32(destination) + } + static func add(_ destination: Int, _ source: Int, immediate: UInt32) -> UInt32 { 0x9100_0000 | (immediate << 10) | (UInt32(source) << 5) | UInt32(destination) } @@ -22,6 +38,23 @@ enum InstructionEncoding { 0xF940_0000 | ((byteOffset / 8) << 10) | (UInt32(base) << 5) | UInt32(destination) } + /// `ldr wt, [xn, #imm]`: a 32-bit load, the displacement scaled by 4. + static func loadWordUnsignedOffset(_ destination: Int, base: Int, byteOffset: UInt32) -> UInt32 { + 0xB940_0000 | ((byteOffset / 4) << 10) | (UInt32(base) << 5) | UInt32(destination) + } + + /// `ldrsw xt, [xn, #imm]`: a 32-bit load, sign-extended to 64 bits. + static func loadSignedWordUnsignedOffset(_ destination: Int, base: Int, byteOffset: UInt32) -> UInt32 { + 0xB980_0000 | ((byteOffset / 4) << 10) | (UInt32(base) << 5) | UInt32(destination) + } + + /// `ldrsw xt, label`: a sign-extended 32-bit load from a slot within a + /// megabyte. + static func loadSignedWordLiteral(_ destination: Int, at address: UInt64, slot: UInt64) -> UInt32 { + let wordDelta = UInt32(truncatingIfNeeded: Int64(bitPattern: slot &- address) >> 2) & 0x7FFFF + return 0x9800_0000 | (wordDelta << 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) } diff --git a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift index dd620a10d..db5fb296c 100644 --- a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift +++ b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift @@ -1,6 +1,8 @@ import Foundation import Testing @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// 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 diff --git a/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift new file mode 100644 index 000000000..82d5d6ace --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift @@ -0,0 +1,252 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding +@testable import CrossReferenceAnalysis + +/// Code the linker rewrote after it laid the image out. +/// +/// ld64 — the linker of Xcode 14 and earlier, and of Xcode 15 and 16 with +/// `-ld_classic` — follows the compiler's linker optimization hints: an +/// `adrp` / `ldr` pair whose slot lies within a megabyte of the load becomes +/// `nop` / `ldr xN, `, an `adrp` / `add` pair `adr xN,

` / +/// `nop`, and a lazily bound stub `nop` / `ldr x16, ` / `br x16`. A +/// third-party app linked that way reaches its selectors, its classes and +/// every imported function only through those shapes: Asset Catalog Viewer, +/// built with the macOS 12 SDK, loads 357 selectors and 71 classes straight +/// from their slots, and every one of its stubs is rewritten. +/// +/// Xcode 26's linker applies no hint and Xcode 27 ships no `ld-classic`, so +/// each fixture is linked as usual and then rewritten here the way ld64 +/// rewrites it. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct LinkerOptimizationHintTests { + private struct Fixtures { + let analyzer: CrossReferenceAnalyzer + let objectiveCImage: Int + let stubImage: Int + + func function(named name: String, inImageAt imageIndex: Int) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: imageIndex).first { $0.name == .symbol(name) }, "no function \(name)") + } + } + + /// Both libraries, loaded before the analyzer that reads them is made. + private static let fixtures = Result { + try CompiledFixture.load( + libraryName: "libCrossReferenceLinkerHints.dylib", + sources: [ + "Probe.m": """ + #import + + @interface CrossReferenceLinkerHintProbe : NSObject + @end + + @implementation CrossReferenceLinkerHintProbe + @end + + id crossReferenceSendsThroughALiteralSelectorLoad(id object) { + return [object description]; + } + + Class crossReferenceLoadsAClassThroughALiteral(void) { + return [CrossReferenceLinkerHintProbe class]; + } + """, + "Probe.s": """ + .section __TEXT,__text,regular,pure_instructions + .globl _crossReferenceAddressesAClassDirectly + .p2align 2 + _crossReferenceAddressesAClassDirectly: + adrp x0, _OBJC_CLASS_$_CrossReferenceLinkerHintProbe@PAGE + add x0, x0, _OBJC_CLASS_$_CrossReferenceLinkerHintProbe@PAGEOFF + ret + """, + ], + compilerArguments: ["-O1", "-mmacosx-version-min=12.0", "-fno-objc-arc", "-fno-objc-msgsend-selector-stubs", "-framework", "Foundation"] + ) { bytes, machO in + let rewrite = try LinkerRewrite(machO: machO) + try rewrite.loadStraightFromTheSlot(into: 1, inFunctionNamed: "_crossReferenceSendsThroughALiteralSelectorLoad", of: &bytes) + try rewrite.loadStraightFromTheSlot(into: 0, inFunctionNamed: "_crossReferenceLoadsAClassThroughALiteral", of: &bytes) + try rewrite.addressDirectly(into: 0, inFunctionNamed: "_crossReferenceAddressesAClassDirectly", of: &bytes) + } + // A stub is shared by every call to its function, so the stub fixture + // imports nothing a send needs. + try CompiledFixture.load( + libraryName: "libCrossReferenceRewrittenStub.dylib", + sources: ["Stub.c": "#include \nvoid crossReferenceCallsThroughARewrittenStub(void) { puts(\"called\"); }\n"], + compilerArguments: ["-O1", "-mmacosx-version-min=12.0"] + ) { bytes, machO in + try LinkerRewrite(machO: machO).loadEveryStubStraightFromItsSlot(of: &bytes) + } + guard let analyzer = CrossReferenceAnalyzer(), + let objectiveCImage = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix("/libCrossReferenceLinkerHints.dylib") }), + let stubImage = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix("/libCrossReferenceRewrittenStub.dylib") }) + else { throw CompiledFixture.Failure(description: "the analyzer does not see the fixtures") } + return Fixtures(analyzer: analyzer, objectiveCImage: objectiveCImage, stubImage: stubImage) + } + + @Test func aSelectorLoadedStraightFromItsSlotNamesTheSend() throws { + let fixtures = try Self.fixtures.get() + let function = try fixtures.function(named: "_crossReferenceSendsThroughALiteralSelectorLoad", inImageAt: fixtures.objectiveCImage) + let targets = fixtures.analyzer.references(madeBy: function).map(\.target) + #expect(targets.contains(.messageSend(selector: "description", receiver: .unknown)), "\(targets)") + } + + @Test func aClassLoadedStraightFromItsSlotIsReferenced() throws { + let fixtures = try Self.fixtures.get() + let function = try fixtures.function(named: "_crossReferenceLoadsAClassThroughALiteral", inImageAt: fixtures.objectiveCImage) + let references = fixtures.analyzer.references(madeBy: function) + #expect(references.contains { Self.isReference(to: "CrossReferenceLinkerHintProbe", $0) }, "\(references.map(\.target))") + } + + @Test func aClassAddressedWithAdrIsReferenced() throws { + let fixtures = try Self.fixtures.get() + let function = try fixtures.function(named: "_crossReferenceAddressesAClassDirectly", inImageAt: fixtures.objectiveCImage) + let references = fixtures.analyzer.references(madeBy: function) + #expect(references.contains { Self.isReference(to: "CrossReferenceLinkerHintProbe", $0) }, "\(references.map(\.target))") + } + + /// MachOKit reads no slot from a rewritten stub; the call reached only + /// the stub's imported name. + @Test func aRewrittenStubReachesItsTarget() throws { + let fixtures = try Self.fixtures.get() + let function = try fixtures.function(named: "_crossReferenceCallsThroughARewrittenStub", inImageAt: fixtures.stubImage) + let call = try #require(fixtures.analyzer.references(madeBy: function).first) + guard case .function(let location) = call.target else { + Issue.record("the call through the rewritten stub resolved to \(call.target), not to a function") + return + } + #expect(fixtures.analyzer.imagePaths[location.imageIndex].hasSuffix("/libsystem_c.dylib")) + let callee = try #require(fixtures.analyzer.function(containing: location)) + let names = (callee.name.map { [$0] } ?? []) + callee.foldedSymbolNames.map { .symbol($0) } + #expect(names.contains(.symbol("_puts")), "callee named \(names)") + } + + private static func isReference(to className: String, _ reference: CodeReference) -> Bool { + guard reference.kind == .reference, case .objectiveCClass(let name, _) = reference.target else { return false } + return name == className + } +} + +/// ld64's rewrites of a linked library's code, applied to its bytes. +private struct LinkerRewrite { + private struct CodeRange { + let address: UInt64 + let size: UInt64 + let fileOffset: Int + } + + private let text: CodeRange + private let stubs: CodeRange? + /// The functions' starts, by symbol. + private let functionStarts: [String: UInt64] + + init(machO: MachOFile) throws { + func codeRange(named sectionName: String) -> CodeRange? { + machO.sections64.first { $0.segmentName == "__TEXT" && $0.sectionName == sectionName }.map { + CodeRange(address: UInt64($0.address), size: UInt64($0.size), fileOffset: $0.offset) + } + } + guard let text = codeRange(named: "__text") else { throw CompiledFixture.Failure(description: "no __text") } + self.text = text + self.stubs = codeRange(named: "__stubs") + var functionStarts: [String: UInt64] = [:] + // A file symbol's offset is its n_value — an address. + for symbol in machO.symbols where UInt64(symbol.offset) >= text.address && UInt64(symbol.offset) < text.address + text.size { + functionStarts[symbol.name] = UInt64(symbol.offset) + } + self.functionStarts = functionStarts + } + + /// `adrp xN, page` / … / `ldr x, [xN, #offset]` → `nop` / + /// … / `ldr x, `, for the first such pair in + /// the function. + func loadStraightFromTheSlot(into destination: Int, inFunctionNamed name: String, of bytes: inout Data) throws { + for (pageAddress, page) in try pageMaterializations(inFunctionNamed: name, of: bytes) { + for loadAddress in stride(from: pageAddress + 4, to: try end(ofFunctionNamed: name), by: 4) { + guard let load = ARM64InstructionWord.load(word(at: loadAddress, of: bytes)), + load.base == page.destination, load.destination == destination, !load.writesBack + else { continue } + let slot = ARM64InstructionWord.adding(load.displacement, to: page.address) + try requireMegabyteReach(from: loadAddress, to: slot) + setWord(ARM64InstructionWord.noOperation, at: pageAddress, of: &bytes) + setWord(InstructionEncoding.loadLiteral(destination, at: loadAddress, slot: slot), at: loadAddress, of: &bytes) + return + } + } + throw CompiledFixture.Failure(description: "\(name) loads x\(destination) through no adrp / ldr pair") + } + + /// `adrp x, page` / `add x, x, + /// #offset` → `adr x, ` / `nop`. + func addressDirectly(into destination: Int, inFunctionNamed name: String, of bytes: inout Data) throws { + for (pageAddress, page) in try pageMaterializations(inFunctionNamed: name, of: bytes) where page.destination == destination { + guard let arithmetic = ARM64InstructionWord.addImmediate(word(at: pageAddress + 4, of: bytes)), + arithmetic.source == destination, arithmetic.destination == destination + else { continue } + let target = ARM64InstructionWord.adding(arithmetic.addend, to: page.address) + try requireMegabyteReach(from: pageAddress, to: target) + setWord(InstructionEncoding.adr(destination, at: pageAddress, target: target), at: pageAddress, of: &bytes) + setWord(ARM64InstructionWord.noOperation, at: pageAddress + 4, of: &bytes) + return + } + throw CompiledFixture.Failure(description: "\(name) builds x\(destination) with no adrp / add pair") + } + + /// Every `adrp x16, page` / `ldr x16, [x16, #offset]` / `br x16` stub → + /// `nop` / `ldr x16, ` / `br x16`. + func loadEveryStubStraightFromItsSlot(of bytes: inout Data) throws { + guard let stubs, stubs.size > 0 else { throw CompiledFixture.Failure(description: "no __stubs") } + for stubAddress in stride(from: stubs.address, to: stubs.address + stubs.size, by: 12) { + guard let page = ARM64InstructionWord.addressMaterialization(word(at: stubAddress, of: bytes), at: stubAddress), page.destination == 16, + let load = ARM64InstructionWord.load(word(at: stubAddress + 4, of: bytes)), load.base == 16, load.destination == 16, + word(at: stubAddress + 8, of: bytes) == InstructionEncoding.branchToRegister(16) + else { throw CompiledFixture.Failure(description: "the stub at \(String(stubAddress, radix: 16)) is no adrp / ldr / br") } + let slot = ARM64InstructionWord.adding(load.displacement, to: page.address) + try requireMegabyteReach(from: stubAddress + 4, to: slot) + setWord(ARM64InstructionWord.noOperation, at: stubAddress, of: &bytes) + setWord(InstructionEncoding.loadLiteral(16, at: stubAddress + 4, slot: slot), at: stubAddress + 4, of: &bytes) + } + } + + /// Every `adrp` in the function, in address order. + private func pageMaterializations(inFunctionNamed name: String, of bytes: Data) throws -> [(UInt64, (destination: Int, address: UInt64))] { + guard let start = functionStarts[name] else { throw CompiledFixture.Failure(description: "no function \(name)") } + return try stride(from: start, to: end(ofFunctionNamed: name), by: 4).compactMap { address in + guard let page = ARM64InstructionWord.addressMaterialization(word(at: address, of: bytes), at: address), page.isPageAddress else { return nil } + return (address, (page.destination, page.address)) + } + } + + private func end(ofFunctionNamed name: String) throws -> UInt64 { + guard let start = functionStarts[name] else { throw CompiledFixture.Failure(description: "no function \(name)") } + return functionStarts.values.filter { $0 > start }.min() ?? text.address + text.size + } + + private func requireMegabyteReach(from address: UInt64, to target: UInt64) throws { + let distance = Int64(bitPattern: target &- address) + guard distance >= -(1 << 20), distance < 1 << 20 else { + throw CompiledFixture.Failure(description: "\(String(target, radix: 16)) lies beyond a megabyte of \(String(address, radix: 16))") + } + } + + private func fileOffset(of address: UInt64) -> Int { + for range in [text, stubs].compactMap({ $0 }) where address >= range.address && address < range.address + range.size { + return range.fileOffset + Int(address - range.address) + } + preconditionFailure("\(String(address, radix: 16)) lies in no code section") + } + + private func word(at address: UInt64, of bytes: Data) -> UInt32 { + let offset = fileOffset(of: address) + return UInt32(littleEndian: bytes.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: offset, as: UInt32.self) }) + } + + private func setWord(_ word: UInt32, at address: UInt64, of bytes: inout Data) { + let offset = fileOffset(of: address) + withUnsafeBytes(of: word.littleEndian) { bytes.replaceSubrange(offset ..< offset + 4, with: $0) } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/MemoryAccessScanTests.swift b/Tests/CrossReferenceAnalysisTests/MemoryAccessScanTests.swift new file mode 100644 index 000000000..f05e1dc86 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/MemoryAccessScanTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing + +/// Every read of image memory in `CrossReferenceAnalysis`, the Swift layer of +/// the cross-reference analysis, goes through `CrossReferenceMemory`, so that +/// an analyzer can read images that were never loaded. The one reader that +/// turns an address into a pointer, `InProcessCrossReferenceMemory`, lives in +/// MachOKitExtensions with the core; it and MachOObjCSection's +/// `ObjCCodeReferences` keep scans of their own. +@Suite +struct MemoryAccessScanTests { + @Test func crossReferenceAnalysisReadsMemoryOnlyThroughCrossReferenceMemory() throws { + var offendingLines: [String] = [] + let files = try Self.moduleSourceFiles() + for fileURL in files { + 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.turnsAnAddressIntoAPointer(code) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect(offendingLines.isEmpty, "read through `CrossReferenceMemory`:\n\(offendingLines.joined(separator: "\n"))") + } + + /// The scan must see a pointer made from an address, and nothing else — + /// its silence proves nothing otherwise. + @Test func theScanDiscriminates() { + #expect(Self.turnsAnAddressIntoAPointer("guard let slot = UnsafeRawPointer(bitPattern: address) else {")) + #expect(Self.turnsAnAddressIntoAPointer("let name = UnsafePointer(bitPattern: string)")) + #expect(Self.turnsAnAddressIntoAPointer("UnsafeMutableRawPointer(bitPattern: 0x1000)")) + #expect(!Self.turnsAnAddressIntoAPointer("let key = UInt(bitPattern: pointer)")) + #expect(!Self.turnsAnAddressIntoAPointer("UInt(bitPattern: Int(bitPattern: UInt(address)) &+ slide)")) + #expect(!Self.turnsAnAddressIntoAPointer("let raw = UnsafeRawPointer(bytes + index)")) + } + + private static let pointerFromAddress = try! NSRegularExpression(pattern: #"Unsafe(Mutable)?(Raw)?Pointer(<[^>]*>)?\(bitPattern:"#) + + private static func turnsAnAddressIntoAPointer(_ code: String) -> Bool { + pointerFromAddress.firstMatch(in: code, range: NSRange(code.startIndex..., in: code)) != nil + } + + /// Every Swift file of `CrossReferenceAnalysis`. + private static func moduleSourceFiles() throws -> [URL] { + let analysisDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // CrossReferenceAnalysisTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + .appendingPathComponent("Sources/Analysis") + var files: [URL] = [] + for moduleName in ["CrossReferenceAnalysis"] { + let moduleDirectory = analysisDirectory.appendingPathComponent(moduleName) + let enumerator = try #require(FileManager.default.enumerator(at: moduleDirectory, includingPropertiesForKeys: nil)) + for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" { + files.append(fileURL) + } + } + #expect(files.count > 10, "found only \(files.count) sources under \(analysisDirectory.path)") + return files + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift index a32ee4bac..038d13eea 100644 --- a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift @@ -2,6 +2,8 @@ import Foundation import Testing import MachOKit @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// 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. diff --git a/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift b/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift index 1ff269aad..8d729664b 100644 --- a/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift +++ b/Tests/CrossReferenceAnalysisTests/PreparedImageDataTests.swift @@ -1,6 +1,8 @@ import Foundation import Testing @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// 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 @@ -22,8 +24,8 @@ struct PreparedImageDataTests { #expect(analyzer.approximateByteCount(ofImageDataAt: foundation) == 0) analyzer.prepareNames(inImageAt: foundation) - let table = try #require(analyzer.existingFunctionTable(ofImageAt: foundation)) - #expect(table.existingFallbackNames?.hasReadEverySource == true) + #expect(analyzer.existingFunctionTable(ofImageAt: foundation) != nil) + #expect(analyzer.hasReadEveryNameSource(ofImageAt: foundation)) let indexes = analyzer.existingIndexes(ofImageAt: foundation) #expect(indexes.classIndex?.hasReadEveryName == true) #expect(indexes.swiftTypeIndex?.builtState.hasReadDescriptorSymbols == true) @@ -58,7 +60,7 @@ struct PreparedImageDataTests { let keptBytes = analyzer.approximateByteCount(ofImageDataAt: libobjc) analyzer.releaseImageData(exceptForImagesAt: [libobjc]) - #expect(analyzer.existingFunctionTable(ofImageAt: libobjc)?.existingFallbackNames?.hasReadEverySource == true) + #expect(analyzer.hasReadEveryNameSource(ofImageAt: libobjc)) #expect(analyzer.existingIndexes(ofImageAt: libobjc).classIndex?.hasReadEveryName == true) #expect(analyzer.approximateByteCount(ofImageDataAt: libobjc) == keptBytes) #expect(analyzer.existingFunctionTable(ofImageAt: foundation) == nil) @@ -86,8 +88,8 @@ struct PreparedImageDataTests { /// 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) + let serial = RenamedReexportIndex(images: analyzer.imageSet, concurrently: false) + let concurrent = RenamedReexportIndex(images: analyzer.imageSet, concurrently: true) #expect(serial.reexportsByProvider.values.reduce(0) { $0 + $1.count } > 1000) #expect(serial.reexportsByProvider == concurrent.reexportsByProvider) } diff --git a/Tests/CrossReferenceAnalysisTests/PublicNameTests.swift b/Tests/CrossReferenceAnalysisTests/PublicNameTests.swift new file mode 100644 index 000000000..b6b685e94 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/PublicNameTests.swift @@ -0,0 +1,22 @@ +import Testing +import CrossReferenceAnalysis + +/// The types the layers below the Swift one define stay part of +/// `CrossReferenceAnalysis`'s public face: a host that imports only it — +/// RuntimeViewer — spells them as before the split. A plain import, not a +/// testable one, so that this file fails to compile when one goes missing. +@Suite +struct PublicNameTests { + @Test func publicNamesStillResolveThroughCrossReferenceAnalysis() { + let location = CodeLocation(imageIndex: 1, address: 0x1000) + let kind: CodeReference.Kind = .call + let route: CodeReference.Route = .imageStub + let receiver: ReceiverClassHint = .methodReceiver + let evidence = IndirectCallEvidence(tableOffset: 8, pointerAuthenticationConstant: nil, isAddressBlended: false) + let reference = CodeReference(function: location, instructionAddress: 0x1004, kind: kind, target: .messageSend(selector: "init", receiver: receiver), route: route, isRuntimeHelperCall: false) + #expect(reference.kind == .call) + #expect(reference.route == .imageStub) + #expect(reference.target.tableKey == .selector("init")) + #expect(CodeReferenceTarget.indirect(evidence).tableKey == nil) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/RecognizerExtensionPointTests.swift b/Tests/CrossReferenceAnalysisTests/RecognizerExtensionPointTests.swift new file mode 100644 index 000000000..7550fecae --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/RecognizerExtensionPointTests.swift @@ -0,0 +1,24 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// What the language layers' sessions do inside the analyzer. That the +/// core's scan takes any recognizer, with no language layer present at all, +/// is MachOKitExtensions' `CoreOnlyScanTests` (proposal +/// `move-cross-reference-layers`). +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct RecognizerExtensionPointTests { + /// A query for the senders of a selector looks up no Swift type: the + /// Swift session skips its accessors, metadata and mangled names when the + /// query keeps none of them. + @Test func selectorQueriesLookUpNoSwiftType() throws { + let freshAnalyzer = try #require(CrossReferenceAnalyzer()) + let swiftUICore = try #require(freshAnalyzer.imagePaths.firstIndex { $0.hasSuffix("/SwiftUICore.framework/Versions/A/SwiftUICore") }) + let sends = freshAnalyzer.references(to: [.selector("init")], inImageAt: swiftUICore) + #expect(!sends.isEmpty) + let builtTypeIndexes = freshAnalyzer.imagePaths.indices.filter { freshAnalyzer.existingIndexes(ofImageAt: $0).swiftTypeIndex != nil } + #expect(builtTypeIndexes.isEmpty, "type indexes built for \(builtTypeIndexes.map { freshAnalyzer.imagePaths[$0] })") + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift new file mode 100644 index 000000000..6ffa3117c --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift @@ -0,0 +1,225 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding +@testable import CrossReferenceAnalysis + +/// The references step 5 of the offline cross-references proposal adds — +/// instance variables, string literals, and the route each reference took — +/// read from libraries compiled for each test and from the running system's +/// shared cache. +@Suite +struct ReferenceKindAndRouteTests { + /// An Objective-C library: a class with an instance variable, methods + /// that send messages, a C string and two constant strings — one ASCII, + /// one that takes UTF-16. The class's superclass lies in another image + /// (Foundation's `NSOperation`): over `NSObject`, whose layout is fixed, + /// clang uses constant instance variable offsets and loads no offset + /// variable. + private static let objectiveCSource = """ + #import + #include + @interface Counter : NSOperation { + @public + long _count; + } + - (void)increment; + - (NSString *)describe; + @end + @implementation Counter + - (void)increment { _count += 1; } + - (NSString *)describe { return [NSString stringWithFormat:@"%ld", _count]; } + @end + __attribute__((noinline)) const char *cStringFunction(void) { return "a C string literal"; } + __attribute__((noinline)) NSString *constantStringFunction(void) { return @"a constant string literal"; } + __attribute__((noinline)) NSString *wideConstantStringFunction(void) { return @"h\\u00e9llo \\u2713"; } + void callEverything(Counter *counter) { + [counter increment]; + puts(cStringFunction()); + NSLog(@"%@ %@", constantStringFunction(), wideConstantStringFunction()); + } + """ + + private func objectiveCLibrary(stripped: Bool = false) throws -> (directory: URL, file: MachOFile) { + let (directory, library) = try CompiledFixture.build( + libraryName: "libKinds.dylib", + sources: ["Kinds.m": Self.objectiveCSource], + compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + (stripped ? ["-Wl,-x"] : []) + ) + return (directory, try MachOFile(url: library)) + } + + private func function(named name: String, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: 0).first { function in + switch function.name { + case .symbol(let symbol)?: symbol == name + case .objectiveCMethod(let className, let selector, let isClassMethod)?: "\(isClassMethod ? "+" : "-")[\(className) \(selector)]" == name + default: false + } + }, "no function \(name)") + } + + /// A method reads its instance variable through the class's offset + /// variable in `__objc_ivar`, named by its `_OBJC_IVAR_$_` symbol — or, + /// when the symbol table is stripped, by the class's instance variable + /// list, whose entry points at the same variable. + @Test(arguments: [false, true]) + func instanceVariableOffsetLoadsBecomeInstanceVariableReferences(stripped: Bool) throws { + let (directory, file) = try objectiveCLibrary(stripped: stripped) + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) + for method in ["-[Counter increment]", "-[Counter describe]"] { + let references = analyzer.references(madeBy: try function(named: method, in: analyzer)) + let variableReferences = references.filter { $0.target == .objectiveCInstanceVariable(className: "Counter", name: "_count") } + #expect(variableReferences.count == 1, "\(method), stripped: \(stripped): \(references.map(\.target))") + #expect(variableReferences.allSatisfy { $0.kind == .reference && ($0.route == .pointerSlot || $0.route == .literalLoad) }) + } + let filed = analyzer.references(to: [.instanceVariable(className: "Counter", name: "_count")], inImageAt: 0) + #expect(filed.count == 2) + } + + /// Strings are recorded when the analyzer is made to, or for a query for + /// a string key — not in a whole-image table otherwise. + @Test func stringReferencesAreRecordedOnlyWhenRequested() throws { + let (directory, file) = try objectiveCLibrary() + defer { try? FileManager.default.removeItem(at: directory) } + let withoutStrings = try CrossReferenceAnalyzer(machOFiles: [file]) + #expect(!withoutStrings.recordsStringReferences) + #expect(!withoutStrings.referenceTable(ofImageAt: 0).references.contains { reference in + switch reference.target { + case .cString, .constantString: true + default: false + } + }) + // In `cStringFunction` and, inlined, in `callEverything`. + let queried = withoutStrings.references(to: [.cString("a C string literal")], inImageAt: 0) + #expect(queried.count == 2) + #expect(queried.allSatisfy { $0.route == .addressMaterialization }) + + let withStrings = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let references = withStrings.references(madeBy: try function(named: "_cStringFunction", in: withStrings)) + #expect(references.map(\.target) == [.cString("a C string literal")]) + } + + /// A constant `CFString` is referenced by its characters, eight-bit or + /// UTF-16 alike. + @Test func constantStringReferencesCarryTheirCharacters() throws { + let (directory, file) = try objectiveCLibrary() + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let ascii = analyzer.references(madeBy: try function(named: "_constantStringFunction", in: analyzer)).map(\.target) + #expect(ascii.contains(.constantString("a constant string literal")), "\(ascii)") + let wide = analyzer.references(madeBy: try function(named: "_wideConstantStringFunction", in: analyzer)).map(\.target) + #expect(wide.contains(.constantString("h\u{e9}llo \u{2713}")), "\(wide)") + let format = analyzer.references(madeBy: try function(named: "_callEverything", in: analyzer)).map(\.target) + #expect(format.contains(.constantString("%@ %@")), "\(format)") + } + + /// Swift keeps a large string literal as its address less 32: `adrp`, + /// `add` to the characters, `sub #0x20`. The `add` names the string; the + /// subtraction names no other. + @Test func swiftLargeStringLiteralPointsAtItsCharacters() throws { + let (directory, library) = try CompiledFixture.buildSwift(libraryName: "libLargeString.dylib", source: """ + @inline(never) public func largeStringLiteral() -> String { + "a string literal longer than fifteen bytes" + } + """) + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)], recordingStringReferences: true) + let function = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_$s7Fixture18largeStringLiteralSSyF") }) + let strings = analyzer.references(madeBy: function).filter { if case .cString = $0.target { true } else { false } } + #expect(strings.map(\.target) == [.cString("a string literal longer than fifteen bytes")]) + } + + /// Every reference says how it got where it points: a call to a function + /// of the library goes straight there, a call into Foundation and a send + /// through `__objc_stubs` go through the library's own stubs, a string's + /// address is built, an instance variable's offset is loaded through its + /// slot. + @Test func everyReferenceCarriesTheRouteItTook() throws { + let (directory, file) = try objectiveCLibrary() + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let references = analyzer.references(madeBy: try function(named: "_callEverything", in: analyzer)) + func route(of target: CodeReferenceTarget) -> CodeReferenceRoute? { + references.first { $0.target == target }?.route + } + let constantStringFunction = try function(named: "_constantStringFunction", in: analyzer) + #expect(route(of: .function(constantStringFunction.location)) == .direct) + #expect(route(of: .importedSymbol(name: "_puts")) == .imageStub) + #expect(references.first { if case .messageSend("increment", _) = $0.target { true } else { false } }?.route == .imageStub, "\(references)") + #expect(route(of: .constantString("%@ %@")) == .addressMaterialization) + } + + /// The process's own cache: macOS 27 sends through the selector stubs the + /// whole cache shares, calls into its own code straight, reads classes + /// both through slots and by building their address, and calls through + /// registers. + @Test(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) + func inProcessReferencesCarryTheirRoutes() throws { + let analyzer = try #require(SharedAnalyzer.analyzer) + let appKit = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) + let references = analyzer.referenceTable(ofImageAt: appKit).references + let routes = Set(references.map(\.route)) + #expect(routes.isSuperset(of: [.direct, .pointerSlot, .addressMaterialization, .indirect]), "\(routes)") + #expect(routes.contains(.cacheSharedStub) || routes.contains(.imageStub), "\(routes)") + for reference in references { + switch reference.target { + case .indirect: + #expect(reference.route == .indirect) + case .objectiveCClass: + #expect([.pointerSlot, .addressMaterialization, .literalLoad].contains(reference.route) || reference.kind != .reference) + default: + break + } + } + } + + /// The table and the index a host keeps answer the same — the new kinds + /// and every route included. + @Test func referenceIndexRoundTripsNewTargetsAndRoutes() throws { + let (directory, file) = try objectiveCLibrary() + defer { try? FileManager.default.removeItem(at: directory) } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let table = analyzer.referenceTable(ofImageAt: 0) + let index = analyzer.referenceIndex(ofImageAt: 0) + let keys: [CodeReferenceTable.Key] = [ + .instanceVariable(className: "Counter", name: "_count"), + .cString("a C string literal"), + .constantString("a constant string literal"), + .constantString("h\u{e9}llo \u{2713}"), + .importedSymbol("_puts"), + .selector("increment"), + ] + for key in keys { + let fromTable = table.references(to: key) + #expect(!fromTable.isEmpty, "\(key)") + #expect(index.references(to: [key]) == fromTable, "\(key)") + } + } + + /// An Objective-C class object can lie exactly on a page: its address is + /// then built by `adrp` and an `add` of 0, which is still a reference to + /// it — a disassembler that takes the `add #0` for a move loses it. + @Test(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) + func pageAlignedClassObjectMaterializationIsAReference() throws { + let analyzer = try #require(SharedAnalyzer.analyzer) + var found: CodeReference? + let candidates = ["/SwiftUI.framework/Versions/A/SwiftUI", "/SwiftUICore.framework/Versions/A/SwiftUICore", "/AppKit.framework/Versions/C/AppKit", "/Foundation.framework/Versions/C/Foundation"] + for suffix in candidates { + guard let imageIndex = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix(suffix) }) else { continue } + found = analyzer.referenceTable(ofImageAt: imageIndex).references.first { reference in + guard reference.route == .addressMaterialization, case .objectiveCClass(_, let location) = reference.target else { return false } + return location.address & 0xFFF == 0 + } + if found != nil { break } + } + let reference = try #require(found, "no page-aligned class object built by adrp / add in \(candidates)") + // The instruction is the `add` of 0. + let word = try #require(analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: reference.function.imageIndex, address: reference.instructionAddress)))) + let arithmetic = try #require(ARM64InstructionWord.addImmediate(word)) + #expect(arithmetic.addend == 0) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ReferenceTableDigestTests.swift b/Tests/CrossReferenceAnalysisTests/ReferenceTableDigestTests.swift new file mode 100644 index 000000000..4b974eafb --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ReferenceTableDigestTests.swift @@ -0,0 +1,123 @@ +import Foundation +import Testing +import CryptoKit +import CrossReferenceAnalysis + +/// Whole reference tables of a few large images, reduced to a count and a +/// SHA-256 per image, so that a refactoring of the analyzer can be shown to +/// change no reference at all. +/// +/// An A/B check, not a regression test: the tables follow the running +/// system's dyld shared cache, so there is no baseline to keep in the +/// repository. The procedure: +/// +/// 1. Export the baseline commit (`git archive`), copy this file into its +/// `Tests/CrossReferenceAnalysisTests/`, and run it there with +/// `CROSS_REFERENCE_TABLE_DIGEST_DIRECTORY=`: it writes one +/// `.digest` file per image. +/// 2. Run it in the candidate with +/// `CROSS_REFERENCE_TABLE_BASELINE_DIRECTORY=`: it +/// compares every image against the baseline's file. +/// +/// It uses the public API alone, which is what lets the same file run on +/// both sides. Without either variable it does not run. +@Suite( + .enabled( + if: ReferenceTableDigestEnvironment.digestDirectory != nil || ReferenceTableDigestEnvironment.baselineDirectory != nil || ReferenceTableDigestEnvironment.dumpDirectory != nil, + "set CROSS_REFERENCE_TABLE_DIGEST_DIRECTORY, CROSS_REFERENCE_TABLE_BASELINE_DIRECTORY or CROSS_REFERENCE_TABLE_DUMP_DIRECTORY" + ) +) +struct ReferenceTableDigestTests { + /// The images compared: Objective-C heavy, Swift heavy, and Foundation, + /// which is both. + static let imageSuffixes = [ + "/AppKit.framework/Versions/C/AppKit", + "/SwiftUICore.framework/Versions/A/SwiftUICore", + "/Foundation.framework/Versions/C/Foundation", + ] + + @Test(arguments: imageSuffixes) + func inProcessReferenceTablesAreUnchangedForAppKitSwiftUICoreAndFoundation(imageSuffix: String) throws { + let analyzer = try #require(CrossReferenceAnalyzer()) + let imageIndex = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix(imageSuffix) }, "no image ending with \(imageSuffix)") + let table = analyzer.referenceTable(ofImageAt: imageIndex) + let digest = Self.digest(of: table) + let fileName = (imageSuffix as NSString).lastPathComponent + ".digest" + + // Every reference, one per line, to find what differs once a digest + // does. + if let dumpDirectory = ReferenceTableDigestEnvironment.dumpDirectory { + try FileManager.default.createDirectory(at: dumpDirectory, withIntermediateDirectories: true) + let lines = table.references.filter { !Self.isAddedByStepFive($0) }.map(Self.spelling(of:)).joined(separator: "\n") + try lines.write(to: dumpDirectory.appendingPathComponent((imageSuffix as NSString).lastPathComponent + ".references"), atomically: true, encoding: .utf8) + } + + if let digestDirectory = ReferenceTableDigestEnvironment.digestDirectory { + try FileManager.default.createDirectory(at: digestDirectory, withIntermediateDirectories: true) + try digest.write(to: digestDirectory.appendingPathComponent(fileName), atomically: true, encoding: .utf8) + } + if let baselineDirectory = ReferenceTableDigestEnvironment.baselineDirectory { + let baseline = try String(contentsOf: baselineDirectory.appendingPathComponent(fileName), encoding: .utf8) + #expect(digest == baseline, "\(imageSuffix): baseline \(baseline), now \(digest)") + } + } + + /// ` `. A + /// reference is spelled the way `String(describing:)` spells it, which + /// covers every stored property — with the modules of the + /// cross-reference layers taken out: it qualifies a type nested in an + /// enum's payload with its module (`CrossReferenceCore.CodeLocation`, `MachOCodeReferences.CodeLocation` since the core moved), + /// and moving a type between the layers is no change to a reference. + static func digest(of table: CodeReferenceTable) -> String { + var hasher = SHA256() + var count = 0 + for reference in table.references where !isAddedByStepFive(reference) { + hasher.update(data: Data((spelling(of: reference) + "\n").utf8)) + count += 1 + } + let hash = hasher.finalize().map { String(format: "%02x", $0) }.joined() + return "\(count) \(hash)" + } + + /// A reference of a kind step 5 of the proposal added — an instance + /// variable, a string literal, a data reference through a slot binding + /// to an imported symbol — which a baseline from before has none of. + static func isAddedByStepFive(_ reference: CodeReference) -> Bool { + switch reference.target { + case .objectiveCInstanceVariable, .cString, .constantString: + return true + case .importedSymbol: + return reference.kind == .reference + default: + return false + } + } + + /// A reference as `String(describing:)` spells it, with what moving a + /// type between the layers changes in that spelling taken out: the + /// module qualifying a type nested in an enum's payload, and + /// `CodeReference.Kind`, which became a typealias of the core's + /// `CodeReferenceKind`. + static func spelling(of reference: CodeReference) -> String { + let description = String(describing: reference).replacingOccurrences(of: "CodeReference.Kind.", with: "CodeReferenceKind.") + let unqualified = moduleQualifier.stringByReplacingMatches(in: description, range: NSRange(location: 0, length: description.utf16.count), withTemplate: "") + // The route came with step 5; a baseline from before has none. + let withoutRoute = routeField.stringByReplacingMatches(in: unqualified, range: NSRange(location: 0, length: unqualified.utf16.count), withTemplate: "") + // `IndirectCallEvidence.table` only ever held `.none` and went away when + // the core moved to MachOKitExtensions (`move-cross-reference-layers`). + return tableField.stringByReplacingMatches(in: withoutRoute, range: NSRange(location: 0, length: withoutRoute.utf16.count), withTemplate: "") + } + + private static let moduleQualifier = try! NSRegularExpression(pattern: #"\b(CrossReferenceCore|CrossReferenceObjC|CrossReferenceAnalysis|MachOCodeReferences|ObjCCodeReferences|MachOAddressResolution|ARM64InstructionDecoding)\."#) + private static let routeField = try! NSRegularExpression(pattern: #", route: CodeReferenceRoute\.[A-Za-z]+"#) + private static let tableField = try! NSRegularExpression(pattern: #"table: IndirectCallEvidence\.Table\.[A-Za-z]+, "#) +} + +/// Where the digests go, and where the baseline's are: outside the suite's +/// own type, which its `@Suite` attribute cannot refer to. +enum ReferenceTableDigestEnvironment { + static let digestDirectory = ProcessInfo.processInfo.environment["CROSS_REFERENCE_TABLE_DIGEST_DIRECTORY"].map(URL.init(fileURLWithPath:)) + static let baselineDirectory = ProcessInfo.processInfo.environment["CROSS_REFERENCE_TABLE_BASELINE_DIRECTORY"].map(URL.init(fileURLWithPath:)) + /// Where to write every reference, one per line, besides the digest. + static let dumpDirectory = ProcessInfo.processInfo.environment["CROSS_REFERENCE_TABLE_DUMP_DIRECTORY"].map(URL.init(fileURLWithPath:)) +} diff --git a/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift b/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift index de6fdef7b..bc0fde370 100644 --- a/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift +++ b/Tests/CrossReferenceAnalysisTests/RegisterFileTests.swift @@ -2,6 +2,8 @@ import Foundation import Testing import Capstone @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// What `RegisterFile.forgetRegistersWritten(by:)` forgets for the /// instructions the scanner does not model: every general-purpose register diff --git a/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift b/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift index c6437bd7f..7b6d1683b 100644 --- a/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift +++ b/Tests/CrossReferenceAnalysisTests/RenamedReexportTests.swift @@ -2,6 +2,8 @@ import Foundation import Testing import MachOKit @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// 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: diff --git a/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift new file mode 100644 index 000000000..3cc6a968d --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift @@ -0,0 +1,116 @@ +import Foundation +import Testing +@testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// clang compiles `[[Foo alloc] init]`, `[x isKindOfClass:c]` and six more +/// sends into calls to libobjc entry points of their own — `objc_alloc_init`, +/// `objc_opt_isKindOfClass` … — so a send of `init` need not pass through +/// `objc_msgSend` at all: macOS 26.6's AppKit calls `objc_alloc_init` 2,488 +/// times against 720 sends of `init` by selector. Each such call is the send +/// it stands for. Evolution proposal `objc-runtime-send-entry-points`. +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct RuntimeSendEntryPointTests { + private struct Fixture { + let analyzer: CrossReferenceAnalyzer + let imageIndex: Int + } + + /// The library is loaded before the analyzer that reads it is made. + private static let fixture = Result { + // Without ARC, so no call the compiler adds stands among them. + try CompiledFixture.load( + libraryName: "libCrossReferenceRuntimeSends.dylib", + sources: [ + "Sends.m": """ + #import + + @interface CrossReferenceRuntimeSendProbe : NSObject + @end + + @implementation CrossReferenceRuntimeSendProbe + @end + + id crossReferenceAllocatesAndInitializes(void) { + return [[CrossReferenceRuntimeSendProbe alloc] init]; + } + + id crossReferenceAllocates(void) { + return [CrossReferenceRuntimeSendProbe alloc]; + } + + id crossReferenceAllocatesWithZone(void) { + return [CrossReferenceRuntimeSendProbe allocWithZone:nil]; + } + + id crossReferenceMakesANewInstance(void) { + return [CrossReferenceRuntimeSendProbe new]; + } + + Class crossReferenceAsksForTheClass(id object) { + return [object class]; + } + + id crossReferenceAsksForSelf(id object) { + return [object self]; + } + + BOOL crossReferenceAsksIsKindOfClass(id object, Class aClass) { + return [object isKindOfClass:aClass]; + } + + BOOL crossReferenceAsksRespondsToSelector(id object, SEL selector) { + return [object respondsToSelector:selector]; + } + """, + ], + compilerArguments: ["-O1", "-mmacosx-version-min=12.0", "-fno-objc-arc", "-framework", "Foundation"] + ) + guard let analyzer = CrossReferenceAnalyzer(), + let imageIndex = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix("/libCrossReferenceRuntimeSends.dylib") }) + else { throw CompiledFixture.Failure(description: "the analyzer does not see the fixture") } + return Fixture(analyzer: analyzer, imageIndex: imageIndex) + } + + static let probe = ReceiverClassHint.classLiteral("CrossReferenceRuntimeSendProbe") + + @Test(arguments: [ + ("_crossReferenceAllocatesAndInitializes", [RuntimeSendEntryPointTests.send("alloc", to: RuntimeSendEntryPointTests.probe), RuntimeSendEntryPointTests.send("init", to: .unknown)]), + ("_crossReferenceAllocates", [RuntimeSendEntryPointTests.send("alloc", to: RuntimeSendEntryPointTests.probe)]), + ("_crossReferenceAllocatesWithZone", [RuntimeSendEntryPointTests.send("allocWithZone:", to: RuntimeSendEntryPointTests.probe)]), + ("_crossReferenceMakesANewInstance", [RuntimeSendEntryPointTests.send("new", to: RuntimeSendEntryPointTests.probe)]), + ("_crossReferenceAsksForTheClass", [RuntimeSendEntryPointTests.send("class", to: .unknown)]), + ("_crossReferenceAsksForSelf", [RuntimeSendEntryPointTests.send("self", to: .unknown)]), + ("_crossReferenceAsksIsKindOfClass", [RuntimeSendEntryPointTests.send("isKindOfClass:", to: .unknown)]), + ("_crossReferenceAsksRespondsToSelector", [RuntimeSendEntryPointTests.send("respondsToSelector:", to: .unknown)]), + ]) + func anEntryPointCallIsTheSendItStandsFor(functionName: String, expectedSends: [CodeReferenceTarget]) throws { + let fixture = try Self.fixture.get() + let function = try #require(fixture.analyzer.functions(inImageAt: fixture.imageIndex).first { $0.name == .symbol(functionName) }, "no function \(functionName)") + let references = fixture.analyzer.references(madeBy: function) + let sends = references.filter { if case .messageSend = $0.target { true } else { false } } + #expect(sends.map(\.target) == expectedSends, "\(references.map(\.target))") + // One call: both sends of `objc_alloc_init` are its instruction's. + #expect(Set(sends.map(\.instructionAddress)).count == 1) + // The call is the send, not also a call to libobjc. + let libobjcCalls = references.filter { reference in + guard case .function(let location) = reference.target else { return false } + return fixture.analyzer.imagePaths[location.imageIndex].hasSuffix("/libobjc.A.dylib") + } + #expect(libobjcCalls.isEmpty, "\(libobjcCalls.map(\.target))") + } + + /// The fixture sends `init`, `isKindOfClass:` and `new` only through + /// entry points, so no selector reference names them; the images that + /// import the entry points are kept all the same. + @Test(arguments: ["init", "alloc", "allocWithZone:", "new", "class", "self", "isKindOfClass:", "respondsToSelector:"]) + func theSelectorPrefilterKeepsImagesSendingThroughEntryPoints(selector: String) throws { + let fixture = try Self.fixture.get() + #expect(fixture.analyzer.imageIndices(referencingSelector: selector, among: [fixture.imageIndex]) == [fixture.imageIndex]) + } + + static func send(_ selector: String, to receiver: ReceiverClassHint) -> CodeReferenceTarget { + .messageSend(selector: selector, receiver: receiver) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ScanThroughputBenchmarkTests.swift b/Tests/CrossReferenceAnalysisTests/ScanThroughputBenchmarkTests.swift new file mode 100644 index 000000000..c1e9ed93b --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ScanThroughputBenchmarkTests.swift @@ -0,0 +1,120 @@ +import Foundation +import Testing +import MachOKit +import CrossReferenceAnalysis + +/// How long the operations the module document's throughput table lists +/// take: building the analyzer, a whole table of every image of the +/// running system's shared cache, and the callers of `init` and of +/// `makeKeyAndOrderFront:`. An A/B measurement, not a regression test: +/// run it on the baseline and on the candidate, on the same machine, in a +/// release build, and compare. +/// +/// Uses the public API alone, so that the same file runs on both sides +/// (copied into an export of the baseline commit). Runs only with +/// `CROSS_REFERENCE_BENCHMARK_OUTPUT=`, where it writes one line per +/// operation: its name and the best of three rounds, in seconds. +/// +/// With `CROSS_REFERENCE_BENCHMARK_DYLD_CACHE=` the analyzer is +/// made from that cache file instead of the process, and before anything +/// else the callers of each selector are timed once — the first query in +/// the process, which reads the cache's pages as the system holds them. +@Suite( + .enabled(if: ScanThroughputBenchmarkEnvironment.outputPath != nil, "set CROSS_REFERENCE_BENCHMARK_OUTPUT"), + .serialized +) +struct ScanThroughputBenchmarkTests { + @Test func scanThroughputAfterTheLayerSplitIsRecordedInTheModuleDocument() throws { + var lines: [String] = [] + var analyzer: CrossReferenceAnalyzer? + let cachePath = ScanThroughputBenchmarkEnvironment.dyldCachePath + let analyzerTime = try Self.bestOfThree { + if let cachePath { + analyzer = try CrossReferenceAnalyzer(dyldCache: FullDyldCache(url: URL(fileURLWithPath: cachePath))) + } else { + analyzer = try #require(CrossReferenceAnalyzer()) + } + } + let built = try #require(analyzer) + lines.append("analyzer \(analyzerTime)") + + let allImages = Array(built.imagePaths.indices) + if cachePath != nil { + for selector in ["makeKeyAndOrderFront:", "init"] { + let start = DispatchTime.now().uptimeNanoseconds + let candidates = built.imageIndices(referencingSelector: selector, among: allImages) + nonisolated(unsafe) var senderCount = 0 + let lock = NSLock() + DispatchQueue.concurrentPerform(iterations: candidates.count) { position in + let count = built.references(to: [.selector(selector)], inImageAt: candidates[position]).count + lock.lock() + senderCount += count + lock.unlock() + } + let seconds = (Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000).rounded() / 1000 + lines.append("firstCallersOf(\(selector)) \(seconds) images=\(candidates.count) references=\(senderCount)") + } + } + var referenceCount = 0 + let tableTime = try Self.bestOfThree { + let counts = UnsafeMutableBufferPointer.allocate(capacity: allImages.count) + counts.initialize(repeating: 0) + defer { counts.deallocate() } + nonisolated(unsafe) let countsBase = counts.baseAddress! + DispatchQueue.concurrentPerform(iterations: allImages.count) { imageIndex in + (countsBase + imageIndex).pointee = built.referenceTable(ofImageAt: imageIndex).references.count + } + referenceCount = counts.reduce(0, +) + if let countsPath = ScanThroughputBenchmarkEnvironment.countsPath { + let perImage = allImages.map { "\(counts[$0]) \(built.imagePaths[$0])" }.joined(separator: "\n") + try? (perImage + "\n").write(toFile: countsPath, atomically: true, encoding: .utf8) + } + } + lines.append("wholeCacheTables \(tableTime) references=\(referenceCount)") + + for selector in ["init", "makeKeyAndOrderFront:"] { + var candidates: [Int] = [] + let prefilterTime = try Self.bestOfThree { + candidates = built.imageIndices(referencingSelector: selector, among: allImages) + } + var senderCount = 0 + // One set of keys for every image, as `refs` and RuntimeViewer + // pass it: each scan checking references against one shared set + // once made a query 15 to 70 times slower than a set per image. + let keys: Set = [.selector(selector)] + let scanTime = try Self.bestOfThree { + let counts = UnsafeMutableBufferPointer.allocate(capacity: candidates.count) + counts.initialize(repeating: 0) + defer { counts.deallocate() } + nonisolated(unsafe) let countsBase = counts.baseAddress! + DispatchQueue.concurrentPerform(iterations: candidates.count) { position in + (countsBase + position).pointee = built.references(to: keys, inImageAt: candidates[position]).count + } + senderCount = counts.reduce(0, +) + } + lines.append("callersOf(\(selector)) prefilter=\(prefilterTime) scan=\(scanTime) images=\(candidates.count) references=\(senderCount)") + } + + let output = try #require(ScanThroughputBenchmarkEnvironment.outputPath) + try (lines.joined(separator: "\n") + "\n").write(toFile: output, atomically: true, encoding: .utf8) + } + + private static func bestOfThree(_ body: () throws -> Void) rethrows -> Double { + var best = Double.infinity + for _ in 0 ..< 3 { + let start = DispatchTime.now().uptimeNanoseconds + try body() + best = min(best, Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000) + } + return (best * 1000).rounded() / 1000 + } +} + +enum ScanThroughputBenchmarkEnvironment { + static let outputPath = ProcessInfo.processInfo.environment["CROSS_REFERENCE_BENCHMARK_OUTPUT"] + /// Where to write each image's reference count, to find which images two + /// sides disagree on when their totals differ. + static let countsPath = ProcessInfo.processInfo.environment["CROSS_REFERENCE_BENCHMARK_COUNTS"] + /// A dyld shared cache file to make the analyzer from. + static let dyldCachePath = ProcessInfo.processInfo.environment["CROSS_REFERENCE_BENCHMARK_DYLD_CACHE"] +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneBindSlotTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneBindSlotTests.swift new file mode 100644 index 000000000..cec84fc1b --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/StandaloneBindSlotTests.swift @@ -0,0 +1,32 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import MachOAddressResolution + +/// MachOKitExtensions' `SlotResolver` on a standalone file, the one of its +/// tests that needs this package's SymbolTestsCore fixture; the rest live +/// with it (`MachOAddressResolutionTests`). +@Suite +struct StandaloneBindSlotTests { + /// A standalone file's GOT binds by name: the fixture links the Swift + /// runtime and Foundation. + @Test func slotResolverResolvesStandaloneBinds() throws { + guard case .machO(let machO) = try loadFromFile(named: .SymbolTestsCore) else { + Issue.record("the SymbolTestsCore fixture is no thin Mach-O") + return + } + let resolver = SlotResolver(machO: machO) + var boundNames: [String] = [] + for section in machO.sections64 where section.sectionName == "__got" || section.sectionName == "__auth_got" { + for slotIndex in 0 ..< section.size / 8 { + let slot = UInt64(section.address) &+ UInt64(slotIndex * 8) + if case .boundSymbol(let name)? = resolver.content(ofSlotAt: slot) { boundNames.append(name) } + } + } + #expect(boundNames.count > 10) + #expect(boundNames.contains { $0.hasPrefix("_swift_") || $0.hasPrefix("_$s") }) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift new file mode 100644 index 000000000..68084ab80 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift @@ -0,0 +1,89 @@ +import Foundation +import Testing +import MachOKit +import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences + +/// Every reference of a standalone binary, read in file mode and written one +/// function at a time, to compare with a disassembler's cross references by +/// hand. Not a regression test: it runs only with +/// `CROSS_REFERENCE_STANDALONE_DUMP_INPUT=` (the arm64e slice of a +/// universal file is taken, else the arm64 one) and +/// `CROSS_REFERENCE_STANDALONE_DUMP_OUTPUT=`. +@Suite(.enabled(if: StandaloneFileReferenceDumpEnvironment.inputPath != nil && StandaloneFileReferenceDumpEnvironment.outputPath != nil, "set CROSS_REFERENCE_STANDALONE_DUMP_INPUT and CROSS_REFERENCE_STANDALONE_DUMP_OUTPUT")) +struct StandaloneFileReferenceDumpTests { + @Test func standaloneFileReferencesAreWrittenForComparison() throws { + let inputPath = try #require(StandaloneFileReferenceDumpEnvironment.inputPath) + let outputPath = try #require(StandaloneFileReferenceDumpEnvironment.outputPath) + let file: MachOFile + switch try MachOKit.loadFromFile(url: URL(fileURLWithPath: inputPath)) { + case .machO(let machO): + file = machO + case .fat(let fatFile): + let slices = try fatFile.machOFiles() + file = try #require( + slices.first { $0.header.cpuSubType == .arm64(.arm64e) } ?? slices.first { $0.header.cpuType == .arm64 }, + "no arm64 slice in \(inputPath)" + ) + } + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let functions = analyzer.functions(inImageAt: 0) + let functionsByLocation = Dictionary(functions.map { ($0.location, $0) }, uniquingKeysWith: { first, _ in first }) + var lines: [String] = [] + var currentFunction: CodeLocation? + for reference in analyzer.referenceTable(ofImageAt: 0).references { + if reference.function != currentFunction { + currentFunction = reference.function + let name = functionsByLocation[reference.function].map { Self.describe($0.name) } ?? "" + lines.append("function 0x\(String(reference.function.address, radix: 16)) \(name)") + } + lines.append(" 0x\(String(reference.instructionAddress, radix: 16)) \(reference.kind) \(Self.describe(reference.target, functionsByLocation: functionsByLocation)) via \(reference.route)\(reference.isRuntimeHelperCall ? " helper" : "")") + } + try (lines.joined(separator: "\n") + "\n").write(toFile: outputPath, atomically: true, encoding: .utf8) + #expect(lines.count > 100) + } + + private static func describe(_ name: CodeFunction.Name?) -> String { + switch name { + case .symbol(let symbol)?: symbol + case .objectiveCMethod(let className, let selector, let isClassMethod)?: "\(isClassMethod ? "+" : "-")[\(className) \(selector)]" + case .swiftMetadata(let mangledName)?: mangledName + case nil: "" + } + } + + private static func describe(_ target: CodeReferenceTarget, functionsByLocation: [CodeLocation: CodeFunction]) -> String { + switch target { + case .function(let location): + "function 0x\(String(location.address, radix: 16)) \(describe(functionsByLocation[location]?.name))" + case .importedSymbol(let name): + "imported \(name)" + case .messageSend(let selector, let receiver): + "send \(selector) receiver \(receiver)" + case .superMessageSend(let selector, let className): + "superSend \(selector) class \(className ?? "?")" + case .swiftType(let descriptor): + "swiftType 0x\(String(descriptor.address, radix: 16))" + case .swiftTypeName(let name): + "swiftTypeName \(name)" + case .objectiveCClass(let name, let location): + "class \(name) 0x\(String(location.address, radix: 16))" + case .objectiveCInstanceVariable(let className, let name): + "ivar \(className).\(name)" + case .cString(let characters): + "cString \(characters.debugDescription)" + case .constantString(let characters): + "constantString \(characters.debugDescription)" + case .indirect(let evidence): + "indirect \(evidence)" + case .unrecognized(let address): + "unrecognized 0x\(String(address, radix: 16))" + } + } +} + +enum StandaloneFileReferenceDumpEnvironment { + static let inputPath = ProcessInfo.processInfo.environment["CROSS_REFERENCE_STANDALONE_DUMP_INPUT"] + static let outputPath = ProcessInfo.processInfo.environment["CROSS_REFERENCE_STANDALONE_DUMP_OUTPUT"] +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift index b7a410050..f9fef11d4 100644 --- a/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift +++ b/Tests/CrossReferenceAnalysisTests/StandaloneImageTests.swift @@ -2,6 +2,8 @@ import Foundation import Testing import MachOKit @testable import CrossReferenceAnalysis +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences /// An image outside the shared cache — a third-party app's own binary, here /// the SymbolTestsCore fixture — calls other images through its own diff --git a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift index 49bf40de5..99e2e984c 100644 --- a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift @@ -2,7 +2,9 @@ import Foundation import Testing import MachOKit import Demangling -import ARM64InstructionDecoding +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding @testable import CrossReferenceAnalysis /// Swift type references: calls to a type's metadata accessor and the @@ -142,7 +144,7 @@ struct SwiftTypeReferenceTests { 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 byte == 0x02 { descriptor = analyzer.memory.pointer(at: descriptor) ?? 0 } if let descriptorLocation = analyzer.location(ofDescriptorAtRuntimeAddress: descriptor) { mentions[descriptorLocation, default: 0] += 1 } } position += byte >= 0x01 && byte <= 0x17 ? 5 : (byte >= 0x18 && byte <= 0x1F ? 9 : 1) @@ -231,7 +233,7 @@ struct SwiftTypeReferenceTests { @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) + let typeIndex = SwiftTypeIndex(image: analyzer.imageSet.images[imageIndex], imageIndex: imageIndex, memory: analyzer.memory) var locationsByKey: [String: Set] = [:] for address in typeIndex.descriptorAddresses { guard let key = typeIndex.key(ofDescriptorAt: address) else { continue } @@ -253,7 +255,7 @@ struct SwiftTypeReferenceTests { 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) + let typeIndex = SwiftTypeIndex(image: analyzer.imageSet.images[imageIndex], imageIndex: imageIndex, memory: analyzer.memory) var exportedTypeCount = 0 for address in typeIndex.descriptorAddresses { guard let key = typeIndex.key(ofDescriptorAt: address) else { continue } @@ -264,6 +266,58 @@ struct SwiftTypeReferenceTests { #expect(exportedTypeCount > 100) } + /// A query for a type imported from C or Objective-C compares the name a + /// descriptor gives its type before anything else. A scan hands it every + /// context descriptor a mangled name's symbolic reference leads to — an + /// opaque type's among them, every `some View` — and only a type + /// descriptor keeps a pointer to its name at +8. An opaque type keeps its + /// generic header there, whose one parameter and one requirement read as + /// an offset of 64 KiB: in a small image, past its end. The query reads no + /// name where no type descriptor of the image is. + /// + /// In a child process, where the read used to fault. + @Test func importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs() async { + await #expect(processExitsWith: .success) { + exit(Self.matchImportedTypeAgainstAnOpaqueTypeHeader()) + } + } + + /// Matches an imported type against an opaque type's descriptor that + /// ends a readable page, with nothing readable 64 KiB on. + private static func matchImportedTypeAgainstAnOpaqueTypeHeader() -> Int32 { + guard let analyzer = CrossReferenceAnalyzer() else { return EXIT_FAILURE } + var importedType: SwiftTypeIdentity? + search: for suffix in ["/SwiftUICore.framework/Versions/A/SwiftUICore", "/AppKit.framework/Versions/C/AppKit"] { + guard let imageIndex = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix(suffix) }) else { continue } + for key in ["So6CGRectV", "So7CGPointV"] { + if let location = analyzer.swiftTypeDescriptorLocations(withKey: key, inImageAt: imageIndex).first, + let identity = analyzer.swiftTypeIdentity(ofDescriptorAt: location) { + importedType = identity + break search + } + } + } + guard let importedType, let slide = analyzer.images[importedType.descriptorLocation.imageIndex].vmaddrSlide else { return EXIT_FAILURE } + let pageSize = Int(getpagesize()) + let regionSize = pageSize + 128 * 1024 + guard let region = mmap(nil, regionSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0), region != MAP_FAILED, + mprotect(region + pageSize, regionSize - pageSize, PROT_NONE) == 0 + else { return EXIT_FAILURE } + let descriptor = region + pageSize - 16 + // Flags: kind 4, an opaque type. No parent. Then the generic header: + // one parameter, one requirement. + descriptor.storeBytes(of: UInt32(4), toByteOffset: 0, as: UInt32.self) + descriptor.storeBytes(of: Int32(0), toByteOffset: 4, as: Int32.self) + descriptor.storeBytes(of: UInt16(1), toByteOffset: 8, as: UInt16.self) + descriptor.storeBytes(of: UInt16(1), toByteOffset: 10, as: UInt16.self) + let location = CodeLocation( + imageIndex: importedType.descriptorLocation.imageIndex, + address: UInt64(bitPattern: Int64(Int(bitPattern: descriptor) &- slide)) + ) + let query = SwiftTypeQuery(identity: importedType, analyzer: analyzer) + return query.matches(.swiftType(descriptor: location)) ? EXIT_FAILURE : EXIT_SUCCESS + } + private func imagesReferencing(_ identity: SwiftTypeIdentity, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer diff --git a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift new file mode 100644 index 000000000..268bdf2f4 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift @@ -0,0 +1,207 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences +@_spi(Internals) import ARM64InstructionDecoding +@testable import CrossReferenceAnalysis + +/// What an address is (evolution proposal +/// `offline-cross-references-and-symbolication`, step 6). +@Suite +struct SymbolicationTests { + /// SwiftUICore's image stubs in the macOS 26.7 cache: each is + /// symbolicated by the slot it loads — where `dyld_info` and MachOKit's + /// reading of the indirect symbol table name 2,195 of them wrongly. Five + /// of those, checked against `ipsw dyld macho --stubs`, which follows + /// the slots too: the indirect symbol table gives all five one SwiftUI + /// witness's name, and they call Accelerate's `Quadrature`. + @Test(.enabled(if: FileManager.default.fileExists(atPath: "/Volumes/DyldSharedCaches/macOS/26.7/dyld_shared_cache_arm64e"), "needs the archived macOS 26.7 cache")) + func symbolicatesSwiftUICoreAuthStubsByTheirSlotsNotTheirIndirectSymbols() throws { + let cache = try FullDyldCache(url: URL(fileURLWithPath: "/Volumes/DyldSharedCaches/macOS/26.7/dyld_shared_cache_arm64e")) + let analyzer = try CrossReferenceAnalyzer(dyldCache: cache) + let swiftUICore = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/SwiftUICore.framework/Versions/A/SwiftUICore") }) + let file = try #require(analyzer.imageSet.images[swiftUICore].reader.asMachOFile) + func names(at location: CodeLocation) -> Set { + guard let function = analyzer.function(containing: location) else { return [] } + return Set([function.name.map(CrossReferenceAnalyzer.spelling(of:))].compactMap { $0 } + function.foldedSymbolNames) + .union(analyzer.exportedNames(at: location)) + } + + let checkedByIpsw: [UInt64: String] = [ + 0x22E6_BA9D0: "_$s10Accelerate10QuadratureV10IntegratorOMa", + 0x22E6_BAA10: "_$s10Accelerate10QuadratureVMa", + 0x22E6_BA9F0: "_$s10Accelerate10QuadratureV5ErrorOMa", + 0x22E6_BA9E0: "_$s10Accelerate10QuadratureV10integrator17absoluteTolerance08relativeE0A2C10IntegratorO_S2dtcfC", + 0x22E6_BAA00: "_$s10Accelerate10QuadratureV9integrate4over9integrands6ResultOySd08integralF0_Sd22estimatedAbsoluteErrortAC0J0OGSNySdG_S2dXEtF", + ] + let symbols = Array(file.symbols) + let indirectSymbols = file.indirectSymbols.map(Array.init) ?? [] + let stubs = file.sections64.filter { $0.sectionName == "__auth_stubs" }.flatMap { $0.stubs(in: file).map(Array.init) ?? [] } + for (stubAddress, expectedName) in checkedByIpsw { + guard case .stub(let hops, .function(let location)) = analyzer.symbolication(of: stubAddress).meaning else { + Issue.record("\(String(stubAddress, radix: 16)): \(analyzer.symbolication(of: stubAddress).meaning)") + continue + } + #expect(hops == [stubAddress]) + #expect(names(at: location).contains(expectedName), "\(String(stubAddress, radix: 16)): \(names(at: location))") + // What the indirect symbol table says instead. + if let stub = stubs.first(where: { $0.address == stubAddress }), let indirectIndex = stub.indirectSymbolIndex, indirectIndex < indirectSymbols.count, + let symbolIndex = indirectSymbols[indirectIndex].index, symbolIndex < symbols.count { + #expect(symbols[symbolIndex].name != expectedName) + } + } + + var resolvedStubCount = 0 + for stub in stubs { + guard case .stub(let hops, let target) = analyzer.symbolication(of: stub.address).meaning, hops == [stub.address] else { + Issue.record("\(String(stub.address, radix: 16)) is no stub") + continue + } + switch target { + case .function, .importedSymbol: resolvedStubCount += 1 + default: break + } + } + #expect(resolvedStubCount > 1000 && resolvedStubCount == stubs.count, "\(resolvedStubCount) of \(stubs.count) stubs resolved") + } + + /// macOS 27's AppKit sends through stubs the whole cache shares: a + /// selector stub, which puts the selector in `x1` and is the message it + /// sends, or a GOT stub, which leads to `objc_msgSend` — or to a libobjc + /// entry point that stands for a send — and leaves the selector to the + /// caller. + @Test(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) + func symbolicatesCacheSharedMessageSendStubToItsSelector() throws { + let analyzer = try #require(SharedAnalyzer.analyzer) + let appKit = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) + let sends = analyzer.referenceTable(ofImageAt: appKit).references.filter { reference in + guard reference.route == .cacheSharedStub, case .messageSend = reference.target else { return false } + return true + } + try #require(!sends.isEmpty, "AppKit sends through no cache-shared stub on this system") + var selectorStubCount = 0 + var globalOffsetTableStubCount = 0 + for send in sends.prefix(2000) { + guard case .messageSend(let selector, _) = send.target, + let word = analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: appKit, address: send.instructionAddress))), + let stub = ARM64InstructionWord.callTarget(word, at: send.instructionAddress) ?? ARM64InstructionWord.branchTarget(word, at: send.instructionAddress) + else { continue } + let symbolication = analyzer.symbolication(of: stub) + #expect(symbolication.imagePath == nil) + switch symbolication.meaning { + case .stub(let hops, .messageSend(let stubSelector, _)): + #expect(hops == [stub] && stubSelector == selector) + selectorStubCount += 1 + case .stub(let hops, .function(let location)): + #expect(hops.first == stub) + // `objc_msgSend`, or a libobjc entry point that stands for a + // send: `objc_alloc_init`, `objc_opt_class`. + let names = [analyzer.function(containing: location)?.name.map(CrossReferenceAnalyzer.spelling(of:))].compactMap { $0 } + analyzer.exportedNames(at: location) + #expect(names.contains { $0.hasPrefix("_objc_") }, "\(String(stub, radix: 16)) leads to \(names)") + globalOffsetTableStubCount += 1 + default: + Issue.record("\(String(stub, radix: 16)): \(symbolication.meaning)") + } + } + #expect(selectorStubCount > 0, "no send of AppKit's first 2,000 through a cache-shared selector stub") + #expect(selectorStubCount + globalOffsetTableStubCount > 100) + } + + /// A standalone library's GOT slot binds by name: to a symbol of a + /// library the analyzer does not cover, or — linked `-interposable` — to + /// its own function. + @Test func symbolicatesGlobalOffsetTableSlotToItsBoundSymbol() throws { + let (directory, library) = try CompiledFixture.build( + libraryName: "libSlots.dylib", + sources: ["Slots.c": """ + #include + __attribute__((noinline)) int slotCallee(int value) { return value * 5; } + int slotCaller(int value) { puts("calling"); return slotCallee(value); } + """], + compilerArguments: ["-O1", "-Wl,-interposable"] + ) + defer { try? FileManager.default.removeItem(at: directory) } + let file = try MachOFile(url: library) + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) + let callee = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_slotCallee") }) + var targets: [CodeReferenceTarget] = [] + for section in file.sections64 where section.sectionName == "__got" || section.sectionName == "__auth_got" { + for slot in stride(from: UInt64(section.address), to: UInt64(section.address) + UInt64(section.size), by: 8) { + let symbolication = analyzer.symbolication(of: slot) + #expect(symbolication.sectionName == section.sectionName) + guard case .pointerSlot(.globalOffsetTable, let target) = symbolication.meaning else { + Issue.record("\(String(slot, radix: 16)): \(symbolication.meaning)") + continue + } + targets.append(target) + } + } + #expect(targets.contains(.importedSymbol(name: "_puts")), "\(targets)") + #expect(targets.contains(.function(callee.location)), "\(targets)") + } + + /// Inside a function the symbol table leaves unnamed: the name its + /// Objective-C method list gives it, and the offset into it. + @Test(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) + func symbolicatesAnAddressInsideAnUnnamedFunctionWithItsFallbackName() throws { + let analyzer = try #require(SharedAnalyzer.analyzer) + let matter = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/Matter.framework/Versions/A/Matter") }) + let function = try #require(analyzer.functions(inImageAt: matter).first { function in + if case .objectiveCMethod = function.name { function.size > 8 } else { false } + }, "Matter has no function its method lists alone name") + let symbolication = analyzer.symbolication(of: function.location.address + 4) + #expect(symbolication.imagePath == analyzer.imagePaths[matter]) + #expect(symbolication.sectionName == "__text") + #expect(symbolication.meaning == .function(start: function.location, name: function.name.map(CrossReferenceAnalyzer.spelling(of:)), offset: 4)) + } + + /// No image maps it: nothing is made up. Read from the cache file: in + /// the process, an image outside the cache linked at 0 — the test + /// bundle — holds the unslid address 0x10, its own Mach header. + @Test(.enabled(if: RunningCacheFileAnalyzer.analyzer != nil, "needs the running system's dyld shared cache file")) + func symbolicatesAnUnmappedAddressAsUnmapped() throws { + let analyzer = try #require(RunningCacheFileAnalyzer.analyzer) + for address: UInt64 in [0x10, 0x7FFF_0000_0000] { + let symbolication = analyzer.symbolication(of: address) + #expect(symbolication.meaning == .unmapped, "\(String(address, radix: 16)): \(symbolication.meaning)") + #expect(symbolication.imagePath == nil) + } + } + + /// Strings, an instance variable's offset variable and a selector + /// reference, in a library compiled for the test. + @Test func symbolicatesStringsAndObjectiveCSlots() throws { + let (directory, library) = try CompiledFixture.build( + libraryName: "libObjectiveCSlots.dylib", + sources: ["Slots.m": """ + #import + @interface Holder : NSOperation { @public long _held; } + @end + @implementation Holder + @end + long readHeld(Holder *holder) { return holder->_held; } + const char *cString(void) { return "symbolicated characters"; } + NSString *constantString(void) { return @"symbolicated constant"; } + """], + compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + ) + defer { try? FileManager.default.removeItem(at: directory) } + let file = try MachOFile(url: library) + let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) + let references = analyzer.referenceTable(ofImageAt: 0).references + func symbolicationOfAddressBuiltFor(_ target: CodeReferenceTarget) throws -> AddressSymbolication { + let reference = try #require(references.first { $0.target == target }, "\(target)") + // `adrp` / `add`: the `add` holds the address. + let word = try #require(analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: 0, address: reference.instructionAddress)))) + let previousWord = try #require(analyzer.memory.load(UInt32.self, at: analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: 0, address: reference.instructionAddress - 4)))) + let page = try #require(ARM64InstructionWord.addressMaterialization(previousWord, at: reference.instructionAddress - 4)) + let addend = try #require(ARM64InstructionWord.addImmediate(word)) + return analyzer.symbolication(of: ARM64InstructionWord.adding(addend.addend, to: page.address)) + } + #expect(try symbolicationOfAddressBuiltFor(.cString("symbolicated characters")).meaning == .cString("symbolicated characters")) + #expect(try symbolicationOfAddressBuiltFor(.constantString("symbolicated constant")).meaning == .constantString("symbolicated constant")) + let instanceVariables = try #require(file.sections64.first { $0.sectionName == "__objc_ivar" }) + #expect(analyzer.symbolication(of: UInt64(instanceVariables.address)).meaning == .pointerSlot(.instanceVariableOffset, target: .objectiveCInstanceVariable(className: "Holder", name: "_held"))) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift index dde419050..ea57e008d 100644 --- a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift +++ b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift @@ -3,6 +3,8 @@ import Testing import Demangling import MachOReading import MachOSwiftSection +@_spi(Internals) import MachOCodeReferences +@_spi(Internals) import ObjCCodeReferences @_spi(Internals) import SwiftInspection @testable import CrossReferenceAnalysis diff --git a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift index 37612520b..18c4c1afb 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift @@ -2,9 +2,9 @@ import Foundation import Testing import Demangling @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport -@_spi(Internals) @testable import MachOSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +@_spi(Internals) @testable import SwiftSymbols @testable @_spi(Internals) import SwiftInspection final class DyldCacheAssociatedTypeTests: DyldCacheTests, @unchecked Sendable { diff --git a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift index 1bbee4eb4..c5402f453 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift @@ -3,8 +3,8 @@ import System import Testing import Demangling import MachOKit -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering diff --git a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift index f95ad788b..5ad3485c9 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift @@ -3,18 +3,18 @@ import MachOResolving import Testing import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import MachOSwiftSection @testable import SwiftDump -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection protocol OpaqueTypeTests {} extension OpaqueTypeTests { func opaqueTypes(in machO: some MachOFieldLayoutRenderable) async throws { - let symbols = SymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machO) + let symbols = SwiftSymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machO) for symbol in symbols { guard symbol.offset > 0 else { continue } print("Offset:", symbol.offset) diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift index fa8605cb5..6c6ed9cee 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import SwiftInspection final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift index 47307d4f4..96a90eead 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport final class ProtocolRequirementSignatureTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @@ -14,7 +14,7 @@ final class ProtocolRequirementSignatureTests: MachOFileTests, @unchecked Sendab for protocolDescriptor in protocolDescriptors { let proto = try Protocol(descriptor: protocolDescriptor, in: machO.context) for requirement in proto.requirements { - print(requirement.flags.kind) + print(requirement.flags.kind.map { "\($0)" } ?? "unknown") } print("-------------------------------") } diff --git a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift index d85e69673..c578f0778 100644 --- a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift @@ -3,8 +3,8 @@ import Testing @testable import Demangling import MachOKit import MachOFoundation -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Dependencies #if !SILENT_TEST && os(macOS) diff --git a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolTests.swift b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolTests.swift index 974df3dfc..1d41d76ba 100644 --- a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolTests.swift @@ -3,8 +3,8 @@ import Testing @testable import Demangling import MachOKit import MachOFoundation -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Dependencies struct MachOSwiftSymbol { diff --git a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift index 16afbf3f8..0b5c2e78a 100644 --- a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift @@ -1,8 +1,9 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport final class ExternalSymbolTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } diff --git a/Tests/IntegrationTests/MachOSymbols/MachOFileSymbolTests.swift b/Tests/IntegrationTests/MachOSymbols/MachOFileSymbolTests.swift index 03df238a3..866aeda59 100644 --- a/Tests/IntegrationTests/MachOSymbols/MachOFileSymbolTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/MachOFileSymbolTests.swift @@ -1,9 +1,9 @@ import Foundation import Testing -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport final class MachOFileSymbolTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } @@ -18,12 +18,12 @@ final class MachOFileSymbolTests: MachOFileTests, @unchecked Sendable { // symbol.name.print() // } -// for symbol in SymbolIndexStore.shared.allSymbols(in: machOFile) { +// for symbol in SwiftSymbolIndexStore.shared.allSymbols(in: machOFile) { // symbol.demangledNode.print().print() // } let duration = ContinuousClock().measure { - _ = SymbolIndexStore.shared.allSymbols(in: machOFile) + _ = SwiftSymbolIndexStore.shared.allSymbols(in: machOFile) } print(duration) @@ -43,12 +43,12 @@ final class MachOImageSymbolTests: MachOImageTests, @unchecked Sendable { // symbol.name.print() // } -// for symbol in SymbolIndexStore.shared.allSymbols(in: machOFile) { +// for symbol in SwiftSymbolIndexStore.shared.allSymbols(in: machOFile) { // symbol.demangledNode.print().print() // } let duration = ContinuousClock().measure { - _ = SymbolIndexStore.shared.allSymbols(in: machOImage) + _ = SwiftSymbolIndexStore.shared.allSymbols(in: machOImage) } print(duration) diff --git a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift index bda000164..54e6913c0 100644 --- a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift @@ -1,13 +1,14 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing import MachO import Demangling -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Stage 0 of the NodeStore migration plan: capture per-image baseline -/// metrics for `SymbolIndexStore.buildStorage` so Stage 1/4 can compare +/// metrics for `SwiftSymbolIndexStore.buildStorage` so Stage 1/4 can compare /// like-for-like. Run this suite alone (`--filter SymbolIndexStoreBaselineTests`) /// so no other test warms the global `NodeCache` or demangles symbols first. @Suite @@ -22,9 +23,9 @@ final class SymbolIndexStoreBaselineTests: MachOImageTests { let subtreeCacheCountBefore = NodeCache.shared.subtreeCount let clock = ContinuousClock() - var builtStorage: SymbolIndexStore.Storage? + var builtStorage: SwiftSymbolIndexStore.Storage? let buildDuration = clock.measure { - builtStorage = SymbolIndexStore.shared.buildStorage(for: machOImage) + builtStorage = SwiftSymbolIndexStore.shared.buildStorage(for: machOImage) } let footprintAfter = ProcessMemory.value(of: .physicalFootprint) let leafCacheCountAfter = NodeCache.shared.count diff --git a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreTests.swift b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreTests.swift index 6ad753388..22732c055 100644 --- a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreTests.swift @@ -1,9 +1,9 @@ import Foundation import Testing import MachO -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite enum SymbolIndexStoreTests { @@ -15,7 +15,7 @@ enum SymbolIndexStoreTests { @Test func main() async throws { ContinuousClock().measure { - SymbolIndexStore.shared.prepare(in: machOImage) + SwiftSymbolIndexStore.shared.prepare(in: machOImage) }.print() ProcessMemory.report() @@ -30,7 +30,7 @@ enum SymbolIndexStoreTests { @Test func main() async throws { ContinuousClock().measure { - SymbolIndexStore.shared.prepare(in: machOImage) + SwiftSymbolIndexStore.shared.prepare(in: machOImage) }.print() ProcessMemory.report() } diff --git a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift new file mode 100644 index 000000000..bf756080b --- /dev/null +++ b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift @@ -0,0 +1,496 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import SwiftIndexing +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing + +/// One image indexed the way the `objc` subcommands index it: the Swift +/// classes that keep no class object supplied from Swift metadata. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +private func preparedObjCIndexer(of machO: MachOFile) async throws -> ObjCInterfaceIndexer { + let indexer = ObjCInterfaceIndexer( + machO: machO, + imagePath: machO.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) + ) + try await indexer.prepare() + return indexer +} + +/// The Objective-C counterpart of ``ABIEvolutionDumpTests``. +/// +/// These index an *ordered series* of versions of one image — or of one +/// group of images per version (evolution proposal `image-group-evolution`) +/// — with MachOObjCSection's `ObjCInterfaceIndexer`, freeze each into an +/// `ObjCAPISnapshotDocument` (round-tripping through the persisted JSON form +/// so the codec and the format-version gate run on real-world data), and run +/// the series through `ObjCAPIEvolutionBuilder` + `ObjCAPIEvolutionReporter` — +/// the `swift-section objc evolution` pipeline. The annotated union header of +/// the same axis is ``ObjCEvolutionInterfaceDumpTests``, below. Like its +/// siblings it is a maintainer-inspection dump: it prints / writes results +/// without assertions. +protocol ObjCAPIEvolutionDumpTests: SwiftInterfaceDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension ObjCAPIEvolutionDumpTests { + /// One image indexed the way `swift-section objc snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what the evolution consumes is exactly what a saved + /// baseline would decode to. + private func snapshotDocument(of machO: MachOFile, label: String) async throws -> ObjCAPISnapshotDocument { + let indexer = try await preparedObjCIndexer(of: machO) + let document = ObjCAPISnapshotDocument( + provenance: ObjCAPIProvenance( + label: label, + binaryPath: machO.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() + ) + return try ObjCAPISnapshotDocument.decode(from: document.encoded()) + } + + /// Every version (oldest first) as `snapshotDocument(of:label:)`. The + /// timed step covers the whole preparation; the lineage math afterwards + /// takes seconds at most. + private func snapshotDocuments(of versions: [(label: String, machO: MachOFile)]) async throws -> [ObjCAPISnapshotDocument] { + var documents: [ObjCAPISnapshotDocument] = [] + try await measuringPreparation { + for version in versions { + documents.append(try await snapshotDocument(of: version.machO, label: version.label)) + } + } + return documents + } + + private func timelineReport(of evolution: ObjCAPIEvolution, documents: [ObjCAPISnapshotDocument]) -> String { + var report = ObjCAPIEvolutionReporter().report(evolution) + // For a two-version series the lineage events must match the + // two-sided differ verbatim — print both verdicts so the manual + // inspection can eyeball the consistency on real-world data. + if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { + let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) + report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" + } + return report + } + + /// Console analogue of `evolutionFile`: prepares every version, then + /// prints the timeline report. + func evolutionString(versions: [(label: String, machO: MachOFile)]) async throws { + let documents = try await snapshotDocuments(of: versions) + let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) + printResult(timelineReport(of: evolution, documents: documents)) + } + + /// Writes the timeline report (`-ObjCEvolution.txt`) and the + /// machine-readable form (`-ObjCEvolution.json`) next to the Swift + /// evolution dumps, both named after the *newest* version. + func evolutionFile(versions: [(label: String, machO: MachOFile)]) async throws { + let documents = try await snapshotDocuments(of: versions) + guard let newestVersion = versions.last else { return } + let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) + try write(timelineReport(of: evolution, documents: documents), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "txt") + try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "json") + } + + // MARK: - Groups of images + + /// Versions made up of groups of images (evolution proposal + /// `image-group-evolution`): every image of every version frozen as + /// `snapshotDocument(of:label:)` freezes one, under its image name. + private func imageGroupEvolution( + of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] + ) async throws -> ObjCAPIEvolution { + var imageGroups: [[ObjCAPIImageSnapshot]] = [] + try await measuringPreparation { + for version in imageGroupVersions { + var imageSnapshots: [ObjCAPIImageSnapshot] = [] + for image in version.images { + let document = try await snapshotDocument(of: image.machO, label: version.label) + imageSnapshots.append(ObjCAPIImageSnapshot(imageName: image.imageName.rawValue, snapshot: document.snapshot)) + } + imageGroups.append(imageSnapshots) + } + } + return try ObjCAPIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: imageGroupVersions.map { ObjCAPIVersionDescriptor(label: $0.label) } + ) + } + + /// Console analogue of `evolutionFile(imageGroupVersions:)`. + func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { + printResult(ObjCAPIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) + } + + /// Writes the timeline report and the JSON of an evolution over groups of + /// images, named after the newest version's group + /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolution.txt` + /// / `.json`). + func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { + let evolution = try await imageGroupEvolution(of: imageGroupVersions) + guard let newestVersion = imageGroupVersions.last else { return } + try write(ObjCAPIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "txt") + try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "json") + } +} + +enum ObjCAPIEvolutionTestSuite { + /// AppKit's Objective-C metadata across an ordered series of dyld shared + /// caches. A version joins the axis when its image carries an `__objc_*` + /// section, which AppKit does in every cache — unlike its Swift sections, + /// which the Swift suites need and which only appear from macOS 14. + class MultiVersionDyldCacheImageTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .AppKit } + + override class func isOnAxis(_ machOFile: MachOFile) -> Bool { + machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__objc_") }) + } + } + + /// AppKit across the three macOS caches the Swift evolution suites + /// default to (15.5 → 26.5.2 → 27.0), so the Objective-C report can be + /// read beside theirs. + final class DyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(versions: versions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(versions: versions) + } + } + + /// AppKit across every archived macOS cache, on the axis of the Swift + /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: the + /// same versions under the same labels, listed there once for both. + /// + /// The method names of a macOS 11 cache read correctly only from + /// MachOObjCSection 0.8.202. Its relative method lists count a selector + /// from the name field itself, where later caches count it from a + /// selector base, and an earlier reader made every class and category + /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 + /// removals and 53,000 additions instead of about 1,200 and 1,400. + final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(versions: versions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(versions: versions) + } + } + + /// AppKit together with the frameworks Apple moved its classes into — + /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default + /// three caches (15.5 → 26.5.2 → 27.0), each version one group of images + /// (evolution proposal `image-group-evolution`). + final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache, on the axis of + /// ``ArchivedDyldCacheTests``: the classes that moved between AppKit, + /// UIFoundation and CollectionViewCore in 13.0 and 15.0 — where an + /// evolution of AppKit alone reads them as removed or added — read as + /// moved. CollectionViewCore joins the group in 13.0. + final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { AppKitImageGroupDyldCacheTests.cacheImageNames } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } + + /// SwiftUI together with SwiftUICore across the default three caches — + /// the Objective-C side of `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. + final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache: SwiftUI alone until + /// 14.8, SwiftUICore joining it in 15.0. + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { SwiftUIImageGroupDyldCacheTests.cacheImageNames } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } +} + +/// The annotated-union-header analogue of ``ObjCAPIEvolutionDumpTests``, and +/// the Objective-C counterpart of ``SwiftEvolutionInterfaceDumpTests``. +/// +/// These run the same series through MachOObjCSection's +/// `ObjCEvolutionInterfaceBuilder` — the `swift-section objc evolution +/// --interface` pipeline: every declaration rendered the way `objc dump` +/// renders it, the versions merged into one header, and each declaration's +/// lifecycle annotated. Read the header against the lineage report of the +/// same axis — the annotations are the same lineages. Like its siblings it is +/// a maintainer-inspection dump: it prints / writes results without +/// assertions. +protocol ObjCEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension ObjCEvolutionInterfaceDumpTests { + /// Indexes every version (oldest first) the way `objc evolution + /// --interface` does and hands it to the builder, which keeps what it + /// rendered and snapshotted, never the indexer. The timed step covers the + /// indexing and rendering of every version. + private func evolutionInterface( + of versions: [(label: String, machO: MachOFile)], + availabilityPlatform: String? + ) async throws -> ObjCEvolutionInterface { + var builder = ObjCEvolutionInterfaceBuilder() + try await measuringPreparation { + for version in versions { + let indexer = try await preparedObjCIndexer(of: version.machO) + builder.addVersion(indexer: indexer, machO: version.machO, version: ObjCAPIVersionDescriptor(label: version.label)) + } + } + return try builder.build(availabilityPlatform: availabilityPlatform) + } + + /// `evolutionInterface(of:availabilityPlatform:)` over versions made up + /// of groups of images (evolution proposal `image-group-evolution`): each + /// version's images handed to the builder together, the primary image + /// first, so a class that moved between them stays one declaration. + private func evolutionInterface( + ofImageGroups imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityPlatform: String? + ) async throws -> ObjCEvolutionInterface { + var builder = ObjCEvolutionInterfaceBuilder() + try await measuringPreparation { + for version in imageGroupVersions { + var images: [ObjCEvolutionInterfaceImage] = [] + for image in version.images { + let indexer = try await preparedObjCIndexer(of: image.machO) + images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName.rawValue, indexer: indexer, machO: image.machO)) + } + builder.addVersion(images: images, version: ObjCAPIVersionDescriptor(label: version.label)) + } + } + return try builder.build(availabilityPlatform: availabilityPlatform) + } + + /// The annotated header plus the per-axis verdict line, so the manual + /// inspection can eyeball the CI-gate input next to the rendering. + private func annotatedHeaderReport(of evolutionInterface: ObjCEvolutionInterface) -> String { + evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)" + } + + /// Console analogue of `evolutionInterfaceFile`. A platform adds the + /// availability macros, as `objc evolution --interface --emit-available + /// --platform` does. + func evolutionInterfaceString(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { + let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) + printResult(annotatedHeaderReport(of: evolutionInterface)) + } + + /// Writes the annotated header (`-ObjCEvolutionInterface.h`) next to the + /// lineage report, named after the *newest* version. + func evolutionInterfaceFile(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { + let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) + guard let newestVersion = versions.last else { return } + try write(annotatedHeaderReport(of: evolutionInterface), for: newestVersion.machO, suffix: "ObjCEvolutionInterface", fileExtension: "h") + } + + /// Console analogue of + /// `evolutionInterfaceFile(imageGroupVersions:availabilityPlatform:)`. + func evolutionInterfaceString( + imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityPlatform: String? = nil + ) async throws { + let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) + printResult(annotatedHeaderReport(of: evolutionInterface)) + } + + /// Writes the annotated header of versions made up of groups of images, + /// named after the newest version's group + /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolutionInterface.h`). + func evolutionInterfaceFile( + imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityPlatform: String? = nil + ) async throws { + let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) + guard let newestVersion = imageGroupVersions.last else { return } + try write(annotatedHeaderReport(of: evolutionInterface), forImageGroup: newestVersion.images, suffix: "ObjCEvolutionInterface", fileExtension: "h") + } +} + +enum ObjCEvolutionInterfaceTestSuite { + /// AppKit across the three macOS caches the evolution suites default to + /// (15.5 → 26.5.2 → 27.0) — the axis of + /// `ObjCAPIEvolutionTestSuite.DyldCacheTests`, so the header and the + /// report can be read side by side. + final class DyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(versions: versions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(versions: versions) + } + } + + /// AppKit across every archived macOS cache, on the axis of + /// `ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests`. Every label is a + /// version number, so the header also spells each lifecycle one macro can + /// express as `API_AVAILABLE` / `API_OBSOLETED`. + final class ArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(versions: versions, availabilityPlatform: "macos") + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(versions: versions, availabilityPlatform: "macos") + } + } + + /// AppKit with UIFoundation, CollectionViewCore and CoreAutoLayout across + /// the default three caches — the axis of + /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests`. + final class AppKitImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { + ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache, on the axis of + /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupArchivedDyldCacheTests`, + /// with the availability macros. + final class AppKitImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { + ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") + } + } + + /// SwiftUI with SwiftUICore across the default three caches — the axis + /// of `ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. + final class SwiftUIImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { + ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache, with the + /// availability macros. + final class SwiftUIImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { + ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") + } + } +} diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift index 8e960a983..c68b38014 100644 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import SwiftDeclarationRendering import MachOKit -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport @testable import MachOSwiftSection @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing @@ -87,6 +87,60 @@ extension ABIEvolutionDumpTests { let evolution = try ABIEvolutionBuilder().evolution(of: documents) try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "Evolution", fileExtension: "json") } + + // MARK: - Groups of images + + /// Versions made up of groups of images (evolution proposal + /// `image-group-evolution`): every image of every version indexed and + /// frozen as `snapshotDocuments(of:)` freezes one, round-tripped through + /// the persisted form, under its image name. + private func imageGroupEvolution( + of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] + ) async throws -> ABIEvolution { + var imageGroups: [[ABIImageSnapshot]] = [] + try await measuringPreparation { + for version in imageGroupVersions { + var imageSnapshots: [ABIImageSnapshot] = [] + for image in version.images { + let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machO) + try await builder.prepare() + let document = ABISnapshotDocument( + provenance: ABIProvenance( + label: version.label, + binaryPath: image.machO.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: builder.snapshot() + ) + imageSnapshots.append(ABIImageSnapshot( + imageName: image.imageName.rawValue, + snapshot: try ABISnapshotDocument.decode(from: document.encoded()).snapshot + )) + } + imageGroups.append(imageSnapshots) + } + } + return try ABIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: imageGroupVersions.map { ABIVersionDescriptor(label: $0.label) } + ) + } + + /// Console analogue of `evolutionFile(imageGroupVersions:)`. + func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { + printResult(ABIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) + } + + /// Writes the timeline report and the JSON of an evolution over groups of + /// images, named after the newest version's group + /// (`…-SwiftUI+SwiftUICore-Evolution.txt` / `.json`). + func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { + let evolution = try await imageGroupEvolution(of: imageGroupVersions) + guard let newestVersion = imageGroupVersions.last else { return } + try write(ABIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "txt") + try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "json") + } } enum ABIEvolutionTestSuite { @@ -96,41 +150,70 @@ enum ABIEvolutionTestSuite { /// The caches are retained because the extracted `MachOFile`s resolve /// cross-image references through them while indexing. /// - /// A version whose cache lacks the image, or whose image has no - /// `__swift5_*` section, is left off the axis: there is nothing to index, - /// and indexing it anyway logs four extraction failures. AppKit kept its - /// Swift API in `libswiftAppKit.dylib` until macOS 14, so an AppKit axis - /// reaching further back starts at 14.0. A cache that cannot be opened - /// still throws. + /// A version whose cache lacks the image, or whose image lacks the metadata + /// a suite reads (`isOnAxis(_:)`), is left off the axis: there is nothing + /// to index. For the Swift suites that is an image with no `__swift5_*` + /// section, and indexing it anyway logs four extraction failures. AppKit + /// kept its Swift API in `libswiftAppKit.dylib` until macOS 14, so a Swift + /// AppKit axis reaching further back starts at 14.0. A cache that cannot + /// be opened still throws. /// /// Each cache is opened whole, the way `swift-section --dyld-shared-cache` /// opens it, so the dumps match what the command line prints. Opened from /// its main file alone, every read into another sub-cache file mapped that /// file once more until MachOObjCSection 0.8.109, and an evolution over /// every archived macOS minor ran past 5 GB. + /// + /// A suite comparing a group of images per version (evolution proposal + /// `image-group-evolution`) lists them in `cacheImageNames`, the primary + /// image first: AppKit with the frameworks Apple moved its classes into, + /// SwiftUI with SwiftUICore. A version joins the axis when its cache has + /// the primary image on the axis; each other image joins its group where + /// the cache has it on the axis — CollectionViewCore is in the macOS + /// caches from 13.0 on, SwiftUICore from 15.0 on. @TestActor class MultiVersionDyldCacheImageTests: Sendable { let caches: [FullDyldCache] + /// Each version's primary image. let versions: [(label: String, machO: MachOFile)] + /// Each version's group of images, the primary image first. + let imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] /// Oldest first; each cache's `versionLabel` labels it on the axis. class var cachePaths: [DyldSharedCachePath] { [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] } class var cacheImageName: MachOImageName { .SwiftUI } + /// The images whose declarations make up one version, the primary + /// image first; by default the primary image alone. + class var cacheImageNames: [MachOImageName] { [cacheImageName] } + + /// Whether a version's image belongs on the axis: it must carry the + /// metadata the suite indexes, which for the Swift suites is a + /// `__swift5_*` section. + class func isOnAxis(_ machOFile: MachOFile) -> Bool { + machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__swift5_") }) + } + init() async throws { var caches: [FullDyldCache] = [] var versions: [(label: String, machO: MachOFile)] = [] + var imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] = [] for cachePath in Self.cachePaths { let cache = try FullDyldCache(path: cachePath) - guard let machOFile = cache.machOFile(named: Self.cacheImageName), - machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__swift5_") }) else { + let images = Self.cacheImageNames.compactMap { imageName -> (imageName: MachOImageName, machO: MachOFile)? in + guard let machOFile = cache.machOFile(named: imageName), Self.isOnAxis(machOFile) else { return nil } + return (imageName, machOFile) + } + guard let primaryImage = images.first, primaryImage.imageName == Self.cacheImageNames.first else { continue } caches.append(cache) - versions.append((cachePath.versionLabel, machOFile)) + versions.append((cachePath.versionLabel, primaryImage.machO)) + imageGroupVersions.append((cachePath.versionLabel, images)) } self.caches = caches self.versions = versions + self.imageGroupVersions = imageGroupVersions } } @@ -149,6 +232,47 @@ enum ABIEvolutionTestSuite { } } + /// SwiftUI together with SwiftUICore across the default three caches + /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution + /// proposal `image-group-evolution`): what moved between the two images + /// after the split reads as moved, not as removed and added. + final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache, on the axis of + /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: + /// SwiftUI alone until 14.8, SwiftUICore joining it in 15.0 — where an + /// evolution of SwiftUI alone reads every declaration moved into + /// SwiftUICore as removed. + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionFile() async throws { + try await evolutionFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionString() async throws { + try await evolutionString(imageGroupVersions: imageGroupVersions) + } + } + /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the /// N == 2 case, whose printed pairwise cross-check line must agree with /// the two-sided differ. diff --git a/Tests/IntegrationTests/SwiftDump/DyldCacheDumpTests.swift b/Tests/IntegrationTests/SwiftDump/DyldCacheDumpTests.swift index fbdd8e34a..c5a5b73c6 100644 --- a/Tests/IntegrationTests/SwiftDump/DyldCacheDumpTests.swift +++ b/Tests/IntegrationTests/SwiftDump/DyldCacheDumpTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite(.serialized) final class DyldCacheDumpTests: DyldCacheTests, DumpableTests, @unchecked Sendable { diff --git a/Tests/IntegrationTests/SwiftDump/MachOFileDumpTests.swift b/Tests/IntegrationTests/SwiftDump/MachOFileDumpTests.swift index 19a18dbff..ec2ac2ccd 100644 --- a/Tests/IntegrationTests/SwiftDump/MachOFileDumpTests.swift +++ b/Tests/IntegrationTests/SwiftDump/MachOFileDumpTests.swift @@ -4,8 +4,8 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection @Suite(.serialized) diff --git a/Tests/IntegrationTests/SwiftDump/MachOImageDumpTests.swift b/Tests/IntegrationTests/SwiftDump/MachOImageDumpTests.swift index b5a62c646..f58b0463a 100644 --- a/Tests/IntegrationTests/SwiftDump/MachOImageDumpTests.swift +++ b/Tests/IntegrationTests/SwiftDump/MachOImageDumpTests.swift @@ -1,13 +1,13 @@ import Foundation import Testing import MachOKit -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection import Dependencies @@ -46,7 +46,7 @@ extension MachOImageDumpTests { } @Test func symbols() async throws { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore let symbols = symbolIndexStore.allSymbols(in: machOImage) diff --git a/Tests/IntegrationTests/SwiftDump/XcodeMachOFileDumpTests.swift b/Tests/IntegrationTests/SwiftDump/XcodeMachOFileDumpTests.swift index 27d4bc1c2..4a10abc3b 100644 --- a/Tests/IntegrationTests/SwiftDump/XcodeMachOFileDumpTests.swift +++ b/Tests/IntegrationTests/SwiftDump/XcodeMachOFileDumpTests.swift @@ -4,8 +4,8 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection @Suite(.serialized) diff --git a/Tests/IntegrationTests/SwiftInspection/ClassHierarchyDumpTests.swift b/Tests/IntegrationTests/SwiftInspection/ClassHierarchyDumpTests.swift index b1a50a9e9..ed6281ff5 100644 --- a/Tests/IntegrationTests/SwiftInspection/ClassHierarchyDumpTests.swift +++ b/Tests/IntegrationTests/SwiftInspection/ClassHierarchyDumpTests.swift @@ -2,14 +2,15 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Core) import MachOObjCSection @testable import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection +@testable @_spi(Internals) import SwiftObjCInterop #if os(macOS) import AppKit diff --git a/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift b/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift index 3f5215bd6..93506649e 100644 --- a/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift +++ b/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection #if canImport(SwiftUI) @@ -163,8 +163,8 @@ private func makeOptionalMetatype(_ metatype: T.Type) -> Any.Type { } extension String { - static func * (lhs: Self, rhs: Int) -> Self { - .init(repeating: lhs, count: rhs) + static func * (repeated: Self, count: Int) -> Self { + .init(repeating: repeated, count: count) } } diff --git a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift index 75997bdea..56bb26a37 100644 --- a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift @@ -6,7 +6,7 @@ import MachOSwiftSection import SwiftDump import SwiftDeclarationRendering import SwiftInterface -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Demangling /// Maintainer-only rendering-verification harness (no assertions — like the rest @@ -30,6 +30,20 @@ import Demangling /// - `RV_OPTS` comma-separated options (default = all): /// `fieldOffset, expandedFieldOffsets, typeLayout, enumLayout, /// spareBitAnalysis, memberAddress, vtableOffset, pwtOffset`. +/// `bareExistentials` (never in the default) prints +/// existentials without the `any` keyword, both outputs +/// on by default since evolution proposal +/// `existential-any`: an A/B run turns it on for the +/// candidate alone to compare against a baseline from +/// before the keyword. +/// `expandsMacros` (never in the default) prints what +/// `@Observable` generated instead of folding it into the +/// attribute, the interface default since evolution +/// proposal `observable-macro-folding`: the candidate +/// turns it on to compare against a baseline from before +/// the folding. The dump has no such switch; its +/// difference is the `@Observation.Observable` on the +/// header line of each class the macro expanded. /// /// Caveat: `expandedFieldOffsets` over a MachOImage of a framework with very /// deeply nested generic types (e.g. SwiftUI) hits a pre-existing stack overflow @@ -108,13 +122,16 @@ struct RenderingVerificationTests { configuration.printConfiguration.printMemberAddress = options.contains("memberAddress") configuration.printConfiguration.printVTableOffset = options.contains("vtableOffset") configuration.printConfiguration.printPWTOffset = options.contains("pwtOffset") + configuration.printConfiguration.usesExistentialAny = !options.contains("bareExistentials") + configuration.printConfiguration.expandsMacros = options.contains("expandsMacros") let builder = try SwiftInterfaceBuilder(configuration: configuration, in: machO) try await builder.prepare() return try await builder.printRoot().string } private func renderDump(in machO: some MachOFieldLayoutRenderable, options: Set) async throws -> String { - var configuration = DumperConfiguration(demangleResolver: .using(options: .test)) + let demangleOptions = options.contains("bareExistentials") ? DemangleOptions.test.subtracting(.useExistentialAny) : .test + var configuration = DumperConfiguration(demangleResolver: .using(options: demangleOptions)) configuration.printFieldOffset = options.contains("fieldOffset") configuration.printExpandedFieldOffsets = options.contains("expandedFieldOffsets") configuration.printTypeLayout = options.contains("typeLayout") diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift index b7a093fe4..c475fbf98 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import SwiftDeclarationRendering import MachOKit -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport @testable import MachOSwiftSection @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing @@ -88,7 +88,7 @@ extension SwiftDiffableInterfaceBuilderTests { } /// Selects the preferred-architecture slice from a loaded `File`, mirroring the -/// loading convention of `MachOTestingSupport`'s single-binary base classes. +/// loading convention of `SwiftSectionTestingSupport`'s single-binary base classes. /// Shared by every cross-version base class below so the fat/thin handling lives /// in one place. private func selectMachOFile(from file: File, architecture: CPUType) throws -> MachOFile { @@ -104,7 +104,7 @@ private func selectMachOFile(from file: File, architecture: CPUType) throws -> M enum SwiftDiffableInterfaceBuilderTestSuite { /// Loads a fixed `(old, new)` pair of `MachOFile`s by name — the two-binary - /// counterpart of `MachOTestingSupport.MachOFileTests`, which only loads one. + /// counterpart of `SwiftSectionTestingSupport.MachOFileTests`, which only loads one. @TestActor class CrossVersionMachOFileTests: Sendable { let oldMachOFile: MachOFile @@ -121,7 +121,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { } /// Extracts the same image from two dyld shared caches — the two-binary, - /// two-cache counterpart of `MachOTestingSupport.DyldCacheTests`. The caches are + /// two-cache counterpart of `SwiftSectionTestingSupport.DyldCacheTests`. The caches are /// retained because the extracted `MachOFile`s resolve cross-image references /// (into Foundation, libswiftCore, …) through them while indexing. @TestActor diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift index 24dfdc6e4..cce847f5c 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import SwiftDeclarationRendering import MachOKit -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing @@ -86,6 +86,50 @@ extension SwiftEvolutionInterfaceDumpTests { guard let newestVersion = versions.last else { return } try await write(annotatedInterfaceReport(of: builder), for: newestVersion.machO, suffix: "EvolutionInterface") } + + // MARK: - Groups of images + + /// Versions made up of groups of images (evolution proposal + /// `image-group-evolution`): each version's images render as one + /// interface, every declaration through the image that indexed it. + private func preparedBuilder( + imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityAnnotationPlatform: String? + ) async throws -> AnySwiftEvolutionInterfaceBuilder { + let builder = try AnySwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + imageGroups: imageGroupVersions.map { version in + version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName.rawValue, machO: $0.machO) } + }, + labels: imageGroupVersions.map(\.label), + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + try await measuringPreparation { + try await builder.prepare() + } + return builder + } + + /// Console analogue of `evolutionInterfaceFile(imageGroupVersions:availabilityAnnotationPlatform:)`. + func evolutionInterfaceString( + imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityAnnotationPlatform: String? = nil + ) async throws { + let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) + printResult(try await annotatedInterfaceReport(of: builder)) + } + + /// Writes the annotated union interface of an evolution over groups of + /// images, named after the newest version's group + /// (`…-SwiftUI+SwiftUICore-EvolutionInterface.swiftinterface`). + func evolutionInterfaceFile( + imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], + availabilityAnnotationPlatform: String? = nil + ) async throws { + let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) + guard let newestVersion = imageGroupVersions.last else { return } + try await write(annotatedInterfaceReport(of: builder), forImageGroup: newestVersion.images, suffix: "EvolutionInterface") + } } enum SwiftEvolutionInterfaceBuilderTestSuite { @@ -232,4 +276,45 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { try await evolutionInterfaceString(versions: versions, availabilityAnnotationPlatform: "macOS") } } + + /// SwiftUI together with SwiftUICore across the default three caches + /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution + /// proposal `image-group-evolution`) — the axis of + /// `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`, so the + /// interface and the report can be read side by side. + final class SwiftUIImageGroupDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) + } + } + + /// The same group across every archived macOS cache (`ArchivedDyldCacheTests`' + /// axis): SwiftUI alone until 14.8, SwiftUICore joining it in 15.0. Every + /// label is a version number, so the interface also spells each + /// lifecycle one attribute can express as `@available(macOS, …)`. + final class SwiftUIImageGroupArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { + ArchivedDyldCacheTests.cachePaths + } + + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") + } + } } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift index 8f3439d45..dffd7785c 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift @@ -7,13 +7,15 @@ import SwiftDeclarationRendering import MachOKit import Dependencies @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import SwiftInterface -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) @testable import MachOCaches -protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests {} +protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests { + var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } +} @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) extension SwiftInterfaceBuilderTests { @@ -30,6 +32,8 @@ extension SwiftInterfaceBuilderTests { printVTableOffset: true, printPWTOffset: true, infersObjCOverridesFromSelectorNames: true, + usesModuleSelectors: true, + protocolRequirementPlacement: .associatedTypes, memberSortOrder: .byOffset, printTypeLayout: true, printEnumLayout: true, @@ -64,7 +68,7 @@ extension SwiftInterfaceBuilderTests { } enum SwiftInterfaceBuilderTestSuite { - class DyldCacheTests: MachOTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .AppKit } @@ -87,7 +91,7 @@ enum SwiftInterfaceBuilderTestSuite { /// The same image from an archived macOS cache, picked by version: point /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` /// that holds a cache. - class ArchivedDyldCacheTests: MachOTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { class var cacheVersion: String { "26.6" } @@ -111,7 +115,7 @@ enum SwiftInterfaceBuilderTestSuite { } } - class MachOFileTests: MachOTestingSupport.MachOFileTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, SwiftInterfaceBuilderTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @@ -127,7 +131,7 @@ enum SwiftInterfaceBuilderTestSuite { } } - class MachOImageTests: MachOTestingSupport.MachOImageTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, SwiftInterfaceBuilderTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } @@ -143,7 +147,30 @@ enum SwiftInterfaceBuilderTestSuite { } } - class XcodeMachOFileTests: MachOTestingSupport.XcodeMachOFileTests, SwiftInterfaceBuilderTests { + class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, SwiftInterfaceBuilderTests { + var builderConfiguration: SwiftInterfaceBuilderConfiguration { + SwiftInterfaceBuilderConfiguration( + indexConfiguration: .init( + showCImportedTypes: false, + ), + printConfiguration: .init( + printStrippedSymbolicItem: true, + printFieldOffset: true, + printExpandedFieldOffsets: true, + printMemberAddress: true, + printVTableOffset: true, + printPWTOffset: true, + printExportedDeclarationsOnly: true, + infersObjCOverridesFromSelectorNames: true, + usesModuleSelectors: true, + protocolRequirementPlacement: .associatedTypes, + memberSortOrder: .byOffset, + printTypeLayout: true, + printEnumLayout: true, + ), + ) + } + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift index b520713f8..d9661cbe0 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift @@ -5,12 +5,12 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport final class SwiftDeclarationIndexerTests: MachOImageTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift index 0a021f449..1a30807cb 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift @@ -1,6 +1,6 @@ import Foundation import MachOKit -import MachOFixtureSupport +import SwiftSectionFixtureSupport @testable import MachOSwiftSection /// Shared scaffolding for the `SwiftInterface`-level integration dumps. @@ -51,6 +51,23 @@ extension SwiftInterfaceDumpTests { let fileName = "\(machO.loadCommands.buildVersionCommand!)-\(machO.imagePath.lastPathComponent)-\(suffix).\(fileExtension)" try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) } + + /// `write(_:for:suffix:fileExtension:)` for a version made up of a group + /// of images (evolution proposal `image-group-evolution`): named after + /// the primary image's build version and every image of the group, + /// joined by `+` (`…-SwiftUI+SwiftUICore-Evolution.txt`). + func write( + _ string: String, + forImageGroup images: [(imageName: MachOImageName, machO: MachOFile)], + suffix: String, + fileExtension: String = "swiftinterface" + ) throws { + guard let primaryImage = images.first else { return } + try rootDirectory.createDirectoryIfNeeded() + let imageGroupName = images.map { $0.machO.imagePath.lastPathComponent }.joined(separator: "+") + let fileName = "\(primaryImage.machO.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" + try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) + } } extension BuildVersionCommand: @retroactive CustomStringConvertible { diff --git a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift index cd61b5312..8ab542beb 100644 --- a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift +++ b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift @@ -1,13 +1,13 @@ #if os(macOS) import Foundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport import MachOKit import MachOSwiftSection import SwiftInterface import Testing import TypeIndexing -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// Maintainer-run end-to-end for the TypeIndexing provider (evolution /// proposal 0008): builds the fixture's interface with and without diff --git a/Tests/MachOCachesTests/DyldCacheImageSearchTests.swift b/Tests/MachOCachesTests/DyldCacheImageSearchTests.swift deleted file mode 100644 index df079422d..000000000 --- a/Tests/MachOCachesTests/DyldCacheImageSearchTests.swift +++ /dev/null @@ -1,178 +0,0 @@ -import MachOKitExtensions -import Testing -import Foundation -import MachOKit - -/// Regression coverage for dyld-shared-cache image selection. -/// -/// Leaf names are not unique inside a cache: iOS 27 ships both -/// `/System/Library/Frameworks/SwiftUI.framework/SwiftUI` and -/// `/System/Library/AccessibilityBundles/SwiftUI.axbundle/SwiftUI`. The old -/// first-match-wins name lookup resolved to whichever the cache enumerated -/// first — on the simulator caches the accessibility bundle, which carries no -/// Swift metadata, so `swift-section --dyld-shared-cache -n SwiftUI` emitted an -/// empty dump and still exited zero. Ranking must make the framework binary win. -/// -/// The ranking is pure path arithmetic, so these cases pin it directly without -/// needing a cache on disk. -@Suite -struct DyldCacheImageSearchTests { - private let iOSFrameworkPath = "/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - private let macOSFrameworkPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" - private let accessibilityBundlePath = "/System/Library/AccessibilityBundles/SwiftUI.axbundle/SwiftUI" - private let catalystFrameworkPath = "/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - - // Both of these exist on macOS 26. Neither sits inside a - // `libGLVMPlugin.framework`, so both classify as plain dylibs. - private let nativePluginDylibPath = "/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLVMPlugin.dylib" - private let catalystPluginDylibPath = "/System/iOSSupport/System/Library/Frameworks/OpenGLES.framework/Versions/A/Libraries/libGLVMPlugin.dylib" - - private let bestRank = DyldCacheImageSearchMode.bestMatchRank - - // MARK: - Name lookup ranking - - @Test func frameworkBinaryScoresBestRank() { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - #expect(mode.matchRank(forImagePath: iOSFrameworkPath) == bestRank) - #expect(mode.matchRank(forImagePath: macOSFrameworkPath) == bestRank) - } - - @Test func accessibilityBundleMatchesButRanksWorseThanFramework() throws { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - // It is still a name match — the cache really does contain it — but it - // must never outrank the framework binary. - let bundleRank = try #require(mode.matchRank(forImagePath: accessibilityBundlePath)) - let frameworkRank = try #require(mode.matchRank(forImagePath: iOSFrameworkPath)) - #expect(bundleRank > frameworkRank) - #expect(frameworkRank == bestRank) - } - - @Test func dylibRanksBetweenFrameworkAndBundle() throws { - let dylibMode = DyldCacheImageSearchMode.name("libswiftCore") - let dylibRank = try #require(dylibMode.matchRank(forImagePath: "/usr/lib/swift/libswiftCore.dylib")) - let bundleMode = DyldCacheImageSearchMode.name("SwiftUI") - let bundleRank = try #require(bundleMode.matchRank(forImagePath: accessibilityBundlePath)) - #expect(dylibRank > bestRank) - #expect(dylibRank < bundleRank) - } - - /// A macOS cache also carries the Mac Catalyst build of the same framework - /// under `/System/iOSSupport` — framework-shaped, same leaf name, a real - /// dylib. 74 frameworks collide this way on macOS 26 (SwiftUI, ARKit, - /// AVKit, GameKit, HealthKit, …). - /// - /// Both used to score `bestMatchRank`, and `accumulateBestMatch` returns at - /// the *first* image reaching that rank, so `-n SwiftUI` resolved to - /// whichever the cache happened to enumerate first — the same - /// order-dependence the ranking was introduced to remove, just moved from - /// bundle-versus-framework to Catalyst-versus-native. Only the native - /// framework may reach `bestMatchRank`. - @Test func catalystVariantMatchesButNeverScoresBestRank() throws { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - let catalystRank = try #require(mode.matchRank(forImagePath: catalystFrameworkPath)) - #expect(catalystRank > bestRank) - #expect(mode.matchRank(forImagePath: iOSFrameworkPath) == bestRank) - #expect(mode.matchRank(forImagePath: macOSFrameworkPath) == bestRank) - } - - /// The Catalyst variant is a real framework binary, so it still outranks a - /// plain dylib and a bundle wearing the same leaf name — it loses only to - /// the native framework. - @Test func catalystVariantOutranksDylibAndBundle() throws { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - let catalystRank = try #require(mode.matchRank(forImagePath: catalystFrameworkPath)) - let bundleRank = try #require(mode.matchRank(forImagePath: accessibilityBundlePath)) - let dylibRank = try #require( - DyldCacheImageSearchMode.name("libswiftCore").matchRank(forImagePath: "/usr/lib/swift/libswiftCore.dylib") - ) - #expect(catalystRank < dylibRank) - #expect(dylibRank < bundleRank) - } - - /// `/System/iOSSupport` demotes only a framework that has a native twin to - /// lose to; the support root must not make a path stop matching. - @Test func catalystVariantIsStillAMatch() { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - #expect(mode.matchRank(forImagePath: catalystFrameworkPath) != nil) - } - - /// The support-root demotion has to apply to **every** path shape, not just - /// to framework-shaped ones. - /// - /// `libGLVMPlugin.dylib` ships natively under `OpenGL.framework` and as a - /// Mac Catalyst build under `iOSSupport/…/OpenGLES.framework`. Neither is - /// inside a `libGLVMPlugin.framework`, so both classify as plain dylibs — - /// and while the demotion lived inside the framework branch they tied, - /// putting `-n libGLVMPlugin` back at the mercy of enumeration order. - @Test func catalystPlainDylibLosesToItsNativeNamesake() throws { - let mode = DyldCacheImageSearchMode.name("libGLVMPlugin") - let nativeRank = try #require(mode.matchRank(forImagePath: nativePluginDylibPath)) - let catalystRank = try #require(mode.matchRank(forImagePath: catalystPluginDylibPath)) - #expect(nativeRank < catalystRank) - } - - /// The penalty is a tiebreak *within* a shape, never a reclassification: a - /// demoted Catalyst build still beats every worse shape. Otherwise a native - /// `.axbundle` — the metadata-less payload that started all of this — could - /// outrank a Catalyst framework binary. - @Test func supportRootPenaltyNeverCrossesAShapeBoundary() throws { - let frameworkMode = DyldCacheImageSearchMode.name("SwiftUI") - let catalystFrameworkRank = try #require(frameworkMode.matchRank(forImagePath: catalystFrameworkPath)) - let nativeBundleRank = try #require(frameworkMode.matchRank(forImagePath: accessibilityBundlePath)) - #expect(catalystFrameworkRank < nativeBundleRank) - - let dylibMode = DyldCacheImageSearchMode.name("libGLVMPlugin") - let catalystDylibRank = try #require(dylibMode.matchRank(forImagePath: catalystPluginDylibPath)) - #expect(catalystFrameworkRank < catalystDylibRank) - #expect(catalystDylibRank < nativeBundleRank) - } - - @Test func nonMatchingLeafNameIsNotAMatch() { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - #expect(mode.matchRank(forImagePath: "/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore") == nil) - #expect(mode.matchRank(forImagePath: "/System/Library/Frameworks/_AVKit_SwiftUI.framework/_AVKit_SwiftUI") == nil) - } - - /// A leaf sitting inside a *different* framework must not be promoted: - /// only `.framework` counts as the canonical home. - @Test func leafInsideForeignFrameworkDoesNotScoreBestRank() throws { - let mode = DyldCacheImageSearchMode.name("SwiftUI") - let rank = try #require(mode.matchRank(forImagePath: "/System/Library/Frameworks/Foo.framework/SwiftUI")) - #expect(rank > bestRank) - } - - // MARK: - Path lookup - - @Test func pathLookupIsExactAndAlwaysBestRank() { - let mode = DyldCacheImageSearchMode.path(iOSFrameworkPath) - #expect(mode.matchRank(forImagePath: iOSFrameworkPath) == bestRank) - #expect(mode.matchRank(forImagePath: macOSFrameworkPath) == nil) - #expect(mode.matchRank(forImagePath: accessibilityBundlePath) == nil) - } -} - -// MARK: - End-to-End Cache Lookup - -/// End-to-end lookup against the CURRENT system's dyld shared cache — the -/// shape all three ranking rounds missed is a plain `.dylib` name, which can -/// never reach `bestMatchRank` (only a native canonical framework can) and -/// therefore always pays the full multi-cache scan before answering. -/// PR #103 review, finding L3. -private let currentSystemDyldSharedCachePath = "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e" - -@Suite(.enabled(if: FileManager.default.fileExists(atPath: currentSystemDyldSharedCachePath))) -struct DyldCacheEndToEndLookupTests { - - @Test func plainDylibNameResolvesToTheRealDylib() throws { - let cache = try DyldCache(url: URL(fileURLWithPath: currentSystemDyldSharedCachePath)) - let machOFile = try #require(cache.machOFile(by: .name("libswiftCore"))) - #expect(machOFile.imagePath == "/usr/lib/swift/libswiftCore.dylib") - } - - @Test func frameworkNameStillResolvesToTheCanonicalBinary() throws { - let cache = try DyldCache(url: URL(fileURLWithPath: currentSystemDyldSharedCachePath)) - let machOFile = try #require(cache.machOFile(by: .name("SwiftUI"))) - #expect(machOFile.imagePath.hasSuffix("SwiftUI.framework/Versions/A/SwiftUI")) - #expect(!machOFile.imagePath.contains("iOSSupport")) - } -} diff --git a/Tests/MachOCachesTests/MachOImageCacheMembershipTests.swift b/Tests/MachOCachesTests/MachOImageCacheMembershipTests.swift deleted file mode 100644 index d1cc03f0d..000000000 --- a/Tests/MachOCachesTests/MachOImageCacheMembershipTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -import MachOKitExtensions -import Testing -import Foundation -import MachOKit - -/// Regression coverage for deciding whether an in-process image belongs to the -/// dyld shared cache. -/// -/// `MachOImage.cache` used to call an image a cache image whenever its mach -/// header sat at or above the cache's unslid `sharedRegionStart` -/// (`0x180000000` on arm64). An image outside the cache usually loads below -/// that, but not always: in a full `swift test` run the dlopen'ed -/// `SymbolTestsCore` fixture landed at `0x70627cc000`, far past the end of the -/// cache. Taken for a cache image, it reported every address shifted by the -/// cache's slide, and `ProtocolRecordTests`, whose fixture picker derives its -/// read offset from the same answer, read `0x180000000` bytes too low — wrong -/// values in one run, a SIGBUS in another. -/// -/// Membership is a property of the image, recorded by the cache builder as the -/// header's `MH_DYLIB_IN_CACHE` flag; where the image happens to be mapped says -/// nothing. The cases below map a copy of this test bundle's own header and -/// load commands past the end of the shared region, so the address is chosen -/// here instead of by wherever dyld found room. -@Suite -struct MachOImageCacheMembershipTests { - @Test func imageOutsideTheCacheIsNotACacheImageWhereverItIsMapped() throws { - try withCopyMappedPastTheSharedRegion(of: MachOImage.current()) { relocatedImage in - #expect(relocatedImage.cache == nil) - } - } - - @Test func imageOutsideTheCacheReportsTheSameAddressesWhereverItIsMapped() throws { - let image = MachOImage.current() - let memberOffset = 0x4000 - try withCopyMappedPastTheSharedRegion(of: image) { relocatedImage in - #expect(relocatedImage.address(forOffset: memberOffset) == image.address(forOffset: memberOffset)) - } - } - - @Test func imageInTheCacheIsACacheImage() throws { - let image = try #require(MachOImage(name: "libswiftCore")) - #expect(image.cache != nil) - } - - /// Maps a copy of `image`'s mach header and load commands at the first free - /// address past the end of the shared region and hands `body` an image over - /// the copy. The header and the load commands are all that the membership - /// answer and `address(forOffset:)` read. - private func withCopyMappedPastTheSharedRegion( - of image: MachOImage, - _ body: (MachOImage) throws -> Void - ) throws { - let currentCache = try #require(DyldCacheLoaded.current) - let sharedRegionEnd = UInt(bitPattern: currentCache.ptr) + UInt(currentCache.mainCacheHeader.sharedRegionSize) - let byteCount = image.headerSize + Int(image.header.sizeofcmds) - let mapping = mmap(UnsafeMutableRawPointer(bitPattern: sharedRegionEnd), byteCount, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0) - let relocatedPointer = try #require(mapping == MAP_FAILED ? nil : mapping) - defer { munmap(relocatedPointer, byteCount) } - // The premise: past the cache, and so above `sharedRegionStart`, where - // the old lower-bound test answered "in the cache". - try #require(UInt(bitPattern: relocatedPointer) >= sharedRegionEnd) - relocatedPointer.copyMemory(from: image.ptr, byteCount: byteCount) - try body(MachOImage(ptr: relocatedPointer.assumingMemoryBound(to: mach_header.self))) - } -} diff --git a/Tests/MachOCachesTests/SharedCacheKeyTests.swift b/Tests/MachOCachesTests/SharedCacheKeyTests.swift deleted file mode 100644 index 5f94f6980..000000000 --- a/Tests/MachOCachesTests/SharedCacheKeyTests.swift +++ /dev/null @@ -1,91 +0,0 @@ -import Foundation -import Testing -import MachOKitExtensions -@_spi(Internals) import MachOCaches - -/// `SharedCacheKey` hashes a `uuidFile` identifier on its UUID alone, a -/// `dyldCacheImage` identifier on its two UUIDs and an `image` identifier on -/// its base address alone; the path still decides equality. These pin both -/// halves, since a key that hashed differently for equal identifiers would -/// miss its own entry, and one that compared equal across paths — or across -/// caches — would hand one binary another binary's index. -@Suite("SharedCacheKey") -struct SharedCacheKeyTests { - private let uuid = UUID() - - @Test func uuidFileKeysHashOnTheUUIDAlone() { - let first = SharedCacheKey(identifier: .uuidFile(path: "/System/Library/Frameworks/SwiftUI.framework/SwiftUI", uuid: uuid)) - let second = SharedCacheKey(identifier: .uuidFile(path: "/tmp/extracted/SwiftUI", uuid: uuid)) - - #expect(first.hashValue == second.hashValue, "two paths carrying the same UUID must hash alike: the path is not part of the hash") - #expect(first != second, "the path still takes part in equality") - } - - @Test func sameIdentifierMakesEqualKeys() { - let path = "/System/Library/Frameworks/AppKit.framework/AppKit" - let first = SharedCacheKey(identifier: .uuidFile(path: path, uuid: uuid)) - let second = SharedCacheKey(identifier: .uuidFile(path: path, uuid: uuid)) - - #expect(first == second) - #expect(first.hashValue == second.hashValue) - } - - @Test func differentUUIDsMakeDifferentKeys() { - let path = "/System/Library/Frameworks/AppKit.framework/AppKit" - let first = SharedCacheKey(identifier: .uuidFile(path: path, uuid: uuid)) - let second = SharedCacheKey(identifier: .uuidFile(path: path, uuid: UUID())) - - #expect(first != second, "the same install path from two builds must not share an entry") - } - - @Test func dyldCacheImageKeysHashOnTheTwoUUIDs() { - let cacheUUID = UUID() - let first = SharedCacheKey(identifier: .dyldCacheImage(path: "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI", uuid: uuid, cacheUUID: cacheUUID)) - let second = SharedCacheKey(identifier: .dyldCacheImage(path: "/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI", uuid: uuid, cacheUUID: cacheUUID)) - - #expect(first.hashValue == second.hashValue, "the path is not part of the hash") - #expect(first != second, "the path still takes part in equality") - } - - /// The macOS 13.5 and 13.6 caches carry the same SwiftUI build, `LC_UUID` - /// included, at different addresses. Sharing an entry between the two - /// copies sent the one read second to the first one's class objects. - @Test func oneBuildInTwoCachesMakesDifferentKeys() { - let path = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" - let first = SharedCacheKey(identifier: .dyldCacheImage(path: path, uuid: uuid, cacheUUID: UUID())) - let second = SharedCacheKey(identifier: .dyldCacheImage(path: path, uuid: uuid, cacheUUID: UUID())) - - #expect(first != second) - #expect(SharedCacheKey(identifier: .dyldCacheImage(path: path, uuid: uuid, cacheUUID: UUID())) != SharedCacheKey(identifier: .uuidFile(path: path, uuid: uuid)), "an image read from a cache is never the extracted file of the same build") - } - - @Test func imageKeysFollowTheBaseAddress() { - let storage = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 8) - defer { storage.deallocate() } - let first = SharedCacheKey(identifier: .image(UnsafeRawPointer(storage))) - let second = SharedCacheKey(identifier: .image(UnsafeRawPointer(storage))) - let other = SharedCacheKey(identifier: .image(UnsafeRawPointer(storage + 8))) - - #expect(first == second) - #expect(first.hashValue == second.hashValue) - #expect(first != other) - } - - @Test func pathOnlyIdentifiersStillHashThePath() { - let first = SharedCacheKey(identifier: .file("/a")) - let second = SharedCacheKey(identifier: .file("/a")) - let other = SharedCacheKey(identifier: .file("/b")) - - #expect(first == second) - #expect(first.hashValue == second.hashValue) - #expect(first != other) - } - - @Test func opaqueKeysNeverCollideWithReaderKeys() { - let opaque = SharedCacheKey(opaque: "/a") - let reader = SharedCacheKey(identifier: .file("/a")) - - #expect(opaque != reader, "a bare value and a reader identifier spelling the same string are different keys") - #expect(SharedCacheKey(opaque: "/a") == opaque) - } -} diff --git a/Tests/MachOCachesTests/SharedCacheRegistryTests.swift b/Tests/MachOCachesTests/SharedCacheRegistryTests.swift deleted file mode 100644 index 9a748c29d..000000000 --- a/Tests/MachOCachesTests/SharedCacheRegistryTests.swift +++ /dev/null @@ -1,202 +0,0 @@ -import Foundation -import Testing -@_spi(Internals) import MachOCaches - -/// The registry's ownership rules, driven on a registry of its own with -/// caches created against it and groups declared here — the registry knows -/// no group by name, so the tests declare the shape they need. The -/// process-wide registry and the real indexer are exercised end to end by -/// `PerImageCacheEvictionTests`. -@Suite("SharedCacheRegistry") -struct SharedCacheRegistryTests { - private enum Group { - static let store = SharedCacheEvictionGroup("test.store") - /// Holds the store's table: follows `store`. - static let table = SharedCacheEvictionGroup("test.table") - static let arena = SharedCacheEvictionGroup("test.arena") - /// Holds references into the arena: follows `arena`. - static let memo = SharedCacheEvictionGroup("test.memo") - /// Holds references into the memo: follows `memo`, and so the arena - /// transitively. - static let annotation = SharedCacheEvictionGroup("test.annotation") - static let catalog = SharedCacheEvictionGroup("test.catalog") - } - - /// A registry plus one cache per group the rules below reach. - private struct Fixture { - let registry = SharedCacheRegistry() - let store: SharedCache - let table: SharedCache - let arena: SharedCache - let memo: SharedCache - let annotation: SharedCache - let catalog: SharedCache - - init() { - store = SharedCache(evictionGroup: Group.store, registry: registry) - table = SharedCache(evictionGroup: Group.table, follows: [Group.store], registry: registry) - arena = SharedCache(evictionGroup: Group.arena, registry: registry) - memo = SharedCache(evictionGroup: Group.memo, follows: [Group.arena], registry: registry) - annotation = SharedCache(evictionGroup: Group.annotation, follows: [Group.memo], registry: registry) - catalog = SharedCache(evictionGroup: Group.catalog, registry: registry) - } - - var everyCache: [SharedCache] { - [store, table, arena, memo, annotation, catalog] - } - - func fill(_ cache: SharedCache, for key: SharedCacheKey) { - _ = cache.resolve(key: key) { 1 } - } - - func fillEverything(for key: SharedCacheKey) { - for cache in everyCache { - fill(cache, for: key) - } - } - } - - private let image = SharedCacheKey(opaque: "image-a") - private let otherImage = SharedCacheKey(opaque: "image-b") - private let owner = ObjectIdentifier(NSObject.self) - private let otherOwner = ObjectIdentifier(NSString.self) - - @Test func registeredGroupsAreWhatTheCachesDeclared() { - let fixture = Fixture() - - #expect(fixture.registry.registeredGroups == [Group.store, Group.table, Group.arena, Group.memo, Group.annotation, Group.catalog]) - #expect(fixture.registry.followers(of: Group.store) == [Group.table]) - #expect(fixture.registry.followers(of: Group.arena) == [Group.memo, Group.annotation], "a group following a follower goes too") - #expect(fixture.registry.followers(of: Group.catalog).isEmpty) - } - - @Test func registrationClaimsTheGroupsAbsentAtThatMoment() { - let fixture = Fixture() - fixture.fill(fixture.arena, for: image) - - fixture.registry.registerLiveOwner(owner, for: image) - - let claims = fixture.registry.claims(for: image) - #expect(!claims.contains(Group.arena), "a group with a finished entry belongs to whoever built it, not to the owner registering later") - #expect(claims.contains(Group.store)) - #expect(claims.contains(Group.catalog)) - } - - @Test func lastOwnerEvictsOnlyWhatWasClaimed() { - let fixture = Fixture() - fixture.fill(fixture.catalog, for: image) - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fillEverything(for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - #expect(!fixture.store.containsEntry(for: image), "the claimed store must go with its last owner") - #expect(fixture.catalog.containsEntry(for: image), "an entry that predates the owner was never claimed and must survive it") - #expect(!fixture.registry.hasLiveOwners(for: image)) - } - - @Test func survivingOwnerKeepsEverything() { - let fixture = Fixture() - fixture.registry.registerLiveOwner(owner, for: image) - fixture.registry.registerLiveOwner(otherOwner, for: image) - fixture.fillEverything(for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - for cache in fixture.everyCache { - #expect(cache.containsEntry(for: image), "an owner leaving while a sibling is live must evict nothing") - } - #expect(fixture.registry.hasLiveOwners(for: image)) - } - - @Test func claimedGroupTakesItsFollowersEvenWhenTheyWereNotClaimed() { - let fixture = Fixture() - // Present at registration, so not claimed on its own. - fixture.fill(fixture.table, for: image) - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fill(fixture.store, for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - #expect(!fixture.store.containsEntry(for: image)) - #expect(!fixture.table.containsEntry(for: image), "the table holds the store's storage; left behind it pins what the eviction meant to free") - } - - @Test func followersAreTakenTransitively() { - let fixture = Fixture() - fixture.fill(fixture.memo, for: image) - fixture.fill(fixture.annotation, for: image) - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fill(fixture.arena, for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - #expect(!fixture.arena.containsEntry(for: image)) - #expect(!fixture.memo.containsEntry(for: image), "the memo's values point into the arena; dropping the arena and keeping the memo frees nothing") - #expect(!fixture.annotation.containsEntry(for: image), "the annotation points into the memo, which points into the arena: it goes with them") - } - - @Test func droppingAFollowerAloneLeavesWhatItFollows() { - let fixture = Fixture() - fixture.fill(fixture.arena, for: image) - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fill(fixture.memo, for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - #expect(!fixture.memo.containsEntry(for: image)) - #expect(fixture.arena.containsEntry(for: image), "following is one-way: the memo follows the arena, the arena does not follow the memo") - } - - @Test func repeatedRegistrationDoesNotResample() { - let fixture = Fixture() - fixture.fill(fixture.arena, for: image) - fixture.registry.registerLiveOwner(owner, for: image) - // Between the two registrations the entry disappears; a second - // sampling would now claim it and the owner would evict what it - // never built. - fixture.arena.removeEntry(for: image) - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fill(fixture.arena, for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - #expect(fixture.arena.containsEntry(for: image), "only an owner's first registration contributes claims") - } - - @Test func explicitEvictionTakesExactlyTheNamedGroups() { - let fixture = Fixture() - fixture.fillEverything(for: image) - - fixture.registry.evict(groups: [Group.store], for: image) - - #expect(!fixture.store.containsEntry(for: image)) - #expect(fixture.table.containsEntry(for: image), "an explicit eviction names what it wants gone; following is an ownership rule, not part of it") - } - - @Test func evictingImagesWithoutLiveOwnersLeavesOwnedImagesAlone() { - let fixture = Fixture() - fixture.registry.registerLiveOwner(owner, for: image) - fixture.fillEverything(for: image) - fixture.fillEverything(for: otherImage) - - let evictedImageCount = fixture.registry.evictImagesWithoutLiveOwners() - - #expect(evictedImageCount == 1) - for cache in fixture.everyCache { - #expect(cache.containsEntry(for: image), "an image with a live owner is in use and must keep its entries") - #expect(!cache.containsEntry(for: otherImage), "an image nobody owns is what the host asked to shed") - } - } - - @Test func deregisteringAnUnknownOwnerIsANoOp() { - let fixture = Fixture() - fixture.fillEverything(for: image) - - fixture.registry.deregisterLiveOwner(owner, for: image) - - for cache in fixture.everyCache { - #expect(cache.containsEntry(for: image)) - } - } -} diff --git a/Tests/MachOCachesTests/SharedCacheTests.swift b/Tests/MachOCachesTests/SharedCacheTests.swift deleted file mode 100644 index 71c30ae2b..000000000 --- a/Tests/MachOCachesTests/SharedCacheTests.swift +++ /dev/null @@ -1,512 +0,0 @@ -import Foundation -import Testing -import os -@_spi(Internals) import MachOCaches - -@Suite("SharedCache.resolve") -struct SharedCacheResolveTests { - /// Single-threaded sanity: a hit reuses the storage, a miss runs build, - /// and a `nil` build is not cached. - @Test func singleThreadedHitMissAndNilDontCache() { - let cache = makeTestCache() - - let first = cache.resolve(key: SharedCacheKey(opaque: "a")) { 1 } - #expect(first == 1) - - // Second call hits the cache: the build closure must not run. - let second = cache.resolve(key: SharedCacheKey(opaque: "a")) { - Issue.record("build was called for an already-cached key") - return 99 - } - #expect(second == 1) - - // A `nil` build is not cached, so the next call gets a fresh attempt. - let nilFirst: Int? = cache.resolve(key: SharedCacheKey(opaque: "b")) { nil } - #expect(nilFirst == nil) - - let nilRetry = cache.resolve(key: SharedCacheKey(opaque: "b")) { 7 } - #expect(nilRetry == 7) - } - - /// Concurrent calls for the **same** key must share one build — the - /// promise-based marker is the whole point of this refactor over the - /// previous "build under the global lock" implementation. - /// - /// The callers run on threads of the test's own, not the global dispatch - /// queue: this synchronous test body blocks a cooperative thread until - /// they finish. On the 3-core CI runner the global queue granted no - /// worker while the cooperative pool was blocked (2026-09-29), and this - /// test, ``registeringOverAnInFlightBuildWinsAndTheBuilderStillAnswersItsWaiters()`` - /// and `reentrancyFromTask()` held all three pool threads between them — - /// no other test in the process could run again. A `Thread` exists the - /// moment it is started, whatever the pools are doing. - @Test func concurrentCallsForSameKeyShareOneBuild() { - let cache = makeTestCache() - let buildCount = OSAllocatedUnfairLock(initialState: 0) - let buildEnter = DispatchSemaphore(value: 0) - let buildRelease = DispatchSemaphore(value: 0) - let waiterCount = 32 - - // First caller installs the in-flight marker and blocks inside - // `build` until we release it. Every subsequent caller must attach - // to that marker rather than invoking `build` again. - let firstCallerDone = DispatchSemaphore(value: 0) - Thread { - let result = cache.resolve(key: SharedCacheKey(opaque: "shared")) { - buildCount.withLock { $0 += 1 } - buildEnter.signal() - buildRelease.wait() - return 42 - } - #expect(result == 42) - firstCallerDone.signal() - }.start() - - buildEnter.wait() // first caller is now blocked inside `build` - - // Fan out a herd of waiters; each must observe the same value and - // none of them should have triggered another build. - let herdDone = DispatchSemaphore(value: 0) - let observed = OSAllocatedUnfairLock(initialState: [Int]()) - for _ in 0 ..< waiterCount { - Thread { - let result = cache.resolve(key: SharedCacheKey(opaque: "shared")) { - Issue.record("a waiter ran build instead of joining the in-flight promise") - return -1 - } - observed.withLock { $0.append(result ?? -1) } - herdDone.signal() - }.start() - } - - // Give the herd a beat to all enter `resolve` and attach to the - // promise. Without this delay the test could pass spuriously if the - // first caller raced ahead of the waiters. - Thread.sleep(forTimeInterval: 0.05) - - buildRelease.signal() // unblock the first caller - firstCallerDone.wait() - for _ in 0 ..< waiterCount { herdDone.wait() } - - #expect(buildCount.withLock { $0 } == 1, "build must run exactly once for the shared key") - let values = observed.withLock { $0 } - #expect(values.count == waiterCount) - #expect(values.allSatisfy { $0 == 42 }, "every waiter must observe the builder's result") - } - - /// Concurrent calls for **different** keys must build in parallel, not - /// serialize behind one another. Verified by rendezvous — every build - /// blocks until the other has entered its closure — on threads of the - /// test's own: with the lock held across the build the second build - /// could never enter, and the timed wait below turns that into a failure. - @Test func concurrentCallsForDifferentKeysRunInParallel() { - let cache = makeTestCache() - // Two keys, on dedicated threads rather than the global dispatch - // queue. The builds block until they meet, so each needs a thread of - // its own for the whole wait; under a saturated full-suite run the - // dispatch pool did not grant eight workers, and then not even two, - // within the 30 s timeout (2026-09-28), which read as the - // serialization failure this test exists to catch. A `Thread` exists - // the moment it is started, whatever the pool is doing. - let keyCount = 2 - - // Deterministic parallelism proof instead of a wall-clock heuristic - // (which flaked under CPU saturation): every build blocks until all - // `keyCount` builds have entered their closure. If `resolve` - // serialized distinct keys — e.g. by holding the cache lock across - // the build — the first build would wait forever for peers that can - // never start, and the generous timeout below turns that into a - // failure rather than a hang. - let enteredBuild = DispatchSemaphore(value: 0) - let proceedWithBuild = DispatchSemaphore(value: 0) - let buildFinished = DispatchSemaphore(value: 0) - let everyBuildEntered = OSAllocatedUnfairLock(initialState: true) - - // The coordinator waits for every build to enter its closure, then - // releases them all at once. Its wait is *timed*, and it signals - // `proceedWithBuild` even after timing out: an untimed wait would park - // every build inside `resolve` for the rest of the process on failure, - // stranding libdispatch threads and leaving those keys permanently - // in-flight — a later test resolving them would then deadlock instead - // of seeing this test's clean failure. - Thread { - for _ in 0 ..< keyCount { - guard enteredBuild.wait(timeout: .now() + 30) == .success else { - everyBuildEntered.withLock { $0 = false } - break - } - } - for _ in 0 ..< keyCount { proceedWithBuild.signal() } - }.start() - - for index in 0 ..< keyCount { - Thread { - _ = cache.resolve(key: SharedCacheKey(opaque: index)) { - enteredBuild.signal() - proceedWithBuild.wait() - return index - } - buildFinished.signal() - }.start() - } - - var timedOut = false - for _ in 0 ..< keyCount where !timedOut { - timedOut = buildFinished.wait(timeout: .now() + 30) == .timedOut - } - #expect(!timedOut, "builds for distinct keys did not finish") - #expect(everyBuildEntered.withLock { $0 }, "builds for distinct keys did not run concurrently: some build never entered its closure while the others were inside theirs") - } - - /// Cache hits stay reentrant: a build for key A may itself call - /// `resolve` for key B without deadlocking. (The fix releases the cache - /// lock around the build call, so this is straightforward — but it's - /// the whole reason the lock-during-build design was a problem to begin - /// with, worth pinning.) - @Test func buildClosureMayResolveOtherKey() { - let cache = makeTestCache() - let result = cache.resolve(key: SharedCacheKey(opaque: "outer")) { - cache.resolve(key: SharedCacheKey(opaque: "inner")) { 5 }.map { $0 * 2 } - } - #expect(result == 10) - } - - /// A build closure that resolves the **same** key on its own thread - /// finds its own in-flight marker and would wait for a promise that only - /// its own return can fulfill. That used to trap on the non-reentrant - /// cache lock; after the promise rewrite it hung silently. The cache now - /// traps on purpose, with a message naming the key, so the hang can never - /// come back unnoticed. An exit test is the only way to pin a trap. - @Test func reentrantBuildForTheSameKeyTrapsInsteadOfHanging() async { - await #expect(processExitsWith: .failure) { - let cache = makeTestCache() - _ = cache.resolve(key: SharedCacheKey(opaque: "self")) { - cache.resolve(key: SharedCacheKey(opaque: "self")) { 1 } - } - } - } - - /// `register(_:for:)` installs a finished entry over whatever is there, - /// an in-flight build included: the builder, once it returns, must not - /// publish over the registered value — but it still hands its own result - /// to the callers that joined it, since their promise is still its own. - /// - /// The builder runs on a thread of its own for the reason - /// ``concurrentCallsForSameKeyShareOneBuild()`` gives. - @Test func registeringOverAnInFlightBuildWinsAndTheBuilderStillAnswersItsWaiters() { - let cache = makeTestCache() - let key = SharedCacheKey(opaque: "k") - let buildEnter = DispatchSemaphore(value: 0) - let buildRelease = DispatchSemaphore(value: 0) - let builderDone = DispatchSemaphore(value: 0) - let builderResult = OSAllocatedUnfairLock(initialState: nil) - - Thread { - let result = cache.resolve(key: key) { - buildEnter.signal() - buildRelease.wait() - return 1 - } - builderResult.withLock { $0 = result } - builderDone.signal() - }.start() - buildEnter.wait() - - cache.register(2, forKey: key) - #expect(cache.containsEntry(for: key), "a registered value is a finished entry at once, in-flight build or not") - - buildRelease.signal() - builderDone.wait() - - #expect(builderResult.withLock { $0 } == 1, "the builder answers with what it built") - let published = cache.resolve(key: key) { - Issue.record("the registered entry must be found, not rebuilt") - return -1 - } - #expect(published == 2, "the builder must not publish over the registered entry") - } -} - -/// Every build blocks inside its closure until `expectedCount` builds have -/// entered theirs, then all of them return together. Two builds for -/// distinct keys can only both be inside their closures at once if the cache -/// does not hold its lock across the build — so the rendezvous completing is -/// the parallelism proof, with no wall-clock involved. -/// -/// The wait is timed: on a scheduler that never gives the second build a -/// thread, an untimed wait would park the first build forever, hang the whole -/// test process and leave the key permanently in flight. On timeout every -/// waiter is released and ``everyBuildOverlapped`` reads `false`, which turns -/// the failure into an ordinary assertion. -private final class BuildRendezvous: @unchecked Sendable { - private let condition = NSCondition() - private let expectedCount: Int - private let timeout: TimeInterval - private var arrivedCount = 0 - private var isAbandoned = false - - init(expectedCount: Int, timeout: TimeInterval = 30) { - self.expectedCount = expectedCount - self.timeout = timeout - } - - func arriveAndWait() { - condition.lock() - defer { condition.unlock() } - arrivedCount += 1 - if arrivedCount >= expectedCount { - condition.broadcast() - return - } - let deadline = Date(timeIntervalSinceNow: timeout) - while arrivedCount < expectedCount, !isAbandoned { - if !condition.wait(until: deadline) { - isAbandoned = true - condition.broadcast() - } - } - } - - /// `true` only when every expected build entered its closure while the - /// earlier arrivals were still blocked inside theirs. - var everyBuildOverlapped: Bool { - condition.lock() - defer { condition.unlock() } - return !isAbandoned && arrivedCount == expectedCount - } -} - -/// The cache under test. `SharedCache.init(evictionGroup:registry:)` is -/// `package`-visible and constructs a usable cache without any Mach-O -/// scaffolding, because every entry point that takes a -/// `MachORepresentableWithCache` delegates to `resolve(key:build:)`. -private typealias TestCache = SharedCache - -/// A cache registered with a registry of its own, so a test's caches never -/// take part in the process-wide registry's eviction sweeps. -private func makeTestCache() -> TestCache { - SharedCache(evictionGroup: SharedCacheEvictionGroup("test.cache"), registry: SharedCacheRegistry()) -} - -/// Mirror of ``SharedCacheResolveTests`` driven through Swift Concurrency -/// primitives (`TaskGroup`, `AsyncStream`) instead of GCD. `resolve` itself -/// is a sync function — calling it from a `Task` body still blocks the -/// cooperative thread pool while the promise's `wait()` is held, but the -/// cache contract (one build per key, parallelism across keys, reentrancy) -/// must hold regardless of how callers spawned the work. -@Suite("SharedCache.resolve under Swift Concurrency") -struct SharedCacheResolveSwiftConcurrencyTests { - @Test func sameKeyDedupViaTaskGroup() async { - let cache = makeTestCache() - let buildCount = OSAllocatedUnfairLock(initialState: 0) - let waiterCount = 16 - - // One-shot signal: the first task yields when it has entered the - // build closure (i.e. the in-flight marker is installed). Spawning - // waiters before this point would race the marker install and could - // false-pass the test. - let (buildEnteredStream, buildEnteredContinuation) = - AsyncStream.makeStream() - - await withTaskGroup(of: Int?.self) { group in - group.addTask { - cache.resolve(key: SharedCacheKey(opaque: "shared")) { - buildCount.withLock { $0 += 1 } - buildEnteredContinuation.yield() - buildEnteredContinuation.finish() - // Stay inside the build long enough for the spawned - // waiter tasks to attach to the in-flight promise. - // Sync sleep is required: the build closure is sync, - // and `await Task.sleep` would compile-error here. - Thread.sleep(forTimeInterval: 0.2) - return 42 - } - } - - // Wait until the builder has entered `resolve` (deterministic). - var iterator = buildEnteredStream.makeAsyncIterator() - _ = await iterator.next() - - for _ in 0 ..< waiterCount { - group.addTask { - cache.resolve(key: SharedCacheKey(opaque: "shared")) { - Issue.record("waiter ran build instead of joining the in-flight promise") - return -1 - } - } - } - - var values: [Int?] = [] - for await result in group { - values.append(result) - } - - #expect(buildCount.withLock { $0 } == 1, - "build must run exactly once for the shared key") - #expect(values.count == waiterCount + 1) - #expect(values.allSatisfy { $0 == 42 }, - "every Task must observe the builder's result") - } - } - - /// Builds for distinct keys spawned as TaskGroup children must overlap. - /// Proven by rendezvous rather than by wall-clock: each build blocks - /// inside its closure until the other has entered too, which can only - /// happen if the cache releases its lock around the build. The earlier - /// form timed 8 sleeping builds against half the serial ceiling, and - /// failed whenever a loaded full-suite run starved the cooperative pool. - /// - /// Two builds, not eight: every build blocks a cooperative-pool thread - /// while it waits, and the pool is only as wide as the core count and is - /// shared with every other test in the process. Two is the smallest - /// count that proves overlap and the largest that cannot starve itself. - @Test func differentKeysParallelViaTaskGroup() async { - let cache = makeTestCache() - let keyCount = 2 - let rendezvous = BuildRendezvous(expectedCount: keyCount) - - var results: [Int?] = [] - await withTaskGroup(of: Int?.self) { group in - for index in 0 ..< keyCount { - group.addTask { - cache.resolve(key: SharedCacheKey(opaque: index)) { - rendezvous.arriveAndWait() - return index - } - } - } - for await result in group { - results.append(result) - } - } - - #expect(results.compactMap { $0 }.sorted() == Array(0 ..< keyCount)) - #expect(rendezvous.everyBuildOverlapped, - "builds for distinct keys did not overlap: the second build never entered its closure while the first was still inside its own") - } - - /// async-let variant of the rendezvous above: the structured-concurrency - /// `async let` form must give distinct keys the same overlap that the - /// TaskGroup form does. - @Test func differentKeysParallelViaAsyncLet() async { - let cache = makeTestCache() - let rendezvous = BuildRendezvous(expectedCount: 2) - - async let first = Task.detached { - cache.resolve(key: SharedCacheKey(opaque: "a")) { - rendezvous.arriveAndWait() - return 1 - } - }.value - async let second = Task.detached { - cache.resolve(key: SharedCacheKey(opaque: "b")) { - rendezvous.arriveAndWait() - return 2 - } - }.value - - let results = await [first, second] - - #expect(results == [1, 2]) - #expect(rendezvous.everyBuildOverlapped, - "builds for distinct keys did not overlap: the second build never entered its closure while the first was still inside its own") - } - - /// Reentrancy through a Task: a build for one key spawns a child Task - /// that calls `resolve` for a different key, and the build waits for the - /// child's result. The fix's lock-free build path keeps this from - /// deadlocking even though both calls share the same cache. - /// - /// The outer build runs on a thread of its own, not in a Task: it blocks - /// until the child Task has run, and a child Task needs a cooperative - /// thread. Blocking one of those to wait for another is what froze the - /// whole test process on the 3-core CI runner (2026-09-29), where the - /// pool is three threads wide — see - /// `SharedCacheResolveTests.concurrentCallsForSameKeyShareOneBuild()`. - @Test func reentrancyFromTask() async { - let cache = makeTestCache() - let outerResult: Int? = await withCheckedContinuation { continuation in - Thread { - let result = cache.resolve(key: SharedCacheKey(opaque: "outer")) { - // Spawn a nested Task that resolves a different key. We can - // only block-wait it because the outer build closure is - // sync — `await` is not allowed here. - let inner = Task.detached { - cache.resolve(key: SharedCacheKey(opaque: "inner")) { 5 } - } - // `Task.value` is async, so we hop back through a Dispatch - // semaphore — proves reentrancy works regardless of how the - // caller chooses to bridge. - let semaphore = DispatchSemaphore(value: 0) - let result = OSAllocatedUnfairLock(initialState: nil) - Task { - let value = await inner.value - result.withLock { $0 = value } - semaphore.signal() - } - semaphore.wait() - let value = result.withLock { $0 } - return value.map { $0 * 2 } - } - continuation.resume(returning: result) - }.start() - } - #expect(outerResult == 10) - } - - /// Cancelling Tasks that are blocked inside `resolve.wait()` must not - /// corrupt cache state: the in-flight build still completes, the cache - /// still publishes the result, and a fresh post-cancellation caller - /// observes the cached value rather than re-running the build. - @Test func cancellingWaitersLeavesCacheIntact() async { - let cache = makeTestCache() - let buildCount = OSAllocatedUnfairLock(initialState: 0) - let (buildEnteredStream, buildEnteredContinuation) = - AsyncStream.makeStream() - - await withTaskGroup(of: Int?.self) { group in - // Builder: blocks long enough that we can spawn-and-cancel a - // herd of waiter tasks while it is still in flight. - group.addTask { - cache.resolve(key: SharedCacheKey(opaque: "k")) { - buildCount.withLock { $0 += 1 } - buildEnteredContinuation.yield() - buildEnteredContinuation.finish() - Thread.sleep(forTimeInterval: 0.15) - return 99 - } - } - - var iterator = buildEnteredStream.makeAsyncIterator() - _ = await iterator.next() - - // Spawn waiters and immediately cancel them. `resolve` doesn't - // observe Task cancellation (it's a sync function), so they - // still complete with the builder's result; we just verify that - // the cache is not poisoned by the cancellation. - for _ in 0 ..< 8 { - let task = Task.detached { - cache.resolve(key: SharedCacheKey(opaque: "k")) { - Issue.record("waiter ran build") - return -1 - } - } - task.cancel() - group.addTask { await task.value } - } - - for await _ in group {} - } - - #expect(buildCount.withLock { $0 } == 1, - "build must run exactly once even when waiter tasks are cancelled") - - // After the builder published, the cache should hold the result — - // a fresh caller must not trigger another build. - let post = cache.resolve(key: SharedCacheKey(opaque: "k")) { - Issue.record("post-cancellation caller ran build, cache was corrupted") - return -1 - } - #expect(post == 99) - } -} diff --git a/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift b/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift deleted file mode 100644 index b80b472a2..000000000 --- a/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift +++ /dev/null @@ -1,80 +0,0 @@ -import Foundation -@_spi(Support) import MachOKit -import MachOKitExtensions -import Testing -@testable import MachODependencies -import MachOFixtureSupport - -/// Where the archived-cache-gated suite below finds its cache. 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 ArchivedMacOS15CacheFixtures { - static let cachePath = DyldSharedCachePath.macOS_15_5 - static let swiftUICoreInstallPath = "/System/Library/Frameworks/SwiftUICore.framework/Versions/A/SwiftUICore" - static let foundationInstallPath = "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation" - static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.rawValue) } -} - -/// An image read out of a dyld shared cache is linked against the images of -/// that cache: dyld resolves its dependencies there and nowhere else. The -/// closure used to look only through the search paths it was handed, whose -/// default is the running system's cache, so an image of an archived macOS -/// 15.5 cache was laid out against the host's Foundation — where `URL` has a -/// different size. -@Suite(.enabled(if: ArchivedMacOS15CacheFixtures.hasCache)) -struct CacheRootDependencyClosureTests { - /// How the caller opened the cache the root is read from. - enum CacheOpening: String, CaseIterable, CustomTestStringConvertible { - /// The cache and its sub-caches, as `swift-section --dyld-shared-cache` opens it. - case fullCache - /// The main cache file alone. - case mainCacheFile - - var testDescription: String { rawValue } - - func swiftUICore() throws -> MachOFile { - let path = ArchivedMacOS15CacheFixtures.cachePath - let image: MachOFile? = switch self { - case .fullCache: try FullDyldCache(path: path).machOFile(by: .path(ArchivedMacOS15CacheFixtures.swiftUICoreInstallPath)) - case .mainCacheFile: try DyldCache(path: path).machOFile(by: .path(ArchivedMacOS15CacheFixtures.swiftUICoreInstallPath)) - } - return try #require(image, "the macOS 15.5 cache has no SwiftUICore") - } - } - - private static func uuid(of image: MachOFile) -> UUID? { - image.loadCommands.info(of: LoadCommand.uuid)?.uuid - } - - @Test("A cache image's dependencies come from its own cache, not the host's", arguments: CacheOpening.allCases) - func dependenciesComeFromTheRootsOwnCache(opening: CacheOpening) throws { - let archivedCache = try FullDyldCache(path: ArchivedMacOS15CacheFixtures.cachePath) - let archivedFoundation = try #require(archivedCache.machOFile(by: .path(ArchivedMacOS15CacheFixtures.foundationInstallPath))) - let archivedFoundationUUID = try #require(Self.uuid(of: archivedFoundation)) - // The premise: the host's Foundation is another build, so a closure - // that resolved there would be told apart. - let hostCache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache") - let hostFoundation = try #require(hostCache.machOFile(by: .path(ArchivedMacOS15CacheFixtures.foundationInstallPath))) - try #require(Self.uuid(of: hostFoundation) != archivedFoundationUUID) - - let root = try opening.swiftUICore() - let closure = DependencyClosure(root: root, traversal: .direct) - let foundation = try #require(closure.images.first { $0.imagePath == ArchivedMacOS15CacheFixtures.foundationInstallPath }) - #expect(Self.uuid(of: foundation) == archivedFoundationUUID) - } - - /// The root's own cache is searched as the instance the root was read - /// from: a fresh opening maps every file of the cache again. - @Test("The root's cache is searched without being opened again") - func rootCacheIsNotOpenedAgain() throws { - let root = try CacheOpening.fullCache.swiftUICore() - let rootCache = try #require(root._cachedFullCache) - let closure = DependencyClosure( - root: root, - searchPaths: [.dyldSharedCache(path: ArchivedMacOS15CacheFixtures.cachePath.rawValue), .systemDyldSharedCache], - traversal: .direct - ) - let foundation = try #require(closure.images.first { $0.imagePath == ArchivedMacOS15CacheFixtures.foundationInstallPath }) - #expect(foundation._cachedFullCache === rootCache) - } -} diff --git a/Tests/MachODependenciesTests/DependencyLoadNameTests.swift b/Tests/MachODependenciesTests/DependencyLoadNameTests.swift deleted file mode 100644 index 4909aa114..000000000 --- a/Tests/MachODependenciesTests/DependencyLoadNameTests.swift +++ /dev/null @@ -1,39 +0,0 @@ -import Foundation -import MachOKit -import Testing -@testable import MachODependencies - -/// Pins the load-name → bare-image-name rule. It is a contract with MachOKit, -/// not a convenience: `MachOImage(name:)` compares the *same* reduction of -/// every mapped image's path, so any drift here silently turns the in-process -/// locator into a no-op (which is exactly how `SwiftInterfaceBuilderDependencies`'s -/// image initializer resolved nothing for its whole life — it handed the raw -/// load path to a bare-name lookup). -@Suite -struct DependencyLoadNameTests { - @Test(arguments: [ - ("@rpath/SymbolTestsHelper.framework/Versions/A/SymbolTestsHelper", "SymbolTestsHelper"), - ("/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation", "Foundation"), - ("/usr/lib/swift/libswiftCore.dylib", "libswiftCore"), - // The FIRST extension component is stripped, not the last — the rule - // MachOKit applies, so `libobjc.A.dylib` keys as `libobjc`. - ("/usr/lib/libobjc.A.dylib", "libobjc"), - ("libc++.1.dylib", "libc++"), - ("Foundation", "Foundation"), - ("", ""), - ]) - func bareImageNameStripsDirectoriesAndTheFirstExtension(loadName: String, expectedBareImageName: String) { - #expect(DependencyLoadName.bareImageName(of: loadName) == expectedBareImageName) - } - - /// The reduction must agree with `MachOImage(name:)` on a real mapped - /// image: the stdlib is loaded in every Swift process, so its absolute - /// load path — never matched raw — must resolve once normalized. - @Test func bareImageNameIsWhatMachOImageLookupMatches() { - let loadName = "/usr/lib/swift/libswiftCore.dylib" - #expect(MachOImage(name: loadName) == nil, "the raw load path must NOT match — that is the trap this rule exists for") - let image = MachOImage(name: DependencyLoadName.bareImageName(of: loadName)) - #expect(image != nil) - #expect(image?.imagePath == loadName) - } -} diff --git a/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift b/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift deleted file mode 100644 index d21ffedfd..000000000 --- a/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift +++ /dev/null @@ -1,142 +0,0 @@ -import Foundation -@_spi(Support) import MachOKit -import MachOKitExtensions -import Testing -@testable import MachODependencies - -/// Pins the two-step lookup of `FileDependencyLocator` against the host's own -/// dyld shared cache: exact install path first, ranked bare name second. -/// -/// The ranking matters on macOS specifically. The macOS cache carries the Mac -/// Catalyst build of SwiftUI under `/System/iOSSupport` next to the native -/// framework, so a first-writer-wins bare-name index (the pre-unification -/// SwiftLayout locator) resolved whichever the cache enumerated first. -@Suite -struct FileDependencyLocatorTests { - private static let nativeSwiftUIPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" - private static let catalystSwiftUIPath = "/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" - - private func hostLocator() -> FileDependencyLocator? { - guard FullDyldCache.cachedHost != nil else { - print("skipped: no host dyld shared cache") - return nil - } - return FileDependencyLocator(searchPaths: [.systemDyldSharedCache]) - } - - @Test func exactInstallPathIsAnsweredVerbatim() throws { - guard let locator = hostLocator() else { return } - let native = try #require(locator.locate(loadName: Self.nativeSwiftUIPath)) - #expect(native.imagePath == Self.nativeSwiftUIPath) - - // The Catalyst build shares SwiftUI's bare name; asked for by exact - // path it must come back as itself, never as the native winner. - if let catalyst = locator.locate(loadName: Self.catalystSwiftUIPath) { - #expect(catalyst.imagePath == Self.catalystSwiftUIPath) - } else { - print("note: this host cache carries no Catalyst SwiftUI; exact-path half of the check skipped") - } - } - - @Test func bareNameFallbackPrefersTheNativeCanonicalFramework() throws { - guard let locator = hostLocator() else { return } - let resolved = try #require(locator.locate(loadName: "@rpath/SwiftUI.framework/SwiftUI")) - #expect(resolved.imagePath == Self.nativeSwiftUIPath) - #expect(!resolved.imagePath.hasPrefix("/System/iOSSupport")) - } - - @Test func bareNameFallbackResolvesAbsolutePathsTheCacheDoesNotSpell() throws { - guard let locator = hostLocator() else { return } - // A plausible load name whose exact path is not in the cache (no - // `Versions/A`), so only the bare-name step can answer. - let resolved = try #require(locator.locate(loadName: "/System/Library/Frameworks/Foundation.framework/Foundation")) - #expect(DependencyLoadName.bareImageName(of: resolved.imagePath) == "Foundation") - } - - // MARK: - Platform guard - - /// The platforms come from `LC_BUILD_VERSION`: the native SwiftUI is a - /// macOS build (zippered ones also declare Mac Catalyst), the copy under - /// `/System/iOSSupport` a Mac Catalyst one and nothing else. - @Test func platformsAreReadFromTheBuildVersionCommands() throws { - guard let locator = hostLocator() else { return } - let native = try #require(locator.locate(loadName: Self.nativeSwiftUIPath)) - #expect(DependencyPlatforms.platforms(of: native).contains(.macOS)) - if let catalyst = locator.locate(loadName: Self.catalystSwiftUIPath) { - let platforms = DependencyPlatforms.platforms(of: catalyst) - #expect(platforms == [.macCatalyst]) - } else { - print("note: this host cache carries no Catalyst SwiftUI; the Catalyst half of the check skipped") - } - #expect(DependencyPlatforms.areCompatible([.macOS], [.macOS, .macCatalyst])) - #expect(!DependencyPlatforms.areCompatible([.iOSSimulator], [.macCatalyst])) - #expect(!DependencyPlatforms.areCompatible([.iOSSimulator], [.iOS])) - #expect(DependencyPlatforms.areCompatible([], [.iOS]), "a root declaring no platform accepts every image") - #expect(DependencyPlatforms.areCompatible([.iOS], []), "an image declaring no platform is never rejected") - } - - /// An iOS-simulator root's `UIKit` must not resolve to the macOS cache's - /// Mac Catalyst UIKit: same class names, another platform's method - /// tables and instance sizes. Without the guard the bare-name fallback - /// handed it back, since no native build exists to outrank it. - @Test func cacheImagesOfAnotherPlatformAreNotCandidates() throws { - guard FullDyldCache.cachedHost != nil else { - print("skipped: no host dyld shared cache") - return - } - let uiKitLoadName = "/System/Library/Frameworks/UIKit.framework/UIKit" - let unguarded = FileDependencyLocator(searchPaths: [.systemDyldSharedCache]) - guard let catalystUIKit = unguarded.locate(loadName: uiKitLoadName) else { - print("note: this host cache carries no Catalyst UIKit; guard check skipped") - return - } - #expect(catalystUIKit.imagePath.hasPrefix("/System/iOSSupport")) - - let simulatorRoot = FileDependencyLocator(searchPaths: [.systemDyldSharedCache], platforms: [.iOSSimulator]) - #expect(simulatorRoot.locate(loadName: uiKitLoadName) == nil) - #expect(simulatorRoot.locate(loadName: "/usr/lib/libobjc.A.dylib") == nil, "an exact install path is rejected on platform too") - - let macOSRoot = FileDependencyLocator(searchPaths: [.systemDyldSharedCache], platforms: [.macOS]) - #expect(macOSRoot.locate(loadName: Self.nativeSwiftUIPath)?.imagePath == Self.nativeSwiftUIPath) - #expect(macOSRoot.locate(loadName: "/usr/lib/libobjc.A.dylib") != nil) - // A zippered root shares a platform with the Catalyst images and - // may take them; a plain macOS root does not. - #expect(macOSRoot.locate(loadName: uiKitLoadName) == nil) - let zipperedRoot = FileDependencyLocator(searchPaths: [.systemDyldSharedCache], platforms: [.macOS, .macCatalyst]) - #expect(zipperedRoot.locate(loadName: uiKitLoadName)?.imagePath == catalystUIKit.imagePath) - } - - /// `FullDyldCache.host` opens and maps every file of the system's cache — - /// 82 on macOS 27 — each time it is read, and a locator is built for every - /// root: an evolution over 51 archived caches held 51 copies open at once. - @Test func locatorsShareOneOpeningOfTheSystemCache() throws { - guard let firstLocator = hostLocator(), let secondLocator = hostLocator() else { return } - let foundationPath = "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation" - let firstFoundation = try #require(firstLocator.locate(loadName: foundationPath)) - let secondFoundation = try #require(secondLocator.locate(loadName: foundationPath)) - let firstSystemCache = try #require(firstFoundation.cache?._cachedFullCache) - let secondSystemCache = try #require(secondFoundation.cache?._cachedFullCache) - - #expect(firstSystemCache === secondSystemCache) - } - - @Test func unknownNameResolvesToNil() { - guard let locator = hostLocator() else { return } - #expect(locator.locate(loadName: "@rpath/NoSuchLibrary.framework/NoSuchLibrary") == nil) - #expect(locator.locate(loadName: "") == nil) - } - - @Test func unopenableCachePathIsRecorded() { - let missingPath = "/nonexistent/dyld_shared_cache_arm64e" - let locator = FileDependencyLocator(searchPaths: [.dyldSharedCache(path: missingPath)]) - #expect(locator.loadFailures.count == 1) - #expect(locator.loadFailures.first?.searchPath == .dyldSharedCache(path: missingPath)) - #expect(locator.locate(loadName: "/usr/lib/swift/libswiftCore.dylib") == nil) - } - - @Test func searchPathDescriptionsAreStable() { - #expect(DependencySearchPath.machOFile(path: "/a").description == "machOFile(/a)") - #expect(DependencySearchPath.dyldSharedCache(path: "/b").description == "dyldSharedCache(/b)") - #expect(DependencySearchPath.systemDyldSharedCache.description == "systemDyldSharedCache") - } -} diff --git a/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift b/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift deleted file mode 100644 index 5d15f24fe..000000000 --- a/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -#if canImport(Darwin) -import Darwin -#endif -import Foundation -import MachOKit -import Testing -@testable import MachODependencies - -/// `InProcessDependencyLocator` answers from one pass over the images dyld -/// has mapped (evolution proposal `faster-lazy-definition-indexing`) and must -/// answer exactly what `MachOImage(name:)`, the per-lookup scan it replaced, -/// answers: the first mapped image carrying the bare name, or nothing. -/// -/// Every mapped image's own path is asked for — absolute paths of system -/// frameworks, Swift runtime dylibs and the test bundle alike, including -/// names several mapped images share — together with load-name spellings -/// that must not resolve. The paths are read before the locator is made: -/// other suites map fixtures while this one runs, and an image mapped after -/// the locator was made is, by design, not one it knows. -@Suite -struct InProcessDependencyLocatorTests { - @Test func answersLikeTheNameLookup() throws { - var loadNames: Set = [ - "/usr/lib/libNoSuchImage.dylib", - "@rpath/NoSuchFramework.framework/Versions/A/NoSuchFramework", - "", - ] - #if canImport(Darwin) - for index in 0 ..< _dyld_image_count() { - if let pathC = _dyld_get_image_name(index) { - loadNames.insert(String(cString: pathC)) - } - } - #endif - #expect(loadNames.count > 50) - let locator = InProcessDependencyLocator() - - var mismatchCount = 0 - for loadName in loadNames.sorted() { - let bareImageName = DependencyLoadName.bareImageName(of: loadName) - let expectedImage = bareImageName.isEmpty ? nil : MachOImage(name: bareImageName) - let locatedImage = locator.locate(loadName: loadName) - if locatedImage?.ptr != expectedImage?.ptr { - mismatchCount += 1 - Issue.record("\(loadName): located \(String(describing: locatedImage?.ptr)), MachOImage(name:) \(String(describing: expectedImage?.ptr))") - } - } - #expect(mismatchCount == 0) - } -} diff --git a/Tests/MachODependenciesTests/SystemRootSearchPathTests.swift b/Tests/MachODependenciesTests/SystemRootSearchPathTests.swift deleted file mode 100644 index 8608ce729..000000000 --- a/Tests/MachODependenciesTests/SystemRootSearchPathTests.swift +++ /dev/null @@ -1,117 +0,0 @@ -import Foundation -import MachOKit -import MachOFixtureSupport -import Testing -@testable import MachODependencies - -/// `DependencySearchPath.systemRoot` and the inference of search paths from -/// a root binary's own location. -/// -/// A system root is a directory tree an absolute load name is resolved -/// under — an iOS 26 or earlier simulator runtime's `RuntimeRoot`, where -/// `/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore` is a file. -/// From iOS 27 beta 3 on the runtime ships a `dyld_sim_shared_cache_arm64` -/// instead, so inference looks for a cache first and takes the root only -/// when the file's path ends with its own install name. -@Suite -struct SystemRootSearchPathTests { - private func temporaryDirectory(named name: String) throws -> URL { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - return directory - } - - /// The fixture framework, reached through the path it was loaded from. - private func fixtureURL() throws -> URL { - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let machOFile): - return machOFile.url - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first).url - } - } - - @Test func aSystemRootResolvesAbsoluteLoadNamesUnderIt() throws { - let root = try temporaryDirectory(named: "SystemRoot") - defer { try? FileManager.default.removeItem(at: root) } - let loadName = "/System/Library/Frameworks/Probe.framework/Probe" - let probeURL = root.appendingPathComponent(String(loadName.dropFirst())) - try FileManager.default.createDirectory(at: probeURL.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: probeURL, withDestinationURL: fixtureURL()) - - let locator = FileDependencyLocator(searchPaths: [.systemRoot(path: root.path)]) - #expect(locator.loadFailures.isEmpty) - let located = try #require(locator.locate(loadName: loadName)) - #expect(located.url.path == probeURL.path) - // Only absolute load names are joined onto the root. - #expect(locator.locate(loadName: "@rpath/Probe.framework/Probe") == nil) - #expect(locator.locate(loadName: "/System/Library/Frameworks/Missing.framework/Missing") == nil) - } - - @Test func aSystemRootThatIsNotADirectoryIsAReportedFailure() throws { - let root = try temporaryDirectory(named: "SystemRootFile") - defer { try? FileManager.default.removeItem(at: root) } - let file = root.appendingPathComponent("not-a-directory") - try Data().write(to: file) - - let locator = FileDependencyLocator(searchPaths: [.systemRoot(path: file.path)]) - #expect(locator.loadFailures.count == 1) - #expect(locator.loadFailures.first?.error as? DependencySearchPathError == .systemRootIsNotADirectory(path: file.path)) - } - - @Test func inferenceTakesARuntimeRootsOwnCacheForTheRootsArchitecture() throws { - let runtimeRoot = try temporaryDirectory(named: "RuntimeRoot") - defer { try? FileManager.default.removeItem(at: runtimeRoot) } - let cacheDirectory = runtimeRoot.appendingPathComponent("System/Library/Caches/com.apple.dyld") - try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true) - for fileName in ["dyld_sim_shared_cache_arm64", "dyld_sim_shared_cache_arm64.01", "dyld_sim_shared_cache_arm64.map", "dyld_sim_shared_cache_arm64.atlas", "dyld_sim_shared_cache_x86_64"] { - try Data().write(to: cacheDirectory.appendingPathComponent(fileName)) - } - let rootFile = runtimeRoot.appendingPathComponent("usr/lib/libProbe.dylib") - - let forArm64 = DependencySearchPath.inferred(forRootFileAt: rootFile, installName: "/usr/lib/libProbe.dylib", architectureName: "arm64") - #expect(forArm64 == [.dyldSharedCache(path: cacheDirectory.appendingPathComponent("dyld_sim_shared_cache_arm64").path)]) - - let forAnyArchitecture = DependencySearchPath.inferred(forRootFileAt: rootFile, installName: "/usr/lib/libProbe.dylib", architectureName: nil) - #expect(forAnyArchitecture == [ - .dyldSharedCache(path: cacheDirectory.appendingPathComponent("dyld_sim_shared_cache_arm64").path), - .dyldSharedCache(path: cacheDirectory.appendingPathComponent("dyld_sim_shared_cache_x86_64").path), - ]) - } - - @Test func inferenceFallsBackToTheInstallNamePrefix() throws { - let root = try temporaryDirectory(named: "FrameworkRoot") - defer { try? FileManager.default.removeItem(at: root) } - let installName = "/System/Library/Frameworks/Probe.framework/Probe" - let rootFile = root.appendingPathComponent(String(installName.dropFirst())) - - #expect(DependencySearchPath.inferred(forRootFileAt: rootFile, installName: installName, architectureName: "arm64") == [.systemRoot(path: root.path)]) - // A relative install name says nothing about the tree the file sits in. - #expect(DependencySearchPath.inferred(forRootFileAt: rootFile, installName: "@rpath/Probe.framework/Probe", architectureName: "arm64").isEmpty) - // A file whose path does not end with its install name is not a system tree either. - #expect(DependencySearchPath.inferred(forRootFileAt: root.appendingPathComponent("Probe"), installName: installName, architectureName: "arm64").isEmpty) - } - - @Test func onlyAMainCacheFileNameCountsAsACache() { - #expect(DependencySearchPath.isMainCacheFileName("dyld_shared_cache_arm64e", architectureName: nil)) - #expect(DependencySearchPath.isMainCacheFileName("dyld_sim_shared_cache_arm64", architectureName: "arm64")) - #expect(!DependencySearchPath.isMainCacheFileName("dyld_sim_shared_cache_arm64", architectureName: "arm64e")) - #expect(!DependencySearchPath.isMainCacheFileName("dyld_shared_cache_arm64e.01", architectureName: nil)) - #expect(!DependencySearchPath.isMainCacheFileName("dyld_shared_cache_arm64e.map", architectureName: nil)) - #expect(!DependencySearchPath.isMainCacheFileName("dyld_shared_cache_", architectureName: nil)) - #expect(!DependencySearchPath.isMainCacheFileName("libswiftCore.dylib", architectureName: nil)) - } - - @Test func classifyingAPathPicksTheKindByItsShape() throws { - let directory = try temporaryDirectory(named: "Classify") - defer { try? FileManager.default.removeItem(at: directory) } - let cacheFile = directory.appendingPathComponent("dyld_sim_shared_cache_arm64") - try Data().write(to: cacheFile) - let otherFile = directory.appendingPathComponent("libProbe.dylib") - try Data().write(to: otherFile) - - #expect(DependencySearchPath(classifyingPath: directory.path) == .systemRoot(path: directory.path)) - #expect(DependencySearchPath(classifyingPath: cacheFile.path) == .dyldSharedCache(path: cacheFile.path)) - #expect(DependencySearchPath(classifyingPath: otherFile.path) == .machOFile(path: otherFile.path)) - } -} diff --git a/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift b/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift deleted file mode 100644 index 95a10caa3..000000000 --- a/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift +++ /dev/null @@ -1,130 +0,0 @@ -import Foundation -import Testing -import MachOKit -@testable import MachOReading -import MachOFixtureSupport - -/// A file's mapping and handle are created on its first read and shared by -/// every read after it. Several readers can make that first read at once: -/// `diff` and `evolution` prepare their inputs concurrently, and each input's -/// dependency lookup reads the host's dyld cache through sub-cache instances -/// every reader shares — a `FullDyldCache` hands the same ones to all its -/// images, and `FullDyldCache.cachedHost` is opened once per process. Every -/// accessor must hand all of them one object. Created unlocked, each racing -/// reader opened the file again and stored its own over the others'. -@Suite -struct ConcurrentFileMappingTests { - /// How many readers make the first read of one instance together. - private static let readerCount = 32 - - /// How many fresh instances each test races on: one round can miss the - /// overlap, which a wrong accessor shows in nearly every round. - private static let roundCount = 20 - - private static var isHostDyldCacheAvailable: Bool { - FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) - } - - @Test func concurrentFirstReadsOfAFileShareOneMapping() throws { - for _ in 0 ..< Self.roundCount { - let machOFile = try Self.freshFixtureFile() - let distinctCount = Self.distinctObjectCount { machOFile.fileIO } - #expect(distinctCount == 1, "\(distinctCount) mappings of one file") - } - } - - @Test func concurrentFirstReadsOfAFileShareOneHandle() throws { - for _ in 0 ..< Self.roundCount { - let machOFile = try Self.freshFixtureFile() - let distinctCount = Self.distinctObjectCount { machOFile.fileHandle } - #expect(distinctCount == 1, "\(distinctCount) handles of one file") - } - } - - @Test(.enabled(if: isHostDyldCacheAvailable)) - func concurrentFirstReadsOfADyldCacheShareOneMapping() throws { - for _ in 0 ..< Self.roundCount { - let dyldCache = try DyldCache(path: .current) - let distinctCount = Self.distinctObjectCount { dyldCache.fileIO } - #expect(distinctCount == 1, "\(distinctCount) mappings of one cache file") - } - } - - @Test(.enabled(if: isHostDyldCacheAvailable)) - func concurrentFirstReadsOfADyldCacheShareOneHandle() throws { - for _ in 0 ..< Self.roundCount { - let dyldCache = try DyldCache(path: .current) - let distinctCount = Self.distinctObjectCount { dyldCache.fileHandle } - #expect(distinctCount == 1, "\(distinctCount) handles of one cache file") - } - } - - /// A new instance each time: the accessor under test must not have run on - /// it yet. - private static func freshFixtureFile() throws -> MachOFile { - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } - } - - /// How many distinct objects `read` hands `readerCount` readers released - /// together. - /// - /// The readers are threads of the test's own, not the global dispatch - /// queue: this body blocks a cooperative thread until they finish (the - /// same arrangement as `SharedCacheResolveTests`). Each one is parked on - /// the start signal before any is let go, so the first reads overlap as - /// closely as threads allow. - private static func distinctObjectCount(returnedBy read: @escaping () -> AnyObject) -> Int { - let reader = UncheckedReader(read: read) - let handedObjects = HandedObjects() - let readersReady = DispatchGroup() - let readersFinished = DispatchGroup() - let startSignal = DispatchSemaphore(value: 0) - for _ in 0 ..< readerCount { - readersReady.enter() - readersFinished.enter() - Thread { - readersReady.leave() - startSignal.wait() - handedObjects.append(reader.read()) - readersFinished.leave() - }.start() - } - readersReady.wait() - for _ in 0 ..< readerCount { - startSignal.signal() - } - readersFinished.wait() - return handedObjects.distinctCount - } -} - -/// Carries a read of a non-`Sendable` file onto the reader threads. Racing on -/// that file is what the test does, so the box only quiets the checker. -private struct UncheckedReader: @unchecked Sendable { - let read: () -> AnyObject -} - -/// The objects the readers were handed, kept alive until they are counted: -/// a mapping replaced and freed mid-round could have its address reused by -/// the next one, and two mappings would count as one. -private final class HandedObjects: @unchecked Sendable { - private let lock = NSLock() - private var objects: [AnyObject] = [] - - func append(_ object: AnyObject) { - lock.lock() - defer { lock.unlock() } - objects.append(object) - } - - var distinctCount: Int { - lock.lock() - defer { lock.unlock() } - return Set(objects.map(ObjectIdentifier.init)).count - } -} diff --git a/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift b/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift deleted file mode 100644 index a8c673abb..000000000 --- a/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift +++ /dev/null @@ -1,56 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -@testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport - -/// The Mach-O and pointer reading forms stay for one release as deprecated -/// forwarders (evolution proposal `reading-context-migration`). They hold no -/// logic of their own, so each test only checks that an old form lands on -/// the context form it should: a mismatch means a forwarder picked the wrong -/// overload, context or reader. Delete this suite together with the -/// forwarders. -@Suite -final class DeprecatedReadingFormsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { - @available(*, deprecated, message: "Exercises the deprecated Mach-O reading forms.") - @Test func machOFormsAnswerWhatTheContextFormsAnswer() throws { - let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) - let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - - #expect(try fileDescriptor.name(in: machOFile) == fileDescriptor.name(in: fileContext)) - #expect(try imageDescriptor.name(in: machOImage) == imageDescriptor.name(in: imageContext)) - #expect(try fileDescriptor.mangledName(in: machOFile) == fileDescriptor.mangledName(in: fileContext)) - #expect(try fileDescriptor.fieldDescriptor(in: machOFile).offset == fileDescriptor.fieldDescriptor(in: fileContext).offset) - #expect(try Struct(descriptor: fileDescriptor, in: machOFile).descriptor.offset == Struct(descriptor: fileDescriptor, in: fileContext).descriptor.offset) - - let resolvedFromMachO = try ContextDescriptorWrapper.resolve(from: fileDescriptor.offset, in: machOFile) as ContextDescriptorWrapper - let resolvedFromContext = try ContextDescriptorWrapper.resolve(at: fileDescriptor.offset, in: fileContext) as ContextDescriptorWrapper - #expect(resolvedFromMachO.contextDescriptor.offset == resolvedFromContext.contextDescriptor.offset) - } - - @available(*, deprecated, message: "Exercises the deprecated pointer reading forms.") - @Test func pointerFormsAnswerWhatTheInProcessContextAnswers() throws { - let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - - #expect(try pointerDescriptor.name() == pointerDescriptor.name(in: inProcessContext)) - #expect(try pointerDescriptor.mangledName() == pointerDescriptor.mangledName(in: inProcessContext)) - #expect(try pointerDescriptor.fieldDescriptor().offset == pointerDescriptor.fieldDescriptor(in: inProcessContext).offset) - #expect(try Struct(descriptor: pointerDescriptor).descriptor.offset == Struct(descriptor: pointerDescriptor, in: inProcessContext).descriptor.offset) - } - - /// The pointer form of a symbol-or-element pointer used to trap on a - /// symbol; it now answers the symbol the way the other forms always did. - @available(*, deprecated, message: "Exercises the deprecated pointer reading forms.") - @Test func thePointerFormOfABoundSymbolAnswersTheSymbol() throws { - let symbol = Symbol(offset: 16, name: "$s4Main9StructureVMn") - let pointer = SymbolOrElementPointer.symbol(symbol) - guard case .symbol(let resolvedSymbol) = try pointer.resolve() else { - Issue.record("a bound symbol resolved to an element") - return - } - #expect(resolvedSymbol == symbol) - } -} diff --git a/Tests/MachOSwiftSectionTests/FileMappingTests.swift b/Tests/MachOSwiftSectionTests/FileMappingTests.swift new file mode 100644 index 000000000..ae739fa01 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/FileMappingTests.swift @@ -0,0 +1,79 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +import SwiftSectionFixtureSupport + +/// A `MachOFile` is read through the mapping MachOKit made when it opened the +/// file (`fileBytes`), which every value assembled from that opening shares +/// (evolution proposal `machofile-performance`). +/// +/// MachOKit hands out a new `DyldCache` for every image a `FullDyldCache` +/// enumerates, MachOKitExtensions another for every sub-cache an image's reads +/// cross into, and a dependency locator makes a `MachOFile` of its own for +/// every image it locates. Mapped once per instance, a cache file was mapped +/// again for each of them, and each mapping holds a descriptor: RuntimeViewer's +/// offline service, reading Dock.app against the system's cache, held 2,548 +/// descriptors on 85 cache files when the next open failed with `EMFILE` and +/// the accessor's `try!` stopped the process. The reading layer then kept one +/// mapping of its own per opening, made on a file's first read; it now reads +/// MachOKit's, so it maps nothing and holds no descriptor of its own. +/// +/// The reading layer itself moved to MachOKitExtensions, and with it the +/// tests of the mapping alone (one mapping shared by the readers of a cache +/// file, a removed file still read, a read past the end throwing). What stays +/// here reads Swift metadata through this package. +@Suite +struct FileMappingTests { + private static var isHostDyldCacheAvailable: Bool { + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + } + + /// More Swift images than an XPC service may hold descriptors: mapped per + /// image the read runs out of them, mapped per file it cannot (the host's + /// cache has fewer than a hundred files). + private static let imageCount = 400 + + /// The descriptor limit launchd starts an XPC service with. + private static let serviceDescriptorLimit: rlim_t = 256 + + @Test(.enabled(if: isHostDyldCacheAvailable)) + func readingManyImagesOfACacheStaysWithinAServiceDescriptorLimit() async { + await #expect(processExitsWith: .success) { + do { + try FileMappingTests.readSwiftImagesOfTheHostCacheUnderTheServiceDescriptorLimit() + } catch { + // A thrown error ends the child on a trap too; exiting keeps a + // read that failed apart from an accessor that stopped. + exit(EXIT_FAILURE) + } + } + } + + // MARK: - Exit test bodies + + /// Reads the type descriptors of `imageCount` Swift images of the host's + /// cache, all kept alive as a host's catalog keeps them, under the service + /// limit. The hard limit comes down too: the first use of `CFSocket` + /// raises the soft one by 2,304 within the hard one, which would hide the + /// exhaustion — it is how the offline service came to have 2,560. + static func readSwiftImagesOfTheHostCacheUnderTheServiceDescriptorLimit() throws { + var limit = rlimit(rlim_cur: serviceDescriptorLimit, rlim_max: serviceDescriptorLimit) + guard setrlimit(RLIMIT_NOFILE, &limit) == 0 else { + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EINVAL) + } + let cache = try FullDyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let swiftImages = Array( + cache.machOFiles() + .lazy + .filter { image in image.sections.contains { $0.sectionName == "__swift5_types" } } + .prefix(imageCount) + ) + guard swiftImages.count == imageCount else { + throw POSIXError(.ENOENT) + } + for image in swiftImages { + _ = try image.swift.typeContextDescriptors + } + } +} diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift index a2402da90..4ff2ef24f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AccessibleFunctionRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift index 75217ca68..2a92540ab 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnonymousContextDescriptorFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift index 46305bfda..d6ce2a62e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnonymousContextDescriptorProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift index 4efa52b6c..02b15b6bb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnonymousContextDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift index b547c700f..a147b3958 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnonymousContext` (the high-level wrapper /// around `AnonymousContextDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift index 3678c1c43..172b3554a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AssociatedTypeDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift index ea07af3d7..9e6539e46 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AssociatedTypeRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift index eb31296b0..02a0164f6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AssociatedType` (the high-level wrapper around /// `AssociatedTypeDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift index 951ae9d4a..089e852bf 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `BuiltinTypeDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift index bdc9d34a2..92c962445 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `BuiltinType` (the high-level wrapper around /// `BuiltinTypeDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift index 5124655bb..27371b800 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CaptureDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift index 648497f06..4b5a0d2a3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CaptureTypeRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift index 2611c12e8..810f4369c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataSourceRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift index ac70bb64f..383857a58 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptorFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift index 547b60f21..56a1660be 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptorKindSpecificFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift index 14e3031ad..a05f3496a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptorKind`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift index 20cb1b48f..3df35e1a5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptorProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift index e31d1f4ec..a64e5d332 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift index 26b9bcac9..948c02350 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextDescriptorWrapper`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift index 30c5341f3..527f81e43 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift index a099e9327..5d4f7ce9f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ContextWrapper`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift index b16600309..25ec4eb26 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `NamedContextDescriptorProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift b/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift index e4053985b..6c9308aa5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift @@ -1,6 +1,6 @@ import Foundation -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Public members of `Sources/ABI/MachOSwiftSection/Models/` that are intentionally /// not under cross-reader fixture coverage. Each entry MUST carry either a diff --git a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift index 87d0b1904..52fa77c5d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `DispatchClassMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift index 20640451f..87fa4fd6c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExistentialMetatypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift index 39daac8fb..cd1b7d76e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExistentialTypeFlags`. /// @@ -13,8 +13,8 @@ import MachOFixtureSupport /// `init(rawValue:)`, `numberOfWitnessTables` (0), /// `hasSuperclassConstraint` (false), `specialProtocol` (`.none`). /// -/// - `AnyObject.self` flags (`0x0`) — anchor `classConstraint` because -/// `Any.self`'s flags trap `UInt8(rawValue & 0x80000000)`. +/// - `AnyObject.self` flags (`0x0`) — anchor `classConstraint` (`.class`); +/// `Any.self` reading `.any` is pinned by `FlagWordDecodingTests`. @Suite final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "ExistentialTypeFlags" @@ -48,7 +48,7 @@ final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func classConstraint() async throws { // `AnyObject.self` flags decode to `classConstraint == .class`. - // `Any.self` flags would trap (UInt8 conversion overflow). + // `Any.self` reads `.any`; `FlagWordDecodingTests` pins that. let result = try usingInProcessOnly { context in try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyObjectExistential, in: context) .layout.flags.classConstraint.rawValue @@ -67,7 +67,7 @@ final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func specialProtocol() async throws { let result = try usingInProcessOnly { context in try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyExistential, in: context) - .layout.flags.specialProtocol.rawValue + .layout.flags.specialProtocol?.rawValue } #expect(result == ExistentialTypeFlagsBaseline.stdlibAnyExistential.specialProtocolRawValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift index 74463e800..eab4bce0c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExistentialTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift index 70f7c459d..23cd23a64 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtendedExistentialTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift index 14e32051f..5a8d1fffe 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtendedExistentialTypeShapeFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift index f5248c33f..f4392031e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtendedExistentialTypeShape`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift index 389516ce6..0551e479e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `NonUniqueExtendedExistentialTypeShape`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift index 1dddc56c6..bdf7179e1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtensionContextDescriptorProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift index 2951a8b4c..154c6d7d7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtensionContextDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift index a2a8ac5bf..cee55c329 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtensionContext` (the high-level wrapper /// around `ExtensionContextDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift index 0e2f996f7..87ca2c077 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FieldDescriptor`. /// @@ -80,6 +80,36 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ // MARK: - Derived var + /// The section is walked by size, so a wrong `actualSize` would desync + /// every later descriptor rather than fail locally. The walk over the + /// whole section is the real assertion here. + @Test func actualSize() async throws { + let genericDescriptors = try loadGenericStructFieldDescriptors() + let genericSize = try acrossAllReaders( + file: { genericDescriptors.file.actualSize }, + image: { genericDescriptors.image.actualSize } + ) + #expect(genericSize == FieldDescriptorBaseline.genericStructNonRequirement.actualSize) + + let structTestDescriptors = try loadStructTestFieldDescriptors() + let structTestSize = try acrossAllReaders( + file: { structTestDescriptors.file.actualSize }, + image: { structTestDescriptors.image.actualSize } + ) + #expect(structTestSize == FieldDescriptorBaseline.structTest.actualSize) + #expect(structTestSize == MemoryLayout.size) + + let descriptors = try BaselineFixturePicker.fieldDescriptors(in: machOFile) + #expect(descriptors.count == FieldDescriptorBaseline.descriptorCount) + for (earlier, later) in zip(descriptors, descriptors.dropFirst()) { + #expect(later.offset - earlier.offset == earlier.actualSize) + } + // The descriptors a type points at are among the ones the walk finds. + #expect(descriptors.contains { $0.offset == genericDescriptors.file.offset }) + #expect(descriptors.contains { $0.offset == structTestDescriptors.file.offset }) + #expect(try BaselineFixturePicker.fieldDescriptors(in: machOImage).count == descriptors.count) + } + @Test func kind() async throws { let descriptors = try loadGenericStructFieldDescriptors() let result = try acrossAllReaders( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift index cc9adb35c..3dc26ed71 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FieldRecordFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift index 93d53f3ca..aace65319 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FieldRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FixtureLoadingProbeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FixtureLoadingProbeTests.swift index d86be0305..ed62faa6f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FixtureLoadingProbeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FixtureLoadingProbeTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite final class FixtureLoadingProbeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift index 96f331938..4c37c8e7c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ForeignClassMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift index 1742e048a..a7109dea3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ForeignReferenceTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift index 536aee6bb..07ff7dfbd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FunctionTypeFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift index 45988099e..02278d74a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FunctionTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift index 52ac7a77b..3ece8a418 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AsyncFunctionPointer`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift index 622d4162e..23aeeeca0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CoroFunctionPointer`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift index 3b6cac3ae..186e03d34 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericContextDescriptorFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift index 8773d63b5..70419ae9e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericContextDescriptorHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift index 5e0cd1b47..6704677d1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TargetGenericContext` (the underlying generic /// struct behind both the `GenericContext` and `TypeGenericContext` @@ -370,15 +370,6 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) } - @Test func uniqueCurrentRequirementsInProcess() async throws { - let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.uniqueCurrentRequirements(in: inProcessContext).count }, - image: { contexts.image.uniqueCurrentRequirements(in: inProcessContext).count } - ) - #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) - } - // MARK: - Three-level-nested counter-examples (P0 regression guards) // // Every `current*` / `all*` / `parent*` derived var on `TargetGenericContext` diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift index 6d1273b62..8209b248e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericEnvironmentFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift index 902736177..ab0c5e089 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericEnvironment`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift index ae8e8b0ba..866b3b138 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericPackShapeDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift index ee4ce36d8..6ace24aaa 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericPackShapeHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift index 1a7592eab..2ed7e6a51 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericParamDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift index 84ae11ecf..b5b1632d6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericRequirementContent.InvertedProtocols`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift index b89c09ffd..80d8c4bf3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericRequirementDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift index 20afa5a16..6d14e0d38 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericRequirementFlags`. /// @@ -29,16 +29,16 @@ final class GenericRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixture @Test func kind() async throws { let protocolDefault = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.protocolDefault.rawValue) - #expect(protocolDefault.kind.rawValue == GenericRequirementFlagsBaseline.protocolDefault.kindRawValue) + #expect(protocolDefault.kind?.rawValue == GenericRequirementFlagsBaseline.protocolDefault.kindRawValue) let sameType = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.sameType.rawValue) - #expect(sameType.kind.rawValue == GenericRequirementFlagsBaseline.sameType.kindRawValue) + #expect(sameType.kind?.rawValue == GenericRequirementFlagsBaseline.sameType.kindRawValue) let layoutOnly = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.layoutOnly.rawValue) - #expect(layoutOnly.kind.rawValue == GenericRequirementFlagsBaseline.layoutOnly.kindRawValue) + #expect(layoutOnly.kind?.rawValue == GenericRequirementFlagsBaseline.layoutOnly.kindRawValue) let packWithKey = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.packWithKey.rawValue) - #expect(packWithKey.kind.rawValue == GenericRequirementFlagsBaseline.packWithKey.kindRawValue) + #expect(packWithKey.kind?.rawValue == GenericRequirementFlagsBaseline.packWithKey.kindRawValue) } @Test func isPackRequirement() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift index 6cef1395b..9e1858f32 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericRequirement`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift index 5a170a88b..23d8c2e6d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericValueDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift index 7b5b53466..d0c10ee51 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericValueHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift index e816324b5..785924a26 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericWitnessTable`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift index 91e704616..4f8e6e029 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericClassMetadataPattern`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift index 2acd05cfd..cd1094c8c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericMetadataPartialPattern`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift index a9092f7f3..9e617f360 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericMetadataPatternProtocol` — the members /// both pattern kinds share. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift index 3c6c8d3c3..610819016 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericValueMetadataPattern`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift index 107ff0b4a..bd7dfb8e0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ResilientClassMetadataPattern`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift index b228e4b11..444bb1037 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeGenericContextDescriptorHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift index a709cbe6b..9b76321d4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GenericBoxHeapMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift index 5b70fa727..7081a0f00 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `HeapLocalVariableMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift index 658831ddf..e4c57be04 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `KeyPathComponentHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift index 1348cf1f1..2cff7d2b0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `KeyPathComputedPropertyBody`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift index adaa82157..592364666 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `KeyPathStoredFieldOffset`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift index d39a7c3db..e1b553516 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `PropertyDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift index 064e47e38..87b42a278 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Static-vs-runtime invariant guard for fixture-based test coverage. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift index d2efe03b4..4c807e9f8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MangledName`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift index c811caf71..ad25f6021 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `BorrowTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift index cb7497f21..e2edefa1e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CanonicalSpecializedMetadataAccessorsListEntry`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift index 4335511aa..1f5a630e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CanonicalSpecializedMetadatasCachingOnceToken`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift index ffa6d1cbf..4493f7209 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CanonicalSpecializedMetadatasListCount`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift index 7092710c8..26a0db65f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `CanonicalSpecializedMetadatasListEntry`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift index cbd22afb2..ce3a4f1f9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FixedArrayTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift index cd295d2f7..26837d627 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FullMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift index bc78d8459..c7f7529a3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `HeapMetadataHeaderPrefix`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift index a6fad261d..0bd74276a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `HeapMetadataHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift index 423e1cd07..4b0349658 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeMetadataHeaderBase`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift index dda61dd4e..c4d176165 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeMetadataHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift index 4f05714ea..cb43f8f52 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeMetadataLayoutPrefix`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift index 18cb1765d..ceab142f0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataAccessorFunction`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift index e345ab615..e8d9545f8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataBoundsProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift index ddf365a25..9de65fa26 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataBounds`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift index f470f5ff4..938a2c587 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ForeignMetadataInitialization`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift index 1aa1103ee..d6f6fe7ad 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `SingletonMetadataInitialization`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift index f35635b91..2394bfb33 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift index 784fe427b..66165e08b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataRequest`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift index 6101e5bff..983deb0cc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataResponse`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift index 4b90e56d6..384fc16a7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `Metadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift index d6ed039b1..7c811a6a8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetadataWrapper`. /// @@ -58,16 +58,6 @@ final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ #expect(metadata.kind == .struct) } - /// `metadata` re-reads the kind-erased `Metadata` prefix at the - /// wrapped metadata's offset, interpreting the offset as a runtime - /// raw pointer. Only the in-process wrapper produces a valid raw - /// pointer, so we materialise the wrapper through `inProcessContext`. - @Test func metadata() async throws { - let wrapper = try loadStructTestInProcessWrapper() - let metadata = try wrapper.anyMetadata.asMetadata(in: inProcessContext) - #expect(metadata.kind == .struct) - } - /// `valueWitnessTable(in:)` resolves the value-witness table through /// the full-metadata header. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift index 0b69e68cf..3c62f0804 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MetatypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift index db8203137..c02546c6e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `SingletonMetadataPointer`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift index 3a72d9022..f65c42127 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ModuleContextDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift index 15daa4ea1..96e7575dc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ModuleContext` (the high-level wrapper around /// `ModuleContextDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift index 4c5ce9775..c43bda67d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `OpaqueMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift index a4e36d15b..39afc7d22 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `OpaqueTypeDescriptorProtocol`'s extension /// members. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift index c76c8d5e8..43c6697f0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `OpaqueTypeDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift index 2b6746891..8fedfdcdc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `OpaqueType` (the high-level wrapper around /// `OpaqueTypeDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift index 57968ef78..bfd1bb76e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `InvertibleProtocolSet`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift index bdd8959d7..20a73c213 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `InvertibleProtocolsRequirementCount`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift index 39d01769e..459cc2bdc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ObjCProtocolPrefix`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift index d983387ea..304c808f8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `RelativeObjCProtocolPrefix`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift index ecc20625e..449139050 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolBaseRequirement`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift index 07ee1e16e..65c380888 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolContextDescriptorFlags`. /// @@ -44,7 +44,7 @@ final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, #expect(constructed.rawValue == ProtocolContextDescriptorFlagsBaseline.protocolTest.rawValue) #expect(constructed.isResilient == ProtocolContextDescriptorFlagsBaseline.protocolTest.isResilient) #expect(constructed.classConstraint.rawValue == ProtocolContextDescriptorFlagsBaseline.protocolTest.classConstraintRawValue) - #expect(constructed.specialProtocolKind.rawValue == ProtocolContextDescriptorFlagsBaseline.protocolTest.specialProtocolKindRawValue) + #expect(constructed.specialProtocolKind?.rawValue == ProtocolContextDescriptorFlagsBaseline.protocolTest.specialProtocolKindRawValue) } @Test func isResilient() async throws { @@ -68,8 +68,8 @@ final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @Test func specialProtocolKind() async throws { let flags = try loadProtocolTestFlags() let result = try acrossAllReaders( - file: { flags.file.specialProtocolKind.rawValue }, - image: { flags.image.specialProtocolKind.rawValue } + file: { flags.file.specialProtocolKind?.rawValue }, + image: { flags.image.specialProtocolKind?.rawValue } ) #expect(result == ProtocolContextDescriptorFlagsBaseline.protocolTest.specialProtocolKindRawValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift index 1b774c1cb..183b28116 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolDescriptorFlags`. /// @@ -51,15 +51,15 @@ final class ProtocolDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixture @Test func dispatchStrategy() async throws { let swiftFlags = ProtocolDescriptorFlags(rawValue: ProtocolDescriptorFlagsBaseline.swift.rawValue) - #expect(swiftFlags.dispatchStrategy.rawValue == ProtocolDescriptorFlagsBaseline.swift.dispatchStrategyRawValue) + #expect(swiftFlags.dispatchStrategy?.rawValue == ProtocolDescriptorFlagsBaseline.swift.dispatchStrategyRawValue) let objcFlags = ProtocolDescriptorFlags(rawValue: ProtocolDescriptorFlagsBaseline.objc.rawValue) - #expect(objcFlags.dispatchStrategy.rawValue == ProtocolDescriptorFlagsBaseline.objc.dispatchStrategyRawValue) + #expect(objcFlags.dispatchStrategy?.rawValue == ProtocolDescriptorFlagsBaseline.objc.dispatchStrategyRawValue) } @Test func specialProtocolKind() async throws { let flags = ProtocolDescriptorFlags(rawValue: ProtocolDescriptorFlagsBaseline.swift.rawValue) - #expect(flags.specialProtocolKind.rawValue == ProtocolDescriptorFlagsBaseline.swift.specialProtocolKindRawValue) + #expect(flags.specialProtocolKind?.rawValue == ProtocolDescriptorFlagsBaseline.swift.specialProtocolKindRawValue) } @Test func needsProtocolWitnessTable() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift index f4a047a88..fc079c5a0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolDescriptorRef`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift index f984549d9..f12a07435 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift index 956a360cd..c571eefa3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift index ed577fe60..aac9fee00 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolRequirementFlags`. /// @@ -46,8 +46,8 @@ final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixtur @Test func kind() async throws { let (file, image) = try loadFirstRequirementFlags() let result = try acrossAllReaders( - file: { file.kind.rawValue }, - image: { image.kind.rawValue } + file: { file.kind?.rawValue }, + image: { image.kind?.rawValue } ) #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.kindRawValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift index 7984b3226..434fb2596 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolRequirementKind`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift index 729d7f1b2..20350d1af 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolRequirement`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift index af21d4ff6..282f6cc10 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `Protocol` (the high-level wrapper around /// `ProtocolDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift index f450775b8..6869cd005 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolWitnessTable`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift index 374a87d96..5f80acdde 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ResilientWitness`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift index a5d3a9028..025627642 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ResilientWitnessesHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift index 5dc03f16d..dba9dbce4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `GlobalActorReference`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift index 67a61aea2..f767935f3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolConformanceDescriptor`. /// @@ -57,8 +57,8 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F @Test func typeReference() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() let kindRawValue = try acrossAllReaders( - file: { file.layout.flags.typeReferenceKind.rawValue }, - image: { image.layout.flags.typeReferenceKind.rawValue } + file: { file.layout.flags.typeReferenceKind?.rawValue }, + image: { image.layout.flags.typeReferenceKind?.rawValue } ) #expect(kindRawValue == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.typeReferenceKindRawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift index 7d98fbe2a..c7cdc2219 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolConformanceFlags`. /// @@ -31,7 +31,7 @@ final class ProtocolConformanceFlagsTests: MachOSwiftSectionFixtureTests, Fixtur @Test func typeReferenceKind() async throws { let flags = ProtocolConformanceFlags(rawValue: ProtocolConformanceFlagsBaseline.structTestProtocolTest.rawValue) - #expect(flags.typeReferenceKind.rawValue == ProtocolConformanceFlagsBaseline.structTestProtocolTest.typeReferenceKindRawValue) + #expect(flags.typeReferenceKind?.rawValue == ProtocolConformanceFlagsBaseline.structTestProtocolTest.typeReferenceKindRawValue) } @Test func isRetroactive() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift index 9ed27cbe4..2f894c46d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ProtocolConformance`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift index a561bc9dd..71c100be4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TupleTypeMetadata.Element`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift index 34cbcdbb9..b706dc56a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TupleTypeMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift index deb83bd3d..aea1d755a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift index c660c0131..48e72e9cc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift @@ -1,16 +1,16 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassFlags`. /// -/// `ClassFlags` is a `UInt32`-raw enum with five named cases. There are no -/// derived properties, so the Suite simply round-trips each case's raw -/// value to catch accidental renumbering. The baseline records no -/// member names because none of the cases or static utilities are -/// scanner-visible as method-keyed members. +/// `ClassFlags` is a `UInt32` option set built by `@FlagSet` from five +/// flags. There are no derived properties, so the Suite simply round-trips +/// each flag's raw value to catch accidental renumbering. The baseline +/// records no member names because neither the `Flag` cases nor the +/// statics `@FlagSet` generates are scanner-visible as method-keyed members. @Suite final class ClassFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "ClassFlags" diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift index 1f0886f4d..2581befcc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `Class` (the high-level wrapper around /// `ClassDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift index 14b977550..e027b4ece 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ExtraClassDescriptorFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift index 8c491d67b..1953498c6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnyClassMetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift index 4c4cf93c4..fdfafdda4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnyClassMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift index 6737afe77..34e27a45d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnyClassMetadataObjCInteropProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift index 155b0b2ff..df9a163eb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `AnyClassMetadataObjCInterop`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift index 477f6f84f..ca7fcf794 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassMetadataBoundsProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift index d97e303fb..23a9ff351 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassMetadataBounds`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift index 62d9defc7..a3b7681da 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `StoredClassMetadataBounds`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift index 7d4057b75..1bc4c3d33 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift index f0fd4c0dd..7d2118698 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ClassMetadataObjCInterop`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift index 7507dbe5f..14c8dee8f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `FinalClassMetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift index 50a9ea0f6..3a39d1626 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ObjCClassWrapperMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift index 809b519e6..849f38ece 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodDefaultOverrideDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift index b274268a9..fa5880186 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodDefaultOverrideTableHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift index 58943b59c..eefa3bbbb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodDescriptorFlags`. /// @@ -44,7 +44,7 @@ final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSu rawValue: MethodDescriptorFlagsBaseline.firstClassTestMethod.rawValue ) #expect(constructed.rawValue == MethodDescriptorFlagsBaseline.firstClassTestMethod.rawValue) - #expect(constructed.kind.rawValue == MethodDescriptorFlagsBaseline.firstClassTestMethod.kindRawValue) + #expect(constructed.kind?.rawValue == MethodDescriptorFlagsBaseline.firstClassTestMethod.kindRawValue) #expect(constructed.isDynamic == MethodDescriptorFlagsBaseline.firstClassTestMethod.isDynamic) #expect(constructed.isInstance == MethodDescriptorFlagsBaseline.firstClassTestMethod.isInstance) } @@ -52,8 +52,8 @@ final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func kind() async throws { let flags = try loadFirstFlags() let result = try acrossAllReaders( - file: { flags.file.kind.rawValue }, - image: { flags.image.kind.rawValue } + file: { flags.file.kind?.rawValue }, + image: { flags.image.kind?.rawValue } ) #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.kindRawValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift index f273c8426..a95f19738 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodDescriptorKind`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift index d8582118f..b25045a81 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift @@ -1,10 +1,11 @@ import Foundation import Testing import MachOFoundation +import SwiftSymbols import SwiftInspection @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift index d404dd0a7..d287ef8f2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MethodOverrideDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift index f1b6a648c..303e3a1a7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `OverrideTableHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift index 3a1e5f2a3..caea69608 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `VTableDescriptorHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift index 920cf2111..1d14fcf87 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ObjCResilientClassStubInfo`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift index d5d27db12..edef621a1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ResilientSuperclass`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift index 952636179..6c32998cc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `EnumDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift index 552d227d3..aaa09591e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `EnumFunctions.swift`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift index 942cdf0c8..f54e2da15 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `Enum` (the high-level wrapper around /// `EnumDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift index 037480c28..9bf7c6948 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `EnumMetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift index 706bc6963..a1cae5a81 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `EnumMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift index 5d21e6c9e..d2ac005f0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `MultiPayloadEnumDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift index 8eebcadb6..6bdb14b62 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `StructDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift index 17b78333f..4811c684a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `StructMetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift index d2f148405..93d5440a4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `StructMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift index c953009b6..d7ae16c26 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `Struct` (the high-level wrapper around /// `StructDescriptor`). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift index afcd8d8a1..6318fdcb6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeContextDescriptorFlags`. /// @@ -149,8 +149,8 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt @Test func classResilientSuperclassReferenceKind() async throws { let flags = try loadClassTestFlags() let result = try acrossAllReaders( - file: { flags.file.classResilientSuperclassReferenceKind.rawValue }, - image: { flags.image.classResilientSuperclassReferenceKind.rawValue } + file: { flags.file.classResilientSuperclassReferenceKind?.rawValue }, + image: { flags.image.classResilientSuperclassReferenceKind?.rawValue } ) #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classResilientSuperclassReferenceKindRawValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift index acb7db040..ee739b3c3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeContextDescriptorProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift index 67fe231da..b0e3c1da2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeContextDescriptor`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift index 920bddf6c..61f2edce2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeContextDescriptorWrapper`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift index ce3868c73..4016556c1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeContextWrapper`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift index 1b7d6dc4d..4181e37b2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift @@ -3,8 +3,8 @@ import Testing import MachOFoundation import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeMetadataRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift index d0771e01b..58bc1bf49 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift @@ -3,8 +3,8 @@ import Testing import MachOFoundation import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeReference`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift index 90da965b5..45cd392db 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ValueMetadataProtocol`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift index 21829e18d..dc867af19 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ValueMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift index daa539e12..332e98e16 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ValueTypeDescriptorWrapper`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift index e15ab2abc..d2eb236ae 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `TypeLayout`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift index 52ce56a0c..47617227d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ValueWitnessFlags`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift index 32808a119..ca1a5aa16 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based Suite for `ValueWitnessTable`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AllFixtureSuites.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AllFixtureSuites.swift index a29698c30..6a0cc711b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AllFixtureSuites.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AllFixtureSuites.swift @@ -1,7 +1,7 @@ // AUTO-GENERATED — DO NOT EDIT. // Regenerate via: swift package --allow-writing-to-package-directory regen-baselines -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport // `FixtureSuite` is `@MainActor`-isolated, so its metatype likewise inherits // main-actor isolation. Annotating the constant binds access to MainActor and diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AnonymousContextBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AnonymousContextBaseline.swift index 9fe0bd09b..aecffe9eb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AnonymousContextBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AnonymousContextBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum AnonymousContextBaseline { - static let registeredTestMethodNames: Set = ["descriptor", "genericContext", "init(descriptor:)", "init(descriptor:in:)", "mangledName"] + static let registeredTestMethodNames: Set = ["descriptor", "genericContext", "init(descriptor:in:)", "mangledName"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AssociatedTypeBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AssociatedTypeBaseline.swift index db313d951..98c0b5388 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AssociatedTypeBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/AssociatedTypeBaseline.swift @@ -8,7 +8,7 @@ // counts / presence flags recorded here. enum AssociatedTypeBaseline { - static let registeredTestMethodNames: Set = ["conformingTypeName", "descriptor", "init(descriptor:)", "init(descriptor:in:)", "protocolTypeName", "records"] + static let registeredTestMethodNames: Set = ["conformingTypeName", "descriptor", "init(descriptor:in:)", "protocolTypeName", "records"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/BuiltinTypeBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/BuiltinTypeBaseline.swift index f7964f5ef..ccbcc0b45 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/BuiltinTypeBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/BuiltinTypeBaseline.swift @@ -8,7 +8,7 @@ // `hasMangledName` flag and equality of the descriptor offset. enum BuiltinTypeBaseline { - static let registeredTestMethodNames: Set = ["descriptor", "init(descriptor:)", "init(descriptor:in:)", "typeName"] + static let registeredTestMethodNames: Set = ["descriptor", "init(descriptor:in:)", "typeName"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassBaseline.swift index 231c811ab..0123b173b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ClassBaseline { - static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadataAccessors", "canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:)", "init(descriptor:in:)", "invertibleProtocolSet", "methodDefaultOverrideDescriptors", "methodDefaultOverrideTableHeader", "methodDescriptors", "methodOverrideDescriptors", "objcResilientClassStubInfo", "overrideTableHeader", "resilientSuperclass", "singletonMetadataInitialization", "singletonMetadataPointer", "vTableDescriptorHeader"] + static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadataAccessors", "canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:in:)", "invertibleProtocolSet", "methodDefaultOverrideDescriptors", "methodDefaultOverrideTableHeader", "methodDescriptors", "methodOverrideDescriptors", "objcResilientClassStubInfo", "overrideTableHeader", "resilientSuperclass", "singletonMetadataInitialization", "singletonMetadataPointer", "vTableDescriptorHeader"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassFlagsBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassFlagsBaseline.swift index 2d32bca0c..c903a68e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassFlagsBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ClassFlagsBaseline.swift @@ -2,9 +2,9 @@ // Regenerate via: Scripts/regen-baselines.sh // Source fixture: SymbolTestsCore.framework // -// ClassFlags is a raw UInt32 enum with five named cases. The Suite -// (ClassFlagsTests) round-trips the raw values to catch any -// accidental case renumbering / renaming. +// ClassFlags is a UInt32 option set with five flags, built by +// @FlagSet. The Suite (ClassFlagsTests) round-trips the raw values to +// catch any accidental flag renumbering / renaming. enum ClassFlagsBaseline { static let registeredTestMethodNames: Set = [] diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/EnumBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/EnumBaseline.swift index 8f3bad2e6..8ed6e0f23 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/EnumBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/EnumBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum EnumBaseline { - static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:)", "init(descriptor:in:)", "invertibleProtocolSet", "singletonMetadataInitialization", "singletonMetadataPointer"] + static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:in:)", "invertibleProtocolSet", "singletonMetadataInitialization", "singletonMetadataPointer"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ExtensionContextBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ExtensionContextBaseline.swift index 326c17766..6e8e7e324 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ExtensionContextBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ExtensionContextBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ExtensionContextBaseline { - static let registeredTestMethodNames: Set = ["descriptor", "extendedContextMangledName", "genericContext", "init(descriptor:)", "init(descriptor:in:)"] + static let registeredTestMethodNames: Set = ["descriptor", "extendedContextMangledName", "genericContext", "init(descriptor:in:)"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/FieldDescriptorBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/FieldDescriptorBaseline.swift index 45c6e7b89..291d7da70 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/FieldDescriptorBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/FieldDescriptorBaseline.swift @@ -8,10 +8,13 @@ // presence flags / counts recorded here. enum FieldDescriptorBaseline { - static let registeredTestMethodNames: Set = ["kind", "layout", "mangledTypeName", "offset", "records"] + static let registeredTestMethodNames: Set = ["actualSize", "kind", "layout", "mangledTypeName", "offset", "records"] + + static let descriptorCount = 455 struct Entry { let offset: Int + let actualSize: Int let kindRawValue: UInt16 let layoutNumFields: Int let layoutFieldRecordSize: Int @@ -21,6 +24,7 @@ enum FieldDescriptorBaseline { static let genericStructNonRequirement = Entry( offset: 0x49da8, + actualSize: 52, kindRawValue: 0x0, layoutNumFields: 3, layoutFieldRecordSize: 12, @@ -30,6 +34,7 @@ enum FieldDescriptorBaseline { static let structTest = Entry( offset: 0x4b90c, + actualSize: 16, kindRawValue: 0x0, layoutNumFields: 0, layoutFieldRecordSize: 12, diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericContextBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericContextBaseline.swift index 5b82413cd..a14fe22eb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericContextBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericContextBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum GenericContextBaseline { - static let registeredTestMethodNames: Set = ["allParameters", "allRequirements", "allTypePacks", "allValues", "asGenericContext", "conditionalInvertibleProtocolSet", "conditionalInvertibleProtocolsRequirements", "conditionalInvertibleProtocolsRequirementsCount", "currentParameters", "currentRequirements", "currentTypePacks", "currentValues", "depth", "header", "init(contextDescriptor:)", "init(contextDescriptor:in:)", "offset", "parameters", "parentParameters", "parentRequirements", "parentTypePacks", "parentValues", "requirements", "size", "typePackHeader", "typePacks", "uniqueCurrentRequirements", "uniqueCurrentRequirementsInProcess", "valueHeader", "values"] + static let registeredTestMethodNames: Set = ["allParameters", "allRequirements", "allTypePacks", "allValues", "asGenericContext", "conditionalInvertibleProtocolSet", "conditionalInvertibleProtocolsRequirements", "conditionalInvertibleProtocolsRequirementsCount", "currentParameters", "currentRequirements", "currentTypePacks", "currentValues", "depth", "header", "init(contextDescriptor:in:)", "offset", "parameters", "parentParameters", "parentRequirements", "parentTypePacks", "parentValues", "requirements", "size", "typePackHeader", "typePacks", "uniqueCurrentRequirements", "valueHeader", "values"] struct Entry { let offset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericRequirementBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericRequirementBaseline.swift index 5fec61603..2e6725a88 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericRequirementBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/GenericRequirementBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum GenericRequirementBaseline { - static let registeredTestMethodNames: Set = ["content", "descriptor", "init(descriptor:)", "init(descriptor:in:)", "paramManagledName"] + static let registeredTestMethodNames: Set = ["content", "descriptor", "init(descriptor:in:)", "paramManagledName"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/InvertibleProtocolSetBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/InvertibleProtocolSetBaseline.swift index 096e11aa4..7e0cefc7a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/InvertibleProtocolSetBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/InvertibleProtocolSetBaseline.swift @@ -8,7 +8,7 @@ // exercise each branch (none / copyable-only / escapable-only / both). enum InvertibleProtocolSetBaseline { - static let registeredTestMethodNames: Set = ["copyable", "escapable", "hasCopyable", "hasEscapable", "init(rawValue:)", "rawValue"] + static let registeredTestMethodNames: Set = ["hasCopyable", "hasEscapable"] struct Entry { let rawValue: UInt16 diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/MetadataWrapperBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/MetadataWrapperBaseline.swift index 6e961d2c8..0de6c44ac 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/MetadataWrapperBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/MetadataWrapperBaseline.swift @@ -9,5 +9,5 @@ // appear in the registered set. enum MetadataWrapperBaseline { - static let registeredTestMethodNames: Set = ["anyMetadata", "metadata", "resolve", "valueWitnessTable"] + static let registeredTestMethodNames: Set = ["anyMetadata", "resolve", "valueWitnessTable"] } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ModuleContextBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ModuleContextBaseline.swift index 1acf72594..154fafa0f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ModuleContextBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ModuleContextBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ModuleContextBaseline { - static let registeredTestMethodNames: Set = ["descriptor", "init(descriptor:)", "init(descriptor:in:)", "name"] + static let registeredTestMethodNames: Set = ["descriptor", "init(descriptor:in:)", "name"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/OpaqueTypeBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/OpaqueTypeBaseline.swift index c287036ee..5f2be3c91 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/OpaqueTypeBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/OpaqueTypeBaseline.swift @@ -9,5 +9,5 @@ // exercises members against a synthetic memberwise instance. enum OpaqueTypeBaseline { - static let registeredTestMethodNames: Set = ["descriptor", "genericContext", "init(descriptor:)", "init(descriptor:in:)", "invertedProtocols", "underlyingTypeArgumentMangledNames"] + static let registeredTestMethodNames: Set = ["descriptor", "genericContext", "init(descriptor:in:)", "invertedProtocols", "underlyingTypeArgumentMangledNames"] } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolBaseline.swift index 106817b50..d8f718334 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ProtocolBaseline { - static let registeredTestMethodNames: Set = ["baseRequirement", "descriptor", "init(descriptor:)", "init(descriptor:in:)", "name", "numberOfRequirements", "numberOfRequirementsInSignature", "protocolFlags", "requirementInSignatures", "requirements"] + static let registeredTestMethodNames: Set = ["baseRequirement", "descriptor", "init(descriptor:in:)", "name", "numberOfRequirements", "numberOfRequirementsInSignature", "protocolFlags", "requirementInSignatures", "requirements"] struct Entry { let name: String diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolConformanceBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolConformanceBaseline.swift index b33d9c0be..02cc8f851 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolConformanceBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ProtocolConformanceBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ProtocolConformanceBaseline { - static let registeredTestMethodNames: Set = ["conditionalPackShapeDescriptors", "conditionalRequirements", "descriptor", "flags", "genericWitnessTable", "globalActorReference", "init(descriptor:)", "init(descriptor:in:)", "protocol", "resilientWitnesses", "resilientWitnessesHeader", "retroactiveContextDescriptor", "typeReference", "witnessTablePattern"] + static let registeredTestMethodNames: Set = ["conditionalPackShapeDescriptors", "conditionalRequirements", "descriptor", "flags", "genericWitnessTable", "globalActorReference", "init(descriptor:in:)", "protocol", "resilientWitnesses", "resilientWitnessesHeader", "retroactiveContextDescriptor", "typeReference", "witnessTablePattern"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/StructBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/StructBaseline.swift index 2eb66ff7e..22c554ae4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/StructBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/StructBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum StructBaseline { - static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:)", "init(descriptor:in:)", "invertibleProtocolSet", "singletonMetadataInitialization", "singletonMetadataPointer"] + static let registeredTestMethodNames: Set = ["canonicalSpecializedMetadatas", "canonicalSpecializedMetadatasCachingOnceToken", "canonicalSpecializedMetadatasListCount", "descriptor", "foreignMetadataInitialization", "genericContext", "init(descriptor:in:)", "invertibleProtocolSet", "singletonMetadataInitialization", "singletonMetadataPointer"] struct Entry { let descriptorOffset: Int diff --git a/Tests/MachOSwiftSectionTests/FlagWordDecodingTests.swift b/Tests/MachOSwiftSectionTests/FlagWordDecodingTests.swift new file mode 100644 index 000000000..d431508b9 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/FlagWordDecodingTests.swift @@ -0,0 +1,65 @@ +import Foundation +import Testing +@testable import MachOSwiftSection + +/// Three flag-word accessors that read the wrong bits until the flag words of +/// the ABI layer were declared with `@BitField` (proposal +/// `abi-flag-words-bit-field`). Each of them stopped the process: two masked a +/// bit without shifting it down, and one converted the whole word. +/// +/// The values come from live metadata where the runtime has it, so that a +/// test reads what a binary actually holds rather than a number written to +/// match the accessor. +@Suite +struct FlagWordDecodingTests { + /// `Any` is not class-constrained, which the runtime records by SETTING + /// bit 31 — the case every non-class existential is in. Masked but not + /// shifted, the bit became `UInt8(0x8000_0000)` and trapped. + @Test func existentialThatIsNotClassConstrainedReadsAny() throws { + let metadata = try ExistentialTypeMetadata.resolve( + at: unsafeBitCast(Any.self, to: UnsafeRawPointer.self), + in: InProcessContext.shared + ) + #expect(metadata.layout.flags.classConstraint == .any) + #expect(!metadata.isClassBounded) + + let classBoundMetadata = try ExistentialTypeMetadata.resolve( + at: unsafeBitCast(AnyObject.self, to: UnsafeRawPointer.self), + in: InProcessContext.shared + ) + #expect(classBoundMetadata.layout.flags.classConstraint == .class) + } + + /// Bit 1 of a protocol descriptor's flags is set when the protocol is not + /// class-constrained. Masked but not shifted, it read as the raw value 2, + /// which `ProtocolClassConstraint` does not have, and the force-unwrap + /// trapped. + @Test func protocolDescriptorWhoseClassConstraintBitIsSetReadsAny() { + #expect(ProtocolDescriptorFlags(rawValue: 0b10).classConstraint == .any) + #expect(ProtocolDescriptorFlags(rawValue: 0b00).classConstraint == .class) + } + + /// The calling convention is bits 16..<24. The accessor converted the + /// whole word instead: a function type whose word is 255 or less read its + /// parameter count as the convention, and any other trapped — every + /// escaping function type has bit 26 set. + @Test func functionTypeReadsItsConventionFromItsOwnBits() throws { + let swiftFunction = try FunctionTypeMetadata.resolve( + at: unsafeBitCast(((Int) -> Void).self, to: UnsafeRawPointer.self), + in: InProcessContext.shared + ) + #expect(swiftFunction.layout.flags.convention == .swift) + + let cFunction = try FunctionTypeMetadata.resolve( + at: unsafeBitCast((@convention(c) (Int32) -> Int32).self, to: UnsafeRawPointer.self), + in: InProcessContext.shared + ) + #expect(cFunction.layout.flags.convention == .cFunctionPointer) + + let block = try FunctionTypeMetadata.resolve( + at: unsafeBitCast((@convention(block) () -> Void).self, to: UnsafeRawPointer.self), + in: InProcessContext.shared + ) + #expect(block.layout.flags.convention == .block) + } +} diff --git a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift index 675398895..d55aa2533 100644 --- a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift +++ b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A `ReadingContext` over a file has to read a pointer slot the way dyld /// leaves it at load time, not the way the file stores it: a rebased slot diff --git a/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift b/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift index a3f0537ae..0e2ed27a7 100644 --- a/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift @@ -2,10 +2,10 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable import SwiftDump import SwiftDeclarationRendering -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Semantic /// Private at file scope, so the compiler parents it on an anonymous context, diff --git a/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift b/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift index 1a0d2bb76..58aa16a2f 100644 --- a/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift +++ b/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport // MARK: - Specialized mangled-name resolution @@ -11,7 +11,7 @@ import MachOKit /// `Any.Type` by deriving the descriptor pointer and the inline /// generic-arguments array from a specialized in-process metadata. /// -/// Fixtures come from `MachOTestingSupport.SpecializedMangledNameFixtures` so +/// Fixtures come from `SwiftSectionTestingSupport.SpecializedMangledNameFixtures` so /// the descriptors live in the shared support module and stay reusable across /// future suites. Each test still touches `T.self` before reading the /// metadata back so the runtime materializes the per-instantiation metadata. diff --git a/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift new file mode 100644 index 000000000..a30ce9301 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift @@ -0,0 +1,62 @@ +import Foundation +import Testing +import MachOKit +import MachOReading +import SwiftSectionFixtureSupport + +/// A read of a standalone file — one not read out of a dyld shared cache — +/// comes from the file's own mapping and never goes back to its path. +/// +/// Every read asks the file for the sub-cache an offset lies in, which only +/// an image of a cache has. MachOKit's `cache` answered that by opening the +/// file's path as a dyld cache, and for a standalone file it failed and was +/// asked again on the next read: each read mapped and unmapped the whole file, +/// two thirds of the time spent reading the iOS 18.5 simulator's SwiftUI. +/// +/// The test opens a copy of the fixture, then puts a dyld cache header at the +/// copy's path. The file's mapping keeps the original bytes, so a read that +/// went back to the path would come from the header instead. +@Suite +struct StandaloneFileReadingTests { + private static var isHostDyldCacheAvailable: Bool { + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + } + + @Test(.enabled(if: isHostDyldCacheAvailable)) + func readsComeFromTheFileEvenAfterItsPathNamesADyldCache() throws { + let temporaryDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("StandaloneFileReadingTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: temporaryDirectory) } + + guard case .machO(let fixture) = try loadFromFile(named: .SymbolTestsCore) else { + Issue.record("the fixture is expected to be a thin file") + return + } + let copyURL = temporaryDirectory.appendingPathComponent("SymbolTestsCore") + try FileManager.default.copyItem(at: fixture.url, to: copyURL) + guard case .machO(let machOFile) = try MachOKit.loadFromFile(url: copyURL) else { + Issue.record("the copy is expected to be a thin file") + return + } + let magic: UInt32 = try machOFile.context.readElement(at: 0) + let headerBytes: [UInt8] = try machOFile.context.readElements(at: 0, numberOfElements: 64) + #expect(!machOFile.isLoadedFromDyldCache) + + // Replace, not overwrite: the mapping `machOFile` reads keeps the + // fixture's bytes. + let cacheHeaderBytes = try Self.hostCacheHeaderBytes() + try cacheHeaderBytes.write(to: copyURL, options: .atomic) + + #expect(try machOFile.context.readElement(at: 0) as UInt32 == magic) + #expect(try machOFile.context.readElements(at: 0, numberOfElements: 64) as [UInt8] == headerBytes) + } + + /// The first bytes of the host's dyld cache: enough for MachOKit to accept + /// a file as a cache. + private static func hostCacheHeaderBytes() throws -> Data { + let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + defer { try? fileHandle.close() } + return try #require(try fileHandle.read(upToCount: 0x10000)) + } +} diff --git a/Tests/MachOSymbolsTests/PackedNameReferenceBudgetTests.swift b/Tests/MachOSymbolsTests/PackedNameReferenceBudgetTests.swift deleted file mode 100644 index bdf7d70a7..000000000 --- a/Tests/MachOSymbolsTests/PackedNameReferenceBudgetTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -import Foundation -import MachOResolving -import Testing -import Demangling -@_spi(Internals) @testable import MachOSymbols - -/// The packed name-reference budgets (22-bit byte length / 40-bit byte -/// offset) are enforced against binary-supplied values: a name that cannot -/// pack must degrade — the build sweep skips its row, the standalone public -/// initializer clamps — never trap. `precondition` here is fatal in release -/// builds, so a malformed or hostile binary's symbol-table geometry would -/// decide whether the host process lives (PR #103 review, finding M3). -@Suite -struct PackedNameReferenceBudgetTests { - private static let oversizedName = "$s" + String(repeating: "A", count: PackedNameReference.maximumByteLength + 64) - - private static func makeNodeReference() -> NodeReference { - var nodeStoreBuilder = NodeStoreBuilder() - let nodeIndex = nodeStoreBuilder.intern(Node.create(kind: .identifier, text: "PackedNameReferenceBudgetTests")) - return nodeStoreBuilder.freeze().reference(at: nodeIndex) - } - - @Test func packedNameReferenceRefusesOverBudgetComponents() { - #expect(PackedNameReference(usesPrivateNameBuffer: true, isExternal: false, byteOffset: 0, byteLength: PackedNameReference.maximumByteLength + 1) == nil) - #expect(PackedNameReference(usesPrivateNameBuffer: true, isExternal: false, byteOffset: PackedNameReference.maximumByteOffset + 1, byteLength: 1) == nil) - #expect(PackedNameReference(usesPrivateNameBuffer: true, isExternal: false, byteOffset: -1, byteLength: 1) == nil) - #expect(PackedNameReference(usesPrivateNameBuffer: true, isExternal: false, byteOffset: 0, byteLength: -1) == nil) - - let packedNameReference = PackedNameReference(usesPrivateNameBuffer: true, isExternal: true, byteOffset: 7, byteLength: 5) - #expect(packedNameReference?.usesPrivateNameBuffer == true) - #expect(packedNameReference?.isExternal == true) - #expect(packedNameReference?.byteOffset == 7) - #expect(packedNameReference?.byteLength == 5) - } - - /// A private-buffer name beyond the byte-length budget is skipped by the - /// build sweep (its row is refused, no orphan bytes are appended), while - /// normal names keep minting rows as before. - @Test func tableBuilderSkipsAnOverBudgetPrivateBufferName() { - var tableBuilder = SymbolTableBuilder(mappedStringTableBase: nil) - #expect(tableBuilder.canonicalRow(forName: Self.oversizedName, canonicalOffset: 0, isExternal: false) == nil) - - let normalRow = tableBuilder.canonicalRow(forName: "$s10NormalNameV", canonicalOffset: 8, isExternal: false) - #expect(normalRow?.isNewRow == true) - - let symbolTable = tableBuilder.freeze() - #expect(symbolTable.rowCount == 1) - #expect(symbolTable.materializedName(atRow: 0) == "$s10NormalNameV") - } - - /// The public `DemangledSymbol(symbol:demangledNode:)` initializer packs - /// the caller's name into a one-row table; a name beyond the budget - /// clamps to the representable prefix instead of trapping (a legitimate - /// mangled name never approaches the 4 MB budget, so the clamp is - /// unreachable for honest input). - @Test func standalonePublicInitializerClampsInsteadOfTrapping() { - let demangledSymbol = DemangledSymbol( - symbol: Symbol(offset: 0, name: Self.oversizedName), - demangledNode: Self.makeNodeReference() - ) - #expect(demangledSymbol.name.utf8.count == PackedNameReference.maximumByteLength) - #expect(Self.oversizedName.hasPrefix(demangledSymbol.name)) - #expect(demangledSymbol.retainedSymbolTableRowCount == 1) - } -} diff --git a/Tests/Projects/SymbolTests/SymbolTestsCore/ForeignTypes.swift b/Tests/Projects/SymbolTests/SymbolTestsCore/ForeignTypes.swift index a7f98e0c6..4d787e533 100644 --- a/Tests/Projects/SymbolTests/SymbolTestsCore/ForeignTypes.swift +++ b/Tests/Projects/SymbolTests/SymbolTestsCore/ForeignTypes.swift @@ -10,7 +10,7 @@ import CoreFoundation // the metadata is reliably mapped into the test process. The real // `ForeignClassMetadata` carrier is reached via // `unsafeBitCast(CFString.self, to: UnsafeRawPointer.self)` from the -// `MachOFixtureSupport` `InProcessMetadataPicker`. +// `SwiftSectionFixtureSupport` `InProcessMetadataPicker`. // // `ForeignReferenceTypeMetadata` requires C++ interop import // (`SWIFT_SHARED_REFERENCE`); SymbolTestsCore does not enable C++ diff --git a/Tests/Projects/SymbolTests/SymbolTestsCore/GenericFieldLayout.swift b/Tests/Projects/SymbolTests/SymbolTestsCore/GenericFieldLayout.swift index 807f04385..24653e0a9 100644 --- a/Tests/Projects/SymbolTests/SymbolTestsCore/GenericFieldLayout.swift +++ b/Tests/Projects/SymbolTests/SymbolTestsCore/GenericFieldLayout.swift @@ -415,9 +415,9 @@ public enum GenericFieldLayout { // MARK: - Swift-declared @objc protocol existentials /// Non-generic holder of existentials over a Swift-declared `@objc` - /// protocol (declared at file scope below — `@objc` protocols cannot nest). - /// Such a protocol emits no Swift protocol descriptor; its only runtime - /// artifact is the ObjC protocol record, so the existential is a single + /// protocol (declared at file scope below). Such a protocol emits no + /// Swift protocol descriptor and contributes no witness table, so the + /// existential is a single /// class reference with no Swift witness table. `anchoredElement` mirrors /// the SwiftUI shape that motivated the fallback /// (`PlatformAccessibilityElementProtocol & NSObject`); `composedElement` @@ -669,10 +669,10 @@ extension GenericFieldLayout.ValueGenericBuffer where count == 5 { } } -/// A Swift-declared `@objc` protocol (file scope — `@objc` protocols cannot be -/// nested): it emits **no** Swift protocol descriptor (`__swift5_protos`); its -/// only runtime artifact is the Objective-C protocol record -/// (`__objc_protolist`, legacy `_TtP…_` name). +/// A Swift-declared `@objc` protocol: it emits **no** Swift protocol +/// descriptor (`__swift5_protos`); its runtime artifact is the Objective-C +/// protocol record (`__objc_protolist`, legacy `_TtP…_` name), with a field +/// descriptor of kind `ObjCProtocol` naming it. @objc public protocol ObjCOnlyElementProtocol { func identify() -> Int } diff --git a/Tests/Projects/SymbolTests/SymbolTestsCore/ObjCClassWrappers.swift b/Tests/Projects/SymbolTests/SymbolTestsCore/ObjCClassWrappers.swift index a1c5243d6..811b117ae 100644 --- a/Tests/Projects/SymbolTests/SymbolTestsCore/ObjCClassWrappers.swift +++ b/Tests/Projects/SymbolTests/SymbolTestsCore/ObjCClassWrappers.swift @@ -14,15 +14,16 @@ public enum ObjCClassWrapperFixtures { @objc public var label: String = "objc" } - /// `@objc protocol` — emits a Swift protocol descriptor with an - /// `ObjCProtocolPrefix`-typed reference to the underlying ObjC - /// protocol. + /// `@objc protocol` — emits no Swift protocol descriptor: only an ObjC + /// protocol record in `__objc_protolist` and a field descriptor of kind + /// `ObjCProtocol` (evolution proposal `swift-declared-objc-protocols`). @objc public protocol ObjCProto { @objc func ping() } - /// Class conforming to `@objc protocol` — surfaces `RelativeObjCProtocolPrefix` - /// in the class's conformance descriptor. + /// Class conforming to an `@objc protocol` — an ObjC protocol has no + /// witness table, so no conformance descriptor records it; the class's + /// `class_ro_t` protocol list does. @objc(SymbolTestsCoreObjCBridgeWithProto) public class ObjCBridgeWithProto: NSObject, ObjCProto { public override init() { super.init() } diff --git a/Tests/Projects/SymbolTests/SymbolTestsCore/PrivateDoppelgangers.swift b/Tests/Projects/SymbolTests/SymbolTestsCore/PrivateDoppelgangers.swift index 0b418ff2a..3d7acccaf 100644 --- a/Tests/Projects/SymbolTests/SymbolTestsCore/PrivateDoppelgangers.swift +++ b/Tests/Projects/SymbolTests/SymbolTestsCore/PrivateDoppelgangers.swift @@ -3,7 +3,7 @@ // The compiler tells them apart only by the per-file private discriminator // (`(PrivateDoppelganger in _XXXX...)`), which `DemangleOptions.interface` // deliberately strips — so the two types collide on the printed-name key of -// `SymbolIndexStore`'s member indexes and only the interned context node can +// `SwiftSymbolIndexStore`'s member indexes and only the interned context node can // attribute their member symbols to the right declaration (issue #115: the // dump path merged both types' initializers and methods into each). // diff --git a/Tests/SwiftAttributeInferenceTests/TypeAttributeInferrerTests.swift b/Tests/SwiftAttributeInferenceTests/TypeAttributeInferrerTests.swift index f7830c898..19430b4a6 100644 --- a/Tests/SwiftAttributeInferenceTests/TypeAttributeInferrerTests.swift +++ b/Tests/SwiftAttributeInferenceTests/TypeAttributeInferrerTests.swift @@ -4,7 +4,7 @@ import MachOFoundation import Testing import SwiftDump import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols // MARK: - TypeAttributeInferrer Static Predicate Tests diff --git a/Tests/SwiftDeclarationRenderingTests/AccessorFunctionReferenceRewriterTests.swift b/Tests/SwiftDeclarationRenderingTests/AccessorFunctionReferenceRewriterTests.swift index 8c8f0cbb8..cfe216519 100644 --- a/Tests/SwiftDeclarationRenderingTests/AccessorFunctionReferenceRewriterTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/AccessorFunctionReferenceRewriterTests.swift @@ -7,8 +7,8 @@ import OrderedCollections @testable import SwiftDeclarationRendering import SwiftThunkAnalysis import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A stand-in for `SwiftThunkAnalysis`: answers from a table keyed by the /// thunk offset the kind-9 node carries, so the rewriter's contract can be diff --git a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift index 36521652f..641029059 100644 --- a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift @@ -7,8 +7,8 @@ import MachOFoundation @testable import SwiftLayout import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Verifies the reader-specialized `FieldLayoutRenderer`: /// diff --git a/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift b/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift index 2d557bf8c..9ddc11eff 100644 --- a/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift @@ -6,7 +6,7 @@ import MachOFoundation @testable import SwiftDeclarationRendering import Demangling @_spi(Internals) import SwiftInspection -import MachOFixtureSupport +import SwiftSectionFixtureSupport /// The in-process leg of kind-9 resolution (evolution proposal /// `offline-opaque-accessor-thunk-resolution`): a witness whose underlying diff --git a/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift b/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift index 51f928567..36df4e2f3 100644 --- a/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift @@ -6,8 +6,8 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Pins the restored `MultiPayloadEnumDescriptorCache` (deleted by the leaf /// migration's `ebb04d3`, which replaced it with a per-enum throwing linear diff --git a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift index e77165c0a..d9ee4f55c 100644 --- a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift @@ -6,8 +6,8 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The in-process nested field-offset expansion reads byte for byte the same /// with its per-metatype memo as without it (evolution proposal diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift index 7061c1db4..c97ba0bfe 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift @@ -6,7 +6,7 @@ import MachOFoundation @testable import SwiftDeclarationRendering import Demangling @_spi(Internals) import SwiftInspection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// An opaque type reference spells its generic arguments as one list per /// declaration around the opaque result, outermost first, and the mangler @@ -134,7 +134,7 @@ struct OpaqueTypeArgumentDepthTests { /// The offset of the opaque type descriptor of the declaration named /// `declarationName`, found by its demangled symbol. private func opaqueTypeDescriptorOffset(ofDeclarationNamed declarationName: String, in machOFile: MachOFile) throws -> Int { - let symbols = SymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machOFile) + let symbols = SwiftSymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machOFile) let symbol = symbols.first { $0.demangledNode.materialize().print(using: .default).contains(declarationName) } return try #require(symbol, "no opaque type descriptor names \(declarationName): \(symbols.map { $0.demangledNode.materialize().print(using: .default) })").offset } diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeGenericParameterSubstitutionTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeGenericParameterSubstitutionTests.swift index 95b329fda..5921a2fd7 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeGenericParameterSubstitutionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeGenericParameterSubstitutionTests.swift @@ -6,8 +6,8 @@ import OrderedCollections @testable import MachOSwiftSection @testable import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The opaque-type rewriter's substitution contract: a /// `dependentGenericParamType` that resolves against the opaque type's type diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift index 7bfc6e12e..3a43c19b5 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift @@ -6,7 +6,7 @@ import MachOFoundation @testable import SwiftDeclarationRendering import Demangling @_spi(Internals) import SwiftInspection -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols /// A declaration may produce more than one opaque type — `-> Pair` /// is two — and the demangled `opaqueType` node says which one it is in its @@ -129,7 +129,7 @@ struct OpaqueTypeOrdinalTests { /// mangles its two results as `Qr` and `QR_`, which is what makes it the /// two-ordinal fixture. private func opaqueTypeDescriptorOffset(in machOFile: MachOFile) throws -> Int { - let symbols = SymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machOFile) + let symbols = SwiftSymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machOFile) // Taken as the only one rather than matched by name: `makeOpaquePair` // is not a substring of its own symbol, because the mangler // substitutes the repeated module prefix and spells it `04makeA4Pair`. diff --git a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift index 901322e83..99ba55f16 100644 --- a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift @@ -6,8 +6,8 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Regression coverage for the nested expanded-field-offset walk on a **cyclic** /// field graph. diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift index 921fda12e..731a345a8 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift @@ -6,8 +6,8 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftDeclarationRendering import Demangling -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Verifies the **MachOImage** (runtime) enum-layout path end-to-end on the /// fixture: single-payload empty cases render their *exact* extra-inhabitant diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift index a5d476541..d4df2380b 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift @@ -3,7 +3,7 @@ import Testing import MachOKit @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable @_spi(Internals) import SwiftInspection @testable import SwiftDeclarationRendering diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift index 3016458ff..52bf5b21e 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift @@ -3,8 +3,9 @@ import Testing import MachOKit @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable @_spi(Internals) import SwiftInspection +@testable @_spi(Internals) import SwiftObjCInterop @testable import SwiftDeclarationRendering /// A name that comes from the runtime (`_mangledTypeName`) spells a private diff --git a/Tests/SwiftDeclarationRenderingTests/StructuredCommentTests.swift b/Tests/SwiftDeclarationRenderingTests/StructuredCommentTests.swift new file mode 100644 index 000000000..5da26b2b7 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/StructuredCommentTests.swift @@ -0,0 +1,367 @@ +import Testing +import Semantic +@testable import SwiftDeclarationRendering +@testable @_spi(Internals) import SwiftInspection + +/// Every comment the printers emit is spelled out once, by a +/// `StructuredComment` factory, as segments that each play a role (evolution +/// proposal `comment-structure`). The text must stay what the printers have +/// always printed — the literals here are taken from their output — and the +/// segments are the split RuntimeViewer draws its comment tags from. +@Suite +struct StructuredCommentTests { + struct Expectation: Sendable, CustomTestStringConvertible { + let comment: StructuredComment + let text: String + let segments: [StructuredComment.Segment] + + var testDescription: String { text } + } + + static let expectations: [Expectation] = [ + Expectation( + comment: .memberAddress(addressString: "135DC"), + text: "// Address: 0x135DC", + segments: [.marker("// "), .label("Address"), .separator(": "), .value("0x135DC")] + ), + Expectation( + comment: .memberAddress(addressString: "135DC", qualifier: "getter"), + text: "// Address (getter): 0x135DC", + segments: [.marker("// "), .label("Address"), .separator(" ("), .qualifier("getter"), .separator("): "), .value("0x135DC")] + ), + Expectation( + comment: .vtableOffset(12), + text: "// VTable offset: 12", + segments: [.marker("// "), .label("VTable offset"), .separator(": "), .value("12")] + ), + Expectation( + comment: .vtableOffset(13, qualifier: "setter"), + text: "// VTable offset (setter): 13", + segments: [.marker("// "), .label("VTable offset"), .separator(" ("), .qualifier("setter"), .separator("): "), .value("13")] + ), + Expectation( + comment: .fieldOffset(0x8), + text: "// Field offset: 0x8", + segments: [.marker("// "), .label("Field offset"), .separator(": "), .value("0x8")] + ), + Expectation( + comment: .pwtOffset(0x18), + text: "// PWT offset: 0x18", + segments: [.marker("// "), .label("PWT offset"), .separator(": "), .value("0x18")] + ), + Expectation( + comment: .unknownFieldOffset(reasonDescription: "generic parameter not substituted"), + text: "// Field offset: unknown (generic parameter not substituted)", + segments: [ + .marker("// "), .label("Field offset"), .separator(": "), .value("unknown"), + .separator(" ("), .text("generic parameter not substituted"), .separator(")"), + ] + ), + Expectation( + comment: .fieldLayoutNode(treePrefix: "│ ├── ", fieldName: "_countAndFlagsBits", typeName: "Swift.UInt64", offset: 0x8), + text: "// │ ├── _countAndFlagsBits (Swift.UInt64): 0x8", + segments: [ + .marker("// "), .treePrefix("│ ├── "), .name("_countAndFlagsBits"), + .separator(" ("), .type("Swift.UInt64"), .separator("): "), .value("0x8"), + ] + ), + Expectation( + comment: .fieldLayoutNode(treePrefix: " └── ", fieldName: "_value", typeName: "", offset: 0x10), + text: "// └── _value: 0x10", + segments: [.marker("// "), .treePrefix(" └── "), .name("_value"), .separator(": "), .value("0x10")] + ), + Expectation( + comment: .typeLayout(size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647), + text: "// Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647)", + segments: [ + .marker("// "), .label("Type Layout"), .separator(": ("), + .key("size"), .separator(": "), .value("16"), .separator(", "), + .key("stride"), .separator(": "), .value("16"), .separator(", "), + .key("alignment"), .separator(": "), .value("8"), .separator(", "), + .key("extraInhabitantCount"), .separator(": "), .value("2147483647"), + .separator(")"), + ] + ), + Expectation( + comment: .typeLayout(labeled: "Layout", size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0), + text: "// Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0)", + segments: [ + .marker("// "), .label("Layout"), .separator(": ("), + .key("size"), .separator(": "), .value("8"), .separator(", "), + .key("stride"), .separator(": "), .value("8"), .separator(", "), + .key("alignment"), .separator(": "), .value("8"), .separator(", "), + .key("extraInhabitantCount"), .separator(": "), .value("0"), + .separator(")"), + ] + ), + Expectation( + comment: .tupleTypeLayoutHeading, + text: "/* Type Layout */", + segments: [.marker("/* "), .label("Type Layout"), .marker(" */")] + ), + Expectation( + comment: .tupleElementType("Swift.Int"), + text: "// Type: Swift.Int", + segments: [.marker("// "), .label("Type"), .separator(": "), .type("Swift.Int")] + ), + Expectation( + comment: .tupleTypeLayoutTotal, + text: "// Total: ", + segments: [.marker("// "), .label("Total"), .separator(": ")] + ), + Expectation( + comment: .enumLayoutCaseHeading, + text: "/* Enum Layout */", + segments: [.marker("/* "), .label("Enum Layout"), .marker(" */")] + ), + Expectation( + comment: .enumLayoutCaseBlock(" // Case 2 (0x02) `empty` — empty case #0\n"), + text: " // Case 2 (0x02) `empty` — empty case #0\n", + segments: [.plain(" // Case 2 (0x02) `empty` — empty case #0\n")] + ), + Expectation( + comment: .spareBits(totalSpareBits: 12), + text: "/* Spare Bits: 12 total */", + segments: [.marker("/* "), .label("Spare Bits"), .separator(": "), .value("12"), .separator(" "), .text("total"), .marker(" */")] + ), + Expectation( + comment: .exportStatus, + text: "// not exported", + segments: [.marker("// "), .label("not exported")] + ), + Expectation( + comment: .protocolExtensionDefault, + text: "// protocol-extension default", + segments: [.marker("// "), .label("protocol-extension default")] + ), + Expectation( + comment: .initAccessorFieldsNotRecorded, + text: "// init accessor: the binary does not record which stored properties it initializes", + segments: [.marker("// "), .label("init accessor"), .separator(": "), .text("the binary does not record which stored properties it initializes")] + ), + Expectation( + comment: .initAccessorInitializedFields(["_x", "_y"]), + text: "// init accessor: initializes _x, _y (inferred from the stored property's name and type)", + segments: [ + .marker("// "), .label("init accessor"), .separator(": "), .text("initializes "), + .name("_x"), .separator(", "), .name("_y"), .text(" (inferred from the stored property's name and type)"), + ] + ), + Expectation( + comment: .refinedForSwiftMember(declaration: [.plain("var "), .name("__settings"), .plain(": "), .type("Settings!"), .plain(" { get set }")]), + text: "// NS_REFINED_FOR_SWIFT: var __settings: Settings! { get set }", + segments: [ + .marker("// "), .label("NS_REFINED_FOR_SWIFT"), .separator(": "), + .plain("var "), .name("__settings"), .plain(": "), .type("Settings!"), .plain(" { get set }"), + ] + ), + Expectation( + comment: .deletedMethodSlot, + text: "// No implementation in this image (deleted method — slot retained for ABI)", + segments: [.marker("// "), .text("No implementation in this image (deleted method — slot retained for ABI)")] + ), + Expectation( + comment: .ambiguousAttribution(foldedSymbolCount: 3), + text: "// Attribution: ambiguous — 3 symbols folded at this address", + segments: [ + .marker("// "), .label("Attribution"), .separator(": "), .value("ambiguous"), + .separator(" — "), .text("3 symbols folded at this address"), + ] + ), + Expectation( + comment: .strippedSymbolicRequirement(kindDescription: "Method", isAsync: false, isInstance: true), + text: "// Kind: Method, isAsync: false, isInstance: true", + segments: [ + .marker("// "), .key("Kind"), .separator(": "), .value("Method"), .separator(", "), + .key("isAsync"), .separator(": "), .value("false"), .separator(", "), + .key("isInstance"), .separator(": "), .value("true"), + ] + ), + Expectation( + comment: .note("Visitor #1 in Holder.countValues()"), + text: "// Visitor #1 in Holder.countValues()", + segments: [.marker("// "), .text("Visitor #1 in Holder.countValues()")] + ), + Expectation( + comment: .note(" `T!` prints as `T?` (ABI-identical) · parameter internal names · @available ·"), + text: "// `T!` prints as `T?` (ABI-identical) · parameter internal names · @available ·", + segments: [.marker("// "), .marker(" "), .text("`T!` prints as `T?` (ABI-identical) · parameter internal names · @available ·")] + ), + Expectation( + comment: .inlineNote("type not recoverable"), + text: "/* type not recoverable */", + segments: [.marker("/* "), .text("type not recoverable"), .marker(" */")] + ), + ] + + @Test("a comment prints what the printers have always printed", arguments: expectations) + func printedText(of expectation: Expectation) { + #expect(expectation.comment.string == expectation.text) + } + + @Test("a comment is made of the segments agreed with RuntimeViewer", arguments: expectations) + func segments(of expectation: Expectation) { + #expect(expectation.comment.segments == expectation.segments) + } + + /// The comment is the atom `Comment` / `InlineComment` made: one + /// `.comment` atom, so a print's spans and elements do not change. + @Test("a comment prints as the one atom Comment and InlineComment made") + func printsAsOneAtom() { + let lineComment = SemanticString { StructuredComment.memberAddress(addressString: "135DC", qualifier: "getter") } + #expect(lineComment.components == SemanticString { Comment("Address (getter): 0x135DC") }.components) + + let inlineComment = SemanticString { StructuredComment.spareBits(totalSpareBits: 12) } + #expect(inlineComment.components == SemanticString { InlineComment("Spare Bits: 12 total") }.components) + } + + // MARK: - Comments built from other values + + /// The output of a tagged multi-payload enum in SymbolTestsCore. + @Test("an enum layout summary is its strategy and the facts of summaryDescription") + func enumLayoutSummary() { + let layoutResult = EnumLayoutCalculator.LayoutResult( + strategyDescription: "Tagged Multi-Payload (tag bytes after the payload area)", + bitsNeededForTag: 8, + bitsAvailableForPayload: 192, + numTags: 3, + extraInhabitantCount: 253, + tagRegion: EnumLayoutCalculator.SpareRegion(range: 24 ..< 25, bitCount: 8, bytes: [0xFF]), + payloadRegion: nil, + cases: [ + .init(caseIndex: 0, caseName: "payload case #0", isPayloadCase: true, tagValue: 0, payloadValue: 0, memoryChanges: [0x18: 0x00]), + .init(caseIndex: 1, caseName: "payload case #1", isPayloadCase: true, tagValue: 1, payloadValue: 0, memoryChanges: [0x18: 0x01]), + .init(caseIndex: 2, caseName: "empty case #0", isPayloadCase: false, tagValue: 2, payloadValue: 0, memoryChanges: [0x18: 0x02]), + ] + ) + let comment = StructuredComment.enumLayoutSummary(layoutResult) + #expect(comment.string == "/* Tagged Multi-Payload (tag bytes after the payload area) — cases: 3 (2 payload + 1 empty); tag values used: 3; tag bits: 8; tag region: offsets 24..<25 (8 bits); leftover extra inhabitants for an outer enum: 253 */") + #expect(comment.segments == [ + .marker("/* "), .label("Tagged Multi-Payload (tag bytes after the payload area)"), .separator(" — "), + .key("cases"), .separator(": "), .value("3 (2 payload + 1 empty)"), .separator("; "), + .key("tag values used"), .separator(": "), .value("3"), .separator("; "), + .key("tag bits"), .separator(": "), .value("8"), .separator("; "), + .key("tag region"), .separator(": "), .value("offsets 24..<25 (8 bits)"), .separator("; "), + .key("leftover extra inhabitants for an outer enum"), .separator(": "), .value("253"), + .marker(" */"), + ]) + } + + @Test("a source-file line names the declaration, the file and the module") + func privateDeclarationSourceSegments() { + let body = PrivateDeclarationSourceFileComments.lineBody( + for: PrivateDeclaration(name: "EnabledKey", discriminator: "_09CE35833F3876FE3A3A46977D61FC64"), + sourceFile: .init(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false), + printedModuleName: "SwiftUI" + ) + #expect(body == [ + .name("EnabledKey"), .separator(" "), .text("is declared in"), .separator(" "), .value("Enabled.swift"), + .separator(" "), .text("of module"), .separator(" "), .name("SwiftUICore"), + ]) + } + + @Test("an unrecovered source file is said so, with its discriminator as a value") + func unrecoveredPrivateDeclarationSourceSegments() { + let body = PrivateDeclarationSourceFileComments.lineBody( + for: PrivateDeclaration(name: nil, discriminator: "_1282F137F8790A6AF4B7E2738A640142"), + sourceFile: nil, + printedModuleName: "SymbolTestsCore" + ) + #expect(body == [ + .text("Declared in a source file whose name could not be recovered"), .separator(" ("), + .key("private discriminator"), .separator(" "), .value("_1282F137F8790A6AF4B7E2738A640142"), .separator(")"), + ]) + } + + // MARK: - Marking + + /// Marked, a comment separates to the atom it prints as, and a + /// continuation's marker is one segment however it was spelled. + @Test("a marked comment separates to its atom, neighbouring markers merged") + func markedCommentSeparatesToItsAtom() { + let comment = StructuredComment.note(" `T!` prints as `T?` (ABI-identical)") + let marked = comment.printed(markingStructure: true, as: .note).frozen().separatingAnnotationRegions() + #expect(marked.text == SemanticString { comment }.frozen()) + #expect(marked.annotations.regions.map(\.kind) == [.note]) + #expect(marked.annotations.segments.map(\.role) == [.marker, .text]) + #expect(marked.annotations.segments.first?.utf8Length == 5) + } + + @Test("a template's output is one text segment") + func templateOutputIsOneTextSegment() { + let output = SemanticString { Comment("addr: 0x135DC") } + let marked = StructuredComment.printedTemplate(output, markingStructure: true, as: .memberAddress).frozen().separatingAnnotationRegions() + #expect(marked.text == output.frozen()) + #expect(marked.annotations.regions.map(\.kind) == [.memberAddress]) + #expect(marked.annotations.segments.map(\.role) == [.text]) + #expect(StructuredComment.printedTemplate(output, markingStructure: false, as: .memberAddress) == output) + } + + /// The case blocks of `EnumLayoutCommentTemplateTests`, and two more: + /// a single payload's payload case, and an empty case with no name in + /// the records that fixes no byte. + static let caseProjections: [EnumLayoutCalculator.EnumCaseProjection] = [ + .init( + caseIndex: 1, caseName: "payload case #1", declaredName: "foregroundKeyColor", isPayloadCase: true, tagValue: 1, payloadValue: 0, + memoryChanges: [0: 0b0000_0000, 7: 0b0100_0000], fixedBitMasks: [0: 0b0000_0111, 7: 0b1111_0000], + encodingExplanation: "tag 1 scattered into the payloads' common spare bits; the occupied (non-spare) bits hold this payload's value" + ), + .init( + caseIndex: 2, caseName: "empty case #0", declaredName: "none", isPayloadCase: false, tagValue: 2, payloadValue: 0, + memoryChanges: [8: 0x01, 9: 0x00], encodingExplanation: "stored via extra tag bytes" + ), + .init( + caseIndex: 3, caseName: "empty case #1", declaredName: "sentinel", isPayloadCase: false, tagValue: 3, payloadValue: 0, + memoryChanges: [:], patternResolution: .unresolvedExtraInhabitant(extraInhabitantIndex: 1), + encodingExplanation: "stored as the payload's extra-inhabitant pattern #1 (an invalid payload bit pattern)" + ), + .init(caseIndex: 0, caseName: "payload case", isPayloadCase: true, tagValue: 0, payloadValue: 0, memoryChanges: [:]), + .init(caseIndex: 4, caseName: "empty case #2", isPayloadCase: false, tagValue: 4, payloadValue: 0, memoryChanges: [:]), + ] + + /// The marked block spells every line a second time; it must spell it + /// as the template does. + @Test("a marked case block separates to the block the template prints", arguments: caseProjections) + func annotatedCaseBlockSeparatesToTheTemplatesBlock(caseProjection: EnumLayoutCalculator.EnumCaseProjection) { + for indentation in [0, 1, 3] { + let marked = SemanticString { StructuredComment.annotatedEnumLayoutCaseBlock(caseProjection, indentation: indentation) }.frozen().separatingAnnotationRegions() + let plain = SemanticString { StructuredComment.enumLayoutCaseBlock(caseProjection.description(indent: indentation, prefix: "//")) }.frozen() + #expect(marked.text == plain, "indentation \(indentation)") + } + } + + @Test("a marked case block is one region per line, in the template's order") + func annotatedCaseBlockLines() { + let lineKinds = Self.caseProjections.map { caseProjection in + SemanticString { StructuredComment.annotatedEnumLayoutCaseBlock(caseProjection, indentation: 1) }.frozen().separatingAnnotationRegions().annotations.regions.map(\.kind) + } + #expect(lineKinds[0] == [.enumLayoutCaseHeader, .enumLayoutCaseEncoding, .enumLayoutCaseFixedBytes, .enumLayoutCaseByte, .enumLayoutCaseByte]) + #expect(lineKinds[2] == [.enumLayoutCaseHeader, .enumLayoutCaseEncoding, .enumLayoutCaseNote, .enumLayoutCaseFixedBytes]) + #expect(lineKinds[3] == [.enumLayoutCaseHeader, .enumLayoutCaseFixedBytes]) + } + + /// The padding that lines the types up belongs to the separator after the + /// condition, never to the condition itself. + @Test("a conditional witness names the associated type, then each branch's condition and type") + func conditionalWitnessSegments() { + let macOS: UInt32 = 1 + let lineBodies = ConditionalWitnessComment.lineBodies( + associatedTypeName: "Body", + branches: [ + ConditionalWitnessComment.Branch( + availability: PlatformAvailabilityCondition(platform: macOS, major: 26, minor: 0, patch: 0, isSatisfiedBranch: true), + typeText: "M.Box" + ), + ConditionalWitnessComment.Branch( + availability: PlatformAvailabilityCondition(platform: macOS, major: 26, minor: 0, patch: 0, isSatisfiedBranch: false), + typeText: "M.Box" + ), + ] + ) + #expect(lineBodies == [ + [.name("Body"), .separator(" "), .text("is picked at run time by an availability check (SE-0360)"), .separator(":")], + [.marker(" "), .qualifier("macOS 26.0 or later"), .separator(": "), .type("M.Box")], + [.marker(" "), .qualifier("before macOS 26.0"), .separator(": "), .type("M.Box")], + ]) + } +} diff --git a/Tests/SwiftDiffingTests/ABIDifferTests.swift b/Tests/SwiftDiffingTests/ABIDifferTests.swift index 850041cb8..55abd423a 100644 --- a/Tests/SwiftDiffingTests/ABIDifferTests.swift +++ b/Tests/SwiftDiffingTests/ABIDifferTests.swift @@ -4,7 +4,7 @@ import MachOFoundation import Testing import Foundation import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols // MARK: - Core three-way set-diff algorithm // @@ -79,6 +79,13 @@ struct ABIDifferAlgorithmTests { let keys = changes.map(\.key.sortKey) #expect(keys == keys.sorted()) } + + @Test("a member's export verdict is not part of its identity or payload") + func exportVerdictIsNotCompared() { + let old = [MemberRecord(identityKey: .mangled("foo"), payloadKey: .mangled("foo"), kind: .function, signature: "foo", isExported: false)] + let new = [MemberRecord(identityKey: .mangled("foo"), payloadKey: .mangled("foo"), kind: .function, signature: "foo", isExported: true)] + #expect(ABIDiffer().diffMembers(old: old, new: new).isEmpty) + } } // MARK: - Projection from the model + keying @@ -172,6 +179,19 @@ struct ABIDifferProjectionTests { #expect(changes.first?.kind == .variable) } + /// An exported init accessor is ABI: a client's inlined initializer calls + /// it (evolution proposal `init-accessor-recovery`). + @Test("gaining an init accessor diffs as .modified") + func gainingInitAccessorIsModified() { + let withoutInitAccessor = [MemberRecord.make(variable("value", accessors: [.getter, .setter]))] + let withInitAccessor = [MemberRecord.make(variable("value", accessors: [.getter, .setter, .initAccessor]))] + #expect(withInitAccessor.first?.payloadKey.sortKey.hasSuffix("|acc:get,init,set") == true) + let changes = ABIDiffer().diffMembers(old: withoutInitAccessor, new: withInitAccessor) + #expect(changes.count == 1) + #expect(changes.first?.status == .modified) + #expect(changes.first?.kind == .variable) + } + @Test("reordering enum cases renumbers tags, so the moved cases diff as .modified") func enumCaseReorderIsModified() { let old = [ diff --git a/Tests/SwiftDiffingTests/ABIExtensionAttributionTests.swift b/Tests/SwiftDiffingTests/ABIExtensionAttributionTests.swift index cf39d6b2b..4168ea6b0 100644 --- a/Tests/SwiftDiffingTests/ABIExtensionAttributionTests.swift +++ b/Tests/SwiftDiffingTests/ABIExtensionAttributionTests.swift @@ -5,7 +5,7 @@ import Testing import Foundation import Demangling import OrderedCollections -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols // MARK: - Per-conformance / per-where-block attribution // @@ -62,7 +62,7 @@ struct ABIExtensionAttributionTests { _ target: String, to protocolText: String, where whereText: String? = nil, - witnesses: [AssociatedTypeWitnessProjection] = [] + witnesses: [ResolvedAssociatedTypeWitness] = [] ) -> (name: ExtensionName, definition: ExtensionDefinition) { let name = extensionName(target) let definition = ExtensionDefinition( diff --git a/Tests/SwiftDiffingTests/ABIImageGroupEvolutionTests.swift b/Tests/SwiftDiffingTests/ABIImageGroupEvolutionTests.swift new file mode 100644 index 000000000..ce02b1261 --- /dev/null +++ b/Tests/SwiftDiffingTests/ABIImageGroupEvolutionTests.swift @@ -0,0 +1,281 @@ +@testable import SwiftDiffing +import Testing +import Foundation + +// MARK: - Versions made up of groups of images +// +// Evolution proposal `image-group-evolution`: a module Apple split across +// images — SwiftUI and SwiftUICore — keeps one API surface, and a +// declaration moved between the images keeps its mangled name. Driven with +// hand-built snapshots, like the other `ABIEvolutionBuilder` suites, so each +// rule is pinned without a Mach-O. + +private func record(_ identity: String, isExported: Bool? = true) -> MemberRecord { + MemberRecord(identityKey: .mangled(identity), payloadKey: .mangled(identity), kind: .function, signature: identity, isExported: isExported) +} + +private func typeContainer(_ name: String, members: [MemberRecord] = []) -> ContainerSnapshot { + ContainerSnapshot(key: .mangled(name), name: name, kind: .type, members: members) +} + +/// An extension of `typeName` with no conformance, no `where` clause and not +/// retroactive, keyed as the differ keys a struct's. +private func plainExtension(of typeName: String, members: [MemberRecord]) -> ContainerSnapshot { + ContainerSnapshot( + key: ABIDiffer.extensionContainerKey( + kindToken: "struct", + targetSortKey: ABIKey.mangled(typeName).sortKey, + protocolSortKey: nil, + whereSortKey: nil, + isRetroactive: false + ), + name: typeName, + kind: .typeExtension, + members: members + ) +} + +private func protocolExtension(of protocolName: String, members: [MemberRecord]) -> ContainerSnapshot { + ContainerSnapshot(key: .printed("extbucket:protocol|\(protocolName)"), name: protocolName, kind: .protocolExtension, members: members) +} + +private func image( + _ name: String, + types: [ContainerSnapshot] = [], + typeExtensions: [ContainerSnapshot] = [], + protocolExtensions: [ContainerSnapshot] = [], + hasLocalSwiftSymbols: Bool = true +) -> ABIImageSnapshot { + ABIImageSnapshot( + imageName: name, + snapshot: ABISnapshot(types: types, typeExtensions: typeExtensions, protocolExtensions: protocolExtensions, hasLocalSwiftSymbols: hasLocalSwiftSymbols) + ) +} + +private func evolution(_ imageGroups: [[ABIImageSnapshot]]) throws -> ABIEvolution { + try ABIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: imageGroups.indices.map { ABIVersionDescriptor(label: "\($0 + 1).0") } + ) +} + +@Suite("ABIEvolutionBuilder: versions made up of groups of images") +struct ABIImageGroupEvolutionTests { + @Test("a type that moves between the images of a group stays present and records its move") + func typeMoveIsNoRemoval() throws { + let result = try evolution([ + [image("SwiftUI", types: [typeContainer("Text", members: [record("body")])])], + [image("SwiftUI"), image("SwiftUICore", types: [typeContainer("Text", members: [record("body")])])], + ]) + let lineage = try #require(result.types.first { $0.name == "Text" }) + #expect(lineage.events.isEmpty) + #expect(lineage.presence == [true, true]) + #expect(lineage.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUICore"])]) + #expect(!result.hasBreakingChange) + } + + @Test("a member that moves with its type records no move of its own") + func memberMovingWithItsTypeIsTheTypesMove() throws { + let result = try evolution([ + [image("SwiftUI", types: [typeContainer("Text", members: [record("body")])])], + [image("SwiftUI"), image("SwiftUICore", types: [typeContainer("Text", members: [record("body")])])], + ]) + let lineage = try #require(result.types.first { $0.name == "Text" }) + #expect(lineage.memberLineages.isEmpty) + } + + @Test("a member another image declares in a plain extension belongs to its type, and stays where it was declared") + func plainExtensionFoldsIntoItsType() throws { + let result = try evolution([ + [image("SwiftUI", types: [typeContainer("Gauge", members: [record("reading"), record("calibrated")])])], + [ + image("SwiftUI", typeExtensions: [plainExtension(of: "Gauge", members: [record("calibrated")])]), + image("SwiftUICore", types: [typeContainer("Gauge", members: [record("reading")])]), + ], + ]) + #expect(result.typeExtensions.isEmpty) + let lineage = try #require(result.types.first { $0.name == "Gauge" }) + #expect(lineage.events.isEmpty) + #expect(lineage.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUICore"])]) + // `calibrated` stayed in SwiftUI and `reading` moved with its type: + // neither has a story of its own. + #expect(lineage.memberLineages.isEmpty) + } + + @Test("a member that moves without its container records its own move") + func memberMovesOnItsOwn() throws { + let result = try evolution([ + [ + image("SwiftUI", typeExtensions: [plainExtension(of: "Gauge", members: [record("calibrated")])]), + image("SwiftUICore", types: [typeContainer("Gauge", members: [record("reading")])]), + ], + [image("SwiftUI"), image("SwiftUICore", types: [typeContainer("Gauge", members: [record("reading"), record("calibrated")])])], + ]) + let lineage = try #require(result.types.first { $0.name == "Gauge" }) + #expect(lineage.imageMoves == nil) + let calibrated = try #require(lineage.memberLineages.first { $0.key == .mangled("calibrated") }) + #expect(calibrated.events.isEmpty) + #expect(calibrated.latestSignature == "calibrated") + #expect(calibrated.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUICore"])]) + } + + @Test("two images extending one protocol make one extension, and a member moving between them is recorded") + func extensionsOfTwoImagesMerge() throws { + let result = try evolution([ + [image("SwiftUI", protocolExtensions: [protocolExtension(of: "View", members: [record("padding"), record("toolbar")])])], + [ + image("SwiftUI", protocolExtensions: [protocolExtension(of: "View", members: [record("toolbar")])]), + image("SwiftUICore", protocolExtensions: [protocolExtension(of: "View", members: [record("padding")])]), + ], + ]) + let lineage = try #require(result.protocolExtensions.first { $0.name == "View" }) + #expect(lineage.events.isEmpty) + #expect(lineage.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUI", "SwiftUICore"])]) + let padding = try #require(lineage.memberLineages.first { $0.key == .mangled("padding") }) + #expect(padding.events.isEmpty) + #expect(padding.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUICore"])]) + // `toolbar` stayed in SwiftUI while its extension gained an image. + #expect(!lineage.memberLineages.contains { $0.key == .mangled("toolbar") }) + #expect(result.keyCollisionsByVersion == nil) + } + + /// Moves compare the images holding a declaration as a set: a caller + /// listing the same images in another order in the next version moved + /// nothing. + @Test("a group listed in another order in the next version moves nothing") + func reorderedGroupMovesNothing() throws { + let result = try evolution([ + [ + image("SwiftUI", protocolExtensions: [protocolExtension(of: "View", members: [record("padding"), record("shared")])]), + image("SwiftUICore", protocolExtensions: [protocolExtension(of: "View", members: [record("toolbar"), record("shared")])]), + ], + [ + image("SwiftUICore", protocolExtensions: [protocolExtension(of: "View", members: [record("toolbar"), record("shared")])]), + image("SwiftUI", protocolExtensions: [protocolExtension(of: "View", members: [record("padding"), record("shared")])]), + ], + ]) + #expect(result.protocolExtensions.allSatisfy { lineage in + lineage.imageMoves == nil && lineage.memberLineages.allSatisfy { $0.imageMoves == nil } + }, "\(result.protocolExtensions)") + } + + /// A collision whose images do not line up with its signatures — only + /// one built by hand or decoded from edited JSON — words its dropped + /// records without images rather than losing a signature. + @Test("dropped records whose images do not line up with them are worded without images") + func misalignedImagesFallBackToSignatures() { + let collision = ABIKeyCollision(key: .mangled("Shared"), containerName: nil, droppedSignatures: ["first", "second"], droppedImageNames: ["UIFoundation"]) + #expect(collision.droppedRecordDescriptions == ["first", "second"]) + } + + @Test("a declaration two images both define is compared once, and the dropped one names its image") + func duplicateAcrossImagesNamesItsImage() throws { + let result = try evolution([ + [image("AppKit", types: [typeContainer("Shared")])], + [image("AppKit", types: [typeContainer("Shared")]), image("UIFoundation", types: [typeContainer("Shared")])], + ]) + let collisions = try #require(result.keyCollisionsByVersion) + #expect(collisions[0].isEmpty) + #expect(collisions[1] == [ABIKeyCollision(key: .mangled("Shared"), containerName: nil, droppedSignatures: ["Shared"], droppedImageNames: ["UIFoundation"])]) + } + + @Test("a move across versions that could not show the member is placed between the observations around them") + func moveAcrossHiddenVersions() throws { + let result = try evolution([ + [image("SwiftUI", types: [typeContainer("Gauge", members: [record("calibrated", isExported: false)])])], + [image("SwiftUI", types: [typeContainer("Gauge")], hasLocalSwiftSymbols: false)], + [ + image("SwiftUI", types: [typeContainer("Gauge")]), + image("SwiftUICore", typeExtensions: [plainExtension(of: "Gauge", members: [record("calibrated", isExported: false)])]), + ], + ]) + let lineage = try #require(result.types.first { $0.name == "Gauge" }) + let calibrated = try #require(lineage.memberLineages.first { $0.key == .mangled("calibrated") }) + #expect(calibrated.presenceStates == [.present, .inferredPresent, .present]) + #expect(calibrated.imageMoves == [ImageMove(versionIndex: 2, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUICore"], earliestVersionIndex: 1)]) + #expect(calibrated.imageMoves?.first?.phrase(on: result.versions) == "moved between 1.0 and 3.0: SwiftUI → SwiftUICore") + } + + @Test("a version hides non-exported members when any image of its group lacks local Swift symbols") + func anyStrippedImageHidesTheVersionsNonExportedMembers() throws { + let result = try evolution([ + [image("SwiftUI", types: [typeContainer("Gauge", members: [record("calibrated", isExported: false)])])], + [image("SwiftUI", types: [typeContainer("Gauge")]), image("SwiftUICore", hasLocalSwiftSymbols: false)], + [image("SwiftUI", types: [typeContainer("Gauge", members: [record("calibrated", isExported: false)])])], + ]) + #expect(result.versionIndicesWithoutLocalSwiftSymbols == [1]) + let lineage = try #require(result.types.first { $0.name == "Gauge" }) + let calibrated = try #require(lineage.memberLineages.first { $0.key == .mangled("calibrated") }) + #expect(calibrated.events.isEmpty) + #expect(calibrated.presenceStates == [.present, .inferredPresent, .present]) + } + + @Test("each version names the images of its group, an empty group holding nothing") + func versionsNameTheirImages() throws { + let result = try evolution([ + [], + [image("AppKit", types: [typeContainer("NSView")]), image("UIFoundation")], + ]) + #expect(result.versions.map(\.imageNames) == [[], ["AppKit", "UIFoundation"]]) + let lineage = try #require(result.types.first { $0.name == "NSView" }) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .added)]) + #expect(result.imagePresences == [ + ImagePresence(imageName: "AppKit", presence: [false, true]), + ImagePresence(imageName: "UIFoundation", presence: [false, true]), + ]) + } + + @Test("an evolution of one image per version names no images and records no moves in its JSON") + func oneImagePerVersionKeepsItsJSON() throws { + let result = try ABIEvolutionBuilder().evolution( + of: [ABISnapshot(types: [typeContainer("Text")]), ABISnapshot(types: [typeContainer("Text"), typeContainer("Label")])], + versions: [ABIVersionDescriptor(label: "1.0"), ABIVersionDescriptor(label: "2.0")] + ) + let json = String(decoding: try ABIJSON.encoder().encode(result), as: UTF8.self) + #expect(!json.contains("imageNames")) + #expect(!json.contains("imageMoves")) + #expect(result.imagePresences == nil) + } +} + +@Suite("ABIEvolutionReporter: versions made up of groups of images") +struct ABIImageGroupEvolutionReportTests { + private func splitReport() throws -> String { + ABIEvolutionReporter().report(try evolution([ + [image("SwiftUI", types: [typeContainer("Text", members: [record("body")])])], + [image("SwiftUI"), image("SwiftUICore", types: [typeContainer("Text", members: [record("body")])])], + ])) + } + + @Test("the header names each image with the versions holding it") + func headerNamesTheImageGroup() throws { + #expect(try splitReport().hasPrefix(""" + ABI evolution across 2 versions: 1.0 → 2.0 + Image group: + [●●] SwiftUI + [○●] SwiftUICore + """)) + } + + @Test("a move reads among the declaration's events") + func moveReadsAmongTheEvents() throws { + #expect(try splitReport().contains(""" + [●●] Text + > moved in 2.0: SwiftUI → SwiftUICore + """)) + } + + @Test("the transition summary counts moves without letting them weigh on the verdict") + func summaryCountsMoves() throws { + #expect(try splitReport().contains(" 1.0 → 2.0: 1 moved · additive")) + } + + @Test("a dropped duplicate names its image") + func droppedDuplicateNamesItsImage() throws { + let report = ABIEvolutionReporter().report(try evolution([ + [image("AppKit", types: [typeContainer("Shared")])], + [image("AppKit", types: [typeContainer("Shared")]), image("UIFoundation", types: [typeContainer("Shared")])], + ])) + #expect(report.contains(" 2.0 · dropped: Shared (UIFoundation)")) + } +} diff --git a/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift b/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift index 2e89ba8e1..d8002c451 100644 --- a/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift +++ b/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift @@ -34,6 +34,21 @@ struct ABISnapshotDocumentTests { #expect(decoded == document) } + @Test("the symbol-table facts survive a round trip") + func symbolTableFactsRoundTrip() throws { + let member = MemberRecord( + identityKey: .mangled("$s3Foo3baryyF"), + payloadKey: .mangled("$s3Foo3baryyF"), + kind: .function, + signature: "bar()", + isExported: false + ) + let document = ABISnapshotDocument(snapshot: ABISnapshot(globalFunctions: [member], hasLocalSwiftSymbols: false)) + let decoded = try ABISnapshotDocument.decode(from: document.encoded()) + #expect(decoded.snapshot.hasLocalSwiftSymbols == false) + #expect(decoded.snapshot.globalFunctions.first?.isExported == false) + } + @Test("encoding is byte-stable") func byteStableEncoding() throws { let document = sampleDocument() diff --git a/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift new file mode 100644 index 000000000..555e87cc3 --- /dev/null +++ b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift @@ -0,0 +1,345 @@ +@testable import SwiftDiffing +import Testing +import Foundation + +// MARK: - Versions that cannot show non-exported members +// +// Evolution proposal `evolution-unobservable-presence`: a version whose image +// carries no local Swift symbols cannot show a member only a non-exported +// symbol evidences. Driven with hand-built snapshots, like the other +// `ABIEvolutionBuilder` suites, so each rule is pinned without a Mach-O. + +private func record( + _ identity: String, + payload: String? = nil, + kind: MemberKind = .function, + isExported: Bool? = false +) -> MemberRecord { + MemberRecord( + identityKey: .mangled(identity), + payloadKey: .mangled(payload ?? identity), + kind: kind, + signature: identity, + isExported: isExported + ) +} + +private func container(_ name: String, kind: ContainerKind = .type, members: [MemberRecord] = []) -> ContainerSnapshot { + ContainerSnapshot(key: .printed(name), name: name, kind: kind, members: members) +} + +/// A version that keeps its local Swift symbols. +private func symbolRich(_ types: [ContainerSnapshot] = [], typeExtensions: [ContainerSnapshot] = [], conformanceExtensions: [ContainerSnapshot] = []) -> ABISnapshot { + ABISnapshot(types: types, typeExtensions: typeExtensions, conformanceExtensions: conformanceExtensions) +} + +/// A version stripped of its local Swift symbols. +private func stripped(_ types: [ContainerSnapshot] = [], typeExtensions: [ContainerSnapshot] = [], conformanceExtensions: [ContainerSnapshot] = []) -> ABISnapshot { + ABISnapshot(types: types, typeExtensions: typeExtensions, conformanceExtensions: conformanceExtensions, hasLocalSwiftSymbols: false) +} + +private func evolution(_ snapshots: [ABISnapshot]) throws -> ABIEvolution { + try ABIEvolutionBuilder().evolution( + of: snapshots.map { ABISnapshotDocument(snapshot: $0) }, + labels: snapshots.indices.map { "\($0 + 1).0" } + ) +} + +private func memberLineage(_ key: String, in result: ABIEvolution, container containerName: String = "Foo") throws -> MemberLineage { + let containerLineage = try #require(result.allContainerLineages.first { $0.name == containerName }) + return try #require(containerLineage.memberLineages.first { $0.key == .mangled(key) }) +} + +@Suite("ABIEvolutionBuilder: versions without local Swift symbols") +struct ABIUnobservablePresenceTests { + @Test("a non-exported member a version cannot show is inferred present between two observations of it") + func inferredPresentBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("hidden")])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("hidden")])]), + ]) + let lineage = try memberLineage("hidden", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.presence == [true, true, true]) + #expect(lineage.events.isEmpty) + #expect(lineage.latestSignature == "hidden") + #expect(result.versionIndicesWithoutLocalSwiftSymbols == [1]) + } + + @Test("a removal across versions that cannot show the member is placed between the observations around them") + func removalPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + let lineage = try memberLineage("retired", in: result) + #expect(lineage.presenceStates == [.present, .unobservable, .absent]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .removed, oldSignature: "retired", earliestVersionIndex: 1)]) + } + + @Test("an addition across versions that cannot show the member is placed between the observations around them") + func additionPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo")]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("fresh")])]), + ]) + let lineage = try memberLineage("fresh", in: result) + #expect(lineage.presenceStates == [.absent, .unobservable, .present]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .added, newSignature: "fresh", earliestVersionIndex: 1)]) + } + + @Test("a payload change across versions that cannot show the member is placed between the observations around them") + func modificationPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("value", payload: "get", kind: .variable)])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("value", payload: "get,set", kind: .variable)])]), + ]) + let lineage = try memberLineage("value", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .modified, oldSignature: "value", newSignature: "value", earliestVersionIndex: 1)]) + } + + @Test("an exported member missing from a version without local Swift symbols is an observed removal") + func exportedMemberAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("public", isExported: true)])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("public", in: result) + #expect(lineage.presenceStates == nil) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed, oldSignature: "public")]) + } + + @Test("a member the image's metadata records stays observable without local Swift symbols") + func metadataMemberAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("field:count", payload: "Int", kind: .field, isExported: nil)])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("field:count", in: result) + #expect(lineage.presenceStates == nil) + #expect(lineage.events.map(\.status) == [.removed]) + } + + @Test("a member whose only neighbour is exported on one side and not on the other is not seen gone") + func oneNonExportedNeighbourHides() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("promoted", isExported: false)])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("promoted", isExported: true)])]), + ]) + let lineage = try memberLineage("promoted", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events.isEmpty) + } + + @Test("versions that cannot show the member at an end of the axis claim nothing") + func spanReachingTheAxisEndStaysUnobservable() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("trailing")])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("trailing", in: result) + #expect(lineage.presenceStates == [.present, .unobservable]) + #expect(lineage.presence == [true, false]) + #expect(lineage.events.isEmpty) + } + + @Test("two absences around versions that cannot show the member infer nothing") + func absencesAroundASpanClaimNothing() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("gone")])]), + symbolRich([container("Foo")]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + let lineage = try memberLineage("gone", in: result) + #expect(lineage.presenceStates == [.present, .absent, .unobservable, .absent]) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed, oldSignature: "gone")]) + } + + /// The container comes and goes around the stripped version, so the + /// member has no event of its own, and the span it cannot be seen in + /// lies between two absences: nothing to tell, so no lineage. + @Test("a member unseen only between two absences carries no lineage of its own") + func spanBetweenAbsencesKeepsNoLineage() throws { + let result = try evolution([ + symbolRich(), + stripped([container("Foo")]), + symbolRich(), + symbolRich([container("Foo", members: [record("late")])]), + ]) + let lineage = try #require(result.types.first) + #expect(lineage.events.map(\.status) == [.added, .removed, .added]) + #expect(lineage.memberLineages.isEmpty) + } + + @Test("an extension made up only of non-exported members cannot be seen where they cannot") + func extensionOfHiddenMembersIsHidden() throws { + let result = try evolution([ + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + stripped(), + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + ]) + let lineage = try #require(result.typeExtensions.first) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events.isEmpty) + } + + /// The members of an added or removed container carry no lineage of + /// their own; neither do the members of a container a version cannot + /// show, unseen only because it is. + @Test("a member unseen only where its container is unseen is left to the container's lineage") + func memberOfAnUnseenContainerHasNoLineage() throws { + let result = try evolution([ + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + stripped(), + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + ]) + #expect(result.typeExtensions.first?.memberLineages.isEmpty == true) + } + + @Test("a conformance stays observable without local Swift symbols") + func conformanceAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich(conformanceExtensions: [container("Foo: Equatable", kind: .conformanceExtension, members: [record("equals")])]), + stripped(), + ]) + let lineage = try #require(result.conformanceExtensions.first) + #expect(lineage.presenceStates == nil) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed)]) + } + + @Test("a change across versions that cannot show the member counts toward the transition that first observes it") + func spanningRemovalIsBreakingWhereObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + #expect(result.transitionCompatibilities == [.additive, .breaking]) + } + + @Test("an axis whose every version keeps its local Swift symbols encodes none of the new fields") + func symbolRichAxisEncodingIsUnchanged() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("a")])]), + symbolRich([container("Foo")]), + ]) + let json = try #require(String(data: ABIJSON.encoder().encode(result), encoding: .utf8)) + for key in ["presenceStates", "latestSignature", "earliestVersionIndex", "versionIndicesWithoutLocalSwiftSymbols"] { + #expect(!json.contains(key), "\(key) leaked into the encoding of an axis without stripped versions") + } + } +} + +// MARK: - Two-sided diff + +@Suite("ABIDiffer: a side without local Swift symbols") +struct ABIDifferUnobservablePresenceTests { + @Test("a non-exported member the new side cannot show is listed apart, neither removed nor breaking") + func hiddenOnTheNewSide() { + let diff = ABIDiffer().diff( + old: symbolRich([container("Foo", members: [record("hidden"), record("public", isExported: true)])]), + new: stripped([container("Foo")]) + ) + let fooChange = diff.types.first { $0.name == "Foo" } + #expect(fooChange?.memberChanges.map(\.key) == [.mangled("public")]) + #expect(diff.unobservableDeclarations == [ + UnobservableDeclaration(side: .new, key: .mangled("hidden"), containerName: "Foo", containerKind: .type, memberKind: .function, signature: "hidden"), + ]) + } + + @Test("a non-exported member the old side cannot show is listed apart, never added") + func hiddenOnTheOldSide() { + let diff = ABIDiffer().diff( + old: stripped([container("Foo")]), + new: symbolRich([container("Foo", members: [record("hidden")])]) + ) + #expect(diff.isEmpty) + #expect(diff.unobservableDeclarations?.map(\.side) == [.old]) + } + + @Test("an extension the new side cannot show is listed apart, its members with it") + func hiddenExtension() { + let diff = ABIDiffer().diff( + old: symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + new: stripped() + ) + #expect(diff.isEmpty) + #expect(diff.unobservableDeclarations?.map(\.key) == [.printed("Swift.Int")]) + #expect(!diff.hasBreakingChange) + } + + @Test("for two versions the diff lists exactly what the evolution leaves unobservable") + func pairwiseConsistencyWithAStrippedSide() throws { + let old = symbolRich( + [container("Foo", members: [record("hidden"), record("public", isExported: true)])], + typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])] + ) + let new = stripped([container("Foo")]) + let diff = ABIDiffer().diff(old: old, new: new) + let result = try evolution([old, new]) + + let changedMemberKeys = Set(diff.types.flatMap(\.memberChanges).map(\.key)) + let eventMemberKeys = Set(result.allContainerLineages.flatMap(\.memberLineages).filter { !$0.events.isEmpty }.map(\.key)) + #expect(changedMemberKeys == eventMemberKeys) + + let unobservableKeys = Set((diff.unobservableDeclarations ?? []).map(\.key)) + let unobservableLineageKeys = Set( + result.allContainerLineages.filter { $0.presenceStates?.contains(.unobservable) == true }.map(\.key) + + result.allContainerLineages.flatMap(\.memberLineages).filter { $0.presenceStates?.contains(.unobservable) == true }.map(\.key) + ) + #expect(unobservableKeys == unobservableLineageKeys) + } +} + +// MARK: - Reports + +@Suite("Reports: versions without local Swift symbols") +struct UnobservablePresenceReportTests { + @Test("the timeline report marks what the stripped version cannot show") + func timelineReport() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("kept"), record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("kept")])]), + ]) + let report = ABIEvolutionReporter().report(result) + #expect(report == """ + ABI evolution across 3 versions: 1.0 → 2.0 → 3.0 + + Transitions: + 1.0 → 2.0: no changes + 2.0 → 3.0: 1 removed · ABI-breaking + (1 of them happened somewhere between 1.0 and 3.0: the versions in between could not show them) + First ABI-breaking transition: 2.0 → 3.0 + No local Swift symbols, so non-exported members cannot be seen: 2.0 (◍ inferred present, ◌ not observable) + + Types: + [●●●] Foo + [●◍●] kept + ◍ inferred present in 2.0 + [●◌○] retired + - removed between 1.0 and 3.0 + """) + } + + @Test("the diff report lists what one side cannot show") + func diffReport() { + let diff = ABIDiffer().diff( + old: symbolRich([container("Foo", members: [record("hidden")])]), + new: stripped([container("Foo")]) + ) + #expect(ABIDiffReporter().report(diff) == """ + No ABI changes. + + Not observable on the new side — it carries no local Swift symbols, so these are neither removed nor added: + hidden + """) + } +} diff --git a/Tests/SwiftDumpTests/ConstrainedExistentialFieldDumpTests.swift b/Tests/SwiftDumpTests/ConstrainedExistentialFieldDumpTests.swift new file mode 100644 index 000000000..e67a442ef --- /dev/null +++ b/Tests/SwiftDumpTests/ConstrainedExistentialFieldDumpTests.swift @@ -0,0 +1,29 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftDump +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// The dump printed a stored property of a constrained existential type +/// (`any Boxed`) as the symbolic reference its field record holds — +/// `symbolic existential type (non-unique) 0x0 ` — which names no +/// protocol (evolution proposal `existential-any`). +@Suite +final class ConstrainedExistentialFieldDumpTests: MachOFileTests, SnapshotDumpableTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + @Test func dumpNamesTheProtocolOfAConstrainedExistentialField() async throws { + let dump = try await collectDumpTypes(for: machOFile, options: [.struct]) + let fieldLines = dump.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + let boxed = try #require(fieldLines.first { $0.hasPrefix("var boxed: ") }) + let optionalBoxed = try #require(fieldLines.first { $0.hasPrefix("var optionalBoxed: ") }) + #expect(boxed.hasPrefix("var boxed: any SymbolTestsCore.GenericFieldLayout.Boxed<"), "\(boxed)") + #expect(boxed.contains("Swift.Int"), "\(boxed)") + #expect(!boxed.contains("symbolic existential type"), "\(boxed)") + #expect(optionalBoxed.hasPrefix("var optionalBoxed: (any SymbolTestsCore.GenericFieldLayout.Boxed<"), "\(optionalBoxed)") + #expect(optionalBoxed.contains("Swift.String"), "\(optionalBoxed)") + } +} diff --git a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift index f1e1ce9e5..8a8cfedee 100644 --- a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift +++ b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift @@ -6,7 +6,8 @@ import MachOFoundation @testable import SwiftDump import SwiftDeclarationRendering import SwiftInspection -@testable import MachOTestingSupport +import SwiftObjCInterop +@testable import SwiftSectionTestingSupport /// The dump path's rendering of a class the source renamed for the /// Objective-C runtime (evolution proposal `objc-custom-class-name`): the diff --git a/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift new file mode 100644 index 000000000..d2318ae48 --- /dev/null +++ b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import SwiftSectionTestingSupport + +/// `dump` with `DemangleOptions.useExistentialAny` (evolution proposal +/// `existential-any`): the field types swift-demangling prints spell +/// existentials with the `any` keyword, by the compiler's rules. The dump +/// turns the option on by default; these cases pin the field lines with and +/// without it. +@Suite +struct ExistentialAnyDumpTests { + private func shapesDump(options: DemangleOptions) async throws -> String { + let machOFile = try ExistentialAnyFixture.machOFile() + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .struct(let structDescriptor) = typeContextDescriptor, try structDescriptor.name(in: machOFile.context) == "Shapes" else { continue } + return try await Struct(descriptor: structDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string + } + Issue.record("struct Shapes not found") + return "" + } + + @Test(arguments: [ + ("var single: ExistentialAnyFixture.Marker\n", "var single: any ExistentialAnyFixture.Marker\n"), + ("var classBound: ExistentialAnyFixture.Marker & Swift.AnyObject\n", "var classBound: any ExistentialAnyFixture.Marker & Swift.AnyObject\n"), + ("var anything: Any\n", "var anything: Any\n"), + ("var anyObject: Swift.AnyObject\n", "var anyObject: Swift.AnyObject\n"), + ("var collection: Swift.Collection\n", "var collection: any Swift.Collection\n"), + ("var optional: ExistentialAnyFixture.Marker?\n", "var optional: (any ExistentialAnyFixture.Marker)?\n"), + ("var optionalAnything: Any?\n", "var optionalAnything: Any?\n"), + ("var existentialMetatype: ExistentialAnyFixture.Marker.Type\n", "var existentialMetatype: any ExistentialAnyFixture.Marker.Type\n"), + ("var compositionMetatype: ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker.Type\n", "var compositionMetatype: any (ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker).Type\n"), + ("var anythingMetatype: Any.Type\n", "var anythingMetatype: any Any.Type\n"), + ("var optionalExistentialMetatype: ExistentialAnyFixture.Marker.Type?\n", "var optionalExistentialMetatype: (any ExistentialAnyFixture.Marker.Type)?\n"), + ("var protocolMetatype: ExistentialAnyFixture.Marker.Protocol\n", "var protocolMetatype: (any ExistentialAnyFixture.Marker).Type\n"), + ("var existentialArray: [ExistentialAnyFixture.Marker]\n", "var existentialArray: [any ExistentialAnyFixture.Marker]\n"), + ("var existentialFunction: (ExistentialAnyFixture.Marker) -> ExistentialAnyFixture.SecondMarker\n", "var existentialFunction: (any ExistentialAnyFixture.Marker) -> any ExistentialAnyFixture.SecondMarker\n"), + ]) + func fieldTypesFollowTheOption(bareSpelling: String, spellingWithKeyword: String) async throws { + let bareDump = try await shapesDump(options: .interface) + #expect(bareDump.contains(bareSpelling), "\(bareDump)") + let dump = try await shapesDump(options: DemangleOptions.interface.union(.useExistentialAny)) + #expect(dump.contains(spellingWithKeyword), "\(dump)") + } + + /// A constrained existential carries its keyword with or without the + /// option, and names its protocol: its field record holds a shape plus the + /// arguments, which used to print as `symbolic existential type … <…>`. + @Test func constrainedExistentialFieldsNameTheirProtocol() async throws { + for options in [DemangleOptions.interface, DemangleOptions.interface.union(.useExistentialAny)] { + let fieldLines = try await shapesDump(options: options).split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + let constrained = try #require(fieldLines.first { $0.hasPrefix("var constrained: ") }) + let constrainedMetatype = try #require(fieldLines.first { $0.hasPrefix("var constrainedMetatype: ") }) + #expect(constrained.hasPrefix("var constrained: any ExistentialAnyFixture.Boxed<") && constrained.contains("Swift.Int"), "\(constrained)") + #expect(constrainedMetatype.hasPrefix("var constrainedMetatype: any ExistentialAnyFixture.Boxed<") && constrainedMetatype.hasSuffix(">.Type"), "\(constrainedMetatype)") + } + } +} diff --git a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift index 9640b45c8..b4371ed4a 100644 --- a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift @@ -5,9 +5,9 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Dump-path coverage for the `// not exported` annotation (evolution /// proposal 0008), pinning the two false-positive classes the member-symbol @@ -61,7 +61,7 @@ final class ExportStatusDumpAnnotationTests: MachOFileTests, SnapshotDumpableTes /// via the store so the exemption, not fixture luck, is what's tested. @Test func overrideImplementationSymbolIsExempt() async throws { let unsafeMachOFile = machOFile - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: Self.overrideImplementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: Self.overrideImplementationName, in: unsafeMachOFile) == false) let output = try await dumpClasses(printExportStatus: true, inNamespace: "Classes") let annotated = try isAnnotated(in: output) { line in @@ -72,8 +72,8 @@ final class ExportStatusDumpAnnotationTests: MachOFileTests, SnapshotDumpableTes @Test func objcDynamicImplementationSymbolIsExempt() async throws { let unsafeMachOFile = machOFile - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: Self.objcDynamicImplementationName, in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.containsSymbol(named: Self.objcDynamicImplementationName + "To", in: unsafeMachOFile)) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: Self.objcDynamicImplementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.containsSymbol(named: Self.objcDynamicImplementationName + "To", in: unsafeMachOFile)) let output = try await dumpClasses(printExportStatus: true, inNamespace: "Attributes") let annotated = try isAnnotated(in: output) { line in diff --git a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift index 68ffff73e..ca505c8b0 100644 --- a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift +++ b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -import MachOTestingSupport +import SwiftSectionTestingSupport /// The dump path's half of `GenericParameterDepthNamingTests`: the dumpers /// render a generic declaration's parameter clause through the same diff --git a/Tests/SwiftDumpTests/InitAccessorDumpTests.swift b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift new file mode 100644 index 000000000..84c78e398 --- /dev/null +++ b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift @@ -0,0 +1,85 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import SwiftSectionTestingSupport + +/// `dump` lists a property's SE-0400 init accessor among its type's variable +/// symbols, with the address and export status every member symbol gets +/// (evolution proposal `init-accessor-recovery`). +@Suite +struct InitAccessorDumpTests { + private typealias Property = InitAccessorFixture.Property + + private func typeDumps(_ variant: InitAccessorFixture.Variant) async throws -> [String: String] { + let machOFile = try await InitAccessorFixture.machOFile(variant) + var dumps: [String: String] = [:] + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + switch typeContextDescriptor { + case .struct(let structDescriptor): + let name = try structDescriptor.name(in: machOFile.context) + dumps[name] = try await Struct(descriptor: structDescriptor, in: machOFile.context).dump(using: .demangleOptions(.interface), in: machOFile).string + case .class(let classDescriptor): + let name = try classDescriptor.name(in: machOFile.context) + dumps[name] = try await Class(descriptor: classDescriptor, in: machOFile.context).dump(using: .demangleOptions(.interface), in: machOFile).string + default: + continue + } + } + return dumps + } + + /// The start of the line naming `property`'s init accessor symbol. + private func initAccessorSymbolPrefix(of property: Property) -> String { + "\(InitAccessorFixture.moduleName).\(property.typeName).\(property.name).init : " + } + + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func everyInitAccessorIsListed(variant: InitAccessorFixture.Variant) async throws { + let dumps = try await typeDumps(variant) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let dump = try #require(dumps[property.typeName], "no type \(property.typeName)") + #expect(dump.contains(initAccessorSymbolPrefix(of: property)), "\(property) not in:\n\(dump)") + } + let angle = try #require(dumps["Angle"]) + #expect(angle.contains("InitAccessorFixture.Angle.radians.init : Swift.Double"), "\(angle)") + } + + /// The line above each init accessor says what it is inferred to + /// initialize, or that the binary does not record it. + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func everyInitAccessorSaysWhatItInitializes(variant: InitAccessorFixture.Variant) async throws { + let dumps = try await typeDumps(variant) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let dump = try #require(dumps[property.typeName], "no type \(property.typeName)") + let lines = dump.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + let index = try #require(lines.firstIndex { $0.hasPrefix(initAccessorSymbolPrefix(of: property)) }, "\(property) not in:\n\(dump)") + let expectedComment = if let fieldNames = InitAccessorFixture.inferredInitializedFieldNames[property] { + "// init accessor: initializes \(fieldNames.joined(separator: ", ")) (inferred from the stored property's name and type)" + } else { + "// init accessor: the binary does not record which stored properties it initializes" + } + #expect(lines[index - 1] == expectedComment, "\(property):\n\(dump)") + } + } + + @Test(arguments: [InitAccessorFixture.Variant.releaseDeadStripped, .releaseStripped]) + func aStrippedImageListsOnlyTheExportedOnes(variant: InitAccessorFixture.Variant) async throws { + let dumps = try await typeDumps(variant) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let dump = try #require(dumps[property.typeName], "no type \(property.typeName)") + #expect(dump.contains(initAccessorSymbolPrefix(of: property)) == InitAccessorFixture.propertiesWithExportedInitAccessors.contains(property), "\(property) in:\n\(dump)") + } + } + + /// The function SwiftUICore keeps under a stored property's init + /// accessor name is a member symbol like any other. + @Test(arguments: InitAccessorFixture.Variant.allCases) + func theStoredPropertysInitAccessorSymbolIsListed(variant: InitAccessorFixture.Variant) async throws { + let property = InitAccessorFixture.storedPropertyWithInitAccessorSymbol + let dump = try #require(try await typeDumps(variant)[property.typeName]) + #expect(dump.contains(initAccessorSymbolPrefix(of: property) + "Swift.Int"), "\(dump)") + } +} diff --git a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift index e0a9efe5f..7b8bbdcc2 100644 --- a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift +++ b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The dump declares a local type under the compiler's full name and lists /// the members its symbols attribute to it (evolution proposal diff --git a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift index 97d489217..9e28b40aa 100644 --- a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift +++ b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftDump -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// `dump` with `DemangleOptions.useModuleSelectors` (evolution proposal /// `module-selectors`): the names swift-demangling prints follow the option, diff --git a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift index 0a44e5655..52589d0e2 100644 --- a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import SwiftDump import SwiftDeclarationRendering -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The dump path's rendering of an `@objc @implementation` class (evolution /// proposal `objc-implementation-class-recognition`): everything the binary diff --git a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift index 2c608f77d..5fd06e5d8 100644 --- a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift @@ -6,8 +6,9 @@ import MachOFoundation @testable import SwiftDump import SwiftDeclarationRendering import SwiftInspection +import SwiftObjCInterop import SwiftThunkAnalysis -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The dump path's rendering of the ObjC member facts (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): diff --git a/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift new file mode 100644 index 000000000..77417b07d --- /dev/null +++ b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift @@ -0,0 +1,48 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import SwiftSectionTestingSupport + +/// `dump` names the macro that generated an `@Observable` class's members on +/// its header line and keeps every member as the records have them +/// (evolution proposal `observable-macro-folding`). +@Suite +struct ObservableMacroDumpTests { + private func classDumps(_ variant: ObservableMacroFixture.Variant, options: DemangleOptions = .interface) async throws -> [String: String] { + let machOFile = try await ObservableMacroFixture.machOFile(variant) + var dumps: [String: String] = [:] + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .class(let classDescriptor) = typeContextDescriptor else { continue } + let name = try classDescriptor.name(in: machOFile.context) + dumps[name] = try await Class(descriptor: classDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string + } + return dumps + } + + @Test(arguments: ObservableMacroFixture.Variant.allCases) + func theHeaderNamesTheMacro(variant: ObservableMacroFixture.Variant) async throws { + let dumps = try await classDumps(variant) + for name in ObservableMacroFixture.observableClassNames { + let dump = try #require(dumps[name], "no class \(name)") + #expect(dump.hasPrefix("@Observation.Observable class ObservableMacroFixture."), "\(dump)") + } + for name in ObservableMacroFixture.lookalikeTypeNames where name != "Clamped" { + let dump = try #require(dumps[name], "no class \(name)") + #expect(!dump.contains("@Observation"), "\(dump)") + } + // Everything the macro generated stays. + let finalModel = try #require(dumps["FinalModel"]) + for generated in ["_$observationRegistrar", "var _name: Swift.String"] { + #expect(finalModel.contains(generated), "\(generated) not in:\n\(finalModel)") + } + } + + @Test func theAttributeFollowsTheDemangleOptions() async throws { + let dumps = try await classDumps(.release, options: DemangleOptions.interface.union([.useModuleSelectors, .useExistentialAny])) + let dump = try #require(dumps["FinalModel"]) + #expect(dump.hasPrefix("@Observation::Observable class ObservableMacroFixture::FinalModel"), "\(dump)") + } +} diff --git a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift index a6d80dc97..e805785e5 100644 --- a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift +++ b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift @@ -4,8 +4,8 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Issue #115: two top-level `private struct PrivateDoppelganger` declarations /// (one per fixture file) share their interface-printed name — the private diff --git a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift index 7047b49b6..b77ab749e 100644 --- a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift +++ b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftDump -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// A protocol's same-type or superclass requirement whose right-hand side is /// a composite type prints that type (evolution proposal diff --git a/Tests/SwiftDumpTests/Snapshots/SymbolTestsCoreDumpSnapshotTests.swift b/Tests/SwiftDumpTests/Snapshots/SymbolTestsCoreDumpSnapshotTests.swift index 9b75a5be8..b5d2e28e5 100644 --- a/Tests/SwiftDumpTests/Snapshots/SymbolTestsCoreDumpSnapshotTests.swift +++ b/Tests/SwiftDumpTests/Snapshots/SymbolTestsCoreDumpSnapshotTests.swift @@ -5,8 +5,8 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite(.serialized, .snapshots(record: .missing)) final class SymbolTestsCoreDumpSnapshotTests: MachOFileTests, SnapshotDumpableTests, @unchecked Sendable { diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/asyncSequenceSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/asyncSequenceSnapshot.1.txt index 047626e0f..48eba4bc5 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/asyncSequenceSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/asyncSequenceSnapshot.1.txt @@ -36,7 +36,7 @@ extension SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator: Sw associated type descriptor for Swift.AsyncIteratorProtocol.Element associated type descriptor for Swift.AsyncIteratorProtocol.Failure async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next() async throws -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore - async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated Swift.Actor?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore + async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated (any Swift.Actor)?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore } extension SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest: Swift.AsyncSequence { associated conformance descriptor for Swift.AsyncSequence.Swift.AsyncSequence.AsyncIterator: Swift.AsyncIteratorProtocol @@ -50,7 +50,7 @@ extension SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIter associated type descriptor for Swift.AsyncIteratorProtocol.Element associated type descriptor for Swift.AsyncIteratorProtocol.Failure async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next() async throws -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore - async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated Swift.Actor?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore + async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated (any Swift.Actor)?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore } extension SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest: Swift.AsyncSequence { associated conformance descriptor for Swift.AsyncSequence.Swift.AsyncSequence.AsyncIterator: Swift.AsyncIteratorProtocol @@ -64,7 +64,7 @@ extension SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncItera associated type descriptor for Swift.AsyncIteratorProtocol.Element associated type descriptor for Swift.AsyncIteratorProtocol.Failure async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next() async throws -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore - async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated Swift.Actor?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore + async function pointer to protocol witness for Swift.AsyncIteratorProtocol.next(isolation: isolated (any Swift.Actor)?) async throws(A.Failure) -> A.Element? in conformance SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncIterator : Swift.AsyncIteratorProtocol in SymbolTestsCore } extension SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest: Swift.AsyncSequence { associated conformance descriptor for Swift.AsyncSequence.Swift.AsyncSequence.AsyncIterator: Swift.AsyncIteratorProtocol diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/classesSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/classesSnapshot.1.txt index ce4722890..cfb968c20 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/classesSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/classesSnapshot.1.txt @@ -34,7 +34,7 @@ class SymbolTestsCore.Classes.ExternalObjCSubclassTest: NSObject { SymbolTestsCore.Classes.ExternalObjCSubclassTest.init() -> SymbolTestsCore.Classes.ExternalObjCSubclassTest // overrides -[NSObject init] (To thunk symbol at the IMP) /* Function */ - SymbolTestsCore.Classes.ExternalObjCSubclassTest.isKind(of: Swift.AnyObject.Type) -> Swift.Bool // overrides -[NSObject isKindOfClass:] (To thunk symbol at the IMP) + SymbolTestsCore.Classes.ExternalObjCSubclassTest.isKind(of: any Swift.AnyObject.Type) -> Swift.Bool // overrides -[NSObject isKindOfClass:] (To thunk symbol at the IMP) } class SymbolTestsCore.Classes.ClassTest { /* [Getter] */ SymbolTestsCore.Classes.ClassTest.instanceVariable.getter : Swift.Bool diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/codableSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/codableSnapshot.1.txt index 42cd2e733..e77df9296 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/codableSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/codableSnapshot.1.txt @@ -8,7 +8,7 @@ struct SymbolTestsCore.CodableTests.SynthesizedCodableTest { /* Allocator */ SymbolTestsCore.CodableTests.SynthesizedCodableTest.init(identifier: Swift.Int, name: Swift.String, optionalValue: Swift.Double?) -> SymbolTestsCore.CodableTests.SynthesizedCodableTest - SymbolTestsCore.CodableTests.SynthesizedCodableTest.init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.SynthesizedCodableTest + SymbolTestsCore.CodableTests.SynthesizedCodableTest.init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.SynthesizedCodableTest /* Variable */ SymbolTestsCore.CodableTests.SynthesizedCodableTest.optionalValue.getter : Swift.Double? @@ -19,7 +19,7 @@ struct SymbolTestsCore.CodableTests.SynthesizedCodableTest { SymbolTestsCore.CodableTests.SynthesizedCodableTest.name.setter : Swift.String /* Function */ - SymbolTestsCore.CodableTests.SynthesizedCodableTest.encode(to: Swift.Encoder) throws -> () + SymbolTestsCore.CodableTests.SynthesizedCodableTest.encode(to: any Swift.Encoder) throws -> () } struct SymbolTestsCore.CodableTests.CustomCodableTest { var displayName: Swift.String @@ -27,7 +27,7 @@ struct SymbolTestsCore.CodableTests.CustomCodableTest { /* Allocator */ SymbolTestsCore.CodableTests.CustomCodableTest.init(displayName: Swift.String, hiddenCount: Swift.Int) -> SymbolTestsCore.CodableTests.CustomCodableTest - SymbolTestsCore.CodableTests.CustomCodableTest.init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CustomCodableTest + SymbolTestsCore.CodableTests.CustomCodableTest.init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CustomCodableTest /* Variable */ SymbolTestsCore.CodableTests.CustomCodableTest.displayName.getter : Swift.String @@ -36,7 +36,7 @@ struct SymbolTestsCore.CodableTests.CustomCodableTest { SymbolTestsCore.CodableTests.CustomCodableTest.hiddenCount.setter : Swift.Int /* Function */ - SymbolTestsCore.CodableTests.CustomCodableTest.encode(to: Swift.Encoder) throws -> () + SymbolTestsCore.CodableTests.CustomCodableTest.encode(to: any Swift.Encoder) throws -> () } class SymbolTestsCore.CodableTests.CodableClassTest { var identifier: Swift.Int @@ -49,19 +49,19 @@ class SymbolTestsCore.CodableTests.CodableClassTest { /* [Setter] */ SymbolTestsCore.CodableTests.CodableClassTest.label.setter : Swift.String /* [Modify] */ SymbolTestsCore.CodableTests.CodableClassTest.label.modify : Swift.String /* [ Init ] */ SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(identifier: Swift.Int, label: Swift.String) -> SymbolTestsCore.CodableTests.CodableClassTest - /* [Method] */ func SymbolTestsCore.CodableTests.CodableClassTest.encode(to: Swift.Encoder) throws -> () - /* [ Init ] */ SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest + /* [Method] */ func SymbolTestsCore.CodableTests.CodableClassTest.encode(to: any Swift.Encoder) throws -> () + /* [ Init ] */ SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest /* Allocator */ SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(identifier: Swift.Int, label: Swift.String) -> SymbolTestsCore.CodableTests.CodableClassTest - SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest + SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest /* Deallocator */ SymbolTestsCore.CodableTests.CodableClassTest.__deallocating_deinit /* Constructor */ SymbolTestsCore.CodableTests.CodableClassTest.init(identifier: Swift.Int, label: Swift.String) -> SymbolTestsCore.CodableTests.CodableClassTest - SymbolTestsCore.CodableTests.CodableClassTest.init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest + SymbolTestsCore.CodableTests.CodableClassTest.init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest /* Destructor */ SymbolTestsCore.CodableTests.CodableClassTest.deinit @@ -73,11 +73,11 @@ class SymbolTestsCore.CodableTests.CodableClassTest { SymbolTestsCore.CodableTests.CodableClassTest.label.setter : Swift.String /* Function */ - SymbolTestsCore.CodableTests.CodableClassTest.encode(to: Swift.Encoder) throws -> () + SymbolTestsCore.CodableTests.CodableClassTest.encode(to: any Swift.Encoder) throws -> () /* [Method] Allocator */ method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(identifier: Swift.Int, label: Swift.String) -> SymbolTestsCore.CodableTests.CodableClassTest - method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest + method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.__allocating_init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableClassTest /* [Method] Variable */ method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.identifier.getter : Swift.Int @@ -86,7 +86,7 @@ class SymbolTestsCore.CodableTests.CodableClassTest { method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.label.setter : Swift.String /* [Method] Function */ - method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.encode(to: Swift.Encoder) throws -> () + method descriptor for SymbolTestsCore.CodableTests.CodableClassTest.encode(to: any Swift.Encoder) throws -> () } enum SymbolTestsCore.CodableTests.CodableEnumTest { case withValue(Swift.Int) @@ -94,10 +94,10 @@ enum SymbolTestsCore.CodableTests.CodableEnumTest { case empty /* Allocator */ - SymbolTestsCore.CodableTests.CodableEnumTest.init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableEnumTest + SymbolTestsCore.CodableTests.CodableEnumTest.init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.CodableEnumTest /* Function */ - SymbolTestsCore.CodableTests.CodableEnumTest.encode(to: Swift.Encoder) throws -> () + SymbolTestsCore.CodableTests.CodableEnumTest.encode(to: any Swift.Encoder) throws -> () } struct SymbolTestsCore.CodableTests.GenericCodableTest where A: Swift.Decodable, A: Swift.Encodable { var element: A @@ -105,7 +105,7 @@ struct SymbolTestsCore.CodableTests.GenericCodableTest where A: Swift.Decodab /* Allocator */ SymbolTestsCore.CodableTests.GenericCodableTest.init(element: A, metadata: [Swift.String : Swift.String]) -> SymbolTestsCore.CodableTests.GenericCodableTest - SymbolTestsCore.CodableTests.GenericCodableTest.init(from: Swift.Decoder) throws -> SymbolTestsCore.CodableTests.GenericCodableTest + SymbolTestsCore.CodableTests.GenericCodableTest.init(from: any Swift.Decoder) throws -> SymbolTestsCore.CodableTests.GenericCodableTest /* Variable */ SymbolTestsCore.CodableTests.GenericCodableTest.metadata.getter : [Swift.String : Swift.String] @@ -114,7 +114,7 @@ struct SymbolTestsCore.CodableTests.GenericCodableTest where A: Swift.Decodab SymbolTestsCore.CodableTests.GenericCodableTest.element.setter : A /* Function */ - SymbolTestsCore.CodableTests.GenericCodableTest.encode(to: Swift.Encoder) throws -> () + SymbolTestsCore.CodableTests.GenericCodableTest.encode(to: any Swift.Encoder) throws -> () } enum SymbolTestsCore.CodableTests.GenericCodableTest.CodingKeys { case element @@ -163,34 +163,34 @@ enum SymbolTestsCore.CodableTests.SynthesizedCodableTest.CodingKeys { // MARK: - Protocol Conformances extension SymbolTestsCore.CodableTests.SynthesizedCodableTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.SynthesizedCodableTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.SynthesizedCodableTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.SynthesizedCodableTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.SynthesizedCodableTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.SynthesizedCodableTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CustomCodableTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CustomCodableTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CustomCodableTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CustomCodableTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CustomCodableTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CustomCodableTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CodableClassTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CodableClassTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CodableClassTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CodableClassTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CodableClassTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CodableClassTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CodableEnumTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CodableEnumTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.CodableEnumTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.CodableEnumTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CodableEnumTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.CodableEnumTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.GenericCodableTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.GenericCodableTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.CodableTests.GenericCodableTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.GenericCodableTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.GenericCodableTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.CodableTests.GenericCodableTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.CodableTests.SynthesizedCodableTest.CodingKeys: Swift.CustomStringConvertible { protocol witness for Swift.CustomStringConvertible.description.getter : Swift.String in conformance SymbolTestsCore.CodableTests.SynthesizedCodableTest.CodingKeys : Swift.CustomStringConvertible in SymbolTestsCore diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/distributedActorsSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/distributedActorsSnapshot.1.txt index 24d7931ba..a57fb03ed 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/distributedActorsSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/distributedActorsSnapshot.1.txt @@ -125,10 +125,10 @@ extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Equatabl protocol witness for static Swift.Equatable.== infix(A, A) -> Swift.Bool in conformance SymbolTestsCore.DistributedActors.DistributedActorTest : Swift.Equatable in SymbolTestsCore } extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.DistributedActors.DistributedActorTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.DistributedActors.DistributedActorTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.DistributedActors.DistributedActorTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.DistributedActors.DistributedActorTest : Swift.Decodable in SymbolTestsCore } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Distributed.DistributedActor { base conformance descriptor for Distributed.DistributedActor: Swift.Hashable @@ -155,8 +155,8 @@ extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.E protocol witness for static Swift.Equatable.== infix(A, A) -> Swift.Bool in conformance SymbolTestsCore.DistributedActors.GenericDistributedActorTest : Swift.Equatable in SymbolTestsCore } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.Encodable { - protocol witness for Swift.Encodable.encode(to: Swift.Encoder) throws -> () in conformance SymbolTestsCore.DistributedActors.GenericDistributedActorTest : Swift.Encodable in SymbolTestsCore + protocol witness for Swift.Encodable.encode(to: any Swift.Encoder) throws -> () in conformance SymbolTestsCore.DistributedActors.GenericDistributedActorTest : Swift.Encodable in SymbolTestsCore } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.Decodable { - protocol witness for Swift.Decodable.init(from: Swift.Decoder) throws -> A in conformance SymbolTestsCore.DistributedActors.GenericDistributedActorTest : Swift.Decodable in SymbolTestsCore + protocol witness for Swift.Decodable.init(from: any Swift.Decoder) throws -> A in conformance SymbolTestsCore.DistributedActors.GenericDistributedActorTest : Swift.Decodable in SymbolTestsCore } \ No newline at end of file diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/errorTypesSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/errorTypesSnapshot.1.txt index 9bc0149ee..3bc2ad401 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/errorTypesSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/errorTypesSnapshot.1.txt @@ -18,7 +18,7 @@ enum SymbolTestsCore.ErrorTypes.SimpleErrorTest { enum SymbolTestsCore.ErrorTypes.AssociatedValueErrorTest { case withMessage(Swift.String) case withCode(Swift.Int) - case withContext(message: Swift.String, code: Swift.Int, underlying: Swift.Error?) + case withContext(message: Swift.String, code: Swift.Int, underlying: (any Swift.Error)?) } struct SymbolTestsCore.ErrorTypes.LocalizedErrorTest { let errorDescription: Swift.String? diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/existentialAnySnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/existentialAnySnapshot.1.txt index 675ba37a0..4fef18a7a 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/existentialAnySnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/existentialAnySnapshot.1.txt @@ -2,40 +2,40 @@ enum SymbolTestsCore.ExistentialAny {} struct SymbolTestsCore.ExistentialAny.ExistentialFieldTest { - var simpleExistential: SymbolTestsCore.Protocols.ProtocolTest - var compositionExistential: SymbolTestsCore.Protocols.ProtocolTest - var optionalExistential: SymbolTestsCore.Protocols.ProtocolTest? - var existentialArray: [SymbolTestsCore.Protocols.ProtocolTest] - var existentialDictionary: [Swift.String : SymbolTestsCore.Protocols.ProtocolTest] - var existentialFunction: (SymbolTestsCore.Protocols.ProtocolTest) -> () + var simpleExistential: any SymbolTestsCore.Protocols.ProtocolTest + var compositionExistential: any SymbolTestsCore.Protocols.ProtocolTest + var optionalExistential: (any SymbolTestsCore.Protocols.ProtocolTest)? + var existentialArray: [any SymbolTestsCore.Protocols.ProtocolTest] + var existentialDictionary: [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest] + var existentialFunction: (any SymbolTestsCore.Protocols.ProtocolTest) -> () /* Allocator */ - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.init(simpleExistential: SymbolTestsCore.Protocols.ProtocolTest, compositionExistential: Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest, optionalExistential: SymbolTestsCore.Protocols.ProtocolTest?, existentialArray: [SymbolTestsCore.Protocols.ProtocolTest], existentialDictionary: [Swift.String : SymbolTestsCore.Protocols.ProtocolTest], existentialFunction: (SymbolTestsCore.Protocols.ProtocolTest) -> ()) -> SymbolTestsCore.ExistentialAny.ExistentialFieldTest + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.init(simpleExistential: any SymbolTestsCore.Protocols.ProtocolTest, compositionExistential: any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest, optionalExistential: (any SymbolTestsCore.Protocols.ProtocolTest)?, existentialArray: [any SymbolTestsCore.Protocols.ProtocolTest], existentialDictionary: [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest], existentialFunction: (any SymbolTestsCore.Protocols.ProtocolTest) -> ()) -> SymbolTestsCore.ExistentialAny.ExistentialFieldTest /* Variable */ - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.simpleExistential.getter : SymbolTestsCore.Protocols.ProtocolTest - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.simpleExistential.setter : SymbolTestsCore.Protocols.ProtocolTest - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.compositionExistential.getter : Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.compositionExistential.setter : Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.optionalExistential.getter : SymbolTestsCore.Protocols.ProtocolTest? - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.optionalExistential.setter : SymbolTestsCore.Protocols.ProtocolTest? - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialArray.getter : [SymbolTestsCore.Protocols.ProtocolTest] - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialArray.setter : [SymbolTestsCore.Protocols.ProtocolTest] - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialDictionary.getter : [Swift.String : SymbolTestsCore.Protocols.ProtocolTest] - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialDictionary.setter : [Swift.String : SymbolTestsCore.Protocols.ProtocolTest] - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialFunction.getter : (SymbolTestsCore.Protocols.ProtocolTest) -> () - SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialFunction.setter : (SymbolTestsCore.Protocols.ProtocolTest) -> () + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.simpleExistential.getter : any SymbolTestsCore.Protocols.ProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.simpleExistential.setter : any SymbolTestsCore.Protocols.ProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.compositionExistential.getter : any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.compositionExistential.setter : any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.optionalExistential.getter : (any SymbolTestsCore.Protocols.ProtocolTest)? + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.optionalExistential.setter : (any SymbolTestsCore.Protocols.ProtocolTest)? + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialArray.getter : [any SymbolTestsCore.Protocols.ProtocolTest] + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialArray.setter : [any SymbolTestsCore.Protocols.ProtocolTest] + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialDictionary.getter : [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest] + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialDictionary.setter : [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest] + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialFunction.getter : (any SymbolTestsCore.Protocols.ProtocolTest) -> () + SymbolTestsCore.ExistentialAny.ExistentialFieldTest.existentialFunction.setter : (any SymbolTestsCore.Protocols.ProtocolTest) -> () } struct SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest { - var classBound: SymbolTestsCore.Protocols.ClassBoundProtocolTest + var classBound: any SymbolTestsCore.Protocols.ClassBoundProtocolTest var anyObjectReference: Swift.AnyObject /* Allocator */ - SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.init(classBound: SymbolTestsCore.Protocols.ClassBoundProtocolTest, anyObjectReference: Swift.AnyObject) -> SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest + SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.init(classBound: any SymbolTestsCore.Protocols.ClassBoundProtocolTest, anyObjectReference: Swift.AnyObject) -> SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest /* Variable */ - SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.classBound.getter : SymbolTestsCore.Protocols.ClassBoundProtocolTest - SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.classBound.setter : SymbolTestsCore.Protocols.ClassBoundProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.classBound.getter : any SymbolTestsCore.Protocols.ClassBoundProtocolTest + SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.classBound.setter : any SymbolTestsCore.Protocols.ClassBoundProtocolTest SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.anyObjectReference.getter : Swift.AnyObject SymbolTestsCore.ExistentialAny.ExistentialClassBoundTest.anyObjectReference.setter : Swift.AnyObject } \ No newline at end of file diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/functionFeaturesSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/functionFeaturesSnapshot.1.txt index ba9ec5ced..cef525681 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/functionFeaturesSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/functionFeaturesSnapshot.1.txt @@ -97,7 +97,7 @@ class SymbolTestsCore.FunctionFeatures.OwnershipParameterTest.Box { } struct SymbolTestsCore.FunctionFeatures.VariadicFunctionTest { /* Function */ - SymbolTestsCore.FunctionFeatures.VariadicFunctionTest.format(Swift.String, Swift.CVarArg...) -> Swift.String + SymbolTestsCore.FunctionFeatures.VariadicFunctionTest.format(Swift.String, any Swift.CVarArg...) -> Swift.String SymbolTestsCore.FunctionFeatures.VariadicFunctionTest.sum(Swift.Int...) -> Swift.Int } struct SymbolTestsCore.FunctionFeatures.ConventionFunctionTest { @@ -107,12 +107,12 @@ struct SymbolTestsCore.FunctionFeatures.ConventionFunctionTest { } struct SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest { /* Function */ - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.returnExistential() -> Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptMetatype(Any.Type) -> Swift.String - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptExistentialCollection([SymbolTestsCore.Protocols.ProtocolTest]) -> Swift.Int - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptProtocolMetatype(SymbolTestsCore.Protocols.ProtocolTest.Protocol) -> Swift.Bool - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptExistential(SymbolTestsCore.Protocols.ProtocolTest) -> () - SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptComposition(Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest) -> () + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.returnExistential() -> any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptMetatype(any Any.Type) -> Swift.String + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptExistentialCollection([any SymbolTestsCore.Protocols.ProtocolTest]) -> Swift.Int + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptProtocolMetatype((any SymbolTestsCore.Protocols.ProtocolTest).Type) -> Swift.Bool + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptExistential(any SymbolTestsCore.Protocols.ProtocolTest) -> () + SymbolTestsCore.FunctionFeatures.ExistentialAndMetatypeTest.acceptComposition(any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest) -> () } struct SymbolTestsCore.FunctionFeatures.FailableInitTest { let value: Swift.Int diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/genericFieldLayoutSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/genericFieldLayoutSnapshot.1.txt index a30b6a135..88b80fb38 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/genericFieldLayoutSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/genericFieldLayoutSnapshot.1.txt @@ -149,6 +149,8 @@ class SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirement where method descriptor for SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirement.field3.setter : Swift.Int } class SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject: NSObject { + // ObjC ancestor chain: NSObject + var field1: Swift.Double var field2: A var field3: Swift.Int @@ -166,7 +168,7 @@ class SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObje /* Allocator */ SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.__allocating_init(field1: Swift.Double, field2: A, field3: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject - SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject + SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject // overrides -[NSObject init] (To thunk symbol at the IMP) /* Deallocator */ merged SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.__deallocating_deinit @@ -174,7 +176,7 @@ class SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObje /* Constructor */ SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.init(field1: Swift.Double, field2: A, field3: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject - SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.init() -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject + SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.init() -> SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject // overrides -[NSObject init] (To thunk symbol at the IMP) /* Variable */ SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.field1.getter : Swift.Double @@ -196,6 +198,8 @@ class SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObje method descriptor for SymbolTestsCore.GenericFieldLayout.GenericClassNonRequirementInheritNSObject.field3.setter : Swift.Int } class SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject: NSObject where A: AnyObject { + // ObjC ancestor chain: NSObject + var field1: Swift.Double var field2: A var field3: Swift.Int @@ -213,14 +217,14 @@ class SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSO /* Allocator */ SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.__allocating_init(field1: Swift.Double, field2: A, field3: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject - SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject + SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject // overrides -[NSObject init] (To thunk symbol at the IMP) /* Deallocator */ SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.__deallocating_deinit /* Constructor */ SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.init(field1: Swift.Double, field2: A, field3: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject - SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.init() -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject + SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.init() -> SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject // overrides -[NSObject init] (To thunk symbol at the IMP) /* Variable */ SymbolTestsCore.GenericFieldLayout.GenericClassLayoutRequirementInheritNSObject.field1.getter : Swift.Double @@ -634,8 +638,8 @@ struct SymbolTestsCore.GenericFieldLayout.AssociatedTypeFieldHolder { } struct SymbolTestsCore.GenericFieldLayout.ConstrainedExistentialFieldHolder { var leading: Swift.Int - var boxed: symbolic existential type (non-unique) 0x0 - var optionalBoxed: (symbolic existential type (non-unique) 0x0 )? + var boxed: any SymbolTestsCore.GenericFieldLayout.Boxed + var optionalBoxed: (any SymbolTestsCore.GenericFieldLayout.Boxed)? var trailing: Swift.Int8 /* Variable */ @@ -733,23 +737,23 @@ struct SymbolTestsCore.GenericFieldLayout.MultiLevelNestedFieldHolder { } struct SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder { var leading: Swift.Int - var bareElement: SymbolTestsCore.ObjCOnlyElementProtocol - var anchoredElement: NSObject & SymbolTestsCore.ObjCOnlyElementProtocol - var optionalElement: SymbolTestsCore.ObjCOnlyElementProtocol? - var composedElement: SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol + var bareElement: any SymbolTestsCore.ObjCOnlyElementProtocol + var anchoredElement: any NSObject & SymbolTestsCore.ObjCOnlyElementProtocol + var optionalElement: (any SymbolTestsCore.ObjCOnlyElementProtocol)? + var composedElement: any SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol var trailing: Swift.Int8 /* Variable */ - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.anchoredElement.getter : NSObject & SymbolTestsCore.ObjCOnlyElementProtocol - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.anchoredElement.setter : NSObject & SymbolTestsCore.ObjCOnlyElementProtocol - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.optionalElement.getter : SymbolTestsCore.ObjCOnlyElementProtocol? - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.optionalElement.setter : SymbolTestsCore.ObjCOnlyElementProtocol? - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.composedElement.getter : SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.composedElement.setter : SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.anchoredElement.getter : any NSObject & SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.anchoredElement.setter : any NSObject & SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.optionalElement.getter : (any SymbolTestsCore.ObjCOnlyElementProtocol)? + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.optionalElement.setter : (any SymbolTestsCore.ObjCOnlyElementProtocol)? + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.composedElement.getter : any SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.composedElement.setter : any SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.trailing.getter : Swift.Int8 SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.trailing.setter : Swift.Int8 - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.bareElement.getter : SymbolTestsCore.ObjCOnlyElementProtocol - SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.bareElement.setter : SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.bareElement.getter : any SymbolTestsCore.ObjCOnlyElementProtocol + SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.bareElement.setter : any SymbolTestsCore.ObjCOnlyElementProtocol SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.leading.getter : Swift.Int SymbolTestsCore.GenericFieldLayout.ObjCProtocolExistentialFieldHolder.leading.setter : Swift.Int } @@ -957,6 +961,8 @@ class SymbolTestsCore.GenericFieldLayout.ClassBoundGenericSubclass: SymbolTes method descriptor for SymbolTestsCore.GenericFieldLayout.ClassBoundGenericSubclass.__allocating_init(baseElement: A, subclassElement: A, subclassIdentifier: Swift.Int64) -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericSubclass } class SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass: NSObject where A: AnyObject { + // ObjC ancestor chain: NSObject + final var element: A final var identifier: Swift.Int @@ -964,14 +970,14 @@ class SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass: N /* Allocator */ SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.__allocating_init(element: A, identifier: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass - SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass + SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.__allocating_init() -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass // overrides -[NSObject init] (To thunk symbol at the IMP) /* Deallocator */ SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.__deallocating_deinit /* Constructor */ SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.init(element: A, identifier: Swift.Int) -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass - SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.init() -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass + SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.init() -> SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass // overrides -[NSObject init] (To thunk symbol at the IMP) /* Variable */ SymbolTestsCore.GenericFieldLayout.ClassBoundGenericNSObjectSubclass.element.getter : A diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/metatypeUsageSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/metatypeUsageSnapshot.1.txt index b0458b9d3..1983f791a 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/metatypeUsageSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/metatypeUsageSnapshot.1.txt @@ -3,26 +3,26 @@ enum SymbolTestsCore.MetatypeUsage {} struct SymbolTestsCore.MetatypeUsage.MetatypeFieldTest { var concreteMetatype: Swift.Int.Type - var anyMetatype: Any.Type - var protocolMetatype: SymbolTestsCore.Protocols.ProtocolTest.Type - var anyObjectMetatype: Swift.AnyObject.Type + var anyMetatype: any Any.Type + var protocolMetatype: any SymbolTestsCore.Protocols.ProtocolTest.Type + var anyObjectMetatype: any Swift.AnyObject.Type /* Allocator */ - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.init(concreteMetatype: Swift.Int.Type, anyMetatype: Any.Type, protocolMetatype: SymbolTestsCore.Protocols.ProtocolTest.Type, anyObjectMetatype: Swift.AnyObject.Type) -> SymbolTestsCore.MetatypeUsage.MetatypeFieldTest + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.init(concreteMetatype: Swift.Int.Type, anyMetatype: any Any.Type, protocolMetatype: any SymbolTestsCore.Protocols.ProtocolTest.Type, anyObjectMetatype: any Swift.AnyObject.Type) -> SymbolTestsCore.MetatypeUsage.MetatypeFieldTest /* Variable */ - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyMetatype.getter : Any.Type - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyMetatype.setter : Any.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyMetatype.getter : any Any.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyMetatype.setter : any Any.Type SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.concreteMetatype.getter : Swift.Int.Type SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.concreteMetatype.setter : Swift.Int.Type - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.protocolMetatype.getter : SymbolTestsCore.Protocols.ProtocolTest.Type - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.protocolMetatype.setter : SymbolTestsCore.Protocols.ProtocolTest.Type - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyObjectMetatype.getter : Swift.AnyObject.Type - SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyObjectMetatype.setter : Swift.AnyObject.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.protocolMetatype.getter : any SymbolTestsCore.Protocols.ProtocolTest.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.protocolMetatype.setter : any SymbolTestsCore.Protocols.ProtocolTest.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyObjectMetatype.getter : any Swift.AnyObject.Type + SymbolTestsCore.MetatypeUsage.MetatypeFieldTest.anyObjectMetatype.setter : any Swift.AnyObject.Type } struct SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest { /* Function */ - SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.acceptProtocolMetatype(SymbolTestsCore.Protocols.ProtocolTest.Type) -> Swift.String + SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.acceptProtocolMetatype(any SymbolTestsCore.Protocols.ProtocolTest.Type) -> Swift.String SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.dynamicType(of: A) -> A.Type SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.acceptMetatype(A.Type) -> A.Type SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.returnMetatype() -> SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.Type diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/objCClassWrappersSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/objCClassWrappersSnapshot.1.txt index 255ab6835..60d3006c3 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/objCClassWrappersSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/objCClassWrappersSnapshot.1.txt @@ -32,6 +32,7 @@ class SymbolTestsCore.ObjCClassWrapperFixtures.ObjCBridge: NSObject { @objc(SymbolTestsCoreObjCBridgeWithProto) class SymbolTestsCore.ObjCClassWrapperFixtures.ObjCBridgeWithProto: NSObject { // ObjC ancestor chain: NSObject + // ObjC protocols: SymbolTestsCore.ObjCClassWrapperFixtures.ObjCProto /* [Method] */ func SymbolTestsCore.ObjCClassWrapperFixtures.ObjCBridgeWithProto.ping() -> () diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/protocolCompositionSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/protocolCompositionSnapshot.1.txt index 145212100..ad6a7515b 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/protocolCompositionSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/protocolCompositionSnapshot.1.txt @@ -2,28 +2,28 @@ enum SymbolTestsCore.ProtocolComposition {} struct SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest { - var twoComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol - var threeComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol - var classBoundComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject - var sendableComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol + var twoComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + var threeComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol + var classBoundComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject + var sendableComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol /* Allocator */ - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.init(twoComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol, threeComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol, classBoundComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject, sendableComposition: Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol) -> SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.init(twoComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol, threeComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol, classBoundComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject, sendableComposition: any Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol) -> SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest /* Variable */ - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.twoComposition.getter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.twoComposition.setter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.threeComposition.getter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.threeComposition.setter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.classBoundComposition.getter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.classBoundComposition.setter : SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.sendableComposition.getter : Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.sendableComposition.setter : Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.twoComposition.getter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.twoComposition.setter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.threeComposition.getter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.threeComposition.setter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.classBoundComposition.getter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.classBoundComposition.setter : any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.sendableComposition.getter : any Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFieldTest.sendableComposition.setter : any Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol } struct SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest { /* Function */ - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest.returnComposition() -> SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol - SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest.acceptComposition(SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol) -> () + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest.returnComposition() -> any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest.acceptComposition(any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol) -> () SymbolTestsCore.ProtocolComposition.ProtocolCompositionFunctionTest.genericCompositionParameter(A) -> () } diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/weakUnownedReferencesSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/weakUnownedReferencesSnapshot.1.txt index 5ae6a3568..27609fc47 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/weakUnownedReferencesSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/weakUnownedReferencesSnapshot.1.txt @@ -201,24 +201,24 @@ enum SymbolTestsCore.WeakUnownedReferences.EnumOverUnownedReferenceStructTest { case second } struct SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest { - weak var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest?) -> SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.init(delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)?) -> SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? - SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.delegate.getter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? + SymbolTestsCore.WeakUnownedReferences.WeakExistentialStructTest.delegate.setter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? } struct SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest { - weak var delegate: (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.init(delegate: (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)?) -> SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.init(delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)?) -> SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.delegate.getter : (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? - SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.delegate.setter : (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? + SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.delegate.getter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? + SymbolTestsCore.WeakUnownedReferences.WeakCompositionExistentialStructTest.delegate.setter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? } struct SymbolTestsCore.WeakUnownedReferences.WeakAnyObjectStructTest { weak var object: Swift.AnyObject? @@ -232,53 +232,53 @@ struct SymbolTestsCore.WeakUnownedReferences.WeakAnyObjectStructTest { SymbolTestsCore.WeakUnownedReferences.WeakAnyObjectStructTest.object.setter : Swift.AnyObject? } struct SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest { - weak var delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedObjCDelegateTest)? /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.init(delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest?) -> SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.init(delegate: (any SymbolTestsCore.WeakUnownedObjCDelegateTest)?) -> SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.delegate.getter : SymbolTestsCore.WeakUnownedObjCDelegateTest? - SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.delegate.setter : SymbolTestsCore.WeakUnownedObjCDelegateTest? + SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.delegate.getter : (any SymbolTestsCore.WeakUnownedObjCDelegateTest)? + SymbolTestsCore.WeakUnownedReferences.WeakObjCExistentialStructTest.delegate.setter : (any SymbolTestsCore.WeakUnownedObjCDelegateTest)? } struct SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest { - unowned var delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest + unowned var delegate: any SymbolTestsCore.WeakUnownedObjCDelegateTest /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.init(delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.init(delegate: any SymbolTestsCore.WeakUnownedObjCDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.delegate.getter : SymbolTestsCore.WeakUnownedObjCDelegateTest - SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.delegate.setter : SymbolTestsCore.WeakUnownedObjCDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.delegate.getter : any SymbolTestsCore.WeakUnownedObjCDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnownedObjCExistentialStructTest.delegate.setter : any SymbolTestsCore.WeakUnownedObjCDelegateTest } struct SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest { - unowned var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + unowned var delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.init(delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest - SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.delegate.getter : any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnownedExistentialStructTest.delegate.setter : any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest } struct SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest { - unowned(unsafe) var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + unowned(unsafe) var delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest /* Allocator */ - SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest + SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.init(delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) -> SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest /* Variable */ - SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest - SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.delegate.setter : any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + SymbolTestsCore.WeakUnownedReferences.UnmanagedExistentialStructTest.delegate.getter : any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest } class SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest { - weak var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? weak var parent: SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? var marker: Swift.Int - /* [Getter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? - /* [Setter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? - /* [Modify] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.modify : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + /* [Getter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? + /* [Setter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? + /* [Modify] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.modify : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? /* [Getter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? /* [Setter] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? /* [Modify] */ SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.modify : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? @@ -301,8 +301,8 @@ class SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest { SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.deinit /* Variable */ - SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? - SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? + SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.marker.getter : Swift.Int @@ -312,8 +312,8 @@ class SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest { method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.__allocating_init() -> SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest /* [Method] Variable */ - method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? - method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.getter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? + method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.delegate.setter : (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.getter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.parent.setter : SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? method descriptor for SymbolTestsCore.WeakUnownedReferences.WeakExistentialHolderTest.marker.getter : Swift.Int diff --git a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift index b9721cf92..5fbc568b8 100644 --- a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift +++ b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftDump -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The dump of the declaration shapes Swift 6.4 introduced (evolution /// proposal `borrow-accessors-and-suppressed-associated-types`): a member diff --git a/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift new file mode 100644 index 000000000..db949d9a0 --- /dev/null +++ b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift @@ -0,0 +1,89 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@testable import SwiftDump +import SwiftDeclarationRendering +@_spi(Internals) import SwiftInspection +@_spi(Internals) import SwiftObjCInterop +@testable import SwiftSectionTestingSupport + +/// The dump of an `@objc` protocol declared in Swift (evolution proposal +/// `swift-declared-objc-protocols`): each requirement as a Swift declaration +/// with its Objective-C facts — selector, required or optional, type +/// encoding, and the class it was taken from when one implements it. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct SwiftDeclaredObjCProtocolDumpTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private func dump(of name: String, in machOFile: MachOFile, using configuration: DumperConfiguration = .demangleOptions(.test)) async throws -> String { + ObjCAncestorResolverStore.shared.register(ObjCAncestorResolver(root: machOFile, searchPaths: try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths()), for: machOFile) + defer { ObjCAncestorResolverStore.shared.remove(for: machOFile) } + let declaredProtocol = try #require(SwiftDeclaredObjCProtocol.all(in: machOFile).first { $0.qualifiedName == "\(Self.moduleName).\(name)" }, "\(name) not found") + return try await declaredProtocol.dump(using: configuration, in: machOFile).string + } + + @Test func requirementsNamedFromSelectorsCarryTheirObjCFacts() async throws { + let output = try await dump(of: "DerivedSelectors", in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + // The test options print imported names without `__C`. + #expect(output.contains("@objc protocol \(Self.moduleName).DerivedSelectors: NSObject {"), "\(output)") + #expect(output.contains("// Evidence: field descriptor of kind ObjCProtocol at 0x"), "\(output)") + #expect(output.contains("// ObjC protocol _TtP\(Self.moduleName.count)\(Self.moduleName)16DerivedSelectors_, record emitted by Swift at 0x"), "\(output)") + #expect(output.contains("// Requirements no class of this image implements are named from their selectors"), "\(output)") + #expect(output.contains("@objc(teamNameFor:error:) \(Self.moduleName).DerivedSelectors.teamName(for: "), "\(output)") + #expect(output.contains(" throws -> Swift.String // -teamNameFor:error: required, @\"NSString\"32@0:8@\"NSString\"16^@24"), "\(output)") + #expect(output.contains("// -isEnabled, -setIsEnabled: required, TB,N"), "\(output)") + #expect(output.contains("// +makeDefault required, @\"NSObject\"16@0:8"), "\(output)") + #expect(output.contains("@objc(scrollTo:animated:) optional \(Self.moduleName).DerivedSelectors.scroll(to: Swift.Int, animated: Swift.Bool) -> () // -scrollTo:animated: optional, v28@0:8q16B24"), "\(output)") + } + + /// Implemented by a class of the image: the member's signature, declared + /// in the protocol, with the class and the evidence that tied it. + @Test func requirementsTakenFromConformersNameTheClass() async throws { + let output = try await dump(of: "RefinedProtocol", in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + #expect(output.contains("@objc protocol \(Self.moduleName).RefinedProtocol: \(Self.moduleName).SameNameRenamed {"), "\(output)") + #expect(output.contains("@objc \(Self.moduleName).RefinedProtocol.refine() -> () // -refine required, v16@0:8; implemented by \(Self.moduleName).ExtensionConformer (To thunk symbol at the IMP)"), "\(output)") + #expect(!output.contains("ClangImporter"), "\(output)") + } + + /// Stripped, the thunk's code ties the member instead of its symbol. + @Test func strippedConformersAreTiedThroughTheThunkCode() async throws { + let output = try await dump(of: "RefinedProtocol", in: SwiftDeclaredObjCProtocolsFixture.machOFile(.strippedLocals)) + #expect(output.contains("implemented by \(Self.moduleName).ExtensionConformer (the IMP's code references the implementation)"), "\(output)") + } + + @Test func unpairedRenamedProtocolSaysSo() async throws { + let output = try await dump(of: "DifferentlyNamed", in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + #expect(output.contains("@objc protocol \(Self.moduleName).DifferentlyNamed {"), "\(output)") + #expect(output.contains("// No Objective-C protocol record pairs with this declaration"), "\(output)") + } + + /// File-private: its Swift name carries a private discriminator, which + /// the name a dump declares leaves out, as a Swift protocol's does. + @Test func privateProtocolDeclaresTheBareName() async throws { + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + var configuration = DumperConfiguration.demangleOptions(.test) + configuration.displayParentName = false + let output = try await dump(of: "PrivateProtocol", in: machOFile, using: configuration) + #expect(output.contains("@objc protocol PrivateProtocol {"), "\(output)") + #expect(!output.contains("PrivateProtocol in _"), "\(output)") + + let declaredProtocol = try #require(SwiftDeclaredObjCProtocol.all(in: machOFile).first { $0.qualifiedName == "\(Self.moduleName).PrivateProtocol" }) + let name = try await declaredProtocol.dumpName(using: configuration, in: machOFile.context).string + #expect(name == "PrivateProtocol") + } + + /// The records no declaration claims: this image's renamed-away one, + /// and the kit's renamed protocols it references — the one renamed to + /// its own name found in the kit. + @Test func unclaimedRecordsAreListed() async throws { + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + ObjCAncestorResolverStore.shared.register(ObjCAncestorResolver(root: machOFile, searchPaths: try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths()), for: machOFile) + defer { ObjCAncestorResolverStore.shared.remove(for: machOFile) } + let comment = try #require(try await SwiftDeclaredObjCProtocol.unclaimedRecordsComment(using: DumperConfiguration.demangleOptions(.test).demangleResolver, in: machOFile)) + #expect(comment.contains("PRBDifferentlyNamed"), "\(comment)") + #expect(comment.contains("KITRenamedObserver,"), "\(comment)") + #expect(comment.contains("KitSameName → \(SwiftDeclaredObjCProtocolsFixture.kitModuleName).KitSameName"), "\(comment)") + } +} diff --git a/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift new file mode 100644 index 000000000..244039042 --- /dev/null +++ b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift @@ -0,0 +1,66 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftDump +import SwiftDeclarationRendering +@testable import SwiftSectionTestingSupport + +/// The dump path's listing of the members an image keeps only as their +/// `@objc` thunk (evolution proposal `thunk-only-objc-members`): the +/// optimizer inlined the Swift body into the thunk and deleted the Swift +/// entry point, so the dump, which lists a class's members from their +/// symbols, listed none of them. They now get a section of their own after +/// the member symbols, printed from the thunk, with the ObjC method table's +/// facts where the class has a table. +@Suite(.serialized, ExclusiveImageAccess(ThunkOnlyMemberFixture.moduleName)) +struct ThunkOnlyObjCMemberDumpTests { + private func classDescriptor(named name: String, in machOFile: MachOFile) throws -> ClassDescriptor { + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .class(let classDescriptor) = typeContextDescriptor else { continue } + guard try classDescriptor.name(in: machOFile.context) == name else { continue } + return classDescriptor + } + Issue.record("fixture is missing the class \(name)") + throw ThunkOnlyMemberFixture.CompilationError(step: "lookup", diagnostics: "class \(name) not found") + } + + private func dump(ofClassNamed name: String, in variant: ThunkOnlyMemberFixture.Variant) async throws -> String { + let machOFile = try ThunkOnlyMemberFixture.machOFile(variant) + let classType = try Class(descriptor: try classDescriptor(named: name, in: machOFile), in: machOFile.context) + return try await classType.dump(using: .demangleOptions(.test), in: machOFile).string + } + + @Test func thunkOnlyMembersAreListedFromTheirThunks() async throws { + let output = try await dump(ofClassNamed: "ThunkOnlyWidget", in: .wholeModuleOptimized) + let moduleName = ThunkOnlyMemberFixture.moduleName + #expect(output.contains("/* [ObjC Thunk] Function */"), "\(output)") + #expect(output.contains("@objc \(moduleName).ThunkOnlyWidget.isEqual(Any?) -> Swift.Bool // overrides -[NSObject isEqual:] (To thunk symbol at the IMP)"), "\(output)") + #expect(output.contains("@objc \(moduleName).ThunkOnlyWidget.handleTick(Any?) -> () // @objc -[\(moduleName).ThunkOnlyWidget handleTick:] (To thunk symbol at the IMP)"), "\(output)") + #expect(output.contains("/* [ObjC Thunk] Variable */"), "\(output)") + #expect(output.contains("@objc \(moduleName).ThunkOnlyWidget.description.getter : Swift.String // overrides -[NSObject description] (To thunk symbol at the IMP)"), "\(output)") + #expect(output.contains("/* [ObjC Thunk] Constructor */"), "\(output)") + #expect(output.contains("@objc \(moduleName).ThunkOnlyWidget.init() -> \(moduleName).ThunkOnlyWidget // overrides -[NSObject init] (To thunk symbol at the IMP)"), "\(output)") + } + + /// The unoptimized build keeps every Swift entry point, so no thunk is a + /// member's only symbol and the section is absent. + @Test func membersWithASwiftEntryPointAreNotListedAgain() async throws { + let output = try await dump(ofClassNamed: "ThunkOnlyWidget", in: .unoptimized) + #expect(!output.contains("[ObjC Thunk]"), "\(output)") + } + + /// A generic class has no static class object; its ObjC method table is + /// the template in its generic metadata pattern (evolution proposal + /// `objc-classes-without-class-objects`), so the thunk carries the same + /// comment as a class with a class object. Its synthesized `init()` kept + /// its initializing entry point, so its thunk is not the only symbol it + /// has. + @Test func genericClassThunkOnlyMembersCarryTheirObjCComment() async throws { + let output = try await dump(ofClassNamed: "GenericThunkOnlyWidget", in: .wholeModuleOptimized) + let moduleName = ThunkOnlyMemberFixture.moduleName + #expect(output.contains("@objc \(moduleName).GenericThunkOnlyWidget.description.getter : Swift.String // overrides -[NSObject description] (To thunk symbol at the IMP)"), "\(output)") + #expect(!output.contains("/* [ObjC Thunk] Constructor */"), "\(output)") + } +} diff --git a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift index 4893afb76..ef5d6df4d 100644 --- a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift +++ b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport /// Vtable slot attribution under identical code folding. /// diff --git a/Tests/SwiftIndexingTests/AnnotatedSymbolTests.swift b/Tests/SwiftIndexingTests/AnnotatedSymbolTests.swift index 3f5bb0472..801aa719e 100644 --- a/Tests/SwiftIndexingTests/AnnotatedSymbolTests.swift +++ b/Tests/SwiftIndexingTests/AnnotatedSymbolTests.swift @@ -1,6 +1,6 @@ import Demangling import MachOResolving -import MachOSymbols +import SwiftSymbols import SwiftDeclaration import Testing diff --git a/Tests/SwiftIndexingTests/ConsoleEventHandlerLineTests.swift b/Tests/SwiftIndexingTests/ConsoleEventHandlerLineTests.swift index a09b8e916..06e8c1fe4 100644 --- a/Tests/SwiftIndexingTests/ConsoleEventHandlerLineTests.swift +++ b/Tests/SwiftIndexingTests/ConsoleEventHandlerLineTests.swift @@ -37,4 +37,37 @@ struct ConsoleEventHandlerLineTests { let line = handler.line(for: .phaseTransition(phase: .indexing, state: .failed(Failure())), timestamp: "12:00:00") #expect(line == "[12:00:00] [new] [ERROR] Indexing failed: boom") } + + /// Most events — one per type, conformance and printed declaration — + /// print nothing. Stamping each of them with the local time built a date + /// formatter per event: a quarter of `swift-section interface` over SwiftUI. + @Test func unreportedEventsAskForNoTimestamp() { + let timestampRequests = TimestampRequestCounter() + let handler = ConsoleEventHandler(label: nil) { + timestampRequests.increment() + return "12:00:00" + } + + handler.handle(event: .moduleCollectionStarted) + handler.handle(event: .phaseTransition(phase: .indexing, state: .started)) + + #expect(timestampRequests.count == 0) + } +} + +private final class TimestampRequestCounter: @unchecked Sendable { + private let lock = NSLock() + private var requestCount = 0 + + var count: Int { + lock.lock() + defer { lock.unlock() } + return requestCount + } + + func increment() { + lock.lock() + defer { lock.unlock() } + requestCount += 1 + } } diff --git a/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift new file mode 100644 index 000000000..2f6577905 --- /dev/null +++ b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift @@ -0,0 +1,163 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Internals) import Demangling +import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@testable import SwiftSectionTestingSupport + +/// A SE-0400 init accessor is one of its property's accessors (evolution +/// proposal `init-accessor-recovery`): the index files its symbol with the +/// property's other accessors, after them, without making the property a +/// stored one or moving it in the member order. Which init accessors an image +/// keeps depends on the build, so each variant is pinned with what it keeps. +@Suite(.serialized) +struct InitAccessorIndexingTests { + private typealias Property = InitAccessorFixture.Property + + private struct Indexed { + var variablesByProperty: [Property: VariableDefinition] = [:] + var fieldsByProperty: [Property: FieldDefinition] = [:] + var orderedMembersByTypeName: [String: [OrderedMember]] = [:] + } + + private func indexed(in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> Indexed { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + var indexed = Indexed() + for definition in indexer.allTypeDefinitions.values { + try definition.index(in: machO) + let typeName = definition.typeName.declaredNameForTesting + for variable in definition.variables { + indexed.variablesByProperty[Property(typeName, variable.name)] = variable + } + for field in definition.fields { + indexed.fieldsByProperty[Property(typeName, field.name)] = field + } + indexed.orderedMembersByTypeName[typeName] = definition.orderedMembers + } + return indexed + } + + private func expectEveryInitAccessorFiled(_ indexed: Indexed, sourceLocation: SourceLocation = #_sourceLocation) throws { + for property in InitAccessorFixture.propertiesWithInitAccessors { + let variable = try #require(indexed.variablesByProperty[property], "no variable \(property)", sourceLocation: sourceLocation) + #expect(variable.hasInitAccessor, "\(property)", sourceLocation: sourceLocation) + #expect(variable.accessors.filter { $0.kind == .initAccessor }.count == 1, "\(property)", sourceLocation: sourceLocation) + // Still computed: an init accessor read as no accessor at all made + // the property a stored one. + #expect(!variable.isStored, "\(property)", sourceLocation: sourceLocation) + // After the accessors that answer for the property. + #expect(variable.accessors.last?.kind == .initAccessor, "\(property)", sourceLocation: sourceLocation) + #expect(variable.accessors.first?.kind != .initAccessor, "\(property)", sourceLocation: sourceLocation) + // The declaration still prints from the getter. + #expect(variable.node.materialize().first(of: .getter) != nil, "\(property)", sourceLocation: sourceLocation) + #expect(variable.node.materialize().first(of: .initAccessor) == nil, "\(property)", sourceLocation: sourceLocation) + } + } + + // MARK: - Images that keep their local symbols + + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func everyInitAccessorIsOneOfItsPropertysAccessors(variant: InitAccessorFixture.Variant) async throws { + try expectEveryInitAccessorFiled(try await indexed(in: try await InitAccessorFixture.machOFile(variant))) + } + + @Test func theInProcessReaderFilesTheSameInitAccessors() async throws { + try expectEveryInitAccessorFiled(try await indexed(in: try await InitAccessorFixture.loadedImage())) + } + + // MARK: - Stripped images + + /// SwiftUI's shape, and an OS framework's: an init accessor the image + /// does not export is gone — the initializers inlined it, so nothing + /// references it — and the property is left with the accessors it + /// exports. + @Test(arguments: [InitAccessorFixture.Variant.releaseDeadStripped, .releaseStripped]) + func onlyTheExportedInitAccessorsSurvive(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.machOFile(variant)) + for property in InitAccessorFixture.propertiesWithInitAccessors { + // Every property here is public: its getter is exported. + let variable = try #require(indexed.variablesByProperty[property], "no variable \(property)") + #expect(variable.hasInitAccessor == InitAccessorFixture.propertiesWithExportedInitAccessors.contains(property), "\(property)") + #expect(!variable.isStored, "\(property)") + } + } + + // MARK: - A stored property with an init accessor's symbol + + /// SwiftUICore's `_GeometryActionModifier.value`: a stored property, with + /// a function under its init accessor's name. It stays stored, the symbol + /// joins the field's accessors, and no computed property appears. + @Test(arguments: InitAccessorFixture.Variant.allCases) + func aStoredPropertyKeepsTheSymbolOnItsField(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.machOFile(variant)) + let property = InitAccessorFixture.storedPropertyWithInitAccessorSymbol + #expect(indexed.variablesByProperty[property] == nil) + let field = try #require(indexed.fieldsByProperty[property], "no field \(property)") + #expect(field.hasInitAccessor) + } + + // MARK: - What an init accessor initializes + + /// No image records `@storageRestrictions`; the field named `_` + /// with the property's type is read as what it initializes. `Angle` and + /// `Pair` initialize fields of other names, `Titled` only accesses one, + /// and `PersistedLookalike._name` has another type: none of them tells. + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func theInitializedFieldIsInferredFromItsNameAndType(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.machOFile(variant)) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let variable = try #require(indexed.variablesByProperty[property], "no variable \(property)") + #expect(variable.initializedFieldNames == InitAccessorFixture.inferredInitializedFieldNames[property], "\(property)") + } + } + + @Test func theInProcessReaderInfersTheSameFields() async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.loadedImage()) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let variable = try #require(indexed.variablesByProperty[property], "no variable \(property)") + #expect(variable.initializedFieldNames == InitAccessorFixture.inferredInitializedFieldNames[property], "\(property)") + } + } + + /// Only a property whose init accessor the image kept is inferred about. + @Test(arguments: [InitAccessorFixture.Variant.releaseDeadStripped, .releaseStripped]) + func aStrippedImageInfersOnlyWhatItKeeps(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.machOFile(variant)) + for property in InitAccessorFixture.propertiesWithInitAccessors { + let variable = try #require(indexed.variablesByProperty[property], "no variable \(property)") + let expected = InitAccessorFixture.propertiesWithExportedInitAccessors.contains(property) ? InitAccessorFixture.inferredInitializedFieldNames[property] : nil + #expect(variable.initializedFieldNames == expected, "\(property)") + } + #expect(indexed.variablesByProperty[Property("FrozenBox", "value")]?.initializedFieldNames == ["_value"]) + } + + // MARK: - The member order + + /// Whether the image kept an init accessor depends on the build, so it + /// must not decide where its property sorts. The release build places + /// `Model.name`'s init accessor before its getter, which the order would + /// otherwise follow. + @Test(arguments: InitAccessorFixture.Variant.allCases) + func theInitAccessorTakesNoPartInTheMemberOrder(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(in: try await InitAccessorFixture.machOFile(variant)) + var hasInitAccessorBeforeTheOthers = false + for (typeName, members) in indexed.orderedMembersByTypeName { + for member in members { + guard case .variable(let variable) = member, variable.hasInitAccessor else { continue } + let initAccessorOffsets = variable.accessors.filter { $0.kind == .initAccessor }.map(\.symbol.offset) + let otherOffsets = variable.accessors.filter { $0.kind != .initAccessor }.map(\.symbol.offset) + #expect(member.minSymbolOffset == otherOffsets.min(), "\(typeName).\(variable.name)") + if let initAccessorOffset = initAccessorOffsets.min(), let otherOffset = otherOffsets.min(), initAccessorOffset < otherOffset { + hasInitAccessorBeforeTheOthers = true + } + } + } + if variant == .release { + #expect(hasInitAccessorBeforeTheOthers, "the release build no longer places an init accessor before its getter; the order test checks nothing there") + } + } +} diff --git a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift index 69b47060f..085ffa43a 100644 --- a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift +++ b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftInspection diff --git a/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift new file mode 100644 index 000000000..5b3944be4 --- /dev/null +++ b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift @@ -0,0 +1,174 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Internals) import Demangling +import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@testable import SwiftSectionTestingSupport + +/// The declaration model of the `@objc` protocols a Swift module declares +/// (evolution proposal `swift-declared-objc-protocols`): one +/// `ObjCProtocolDefinition` each, their requirements read on `index(in:)` — +/// spelled from a Swift class of the image that implements them where there +/// is one, from the selector otherwise — and the image's extensions of them +/// attached as their default implementations. +/// +/// Holds `ExclusiveImageAccess` because the indexer registers an ancestor +/// resolver per image and the requirements read per-image ObjC indexes. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct ObjCProtocolDefinitionIndexingTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private static func indexer(for machO: MachO) async throws -> SwiftDeclarationIndexer { + var configuration = SwiftDeclarationIndexConfiguration() + configuration.dependencySearchPaths = try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths() + let indexer = SwiftDeclarationIndexer(configuration: configuration, in: machO) + try await indexer.prepare() + return indexer + } + + private static func definitionsByName(_ definitions: some Sequence) -> [String: ObjCProtocolDefinition] { + Dictionary(definitions.map { ($0.protocolName.name, $0) }, uniquingKeysWith: { first, _ in first }) + } + + /// The qualified name of the class a requirement was taken from, `nil` + /// for one spelled from its selector. + private static func conformerName(of requirement: ObjCProtocolRequirementDefinition) -> String? { + guard case .conformer(let className) = requirement.origin else { return nil } + return className.name + } + + /// `keepsLocalSymbols` is false for the stripped file: an internal + /// class's members lose every symbol there, and its requirement falls + /// back to the selector. + private static func expectModel(in machO: some MachOSwiftSectionRepresentableWithCache, keepsLocalSymbols: Bool = true) async throws { + let indexer = try await indexer(for: machO) + let definitions = definitionsByName(indexer.objcProtocolDefinitions.values) + #expect(Set(definitions.keys) == Set(["DerivedSelectors", "SameNameRenamed", "DifferentlyNamed", "RefinedProtocol", "InternalProtocol", "PrivateProtocol", "Outer.NestedProtocol", "KitWidgetAdopted"].map { "\(moduleName).\($0)" })) + // None is a `ProtocolDefinition`: no protocol descriptor lists them. + #expect(indexer.allProtocolDefinitions.keys.allSatisfy { !definitions.keys.contains($0.name) }) + for definition in definitions.values { + // No protocol has a symbol of its own, so only a name rules: the + // private one's discriminator says it is not exported (evolution + // proposal `export-verdict-without-local-symbols`). + let expectedStatus: ExportStatus = definition.protocolName.name == "\(moduleName).PrivateProtocol" ? .notExported : .declarationHasNoSymbol + #expect(definition.exportStatus == expectedStatus, "\(definition.protocolName.name)") + try definition.index(in: machO) + } + + let derivedSelectors = try #require(definitions["\(moduleName).DerivedSelectors"]) + #expect(derivedSelectors.objcRuntimeName == "_TtP\(moduleName.count)\(moduleName)16DerivedSelectors_") + #expect(!derivedSelectors.hasExplicitObjCName) + #expect(derivedSelectors.inheritedProtocolNames.map(\.name) == ["__C.NSObject"]) + #expect(derivedSelectors.requirements.count == 15) + // No class of the image adopts it: every requirement is spelled from + // its selector, and pinned. + #expect(derivedSelectors.requirements.allSatisfy { $0.origin == .selector && $0.hasExplicitSelector }) + // Its extension is its default implementation, out of the top-level + // extensions. + let defaultImplementation = try #require(derivedSelectors.defaultImplementationExtensions.first) + #expect(defaultImplementation.isAttachedToProtocolDefinition) + #expect(defaultImplementation.functions.map(\.name) == ["describe"]) + + // Implemented by `Conformer` (in its declaration) and by + // `ExtensionConformer` (through `RefinedProtocol`, in an extension): + // the first class in the class list gives the signature. + let sameNameRenamed = try #require(definitions["\(moduleName).SameNameRenamed"]) + #expect(sameNameRenamed.objcRuntimeName == "SameNameRenamed") + #expect(sameNameRenamed.hasExplicitObjCName) + let ping = try #require(sameNameRenamed.requirements.first) + #expect(sameNameRenamed.requirements.map(\.selector) == ["ping"]) + let pingClassName = try #require(conformerName(of: ping), "ping was not taken from a conformer") + #expect(["\(moduleName).Conformer", "\(moduleName).ExtensionConformer"].contains(pingClassName)) + // `ping()` derives `ping`: nothing to spell out. + #expect(!ping.hasExplicitSelector) + let printedPing = await ping.node.materialize().print(using: .interface) + #expect(printedPing.contains("ping() -> ()"), "\(printedPing)") + + let refined = try #require(definitions["\(moduleName).RefinedProtocol"]) + #expect(refined.inheritedProtocolNames.map(\.name) == ["\(moduleName).SameNameRenamed"]) + #expect(refined.requirements.map(conformerName(of:)) == ["\(moduleName).ExtensionConformer"]) + + let internalProtocol = try #require(definitions["\(moduleName).InternalProtocol"]) + if keepsLocalSymbols { + #expect(internalProtocol.requirements.map(conformerName(of:)) == ["\(moduleName).InternalConformer"]) + } else { + #expect(internalProtocol.requirements.map(\.origin) == [.selector]) + #expect(internalProtocol.requirements.map(\.hasExplicitSelector) == [true]) + } + + // Declared in a type: its name and runtime name carry the parent. + let nestedProtocol = try #require(definitions["\(moduleName).Outer.NestedProtocol"]) + #expect(nestedProtocol.objcRuntimeName == "_TtPC\(moduleName.count)\(moduleName)5Outer14NestedProtocol_") + #expect(nestedProtocol.requirements.map(conformerName(of:)) == ["\(moduleName).NestedConformer"]) + + // Adopted in an extension of another module's Swift class: the + // member is that class's, found by the runtime name the category + // gives it. + let kitWidgetAdopted = try #require(definitions["\(moduleName).KitWidgetAdopted"]) + #expect(kitWidgetAdopted.requirements.map(conformerName(of:)) == ["\(SwiftDeclaredObjCProtocolsFixture.kitModuleName).KitWidget"]) + + // Renamed to another name: no record pairs with it, so nothing lists + // its requirements. + let differentlyNamed = try #require(definitions["\(moduleName).DifferentlyNamed"]) + #expect(differentlyNamed.objcRuntimeName == nil) + #expect(differentlyNamed.hasExplicitObjCName) + #expect(differentlyNamed.requirements.isEmpty) + + try expectClassAdoptions(in: indexer, machO: machO) + } + + /// The Objective-C protocols the classes adopt: in their own data, read + /// into the type definitions on `index(in:)`, and in the image's + /// categories, collected by `prepare()`. + private static func expectClassAdoptions(in indexer: SwiftDeclarationIndexer, machO: MachO) throws { + let kitModuleName = SwiftDeclaredObjCProtocolsFixture.kitModuleName + func objcProtocolNames(ofClassNamed name: String) throws -> [String] { + let typeDefinition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.name == "\(moduleName).\(name)" }, "\(name) not indexed") + try typeDefinition.index(in: machO) + return typeDefinition.objcProtocolNames.map(\.name) + } + #expect(try objcProtocolNames(ofClassNamed: "Conformer") == ["\(moduleName).SameNameRenamed", "__C.NSCopying"]) + // Adopted in an extension of the class's own module: folded into the + // class's own data. + #expect(try objcProtocolNames(ofClassNamed: "ExtensionConformer") == ["\(moduleName).RefinedProtocol"]) + // Another module's: renamed to its own name, found in the kit; + // renamed to another, kept as the runtime knows it. + #expect(try objcProtocolNames(ofClassNamed: "KitObserverConformer") == ["\(kitModuleName).KitObserver", "__C.KITRenamedObserver", "\(kitModuleName).KitSameName"]) + // `NSCopying` comes with `CopyingRefinement`, a Swift conformance. + #expect(try objcProtocolNames(ofClassNamed: "ImpliedConformer").isEmpty) + #expect(try objcProtocolNames(ofClassNamed: "Outer").isEmpty) + + // An Objective-C class keeps its Objective-C name; another module's + // Swift class reads as Swift spells it, whether the category names + // it by its runtime name (in process) or by the class metadata + // symbol it is bound to (in a file). + #expect(indexer.objcCategoryConformances.map(\.extendedTypeName.name) == ["__C.NSDateFormatter", "\(kitModuleName).KitWidget"]) + #expect(indexer.objcCategoryConformances.map { $0.protocolNames.map(\.name) } == [["\(moduleName).SameNameRenamed"], ["\(moduleName).KitWidgetAdopted"]]) + } + + @Test func modelFromTheFile() async throws { + try await Self.expectModel(in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + } + + @Test func modelFromTheLoadedImage() async throws { + try await Self.expectModel(in: SwiftDeclaredObjCProtocolsFixture.loadedImage()) + } + + /// Stripped of local symbols, a public class's member is still tied to + /// its Objective-C method through the thunk's code, which calls the + /// exported implementation. + @Test func modelFromTheStrippedFile() async throws { + try await Self.expectModel(in: SwiftDeclaredObjCProtocolsFixture.machOFile(.strippedLocals), keepsLocalSymbols: false) + } + + /// Without reflection metadata only the protocols whose runtime names + /// spell the module are found; the renamed ones are not. + @Test func modelWithoutReflectionMetadata() async throws { + let indexer = try await Self.indexer(for: try SwiftDeclaredObjCProtocolsFixture.machOFile(.withoutReflectionMetadata)) + let names = Set(indexer.objcProtocolDefinitions.values.map(\.protocolName.name)) + #expect(names == Set(["DerivedSelectors", "RefinedProtocol", "InternalProtocol", "PrivateProtocol", "Outer.NestedProtocol", "KitWidgetAdopted"].map { "\(Self.moduleName).\($0)" })) + } +} diff --git a/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift new file mode 100644 index 000000000..c5b49d6d0 --- /dev/null +++ b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift @@ -0,0 +1,317 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Internals) import Demangling +import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import SwiftInspection +@testable import SwiftSectionTestingSupport + +/// `TypeDefinition.observableMacroExpansion` sorts an `@Observable` class's +/// stored `var`s into the storage of the properties the macro tracks and the +/// ones it left alone, and picks out the methods it generated (evolution +/// proposal `observable-macro-folding`). What tells a tracked property's +/// storage `_x` from a stored property the source named `_x` depends on what +/// the symbol table kept, so each variant is pinned with the evidence it +/// gives. +@Suite(.serialized) +struct ObservableMacroExpansionRecoveryTests { + private typealias TrackedProperty = ObservableMacroExpansion.TrackedProperty + + private func expansion(of typeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> ObservableMacroExpansion { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + let definition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == typeName }, "no type named \(typeName)") + try definition.index(in: machO) + return try #require(definition.observableMacroExpansion, "\(typeName) has no expansion") + } + + private func trackedProperties(of typeName: String, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> [TrackedProperty] { + try await expansion(of: typeName, in: machO).trackedProperties + } + + // MARK: - Images that keep their local symbols + + /// SwiftUI's `makeFileCoordinator` properties are this shape: a function + /// type with `sending`, which the storage's field record spells and the + /// accessor symbols do not. Every variant keeps the public accessors. + @Test(arguments: ObservableMacroFixture.Variant.allCases) + func aPropertyOfAFunctionTypeWithSendingIsTracked(variant: ObservableMacroFixture.Variant) async throws { + let sendingModel = try await expansion(of: "SendingModel", in: try await ObservableMacroFixture.machOFile(variant)) + #expect(sendingModel.trackedProperties.map(\.name) == ["makeCoordinator", "takeCoordinator"]) + #expect(sendingModel.ignoredStoredPropertyNames.isEmpty) + } + + @Test(arguments: [ObservableMacroFixture.Variant.debug, .release]) + func everyTrackedPropertyIsToldByItsInitAccessor(variant: ObservableMacroFixture.Variant) async throws { + let machO = try await ObservableMacroFixture.machOFile(variant) + let finalModel = try await expansion(of: "FinalModel", in: machO) + #expect(finalModel.trackedProperties == [ + TrackedProperty(name: "name", backingFieldName: "_name", origin: .declaredMember, evidence: .initAccessor), + TrackedProperty(name: "count", backingFieldName: "_count", origin: .declaredMember, evidence: .initAccessor), + TrackedProperty(name: "uninitialized", backingFieldName: "_uninitialized", origin: .declaredMember, evidence: .initAccessor), + ]) + // `_cache` has no init accessor named `cache`: it is a stored + // property of its own. A `let` is never listed. + #expect(finalModel.ignoredStoredPropertyNames == ["ignored", "_cache", "lazyValue"]) + #expect(Set(finalModel.generatedFunctions.map(\.name)).isSuperset(of: ["access", "withMutation"])) + + let internalModel = try await expansion(of: "InternalModel", in: machO) + #expect(internalModel.trackedProperties.map(\.name) == ["value", "optionalText", "delegate"]) + #expect(internalModel.trackedProperties.allSatisfy { $0.origin == .declaredMember && $0.evidence == .initAccessor }) + #expect(internalModel.ignoredStoredPropertyNames == ["_underscored"]) + + #expect(try await trackedProperties(of: "OpenModel", in: machO).map(\.name) == ["title", "items"]) + #expect(try await trackedProperties(of: "SubModel", in: machO).map(\.name) == ["extra"]) + #expect(try await trackedProperties(of: "GenericModel", in: machO).map(\.name) == ["elements"]) + + // A wrapper's storage belongs to the wrapped property, which the + // source declared `@ObservationIgnored`. + let wrapperModel = try await expansion(of: "WrapperModel", in: machO) + #expect(wrapperModel.trackedProperties.map(\.name) == ["tracked"]) + #expect(wrapperModel.ignoredStoredPropertyNames == ["_clamped"]) + } + + @Test func theInProcessReaderRecoversTheSameExpansion() async throws { + let image = try await ObservableMacroFixture.loadedImage() + let finalModel = try await expansion(of: "FinalModel", in: image) + #expect(finalModel.trackedProperties.map(\.name) == ["name", "count", "uninitialized"]) + #expect(finalModel.trackedProperties.allSatisfy { $0.evidence == .initAccessor }) + #expect(finalModel.ignoredStoredPropertyNames == ["ignored", "_cache", "lazyValue"]) + let internalModel = try await expansion(of: "InternalModel", in: image) + #expect(internalModel.trackedProperties.map(\.name) == ["value", "optionalText", "delegate"]) + #expect(internalModel.ignoredStoredPropertyNames == ["_underscored"]) + } + + // MARK: - A dead-stripped image + + /// SwiftUI's shape: the image keeps its local symbols, but linking with + /// `-dead_strip` dropped every function nothing references — most init + /// accessors, and every accessor of a final class's internal properties. + /// The absence of an init accessor must not turn a tracked property's + /// storage into a stored property of its own; it did, and SwiftUI's + /// `Immersion` printed `@ObservationIgnored var _amount` beside the + /// computed `amount`. + @Test func aDeadStrippedImageIsReadFromWhatItKeeps() async throws { + let machO = try await ObservableMacroFixture.machOFile(.releaseDeadStripped) + let internalModel = try await expansion(of: "InternalModel", in: machO) + #expect(internalModel.trackedProperties == [ + // The vtable keeps the computed properties' accessors. + TrackedProperty(name: "value", backingFieldName: "_value", origin: .declaredMember, evidence: .accessors), + TrackedProperty(name: "optionalText", backingFieldName: "_optionalText", origin: .declaredMember, evidence: .accessors), + TrackedProperty(name: "delegate", backingFieldName: "_delegate", origin: .declaredMember, evidence: .accessors), + ]) + // `_underscored` keeps accessors of its own while nothing names + // `underscored`: a stored property of its own. + #expect(internalModel.ignoredStoredPropertyNames == ["_underscored"]) + + let finalModel = try await expansion(of: "FinalModel", in: machO) + #expect(finalModel.trackedProperties == [ + // `name`'s init accessor is one the strip kept. + TrackedProperty(name: "name", backingFieldName: "_name", origin: .declaredMember, evidence: .initAccessor), + // The rest of the final class's accessors are gone. + TrackedProperty(name: "count", backingFieldName: "_count", origin: .synthesized, evidence: .initialValueExpression), + TrackedProperty(name: "uninitialized", backingFieldName: "_uninitialized", origin: .synthesized, evidence: .backingFieldName), + ]) + #expect(finalModel.ignoredStoredPropertyNames == ["ignored", "_cache", "lazyValue"]) + } + + // MARK: - An image stripped of its local symbols + + @Test func aStrippedPublicClassIsReadFromItsExports() async throws { + let machO = try await ObservableMacroFixture.machOFile(.releaseStripped) + let finalModel = try await expansion(of: "FinalModel", in: machO) + #expect(finalModel.trackedProperties == [ + // Public: the computed property's setter is exported. + TrackedProperty(name: "name", backingFieldName: "_name", origin: .declaredMember, evidence: .accessors), + // Internal, with an initial value: the exported initial-value + // expression is `count`'s, not `_count`'s. + TrackedProperty(name: "count", backingFieldName: "_count", origin: .synthesized, evidence: .initialValueExpression), + // Internal, without one: only the storage's name says it. + TrackedProperty(name: "uninitialized", backingFieldName: "_uninitialized", origin: .synthesized, evidence: .backingFieldName), + ]) + // `_cache` carries its own exported initial-value expression. + #expect(finalModel.ignoredStoredPropertyNames == ["ignored", "_cache", "lazyValue"]) + + // An open class exports its init accessors. + let openModel = try await trackedProperties(of: "OpenModel", in: machO) + #expect(openModel.map(\.name) == ["title", "items"]) + #expect(openModel.allSatisfy { $0.evidence == .initAccessor }) + } + + /// The limit the evidence leaves: an internal class whose symbols are all + /// stripped keeps only its field records, so an `@ObservationIgnored` + /// property named `_underscored` reads as the storage of a tracked + /// `underscored`. It is recorded with the evidence that says so. + @Test func aStrippedInternalClassIsReadFromItsStorageNames() async throws { + let machO = try await ObservableMacroFixture.machOFile(.releaseStripped) + let internalModel = try await trackedProperties(of: "InternalModel", in: machO) + #expect(internalModel == [ + TrackedProperty(name: "value", backingFieldName: "_value", origin: .synthesized, evidence: .backingFieldName), + TrackedProperty(name: "optionalText", backingFieldName: "_optionalText", origin: .synthesized, evidence: .backingFieldName), + TrackedProperty(name: "delegate", backingFieldName: "_delegate", origin: .synthesized, evidence: .backingFieldName), + TrackedProperty(name: "underscored", backingFieldName: "_underscored", origin: .synthesized, evidence: .backingFieldName), + ]) + } + + // MARK: - The rules on hand-built inputs + + private static let intTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Swift"), + Node.createTransient(kind: .identifier, text: "Int"), + ])) + + private static let stringTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Swift"), + Node.createTransient(kind: .identifier, text: "String"), + ])) + + /// `(sending Swift.Int) -> sending Swift.Int` in the demangler's shape, + /// either `sending` optional: a field record spells both, a declaration's + /// symbol neither. + private static func functionTypeNode(sendingResult: Bool, sendingParameter: Bool) -> Node { + let intStructureNode = Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Swift"), + Node.createTransient(kind: .identifier, text: "Int"), + ]) + let parameterTypeNode = sendingParameter + ? Node.createTransient(kind: .type, child: Node.createTransient(kind: .sending, child: intStructureNode)) + : Node.createTransient(kind: .type, child: intStructureNode) + var children: [Node] = sendingResult ? [Node.createTransient(kind: .sendingResultFunctionType)] : [] + children.append(Node.createTransient(kind: .argumentTuple, child: parameterTypeNode)) + children.append(Node.createTransient(kind: .returnType, child: Node.createTransient(kind: .type, child: intStructureNode))) + return Node.createTransient(kind: .type, child: Node.createTransient(kind: .functionType, children: children)) + } + + @Test func onlyAnUnderscoredNameWithoutADollarSignCanBeStorage() { + #expect(ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: "_value") == "value") + #expect(ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: "__value") == "_value") + #expect(ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: "value") == nil) + #expect(ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: "_") == nil) + #expect(ObservableMacroExpansionRecovery.trackedPropertyName(forBackingFieldName: "_$observationRegistrar") == nil) + } + + @Test func aWeakStorageStoresTheTypeItsPropertyDeclares() { + let weakTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .weak, child: Self.intTypeNode)) + #expect(StoredTypeMatching.referencedTypeNode(ofStoredType: weakTypeNode) == Self.intTypeNode) + #expect(StoredTypeMatching.referencedTypeNode(ofStoredType: Self.intTypeNode) == Self.intTypeNode) + } + + /// The methods the macro generates are told by name, labels and shape: a + /// method the source declares under one of their names in another shape + /// — `shouldNotifyObservers()`, `access(keyPath: String)` — is not among + /// them, while the macro's own beside it are. + @Test(arguments: [ObservableMacroFixture.Variant.debug, .release]) + func theGeneratedMethodsAreToldByTheirShape(variant: ObservableMacroFixture.Variant) async throws { + let machO = try await ObservableMacroFixture.machOFile(variant) + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + let definition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == "HandwrittenNamesModel" }) + try definition.index(in: machO) + let expansion = try #require(definition.observableMacroExpansion) + let generatedSymbolNames = Set(expansion.generatedFunctions.map(\.symbol.name)) + let sourceDeclared = definition.functions.filter { !generatedSymbolNames.contains($0.symbol.name) } + #expect(Set(sourceDeclared.map(\.name)).isSuperset(of: ["access", "shouldNotifyObservers"])) + #expect(Set(expansion.generatedFunctions.map(\.name)).isSuperset(of: ["access", "withMutation"])) + } + + @Test func anInitAccessorOrTheComputedPropertysSetterTellsATrackedProperty() { + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: [ + .init(name: "_initialized", typeNode: Self.intTypeNode, isVariable: true), + .init(name: "_settable", typeNode: Self.intTypeNode, isVariable: true, hasAccessors: true), + .init(name: "_constant", typeNode: Self.intTypeNode, isVariable: false), + .init(name: "_$observationRegistrar", typeNode: Self.intTypeNode, isVariable: false), + ], + // No init accessor for `settable`: dead-stripped, as in SwiftUI. + memberVariables: [.init(name: "settable", declaredTypeNode: Self.intTypeNode, hasSetterOrModify: true)], + claimedBackingFieldNames: [], + evidence: .init(initAccessorNames: ["initialized"]) + ) + #expect(recovered.trackedProperties == [ + TrackedProperty(name: "initialized", backingFieldName: "_initialized", origin: .synthesized, evidence: .initAccessor), + TrackedProperty(name: "settable", backingFieldName: "_settable", origin: .declaredMember, evidence: .accessors), + ]) + #expect(recovered.ignoredStoredPropertyNames.isEmpty) + } + + @Test func aMemberOfAnotherTypeIsNotWhatTheStorageHolds() { + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: [.init(name: "_label", typeNode: Self.intTypeNode, isVariable: true)], + memberVariables: [.init(name: "label", declaredTypeNode: Self.stringTypeNode, hasSetterOrModify: true)], + claimedBackingFieldNames: [], + evidence: .init(initAccessorNames: ["label"]) + ) + #expect(recovered.trackedProperties.isEmpty) + #expect(recovered.ignoredStoredPropertyNames == ["_label"]) + } + + /// The accessor symbols never spell `sending` on the property's own + /// function type — the mangler leaves it out of a declaration's type + /// (`ASTMangler::appendDeclType`) — while the storage's field record + /// does. The two name one type. + @Test func aStorageOfAFunctionTypeWithSendingIsThePropertysWithout() { + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: [.init(name: "_make", typeNode: Self.functionTypeNode(sendingResult: true, sendingParameter: true), isVariable: true)], + memberVariables: [.init(name: "make", declaredTypeNode: Self.functionTypeNode(sendingResult: false, sendingParameter: false), hasSetterOrModify: true)], + claimedBackingFieldNames: [], + evidence: .init(initAccessorNames: ["make"]) + ) + #expect(recovered.trackedProperties == [ + TrackedProperty(name: "make", backingFieldName: "_make", origin: .declaredMember, evidence: .initAccessor), + ]) + #expect(recovered.ignoredStoredPropertyNames.isEmpty) + } + + @Test func aWrappersStorageIsLeftToTheWrappedProperty() { + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: [.init(name: "_clamped", typeNode: Self.intTypeNode, isVariable: true)], + memberVariables: [], + claimedBackingFieldNames: ["_clamped"], + evidence: .init(initAccessorNames: ["clamped"]) + ) + #expect(recovered.trackedProperties.isEmpty) + #expect(recovered.ignoredStoredPropertyNames == ["_clamped"]) + } + + @Test func whatTheStorageHasOfItsOwnRulesItOut() { + var askedForInitialValueExpressions = 0 + let recovered = ObservableMacroExpansionRecovery.recover( + storedProperties: [ + .init(name: "_initialized", typeNode: Self.intTypeNode, isVariable: true), + .init(name: "_ownInitialValue", typeNode: Self.intTypeNode, isVariable: true), + .init(name: "_ownAccessors", typeNode: Self.intTypeNode, isVariable: true, hasAccessors: true), + .init(name: "_unnamed", typeNode: Self.intTypeNode, isVariable: true), + ], + memberVariables: [], + claimedBackingFieldNames: [], + evidence: .init(initialValueExpressionNames: { + askedForInitialValueExpressions += 1 + return ["initialized", "_ownInitialValue"] + }) + ) + #expect(recovered.trackedProperties == [ + TrackedProperty(name: "initialized", backingFieldName: "_initialized", origin: .synthesized, evidence: .initialValueExpression), + TrackedProperty(name: "unnamed", backingFieldName: "_unnamed", origin: .synthesized, evidence: .backingFieldName), + ]) + #expect(recovered.ignoredStoredPropertyNames == ["_ownInitialValue", "_ownAccessors"]) + // Gathered once, however many storages ask. + #expect(askedForInitialValueExpressions == 1) + } + + @Test func theInitialValueExpressionsAreNotGatheredWhenTheAccessorsDecide() { + var askedForInitialValueExpressions = 0 + _ = ObservableMacroExpansionRecovery.recover( + storedProperties: [.init(name: "_value", typeNode: Self.intTypeNode, isVariable: true)], + memberVariables: [.init(name: "value", declaredTypeNode: Self.intTypeNode, hasSetterOrModify: true)], + claimedBackingFieldNames: [], + evidence: .init(initialValueExpressionNames: { + askedForInitialValueExpressions += 1 + return [] + }) + ) + #expect(askedForInitialValueExpressions == 0) + } +} diff --git a/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift new file mode 100644 index 000000000..53302a6a5 --- /dev/null +++ b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift @@ -0,0 +1,107 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Internals) import Demangling +import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@testable import SwiftInspection +@testable import SwiftSectionTestingSupport + +/// `TypeDefinition.attachedMacros` recognizes a class `@Observable` expanded +/// from its field records when the definition is built, before anything is +/// indexed, and `ExtensionDefinition.generatingMacro` marks the conformance +/// the macro generated (evolution proposal `observable-macro-folding`). The +/// field records survive stripping, so every variant answers the same. +@Suite(.serialized) +struct ObservableMacroRecognitionTests { + private struct Recognition { + var attachedMacrosByTypeName: [String: Set] = [:] + /// The `Observation.Observable` conformance extensions, by the name + /// of the type they extend. + var generatingMacrosByConformingTypeName: [String: SwiftAttachedMacro?] = [:] + } + + private func recognition(in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> Recognition { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + var recognition = Recognition() + for definition in indexer.allTypeDefinitions.values { + // Nothing is indexed: the macros are known as soon as the model is. + #expect(!definition.isIndexed) + recognition.attachedMacrosByTypeName[definition.typeName.declaredNameForTesting] = definition.attachedMacros + } + for (extensionName, extensionDefinitions) in indexer.conformanceExtensionDefinitions { + for extensionDefinition in extensionDefinitions { + guard let protocolName = extensionDefinition.conformingProtocolName, + ObservableMacroRecognition.isObservableProtocol(protocolName.node.materialize()) + else { continue } + recognition.generatingMacrosByConformingTypeName[extensionName.declaredNameForTesting] = extensionDefinition.generatingMacro + } + } + return recognition + } + + private func expectFixtureRecognition(_ recognition: Recognition, sourceLocation: SourceLocation = #_sourceLocation) { + for typeName in ObservableMacroFixture.observableClassNames { + #expect(recognition.attachedMacrosByTypeName[typeName] == [.observable], "\(typeName)", sourceLocation: sourceLocation) + } + for typeName in ObservableMacroFixture.lookalikeTypeNames { + #expect(recognition.attachedMacrosByTypeName[typeName] == [], "\(typeName)", sourceLocation: sourceLocation) + } + // The macro's conformances are marked; the hand-written one is not. + // The subclass inherits its conformance and has no record of its own. + #expect( + recognition.generatingMacrosByConformingTypeName == [ + "FinalModel": .observable, + "OpenModel": .observable, + "InternalModel": .observable, + "GenericModel": .observable, + "WrapperModel": .observable, + "ContainerModel": .observable, + "NestedModel": .observable, + "SendingModel": .observable, + "HandwrittenNamesModel": .observable, + "ManualObservable": nil, + ], + sourceLocation: sourceLocation + ) + } + + @Test(arguments: ObservableMacroFixture.Variant.allCases) + func everyVariantRecognizesTheSameClasses(variant: ObservableMacroFixture.Variant) async throws { + expectFixtureRecognition(try await recognition(in: try await ObservableMacroFixture.machOFile(variant))) + } + + @Test func theInProcessReaderRecognizesTheSameClasses() async throws { + expectFixtureRecognition(try await recognition(in: try await ObservableMacroFixture.loadedImage())) + } + + @Test func theRegistrarTypeIsReadWithOrWithoutItsTypeNode() { + let registrar = Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Observation"), + Node.createTransient(kind: .identifier, text: "ObservationRegistrar"), + ]) + #expect(ObservableMacroRecognition.isObservationRegistrarType(registrar)) + #expect(ObservableMacroRecognition.isObservationRegistrarType(Node.createTransient(kind: .type, child: registrar))) + let lookalike = Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "ComposableArchitecture"), + Node.createTransient(kind: .identifier, text: "ObservationRegistrar"), + ]) + #expect(!ObservableMacroRecognition.isObservationRegistrarType(lookalike)) + } + + @Test func theConformanceIsToTheObservationModulesProtocol() { + let observable = Node.createTransient(kind: .protocol, children: [ + Node.createTransient(kind: .module, text: "Observation"), + Node.createTransient(kind: .identifier, text: "Observable"), + ]) + #expect(ObservableMacroRecognition.isObservableProtocol(Node.createTransient(kind: .type, child: observable))) + let structure = Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Observation"), + Node.createTransient(kind: .identifier, text: "Observable"), + ]) + #expect(!ObservableMacroRecognition.isObservableProtocol(structure)) + } +} diff --git a/Tests/SwiftIndexingTests/OverrideRecoveryPredicateTests.swift b/Tests/SwiftIndexingTests/OverrideRecoveryPredicateTests.swift index 5c37ded49..9c8d65740 100644 --- a/Tests/SwiftIndexingTests/OverrideRecoveryPredicateTests.swift +++ b/Tests/SwiftIndexingTests/OverrideRecoveryPredicateTests.swift @@ -2,7 +2,7 @@ import Foundation import MachOResolving import Testing import Demangling -import MachOSymbols +import SwiftSymbols @testable import MachOSwiftSection import SwiftDeclaration diff --git a/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift b/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift index c88968517..f79b805a3 100644 --- a/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift +++ b/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift @@ -3,11 +3,12 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop @_spi(Internals) import Demangling @testable import MachOSwiftSection @testable import SwiftDeclarationRendering @@ -48,7 +49,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsHelper } private func clearAllPerImageCaches(for machOFile: MachOFile) { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) var symbolIndexStore symbolIndexStore.remove(for: machOFile) SymbolicManglingIndex.shared.remove(for: machOFile) @@ -126,10 +127,10 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { for cycle in 1 ... 3 { var indexer: SwiftDeclarationIndexer? = SwiftDeclarationIndexer(in: unsafeMachOFile) try await indexer?.prepare() - try #require(SymbolIndexStore.shared.contains(in: unsafeMachOFile)) + try #require(SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile)) indexer = nil - #expect(!SymbolIndexStore.shared.contains(in: unsafeMachOFile), "cycle \(cycle) left the symbol store behind") + #expect(!SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile), "cycle \(cycle) left the symbol store behind") #expect(!InternedNodeReferenceCache.shared.contains(in: unsafeMachOFile), "cycle \(cycle) left the interned store behind") #expect(!SymbolicDemangler.cacheExists(for: unsafeMachOFile), "cycle \(cycle) left the demangle memo behind") } @@ -150,7 +151,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { indexer = nil - #expect(!SymbolIndexStore.shared.contains(in: unsafeMachOFile), "the indexer built the symbol store, so it must reclaim it") + #expect(!SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile), "the indexer built the symbol store, so it must reclaim it") #expect( !SymbolicManglingIndex.shared.contains(in: unsafeMachOFile), "the index outlived the symbol store and pins its symbolic-mangling table" @@ -178,6 +179,25 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { ) } + /// `SwiftClassWithoutClassObjectIndex` is ObjC-side per-image state of the + /// same lifetime (evolution proposal `objc-classes-without-class-objects`). + @Test func classesWithoutClassObjectsIndexGoesWithTheObjCClassHierarchies() async throws { + let unsafeMachOFile = machOFile + clearAllPerImageCaches(for: unsafeMachOFile) + + var indexer: SwiftDeclarationIndexer? = SwiftDeclarationIndexer(in: unsafeMachOFile) + try await indexer?.prepare() + _ = SwiftClassWithoutClassObjectIndex.shared.classes(in: unsafeMachOFile) + try #require(SwiftClassWithoutClassObjectIndex.shared.contains(in: unsafeMachOFile)) + + indexer = nil + + #expect( + !SwiftClassWithoutClassObjectIndex.shared.contains(in: unsafeMachOFile), + "the index of classes without a class object outlived the indexer that reclaims the image's ObjC-side state" + ) + } + @Test func survivingIndexerKeepsPerImageCaches() async throws { let unsafeMachOFile = machOFile clearAllPerImageCaches(for: unsafeMachOFile) @@ -189,7 +209,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { // All three must genuinely be populated, or the survivor assertions // below degrade to `false == false` and pin nothing. - try #require(SymbolIndexStore.shared.contains(in: unsafeMachOFile)) + try #require(SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile)) try #require(InternedNodeReferenceCache.shared.contains(in: unsafeMachOFile)) try #require(SymbolicDemangler.cacheExists(for: unsafeMachOFile)) @@ -199,7 +219,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { firstIndexer = nil #expect( - SymbolIndexStore.shared.contains(in: unsafeMachOFile), + SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile), "the first indexer's deinit evicted the symbol store while a second live indexer was using the image" ) #expect( @@ -223,7 +243,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { var secondIndexer: SwiftDeclarationIndexer? = SwiftDeclarationIndexer(in: unsafeMachOFile) try await secondIndexer?.prepare() - try #require(SymbolIndexStore.shared.contains(in: unsafeMachOFile)) + try #require(SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile)) try #require(InternedNodeReferenceCache.shared.contains(in: unsafeMachOFile)) try #require(SymbolicDemangler.cacheExists(for: unsafeMachOFile)) @@ -231,7 +251,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { secondIndexer = nil #expect( - !SymbolIndexStore.shared.contains(in: unsafeMachOFile), + !SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile), "the image's LAST live indexer must still perform the eviction — otherwise the per-image caches leak for the rest of the process lifetime" ) #expect(!InternedNodeReferenceCache.shared.contains(in: unsafeMachOFile)) @@ -261,7 +281,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { // claim reads backwards. try #require(InternedNodeReferenceCache.shared.contains(in: unsafeMachOFile)) try #require(SymbolicDemangler.cacheExists(for: unsafeMachOFile)) - try #require(!SymbolIndexStore.shared.contains(in: unsafeMachOFile)) + try #require(!SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile)) var indexer: SwiftDeclarationIndexer? = SwiftDeclarationIndexer(in: unsafeMachOFile) try await indexer?.prepare() @@ -277,7 +297,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { ) // The symbol store IS the indexer's to reclaim: it built that one. #expect( - !SymbolIndexStore.shared.contains(in: unsafeMachOFile), + !SwiftSymbolIndexStore.shared.contains(in: unsafeMachOFile), "the symbol store the indexer built must still be reclaimed" ) } diff --git a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift index f2f94edb8..2d9133a19 100644 --- a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift +++ b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing import MachOKit -import MachOFixtureSupport -@testable import MachOTestingSupport +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport import Demangling import SwiftDeclaration @_spi(Support) import SwiftIndexing diff --git a/Tests/SwiftIndexingTests/AssociatedTypeWitnessProjectionTests.swift b/Tests/SwiftIndexingTests/ResolvedAssociatedTypeWitnessTests.swift similarity index 60% rename from Tests/SwiftIndexingTests/AssociatedTypeWitnessProjectionTests.swift rename to Tests/SwiftIndexingTests/ResolvedAssociatedTypeWitnessTests.swift index 8b44d9f0e..5129664f9 100644 --- a/Tests/SwiftIndexingTests/AssociatedTypeWitnessProjectionTests.swift +++ b/Tests/SwiftIndexingTests/ResolvedAssociatedTypeWitnessTests.swift @@ -7,7 +7,7 @@ import SwiftDeclarationRendering /// trip, and a projection persisted before `conditionalCandidates` existed /// still decodes (the key is optional on the way in). @Suite -struct AssociatedTypeWitnessProjectionTests { +struct ResolvedAssociatedTypeWitnessTests { private func encoder() -> JSONEncoder { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys] @@ -17,23 +17,23 @@ struct AssociatedTypeWitnessProjectionTests { @Test func roundTripsConditionalCandidates() throws { let satisfied = PlatformAvailabilityCondition(platform: 1, major: 26, minor: 0, patch: 0, isSatisfiedBranch: true) let notSatisfied = PlatformAvailabilityCondition(platform: 1, major: 26, minor: 0, patch: 0, isSatisfiedBranch: false) - let projection = AssociatedTypeWitnessProjection( + let projection = ResolvedAssociatedTypeWitness( name: "Body", substitutedTypeText: "M.Box", conditionalCandidates: [ - ConditionalWitnessCandidate(availability: satisfied, candidateTypeText: "M.Static", substitutedTypeText: "M.Box"), - ConditionalWitnessCandidate(availability: notSatisfied, candidateTypeText: "M.Dynamic", substitutedTypeText: "M.Box"), + ResolvedAssociatedTypeWitness.ConditionalCandidate(availability: satisfied, candidateTypeText: "M.Static", substitutedTypeText: "M.Box"), + ResolvedAssociatedTypeWitness.ConditionalCandidate(availability: notSatisfied, candidateTypeText: "M.Dynamic", substitutedTypeText: "M.Box"), ] ) let data = try encoder().encode(projection) - let decoded = try JSONDecoder().decode(AssociatedTypeWitnessProjection.self, from: data) + let decoded = try JSONDecoder().decode(ResolvedAssociatedTypeWitness.self, from: data) #expect(decoded == projection) } @Test func decodesAProjectionPersistedWithoutCandidates() throws { let legacy = Data(#"{"name":"Element","substitutedTypeText":"Swift.Int"}"#.utf8) - let decoded = try JSONDecoder().decode(AssociatedTypeWitnessProjection.self, from: legacy) - #expect(decoded == AssociatedTypeWitnessProjection(name: "Element", substitutedTypeText: "Swift.Int")) + let decoded = try JSONDecoder().decode(ResolvedAssociatedTypeWitness.self, from: legacy) + #expect(decoded == ResolvedAssociatedTypeWitness(name: "Element", substitutedTypeText: "Swift.Int")) #expect(decoded.conditionalCandidates.isEmpty) } @@ -41,12 +41,12 @@ struct AssociatedTypeWitnessProjectionTests { /// availability, and that absence survives the round trip as `nil` /// rather than decoding as a zero version. @Test func roundTripsAnUnconditionalCandidate() throws { - let projection = AssociatedTypeWitnessProjection( + let projection = ResolvedAssociatedTypeWitness( name: "Body", substitutedTypeText: "M.Static", - conditionalCandidates: [ConditionalWitnessCandidate(availability: nil, candidateTypeText: "M.Static", substitutedTypeText: "M.Static")] + conditionalCandidates: [ResolvedAssociatedTypeWitness.ConditionalCandidate(availability: nil, candidateTypeText: "M.Static", substitutedTypeText: "M.Static")] ) - let decoded = try JSONDecoder().decode(AssociatedTypeWitnessProjection.self, from: try encoder().encode(projection)) + let decoded = try JSONDecoder().decode(ResolvedAssociatedTypeWitness.self, from: try encoder().encode(projection)) #expect(decoded == projection) #expect(decoded.conditionalCandidates.first?.availability == nil) } diff --git a/Tests/SwiftIndexingTests/SpecializedInitializerNameTests.swift b/Tests/SwiftIndexingTests/SpecializedInitializerNameTests.swift new file mode 100644 index 000000000..60f203f70 --- /dev/null +++ b/Tests/SwiftIndexingTests/SpecializedInitializerNameTests.swift @@ -0,0 +1,40 @@ +import Foundation +import Testing +import Demangling +import MachOResolving +import SwiftSymbols +import SwiftDeclaration + +/// `StandInMemberSymbolBuilder.specializedInitializerName(of:)`: the name of +/// the initializing entry point a function signature specialization +/// specializes, read off the specialization's own name. Swift 6.4's +/// whole-module optimization leaves an internal class's initializer only as +/// such a specialization (`ThunkOnlyObjCMemberTests` covers the image); these +/// pin the name on its own, whatever the compiler at hand emits. +@Suite +struct SpecializedInitializerNameTests { + private static let initializingEntryPointName = "_$s22ThunkOnlyMemberFixture017InitializingEntryB6HolderC6valuesACSaySSG_tcfc" + + private func demangledSymbol(named name: String) throws -> DemangledSymbol { + DemangledSymbol(symbol: Symbol(offset: 0, name: name, isExternal: false), demangledNode: NodeReference(interning: try demangleAsNode(name))) + } + + @Test func aSpecializationReadsBackToItsInitializingEntryPoint() throws { + let specialization = try demangledSymbol(named: Self.initializingEntryPointName + "Tf4gn_n") + #expect(StandInMemberSymbolBuilder.specializedInitializerName(of: specialization) == Self.initializingEntryPointName) + } + + /// The last `Tf` suffix belongs to the outer specialization; the name + /// before it ends in another specialization, not in `fc`. + @Test func aSpecializationOfASpecializationReadsBackToo() throws { + let specialization = try demangledSymbol(named: Self.initializingEntryPointName + "Tf4gn_nTf4n_g") + #expect(StandInMemberSymbolBuilder.specializedInitializerName(of: specialization) == Self.initializingEntryPointName) + } + + @Test func anythingElseHasNone() throws { + // The initializing entry point itself. + #expect(StandInMemberSymbolBuilder.specializedInitializerName(of: try demangledSymbol(named: Self.initializingEntryPointName)) == nil) + // A method's specialization. + #expect(StandInMemberSymbolBuilder.specializedInitializerName(of: try demangledSymbol(named: "_$s15SymbolTestsCore3FooC3baryyFTf4n_n")) == nil) + } +} diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index f21781626..e458c4c52 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -6,12 +6,12 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import SwiftDump // MARK: - Shared Setup diff --git a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift index 39608cb62..0ca9e8fba 100644 --- a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import MachOKit import MachOFoundation -import Demangling +@_spi(Internals) import Demangling import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @@ -259,3 +259,63 @@ struct WrappedPropertyRecoveryTests { #expect(byName["manual"] == nil) } } + +/// The node-level rule that decides how a recovered wrapper attribute is +/// spelled, pinned on hand-built trees. +struct WrappedPropertyAttributeSpellingTests { + private static let intStructureNode = Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Swift"), + Node.createTransient(kind: .identifier, text: "Int"), + ]) + + private static let wrapperNominalTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "ProbeWrapperKit"), + Node.createTransient(kind: .identifier, text: "Box"), + ])) + + /// `() -> sending Swift.Int`, or `() -> Swift.Int`. + private static func functionTypeNode(sendingResult: Bool) -> Node { + var children: [Node] = sendingResult ? [Node.createTransient(kind: .sendingResultFunctionType)] : [] + children.append(Node.createTransient(kind: .argumentTuple, child: Node.createTransient(kind: .type, child: Node.createTransient(kind: .tuple)))) + children.append(Node.createTransient(kind: .returnType, child: Node.createTransient(kind: .type, child: intStructureNode))) + return Node.createTransient(kind: .type, child: Node.createTransient(kind: .functionType, children: children)) + } + + /// The wrapper's generic argument comes from the field record, which + /// keeps `sending` in a function type nested in the bound type; the + /// property's type comes from its getter's symbol, which leaves `sending` + /// out of the declaration's own function type. The argument is the + /// property's type all the same, so the attribute stays bare + /// (`@Box var make: () -> sending Int`). + @Test func anArgumentDifferingOnlyInSendingLeavesTheAttributeBare() { + let fieldTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .boundGenericStructure, children: [ + Self.wrapperNominalTypeNode, + Node.createTransient(kind: .typeList, child: Self.functionTypeNode(sendingResult: true)), + ])) + let attributeTypeNode = WrappedPropertyRecovery.attributeTypeNode( + fieldTypeNode: fieldTypeNode, + wrapperNominalTypeNode: Self.wrapperNominalTypeNode, + wrappedPropertyTypeNode: Self.functionTypeNode(sendingResult: false) + ) + #expect(attributeTypeNode == Self.wrapperNominalTypeNode) + } + + /// `sending` is all that is set aside: an argument of another type keeps + /// the attribute's arguments. + @Test func anArgumentOfAnotherTypeKeepsTheArguments() { + let fieldTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .boundGenericStructure, children: [ + Self.wrapperNominalTypeNode, + Node.createTransient(kind: .typeList, child: Self.functionTypeNode(sendingResult: true)), + ])) + let stringTypeNode = Node.createTransient(kind: .type, child: Node.createTransient(kind: .structure, children: [ + Node.createTransient(kind: .module, text: "Swift"), + Node.createTransient(kind: .identifier, text: "String"), + ])) + let attributeTypeNode = WrappedPropertyRecovery.attributeTypeNode( + fieldTypeNode: fieldTypeNode, + wrapperNominalTypeNode: Self.wrapperNominalTypeNode, + wrappedPropertyTypeNode: stringTypeNode + ) + #expect(attributeTypeNode == fieldTypeNode) + } +} diff --git a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift index 0bea5e352..da7b37551 100644 --- a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift +++ b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift @@ -4,9 +4,10 @@ import MachOKit import MachOObjCSection @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection +@testable @_spi(Internals) import SwiftObjCInterop /// A private type's descriptor hangs off an anonymous context, and the private /// discriminator its name needs is recorded in only two places the demangler diff --git a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift index 696af7161..b07d82346 100644 --- a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift +++ b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift @@ -3,6 +3,7 @@ import Testing import MachOKit import MachOObjCSection @testable import SwiftInspection +@testable import SwiftObjCInterop private enum TwinSwiftUICaches { static let swiftUIPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" diff --git a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift index 7d12f5e6b..26aeb13f7 100644 --- a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift +++ b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection // MARK: - Test Enum Definitions diff --git a/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift b/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift index 0b8e1b009..622db63be 100644 --- a/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift +++ b/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift @@ -3,7 +3,7 @@ import Testing import MachOKit @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable @_spi(Internals) import SwiftInspection /// A type declared in a function or closure body hangs off a chain of diff --git a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift index b13bb860c..1310c3049 100644 --- a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift +++ b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift @@ -1,9 +1,11 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing import MachOKit import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection +@testable @_spi(Internals) import SwiftObjCInterop /// A symbol's value is the binary's own claim about where something sits, and /// two indexes read the bytes there: `SymbolicManglingIndex` (the mangled name @@ -109,7 +111,7 @@ struct MalformedSymbolValueTests { let machOFile = try Self.fixtureFile() // Read through the symbol store, which collects the symbol without // reading what it points at — asking the index would build it. - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) let malformedPosition = try #require(collectedSymbols.position(ofSymbolNamed: Self.malformedSymbolicManglingSymbolName), "the premise: the linker kept the malformed symbol") try #require(collectedSymbols[malformedPosition].offset < 0, "the premise: MachOKit hands the value back as a negative offset") @@ -125,7 +127,7 @@ struct MalformedSymbolValueTests { func fieldOffsetSymbolWhoseValueIsNoOffsetIsSkipped() throws { let machOFile = try Self.fixtureFile() let malformedSymbol = try #require( - SymbolIndexStore.shared.symbols(of: .fieldOffset, in: machOFile).first { $0.symbol.name == Self.malformedFieldOffsetSymbolName }, + SwiftSymbolIndexStore.shared.symbols(of: .fieldOffset, in: machOFile).first { $0.symbol.name == Self.malformedFieldOffsetSymbolName }, "the premise: the symbol index demangles the malformed field offset symbol" ) try #require(malformedSymbol.offset < 0, "the premise: MachOKit hands the value back as a negative offset") diff --git a/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift b/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift index acbb70d39..889f2c22d 100644 --- a/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift +++ b/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift @@ -3,7 +3,7 @@ import Testing import MachOKit @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable @_spi(Internals) import SwiftInspection /// The private declarations a name reads (evolution proposal diff --git a/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift b/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift index 26eab6e2d..ebf28f9cd 100644 --- a/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift +++ b/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift @@ -4,8 +4,8 @@ import MachOKit import Demangling @_spi(Internals) import MachOCaches @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection /// A `ReadingContext` declares where memo caches may file what they compute diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift index 3d3154936..b11087e0a 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift @@ -2,8 +2,8 @@ import Foundation import Testing @testable import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection // MARK: - Unit Tests for SymbolicDemangler demangling functions diff --git a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift index 4b2fb519a..cfdb98a88 100644 --- a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift @@ -4,10 +4,11 @@ import MachOKit import MachOObjCSection @testable import Demangling @testable import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection +@testable @_spi(Internals) import SwiftObjCInterop /// The decoding layer of evolution proposal `symbolic-mangling-symbol-index`: /// `SymbolicManglingIndex` pairs every symbolic reference in the mangled names diff --git a/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift b/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift index 3d952bf46..c24e17975 100644 --- a/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift +++ b/Tests/SwiftInspectionTests/WrappedReaderDemanglingTests.swift @@ -5,8 +5,8 @@ import MachOFoundation import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection -import MachOTestingSupport -import MachOFixtureSupport +import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A host's wrapper around an in-process `MachOImage` — MachOKitUI's /// `MachOImageSource` — demangling the image's names. diff --git a/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift new file mode 100644 index 000000000..b1065e79a --- /dev/null +++ b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift @@ -0,0 +1,84 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDeclaration +import SwiftDeclarationRendering +import SwiftInterface +import SwiftThunkAnalysis +@_spi(Internals) import SwiftInspection +@testable import SwiftSectionTestingSupport + +/// Swift classes without a class object on the interface path (evolution +/// proposal `objc-classes-without-class-objects`): a generic class, or one +/// with generic ancestry, has its ObjC method table in Swift metadata only, +/// and the ObjC member recovery — the `override` of an ObjC-inherited +/// member, which Swift metadata does not record — used to find none. +/// +/// Holds `ExclusiveImageAccess` because the indexer registers an ancestor +/// resolver per image for the file leg. +@Suite(.serialized, ExclusiveImageAccess(ClassesWithoutClassObjectsFixture.moduleName)) +struct ClassesWithoutClassObjectsInterfaceTests { + private static let moduleName = ClassesWithoutClassObjectsFixture.moduleName + + private func interface(of variant: ClassesWithoutClassObjectsFixture.Variant) async throws -> String { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.indexConfiguration.dependencySearchPaths = try ClassesWithoutClassObjectsFixture.dependencySearchPaths() + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: try ClassesWithoutClassObjectsFixture.machOFile(variant)) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The block whose header line STARTS with `prefix`, through its closing + /// brace at the same indentation. + private func block(startingWith prefix: String, in interface: String) -> String? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[start...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[start...end].joined(separator: "\n") + } + + /// The generic class's method table sits in its metadata pattern: + /// `description` overrides NSObject's, `poke` is its own. + @Test func genericClassOverridesAreMarked() async throws { + let interface = try await interface(of: .full) + let widget = try #require(block(startingWith: "class GenericWidget<", in: interface), "\(interface)") + #expect(widget.contains("@objc override var description: Swift.String"), "\(widget)") + #expect(widget.contains("@objc func poke()"), "\(widget)") + #expect(!widget.contains("override func poke()"), "\(widget)") + } + + /// Generic ancestry: the chain runs through the generic superclass's + /// pattern on to NSObject. + @Test func classWithGenericAncestryOverridesAreMarked() async throws { + let interface = try await interface(of: .full) + let subclass = try #require(block(startingWith: "class ConcreteSubclass:", in: interface), "\(interface)") + #expect(subclass.contains("@objc override var description: Swift.String"), "\(subclass)") + #expect(subclass.contains("@objc func concretePoke()"), "\(subclass)") + #expect(!subclass.contains("override func concretePoke()"), "\(subclass)") + } + + /// With the `To` thunks stripped, as in every OS framework, the method + /// table is the only `@objc` evidence. + @Test func strippedGenericClassMembersJoinTheirObjCMethodTable() async throws { + let interface = try await interface(of: .strippedLocals) + let widget = try #require(block(startingWith: "class GenericWidget<", in: interface), "\(interface)") + #expect(widget.contains("@objc override var description: Swift.String"), "\(widget)") + #expect(widget.contains("@objc func poke()"), "\(widget)") + #expect(!widget.contains("final"), "\(widget)") + let subclass = try #require(block(startingWith: "class ConcreteSubclass:", in: interface), "\(interface)") + #expect(subclass.contains("@objc override var description: Swift.String"), "\(subclass)") + #expect(subclass.contains("@objc func concretePoke()"), "\(subclass)") + } + + /// The table itself, asked by the Swift qualified name the way every + /// consumer asks: a generic class answers under its name with its + /// generic parameters, the one its template's null name leaves to us. + @Test func memberTableOfAGenericClassIsFoundByItsQualifiedName() throws { + let machOFile = try ClassesWithoutClassObjectsFixture.machOFile(.full) + let table = try #require(ObjCMembers.table(forSwiftClassQualifiedName: "\(Self.moduleName).GenericWidget", in: machOFile)) + #expect(table.hierarchy.className == "\(Self.moduleName).GenericWidget") + } +} diff --git a/Tests/SwiftInterfaceTests/CommentConstructionScanTests.swift b/Tests/SwiftInterfaceTests/CommentConstructionScanTests.swift new file mode 100644 index 000000000..fdc2d4d37 --- /dev/null +++ b/Tests/SwiftInterfaceTests/CommentConstructionScanTests.swift @@ -0,0 +1,93 @@ +import Foundation +import Testing + +/// Every comment the interface prints is built as a `StructuredComment` +/// (evolution proposal `comment-structure`), never as a bare `Comment`, +/// `InlineComment`, `MultipleLineComment` or `.comment` atom. +/// +/// The structured form is what lets a print mark each comment's kind and +/// segments; a comment built any other way prints fine and silently carries +/// no structure, which nothing else would notice until a host drew it as an +/// untagged line. The evolution renderer's own annotations +/// (`EvolutionMarking.swift`) are outside the proposal and stay as they are. +@Suite +struct CommentConstructionScanTests { + @Test("the interface modules build every comment as a StructuredComment") + func interfaceModulesBuildStructuredComments() throws { + var offendingLines: [String] = [] + for fileURL in try Self.scannedSourceFiles() { + 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.buildsABareComment(code) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect( + offendingLines.isEmpty, + """ + build the comment with a `StructuredComment` factory, so a print marking comment structure can \ + tell its kind and segments: + \(offendingLines.joined(separator: "\n")) + """ + ) + } + + /// The scan must be able to see a bare comment, and must not invent one — + /// its silence proves nothing otherwise. + @Test("the scan sees a bare comment and nothing else") + func theScanDiscriminates() { + #expect(Self.buildsABareComment(#"Comment("not exported")"#)) + #expect(Self.buildsABareComment(#"InlineComment("Enum Layout")"#)) + #expect(Self.buildsABareComment(#"MultipleLineComment(text)"#)) + #expect(Self.buildsABareComment(#"AtomicComponent(string: block, type: .comment)"#)) + #expect(Self.buildsABareComment(#"result.append(line, type: .comment)"#)) + + #expect(!Self.buildsABareComment(#"StructuredComment.note("not exported")"#)) + #expect(!Self.buildsABareComment(#"OffsetComment(prefix: offsetCommentPrefix, offset: function.offset, emit: true)"#)) + #expect(!Self.buildsABareComment(#"ExportStatusComment(isExported: verdict)"#)) + #expect(!Self.buildsABareComment(#"if atom.type == .comment {"#)) + } + + private static let bareCommentExpression = try! NSRegularExpression( + pattern: #"\b(Comment|InlineComment|MultipleLineComment)\(|\btype:\s*\.comment\b"# + ) + + private static func buildsABareComment(_ code: String) -> Bool { + bareCommentExpression.firstMatch(in: code, range: NSRange(code.startIndex..., in: code)) != nil + } + + /// The modules whose comments the interface prints. + private static let scannedModuleDirectories = [ + "Output/SwiftDeclarationRendering", + "Output/SwiftPrinting", + "Output/SwiftInterface", + "Declaration/SwiftDeclaration", + ] + + /// Renderers of their own, outside the proposal. + private static let unscannedFileNames: Set = ["EvolutionMarking.swift"] + + /// `StructuredComment` itself: the one place a comment's atoms are made. + private static func isStructuredCommentSource(_ fileURL: URL) -> Bool { + fileURL.lastPathComponent.hasPrefix("StructuredComment") + } + + private static func scannedSourceFiles() throws -> [URL] { + let sourcesDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // SwiftInterfaceTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + .appendingPathComponent("Sources") + var files: [URL] = [] + for moduleDirectory in scannedModuleDirectories { + let directory = sourcesDirectory.appendingPathComponent(moduleDirectory) + let enumerator = try #require(FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil)) + for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" && !unscannedFileNames.contains(fileURL.lastPathComponent) && !isStructuredCommentSource(fileURL) { + files.append(fileURL) + } + } + #expect(files.count > 100, "the scan found \(files.count) files; a moved module would leave it scanning nothing") + return files + } +} diff --git a/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift new file mode 100644 index 000000000..2f3ec831a --- /dev/null +++ b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift @@ -0,0 +1,274 @@ +@_spi(Support) @testable import SwiftDeclaration +@_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 +import Semantic +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// With `SwiftDeclarationPrintConfiguration.marksCommentStructure`, every +/// definition of the SymbolTestsCore fixture separates to exactly its print +/// without the marks — text, spans, identifiers — and every comment in it +/// lies in an annotation region (evolution proposal `comment-structure`). +/// Checked in process and from the file: with every comment option on, with +/// the `Transformer` templates installed, marking optional content as well, +/// and with the source files of private declarations. +/// +/// A comment built without `StructuredComment`, or printed without asking +/// whether to mark it, shows up here as a comment in no region; a marked +/// rendering that spells a comment differently from the plain one shows up +/// as a separated print that differs. +@Suite(.serialized) +final class CommentStructureContractTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + enum Variant: CaseIterable, Sendable, CustomStringConvertible { + case everyComment + case everyCommentWithTransformers + case markedOptionalContent + case privateDeclarationSourceFiles + + var description: String { + switch self { + case .everyComment: "every comment" + case .everyCommentWithTransformers: "every comment with transformers" + case .markedOptionalContent: "marked optional content" + case .privateDeclarationSourceFiles: "private declaration source files" + } + } + + func configuration(marksCommentStructure: Bool) -> SwiftDeclarationPrintConfiguration { + var configuration = CommentStructureContractTests.everyCommentConfiguration + configuration.marksCommentStructure = marksCommentStructure + switch self { + case .everyComment, .privateDeclarationSourceFiles: + break + case .everyCommentWithTransformers: + var transformers = Transformer.SwiftConfiguration() + transformers.swiftFieldOffset.isEnabled = true + transformers.swiftVTableOffset.isEnabled = true + transformers.swiftMemberAddress.isEnabled = true + transformers.swiftTypeLayout.isEnabled = true + transformers.swiftEnumLayout.isEnabled = true + configuration.applyTransformers(transformers) + case .markedOptionalContent: + configuration.marksOptionalContent = true + } + return configuration + } + } + + /// Every option that prints a comment. + nonisolated static var everyCommentConfiguration: SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.printFieldOffset = true + configuration.printExpandedFieldOffsets = true + configuration.printMemberAddress = true + configuration.printVTableOffset = true + configuration.printPWTOffset = true + configuration.printTypeLayout = true + configuration.printEnumLayout = true + configuration.printExportStatus = true + return configuration + } + + 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 + } + } + + /// A printer for `variant`, set up as a host printing one declaration at + /// a time sets one up. + private static func printer( + for variant: Variant, + marksCommentStructure: Bool, + indexer: SwiftDeclarationIndexer, + sourceFileIndex: PrivateDiscriminatorSourceFileIndex?, + in machO: MachO + ) -> SwiftDeclarationPrinter where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let printer = SwiftDeclarationPrinter(configuration: variant.configuration(marksCommentStructure: marksCommentStructure), in: machO) + printer.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + if let sourceFileIndex { + printer.setPrivateDeclarationSourceFileProvider(sourceFileIndex) + } + if variant == .markedOptionalContent { + printer.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + } + return printer + } + + /// Prints every root type, every protocol and every extension of the + /// image marked and plain, and describes the first few that break the + /// contract. + private static func violations( + in machO: MachO, + variant: Variant + ) async throws -> (regionCount: Int, violations: [String]) where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + var sourceFileIndex: PrivateDiscriminatorSourceFileIndex? + if variant == .privateDeclarationSourceFiles { + let index = try #require(Self.privateDeclarationSourceFileIndex(of: indexer)) + index.recoverSourceFiles(ofEveryDeclarationIn: indexer) + sourceFileIndex = index + } + let markedPrinter = Self.printer(for: variant, marksCommentStructure: true, indexer: indexer, sourceFileIndex: sourceFileIndex, in: machO) + let plainPrinter = Self.printer(for: variant, marksCommentStructure: false, indexer: indexer, sourceFileIndex: sourceFileIndex, in: machO) + + typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString + var printings: [(label: String, print: Printing)] = [] + for (name, typeDefinition) in indexer.rootTypeDefinitions { + printings.append(("type \(name.name)", { try await $0.printTypeDefinition(typeDefinition) })) + } + for (name, protocolDefinition) in indexer.allProtocolDefinitions { + printings.append(("protocol \(name.name)", { try await $0.printProtocolDefinition(protocolDefinition) })) + } + let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] + for extensionGroup in extensionGroups { + for (name, extensionDefinitions) in extensionGroup { + for extensionDefinition in extensionDefinitions { + printings.append(("extension \(name.name)", { try await $0.printExtensionDefinition(extensionDefinition) })) + } + } + } + + var regionCount = 0 + var violations: [String] = [] + for printing in printings { + let marked = try await printing.print(markedPrinter).frozen() + let plain = try await printing.print(plainPrinter).frozen() + if let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) { + violations.append("\(printing.label): \(violation)") + if violations.count >= 5 { break } + } + regionCount += marked.separatingAnnotationRegions().annotations.regions.count + } + return (regionCount, violations) + } + + @Test(arguments: Variant.allCases) + func inProcessPrintsSeparateToTheirPlainPrints(variant: Variant) async throws { + let result = try await Self.violations(in: machOImage, variant: variant) + #expect(result.regionCount > 1000) + #expect(result.violations.isEmpty, "\(result.violations.joined(separator: "\n\n"))") + } + + @Test(arguments: Variant.allCases) + func filePrintsSeparateToTheirPlainPrints(variant: Variant) async throws { + let result = try await Self.violations(in: machOFile, variant: variant) + #expect(result.regionCount > 1000) + #expect(result.violations.isEmpty, "\(result.violations.joined(separator: "\n\n"))") + } + + /// The whole interface: the header, the globals, every block. + @Test func theWholeInterfaceSeparatesToItsPlainPrint() async throws { + func interface(marksCommentStructure: Bool) async throws -> FrozenSemanticString { + var printConfiguration = Self.everyCommentConfiguration + printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder( + configuration: SwiftInterfaceBuilderConfiguration( + indexConfiguration: .init(showCImportedTypes: false), + printConfiguration: printConfiguration, + interfaceHeaderInfo: InterfaceHeaderInfo( + generatorName: "swift-section", + generatorVersion: "test", + imagePath: "/SymbolTestsCore", + cpuDescription: "arm64", + fileTypeDescription: "dylib", + dispatchThunkCount: 3 + ) + ), + eventHandlers: [], + in: machOFile + ) + try await builder.prepare() + return try await builder.printRoot().frozen() + } + let marked = try await interface(marksCommentStructure: true) + let plain = try await interface(marksCommentStructure: false) + #expect(marked.separatingAnnotationRegions().annotations.regions(ofKind: .note).count >= 5, "the header's lines are notes") + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") + } + + /// Marking optional content as well, a projection separates to the + /// regions of printing with the projected configuration: the regions + /// follow what the projection keeps — a field offset whose tree is + /// projected away is a region of its one line. + @Test func projectionsSeparateToThePrintsOfTheirConfigurations() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + var markedConfiguration = SwiftDeclarationPrintConfiguration() + markedConfiguration.marksOptionalContent = true + markedConfiguration.marksCommentStructure = true + markedConfiguration.printExportStatus = true + let markedPrinter = SwiftDeclarationPrinter(configuration: markedConfiguration, in: machOFile) + markedPrinter.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + markedPrinter.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + + func projectedConfiguration(_ configure: (inout SwiftDeclarationPrintConfiguration) -> Void) -> SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configure(&configuration) + configuration.marksCommentStructure = true + configuration.printExportStatus = true + return configuration + } + let projectedConfigurations = [ + projectedConfiguration { $0 = Self.everyCommentConfiguration }, + // A field offset whose tree the projection leaves out. + projectedConfiguration { $0.printFieldOffset = true; $0.printTypeLayout = true }, + projectedConfiguration { $0.printEnumLayout = true }, + projectedConfiguration { _ in }, + ] + let projectedPrinters = projectedConfigurations.map { configuration in + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + printer.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + return printer + } + + var checkedCount = 0 + var mismatches: [String] = [] + for (name, typeDefinition) in indexer.rootTypeDefinitions { + let separatedVisibility = try await markedPrinter.printTypeDefinition(typeDefinition).frozen().separatingVisibilityRegions() + for (configuration, printer) in zip(projectedConfigurations, projectedPrinters) { + let projected = separatedVisibility.regions.projection(of: separatedVisibility.text) { + configuration.isVisibilityOptionEnabled($0, resolvesOpaqueTypes: true) + }.text.separatingAnnotationRegions() + let ownPrint = try await printer.printTypeDefinition(typeDefinition).frozen().separatingAnnotationRegions() + checkedCount += 1 + if projected.text != ownPrint.text { + mismatches.append("type \(name.name): \(CommentStructureContract.firstDifference(between: projected.text, and: ownPrint.text))") + } else if projected.annotations != ownPrint.annotations { + mismatches.append("type \(name.name): the annotation regions differ") + } + } + if mismatches.count >= 5 { break } + } + #expect(checkedCount > 100) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n\n"))") + } + + @Test func plainPrintsCarryNoAnnotations() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + let printer = SwiftDeclarationPrinter(configuration: Self.everyCommentConfiguration, in: machOFile) + var checkedCount = 0 + for typeDefinition in indexer.rootTypeDefinitions.values { + let plain = try await printer.printTypeDefinition(typeDefinition).frozen() + #expect(plain.separatingAnnotationRegions().annotations.isEmpty) + checkedCount += 1 + } + #expect(checkedCount > 50) + } +} diff --git a/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift new file mode 100644 index 000000000..f1aa7af6b --- /dev/null +++ b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift @@ -0,0 +1,180 @@ +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +import SwiftDeclarationRendering +import Semantic +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// The shapes RuntimeViewer draws its comment tags and folds from (evolution +/// proposal `comment-structure`), read from the table a marked print of the +/// SymbolTestsCore fixture separates to: a field offset and the tree under +/// it, an enum's layout summary and one case's block, a tuple's type layout, +/// and the segments of the one-line comments. +@Suite(.serialized) +final class CommentStructureShapeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + /// A marked print, separated. + private struct SeparatedPrint { + let utf8: [UInt8] + let annotations: AnnotationRegionTable + + init(_ printed: SemanticString) { + let separated = printed.frozen().separatingAnnotationRegions() + utf8 = Array(separated.text.string.utf8) + annotations = separated.annotations + } + + func text(ofRegionAt regionIndex: Int) -> String { + let region = annotations.regions[regionIndex] + return text(utf8Offset: region.utf8Offset, utf8Length: region.utf8Length) + } + + /// The role and text of the segments directly in the region — not in + /// a region nested in it. + func segments(ofRegionAt regionIndex: Int) -> [(role: String, text: String)] { + annotations.segments(inRegionAt: regionIndex).map { ($0.role.rawValue, text(utf8Offset: $0.utf8Offset, utf8Length: $0.utf8Length)) } + } + + func childRegionIndices(of regionIndex: Int) -> [Int] { + annotations.regions.indices.filter { annotations.regions[$0].enclosingRegionIndex == regionIndex } + } + + func regionIndices(ofKind kind: AnnotationRegion.Kind) -> [Int] { + annotations.regions.indices.filter { annotations.regions[$0].kind == kind } + } + + /// The text of the region's first segment of `role`. + func firstSegmentText(ofRegionAt regionIndex: Int, role: AnnotationSegment.Role) -> String? { + segments(ofRegionAt: regionIndex).first { $0.role == role.rawValue }?.text + } + + private func text(utf8Offset: UInt32, utf8Length: UInt32) -> String { + let start = Int(utf8Offset) + return String(decoding: utf8[start ..< start + Int(utf8Length)], as: UTF8.self) + } + } + + private static func markedPrint(ofTypeNamed name: String, in machO: MachO) async throws -> SeparatedPrint where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + let typeDefinition = try #require(indexer.allTypeDefinitions.first { $0.key.name == name }?.value, "no type \(name)") + var configuration = CommentStructureContractTests.everyCommentConfiguration + configuration.marksCommentStructure = true + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machO) + return SeparatedPrint(try await printer.printTypeDefinition(typeDefinition)) + } + + /// The tree of `characterField: Character` — `_str` holds `_guts`, + /// which holds `_object`, which holds the two words of a string — is the + /// nesting of its regions, every node's region ending at its last row. + @Test(arguments: [false, true]) + func aFieldOffsetHoldsItsTreeAsNestedRegions(inProcess: Bool) async throws { + let printed = inProcess + ? try await Self.markedPrint(ofTypeNamed: "SymbolTestsCore.BuiltinTypeFields.PrimitiveTypesTest", in: machOImage) + : try await Self.markedPrint(ofTypeNamed: "SymbolTestsCore.BuiltinTypeFields.PrimitiveTypesTest", in: machOFile) + let rootIndex = try #require(printed.regionIndices(ofKind: .fieldOffset).first { printed.text(ofRegionAt: $0).hasPrefix("// Field offset: 0x8\n") }) + #expect(printed.segments(ofRegionAt: rootIndex).map(\.role) == ["marker", "label", "separator", "value"]) + + func nodeName(_ regionIndex: Int) -> String? { + printed.firstSegmentText(ofRegionAt: regionIndex, role: .name) + } + func childNames(_ regionIndex: Int) -> [String?] { + printed.childRegionIndices(of: regionIndex).map(nodeName) + } + let stringIndex = try #require(printed.childRegionIndices(of: rootIndex).first) + #expect(childNames(rootIndex) == ["_str"]) + let gutsIndex = try #require(printed.childRegionIndices(of: stringIndex).first) + #expect(childNames(stringIndex) == ["_guts"]) + let objectIndex = try #require(printed.childRegionIndices(of: gutsIndex).first) + #expect(childNames(gutsIndex) == ["_object"]) + #expect(childNames(objectIndex) == ["_countAndFlagsBits", "_object"]) + let countAndFlagsIndex = try #require(printed.childRegionIndices(of: objectIndex).first) + #expect(childNames(countAndFlagsIndex) == ["_value"]) + #expect(printed.annotations.regions[countAndFlagsIndex].depth == printed.annotations.regions[rootIndex].depth + 4) + + #expect(printed.childRegionIndices(of: rootIndex).allSatisfy { printed.annotations.regions[$0].kind == .fieldLayoutNode }) + #expect(printed.segments(ofRegionAt: countAndFlagsIndex).map(\.role) == ["marker", "treePrefix", "name", "separator", "type", "separator", "value"]) + #expect(printed.firstSegmentText(ofRegionAt: countAndFlagsIndex, role: .type) == "Swift.UInt64") + // A region ends at its last row, not at the line break after it. + #expect(printed.text(ofRegionAt: rootIndex).hasSuffix("_object (Builtin.BridgeObject): 0x10")) + #expect(printed.text(ofRegionAt: objectIndex).hasSuffix("_object (Builtin.BridgeObject): 0x10")) + } + + /// `empty`, `withValue(Int)` and `withPair(left:right:)`: tag bytes after + /// the payload area, a summary of five facts, and for each case a block + /// of one region per line. + @Test func anEnumLayoutIsASummaryAndOneBlockPerCase() async throws { + let printed = try await Self.markedPrint(ofTypeNamed: "SymbolTestsCore.CodableTests.CodableEnumTest", in: machOFile) + let summaryIndex = try #require(printed.regionIndices(ofKind: .enumLayoutSummary).first) + #expect(printed.firstSegmentText(ofRegionAt: summaryIndex, role: .label) == "Tagged Multi-Payload (tag bytes after the payload area)") + #expect(printed.segments(ofRegionAt: summaryIndex).filter { $0.role == "key" }.map(\.text) == [ + "cases", "tag values used", "tag bits", "tag region", "leftover extra inhabitants for an outer enum", + ]) + + let caseIndices = printed.regionIndices(ofKind: .enumLayoutCase) + try #require(caseIndices.count == 3) + #expect(caseIndices.allSatisfy { printed.text(ofRegionAt: $0).hasPrefix("/* Enum Layout */\n") }) + + let withPairIndex = caseIndices[1] + let lineIndices = printed.childRegionIndices(of: withPairIndex) + #expect(lineIndices.map { printed.annotations.regions[$0].kind } == [.enumLayoutCaseHeader, .enumLayoutCaseEncoding, .enumLayoutCaseFixedBytes, .enumLayoutCaseByte]) + let headerSegments = printed.segments(ofRegionAt: lineIndices[0]) + #expect(headerSegments.map(\.role) == ["marker", "label", "separator", "value", "separator", "value", "separator", "name", "separator", "key", "separator", "value"]) + #expect(headerSegments.map(\.text) == ["// ", "Case", " ", "1", " (", "0x01", ") `", "withPair", "` — ", "payload case", " #", "1"]) + let byteSegments = printed.segments(ofRegionAt: lineIndices[3]) + #expect(byteSegments.map(\.text) == ["// ", "offset", " ", "0x18", " = ", "0x01", " (", "0b00000001", ")"]) + #expect(byteSegments.map(\.role) == ["marker", "label", "separator", "key", "separator", "value", "separator", "value", "separator"]) + // The block ends at the last byte line, not at the line break after it. + #expect(printed.text(ofRegionAt: withPairIndex).hasSuffix("offset 0x18 = 0x01 (0b00000001)")) + + let emptyIndex = caseIndices[2] + #expect(printed.childRegionIndices(of: emptyIndex).count > 4, "the empty case fixes every byte of the payload area") + } + + /// In process, a tuple field's layout is a block: one region over all of + /// it, a region for each element. + @Test func aTupleTypeLayoutIsOneRegionWithARegionPerElement() async throws { + let printed = try await Self.markedPrint(ofTypeNamed: "SymbolTestsCore.BuiltinTypeFields.TupleBuiltinTest", in: machOImage) + let blockIndex = try #require(printed.regionIndices(ofKind: .typeLayout).first { printed.text(ofRegionAt: $0).hasPrefix("/* Type Layout */\n") }) + let elementIndices = printed.childRegionIndices(of: blockIndex) + #expect(elementIndices.count == 2) + #expect(elementIndices.allSatisfy { printed.annotations.regions[$0].kind == .typeLayoutElement }) + #expect(printed.firstSegmentText(ofRegionAt: elementIndices[0], role: .type) == "Swift.Int") + #expect(printed.text(ofRegionAt: blockIndex).hasSuffix("extraInhabitantCount: 0)")) + } + + @Test func anOffsetThatCouldNotBeComputedSaysWhy() async throws { + let printed = try await Self.markedPrint(ofTypeNamed: "SymbolTestsCore.AccessorFunctionReferences.NoncopyableGenericBoxTest", in: machOFile) + let unknownIndex = try #require(printed.regionIndices(ofKind: .fieldOffsetUnknown).first) + #expect(printed.segments(ofRegionAt: unknownIndex).map(\.text) == ["// ", "Field offset", ": ", "unknown", " (", "generic parameter not substituted", ")"]) + #expect(printed.segments(ofRegionAt: unknownIndex).map(\.role) == ["marker", "label", "separator", "value", "separator", "text", "separator"]) + } + + /// An accessor's address and vtable slot name the accessor as a + /// qualifier. + @Test func anAccessorsAddressAndSlotNameTheAccessor() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + var configuration = CommentStructureContractTests.everyCommentConfiguration + configuration.marksCommentStructure = true + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + var addressSegments: [(role: String, text: String)]? + var slotSegments: [(role: String, text: String)]? + for typeDefinition in indexer.rootTypeDefinitions.values where addressSegments == nil || slotSegments == nil { + let printed = SeparatedPrint(try await printer.printTypeDefinition(typeDefinition)) + addressSegments = addressSegments ?? printed.regionIndices(ofKind: .memberAddress).lazy.map { printed.segments(ofRegionAt: $0) }.first { $0.contains { $0.role == "qualifier" && $0.text == "getter" } } + slotSegments = slotSegments ?? printed.regionIndices(ofKind: .vtableOffset).lazy.map { printed.segments(ofRegionAt: $0) }.first { $0.contains { $0.role == "qualifier" && $0.text == "setter" } } + } + let address = try #require(addressSegments) + #expect(address.map(\.role) == ["marker", "label", "separator", "qualifier", "separator", "value"]) + #expect(address.map(\.text).prefix(5) == ["// ", "Address", " (", "getter", "): "]) + let slot = try #require(slotSegments) + #expect(slot.map(\.role) == ["marker", "label", "separator", "qualifier", "separator", "value"]) + #expect(slot.map(\.text).prefix(5) == ["// ", "VTable offset", " (", "setter", "): "]) + } +} diff --git a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift new file mode 100644 index 000000000..67bdce374 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift @@ -0,0 +1,147 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDeclarationRendering +import SwiftPrinting +import SwiftInterface +// Scoped: the module's `Error` component would shadow `Swift.Error` here. +import struct Semantic.SemanticString +import struct Semantic.FrozenSemanticString +import struct Semantic.AnnotationRegionTable +import struct Semantic.AnnotationRegion +import struct Semantic.AnnotationSegment +import SwiftSectionTestingSupport + +/// The comment above an availability-conditional witness (SE-0360) — the +/// associated type's line and one line per branch — marked as one +/// `conditionalWitness` region holding a `conditionalWitnessBranch` for each +/// branch (evolution proposal `comment-structure`). SymbolTestsCore keeps no +/// such witness: a conformance whose underlying type the compiler can see is +/// written into the witness record, so the fixture here is built for it. +@Suite +struct ConditionalWitnessCommentStructureTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "conditional-witness fixture compilation failed:\n\(diagnostics)" } + } + + private static let moduleName = "CommentStructureConditionalWitnessFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + /// + /// Each branch returns a type whose metadata the thunk has to call for, + /// so the thunk branches on the availability check. Two types it can load + /// directly (`1` and `"one"`) compile to a `csel` between two metadata + /// addresses, which the thunk reader does not evaluate: the witness then + /// prints as `accessor function at …` with no comment. + private static let fixtureSource = """ + public final class FixtureAnchor {} + + public protocol Shape { + associatedtype Body + var body: Body { get } + } + + public struct ConditionalConcrete: Shape { + public init() {} + public var body: some Equatable { + if #available(macOS 26, *) { + return [1] + } else { + return ["one": 1] + } + } + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-swift-version", "5", "-O", "-emit-library", + "-module-name", moduleName, + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func printInterface(marksCommentStructure: Bool) async throws -> FrozenSemanticString { + let libraryURL = try Self.fixtureCompilationResult.get() + let machOFile: MachOFile + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let file): + machOFile = file + case .fat(let fatFile): + machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) + // The witness is an opaque type: read through its accessor thunk. + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + try await builder.prepare() + return try await builder.printRoot().frozen() + } + + @Test func aConditionalWitnessIsOneRegionWithARegionPerBranch() async throws { + let marked = try await printInterface(marksCommentStructure: true) + let plain = try await printInterface(marksCommentStructure: false) + try #require(plain.string.contains("is picked at run time by an availability check (SE-0360):"), "no conditional witness in:\n\(plain.string)") + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") + + let (separatedText, annotations) = marked.separatingAnnotationRegions() + let utf8 = Array(separatedText.string.utf8) + func substring(utf8Offset: UInt32, utf8Length: UInt32) -> String { + String(decoding: utf8[Int(utf8Offset) ..< Int(utf8Offset) + Int(utf8Length)], as: UTF8.self) + } + let witnessIndex = try #require(annotations.regions.firstIndex { $0.kind == .conditionalWitness }) + let witnessSegments: [(role: String, text: String)] = annotations.segments(inRegionAt: witnessIndex).map { ($0.role.rawValue, substring(utf8Offset: $0.utf8Offset, utf8Length: $0.utf8Length)) } + #expect(witnessSegments.map(\.role) == ["marker", "name", "separator", "text", "separator"]) + #expect(witnessSegments.first { $0.role == "name" }?.text == "Body") + + let branchIndices = annotations.regions.indices.filter { annotations.regions[$0].enclosingRegionIndex == witnessIndex } + #expect(branchIndices.map { annotations.regions[$0].kind } == [.conditionalWitnessBranch, .conditionalWitnessBranch]) + func branchSegmentText(at branchIndex: Int, role: AnnotationSegment.Role) -> String? { + annotations.segments(inRegionAt: branchIndex).first { $0.role == role }.map { substring(utf8Offset: $0.utf8Offset, utf8Length: $0.utf8Length) } + } + #expect(branchIndices.map { branchSegmentText(at: $0, role: .qualifier) } == ["macOS 26.0 or later", "before macOS 26.0"]) + #expect(branchIndices.map { branchSegmentText(at: $0, role: .type) } == ["[Swift.Int]", "[Swift.String : Swift.Int]"]) + } +} diff --git a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift index 9a9e3bca9..c1ae60d22 100644 --- a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift +++ b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift @@ -7,8 +7,8 @@ import Semantic @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The protocol a conformance extension names is a type reference like any /// other, so its name must carry the semantic type the rest of the interface diff --git a/Tests/SwiftInterfaceTests/ConstrainedExistentialFieldTests.swift b/Tests/SwiftInterfaceTests/ConstrainedExistentialFieldTests.swift new file mode 100644 index 000000000..7bfc51db1 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ConstrainedExistentialFieldTests.swift @@ -0,0 +1,42 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +import SwiftDiffing +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +@testable import SwiftInterface + +/// A stored property of a constrained existential type (`any Boxed`) +/// reaches the field record as a symbolic reference to an extended existential +/// type shape — `any Boxed<τ_0_0>` — plus the arguments that instantiate it, +/// `[Swift.Int]`. The interface printed the arguments alone, so the property +/// read `var boxed: Swift.Int`: a real, wrong type. The ABI snapshot recorded +/// the symbolic form, which printed every such field of `Swift.Int` the same, +/// whatever its protocol (evolution proposal `existential-any`). +@Suite +final class ConstrainedExistentialFieldTests: MachOFileTests, SnapshotInterfaceTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + private static let holderName = "SymbolTestsCore.GenericFieldLayout.ConstrainedExistentialFieldHolder" + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func interfacePrintsTheConstrainedExistentialOfAStoredProperty() async throws { + let interface = try await collectInterfaceString(in: machOFile) + #expect(interface.contains("var boxed: any SymbolTestsCore.GenericFieldLayout.Boxed\n")) + #expect(interface.contains("var optionalBoxed: (any SymbolTestsCore.GenericFieldLayout.Boxed)?\n")) + } + + @Test func abiSnapshotRecordsTheProtocolOfAConstrainedExistentialField() async throws { + let builder = SwiftDiffableInterfaceBuilder(in: machOFile) + try await builder.prepare() + let snapshot = builder.snapshot() + let holder = try #require(snapshot.types.first { $0.name == Self.holderName }) + let boxed = try #require(holder.members.first { $0.kind == .field && $0.signature.hasPrefix("boxed: ") }) + let optionalBoxed = try #require(holder.members.first { $0.kind == .field && $0.signature.hasPrefix("optionalBoxed: ") }) + #expect(boxed.signature.contains("SymbolTestsCore.GenericFieldLayout.Boxed<"), "\(boxed.signature)") + #expect(boxed.signature.contains("Swift.Int"), "\(boxed.signature)") + #expect(optionalBoxed.signature.contains("SymbolTestsCore.GenericFieldLayout.Boxed<"), "\(optionalBoxed.signature)") + #expect(optionalBoxed.signature.contains("Swift.String"), "\(optionalBoxed.signature)") + } +} diff --git a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift index bb238bbf4..a6c17d13d 100644 --- a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift @@ -8,7 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface import SwiftThunkAnalysis @_spi(Internals) import SwiftInspection -@testable import MachOTestingSupport +@_spi(Internals) import SwiftObjCInterop +@testable import SwiftSectionTestingSupport /// Classes a source renamed for the Objective-C runtime on the interface /// path (evolution proposal `objc-custom-class-name`): the attribute the diff --git a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift index b9fc55ae4..80124f918 100644 --- a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift +++ b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift @@ -5,7 +5,7 @@ import MachOFoundation import MachOSwiftSection import SwiftDeclarationRendering import SwiftInterface -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// An on-the-fly fixture for class members whose only symbol is their method /// descriptor, compiled twice over: `.full` keeps every symbol, and diff --git a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift index 593bdf33c..9bd4e2627 100644 --- a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift +++ b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift @@ -6,10 +6,10 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The diff renderer's header contract: a declaration whose HEADER cannot be /// rendered must be dropped whole, never rendered as a body under a blank diff --git a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift index 4ee532e95..e1fa7a2cc 100644 --- a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift +++ b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift @@ -74,6 +74,151 @@ struct EvolutionMarkingTests { ) } + // MARK: - Versions that cannot show a declaration + + // Evolution proposal `evolution-unobservable-presence`: a version whose + // image carries no local Swift symbols cannot show a non-exported member. + + @Test func bitmapDrawsTheVersionsThatCouldNotShowTheDeclaration() { + let annotation = EvolutionAnnotation( + presence: [true, true, false], + events: [], + presenceStates: [.present, .inferredPresent, .unobservable] + ) + #expect(EvolutionMarking.bitmap(for: annotation) == "[●◍◌]") + } + + @Test func changeAcrossSuchVersionsIsPlacedBetweenTheVersionsThatSawIt() { + let removed = LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1) + let added = LineageEvent(versionIndex: 2, status: .added, earliestVersionIndex: 1) + let modified = LineageEvent(versionIndex: 2, status: .modified, oldSignature: "var x: Swift.Int", newSignature: "let x: Swift.Int", earliestVersionIndex: 1) + #expect(EvolutionMarking.phrase(for: removed, versions: versionAxis) == "removed between 1.0 and 3.0") + #expect(EvolutionMarking.phrase(for: added, versions: versionAxis) == "added between 1.0 and 3.0") + #expect(EvolutionMarking.phrase(for: modified, versions: versionAxis) == "modified between 1.0 and 3.0: var x: Swift.Int → let x: Swift.Int") + } + + @Test func inferredPresenceIsPhrasedWithItsVersions() { + let annotation = EvolutionAnnotation( + presence: [true, true, true], + events: [], + presenceStates: [.present, .inferredPresent, .present] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: versionAxis) == "// [●◍●] inferred present in 2.0") + } + + /// The versions an event spans are phrased by the event alone; others + /// say they could not show the declaration. + @Test func unobservableVersionsArePhrasedOnlyWhereNoEventSpansThem() { + let trailing = EvolutionAnnotation(presence: [true, false, false], events: [], presenceStates: [.present, .unobservable, .unobservable]) + #expect(EvolutionMarking.annotationText(for: trailing, versions: versionAxis) == "// [●◌◌] not observable in 2.0–3.0") + let spanned = EvolutionAnnotation( + presence: [true, false, false], + events: [LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1)], + presenceStates: [.present, .unobservable, .absent] + ) + #expect(EvolutionMarking.annotationText(for: spanned, versions: versionAxis) == "// [●◌○] removed between 1.0 and 3.0") + } + + /// Between two absences the versions only infer absence: the `◌`s say + /// enough, and the bounds stay observed. + @Test func unobservableVersionsBetweenTwoAbsencesAddNoPhraseAndKeepTheAttribute() { + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + let removedEarlier = EvolutionAnnotation( + presence: [true, false, false, false], + events: [LineageEvent(versionIndex: 1, status: .removed)], + presenceStates: [.present, .absent, .unobservable, .absent] + ) + #expect(EvolutionMarking.annotationText(for: removedEarlier, versions: fourVersionAxis) == "// [●○◌○] removed in 2.0") + #expect(EvolutionMarking.availabilityAttributeText(for: removedEarlier, versions: fourVersionAxis, platform: "macOS") == "@available(macOS, obsoleted: 2.0)") + } + + @Test func phrasesFollowAxisOrder() { + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + let annotation = EvolutionAnnotation( + presence: [false, true, true, true], + events: [LineageEvent(versionIndex: 1, status: .added)], + presenceStates: [.absent, .present, .inferredPresent, .present] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: fourVersionAxis) == "// [○●◍●] added in 2.0 · inferred present in 3.0") + } + + /// A move between the images of a group (evolution proposal + /// `image-group-evolution`) phrases with the images of both sides, a + /// group of them joined by ` + `, in axis order with the other phrases. + @Test func moveBetweenImagesPhrasesWithItsImages() { + let annotation = EvolutionAnnotation( + presence: [false, true, true], + events: [LineageEvent(versionIndex: 1, status: .added)], + imageMoves: [ImageMove(versionIndex: 2, oldImageNames: ["SwiftUI"], newImageNames: ["SwiftUI", "SwiftUICore"])] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: versionAxis) == "// [○●●] added in 2.0 · moved in 3.0: SwiftUI → SwiftUI + SwiftUICore") + } + + /// Within one version an event reads before the move: a member that + /// changed while it moved. + @Test func eventsOfAVersionReadBeforeItsMoves() { + let annotation = EvolutionAnnotation( + presence: [true, true, true], + events: [LineageEvent(versionIndex: 2, status: .modified)], + imageMoves: [ImageMove(versionIndex: 2, oldImageNames: ["AppKit"], newImageNames: ["UIFoundation"])] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: versionAxis) == "// [●●●] modified in 3.0 · moved in 3.0: AppKit → UIFoundation") + } + + /// The warnings tail words a collision as the lineage report does: over + /// groups of images, each dropped record names its image. + @Test func warningsNameEachDroppedRecordsImage() throws { + let evolution = ABIEvolution( + versions: [ + ABIVersionDescriptor(label: "1.0", imageNames: ["AppKit"]), + ABIVersionDescriptor(label: "2.0", imageNames: ["AppKit", "UIFoundation"]), + ], + keyCollisionsByVersion: [ + [], + [ABIKeyCollision(key: .mangled("Shared"), containerName: nil, droppedSignatures: ["Shared"], droppedImageNames: ["UIFoundation"])], + ] + ) + let warnings = try #require(EvolutionMarking.warningsLines(for: evolution)).string + #expect(warnings.contains("// 2.0 · dropped: Shared (UIFoundation)"), "\(warnings)") + } + + @Test func legendNamesTheImageGroupBeforeTheAvailabilityNote() { + let evolution = ABIEvolution(versions: [ + ABIVersionDescriptor(label: "1.0", imageNames: ["SwiftUI"]), + ABIVersionDescriptor(label: "2.0", imageNames: ["SwiftUI", "SwiftUICore"]), + ]) + let legend = EvolutionMarking.legendLines(for: evolution, availabilityAnnotationPlatform: "macOS").string + #expect(legend.hasPrefix(""" + // Swift ABI evolution across 2 versions: 1.0 → 2.0 + // Bitmap positions: [1] 1.0 [2] 2.0 + // Image group: + // [●●] SwiftUI + // [○●] SwiftUICore + // @available(macOS, …) + """)) + } + + /// An unknown bound — a version that could not show the declaration and + /// was not inferred present — leaves the lifecycle without an attribute; + /// inferred presence counts as presence. + @Test func availabilityAttributeNeedsKnownBounds() { + let trailing = EvolutionAnnotation(presence: [true, true, false], events: [], presenceStates: [.present, .present, .unobservable]) + #expect(EvolutionMarking.availabilityAttributeText(for: trailing, versions: versionAxis, platform: "macOS") == nil) + let spanned = EvolutionAnnotation( + presence: [true, false, false], + events: [LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1)], + presenceStates: [.present, .unobservable, .absent] + ) + #expect(EvolutionMarking.availabilityAttributeText(for: spanned, versions: versionAxis, platform: "macOS") == nil) + let inferred = EvolutionAnnotation( + presence: [false, true, true, true], + events: [LineageEvent(versionIndex: 1, status: .added)], + presenceStates: [.absent, .present, .inferredPresent, .present] + ) + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + #expect(EvolutionMarking.availabilityAttributeText(for: inferred, versions: fourVersionAxis, platform: "macOS") == "@available(macOS, introduced: 2.0)") + } + // MARK: - Line classification /// A container header's attribute lines precede the declaration, so the @@ -296,6 +441,13 @@ struct EvolutionMarkingTests { #expect(annotatedLegend.contains("// @available(iOS, …) attributes are axis-resolution facts")) } + @Test func legendNamesTheVersionsWithoutLocalSwiftSymbols() { + let evolution = ABIEvolution(versions: versionAxis, versionIndicesWithoutLocalSwiftSymbols: [1]) + let legend = EvolutionMarking.legendLines(for: evolution).string + #expect(legend.contains("\n// 2.0 carries no local Swift symbols, so its non-exported declarations cannot be seen: ◌ not observable, ◍ not observable but present in the versions on both sides (inferred).")) + #expect(!EvolutionMarking.legendLines(for: ABIEvolution(versions: versionAxis)).string.contains("local Swift symbols")) + } + @Test func warningsAreNilWithoutDiagnostics() { #expect(EvolutionMarking.warningsLines(for: ABIEvolution(versions: versionAxis)) == nil) } diff --git a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift index 110c1d473..f9d764739 100644 --- a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift +++ b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift @@ -1,3 +1,4 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing import MachOKit @@ -7,9 +8,9 @@ import Demangling import SwiftDeclarationRendering import SwiftInterface @testable import SwiftDump -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// An on-the-fly fixture compiled twice from one class: as a main executable, /// whose `__TEXT` sits at 0x100000000, and as a dylib, whose `__TEXT` sits at @@ -240,7 +241,7 @@ struct ExecutableImageSymbolOffsetTests { expectedOffsetByName[symbol.name] = Int(try #require(machOFile.fileOffset(of: symbol.address))) } try #require(!expectedOffsetByName.isEmpty, "premise: the fixture carries `_symbolic` symbols") - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) var collectedOffsetByName: [String: Int] = [:] for symbol in collectedSymbols { collectedOffsetByName[symbol.name] = symbol.offset diff --git a/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift new file mode 100644 index 000000000..6c1f7fe20 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift @@ -0,0 +1,218 @@ +import Foundation +import Testing +import MachOKit +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@testable import SwiftSectionTestingSupport + +/// `SwiftDeclarationPrintConfiguration.usesExistentialAny`, on by default, +/// spells existential types with the `any` keyword by the rules the compiler +/// applies when it writes a `.swiftinterface` (evolution proposal +/// `existential-any`): every existential but a lone `Any` or `AnyObject` +/// takes the keyword, an existential metatype always does +/// (`any Any.Type`), the metatype of the existential itself reads +/// `(any P).Type`, and an existential written with the keyword is +/// parenthesized wherever a suffix would bind to its last protocol. +/// +/// The spelling with the option off — the interface before it — is pinned +/// beside each one, so a case also proves the option changes nothing but the +/// keyword and the parentheses it needs. +@Suite(.serialized) +struct ExistentialAnyInterfaceTests { + private func printedInterface(usesExistentialAny: Bool, usesModuleSelectors: Bool = false) async throws -> String { + let machOFile = try ExistentialAnyFixture.machOFile() + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesExistentialAny = usesExistentialAny + printConfiguration.usesModuleSelectors = usesModuleSelectors + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: machOFile) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + try await builder.prepare() + return try await builder.printRoot().string + } + + struct SpellingCase: Sendable, CustomTestStringConvertible { + let summary: String + let bareSpelling: String + let spellingWithKeyword: String + + var testDescription: String { summary } + } + + static let spellingCases: [SpellingCase] = [ + SpellingCase( + summary: "a protocol", + bareSpelling: "var single: ExistentialAnyFixture.Marker\n", + spellingWithKeyword: "var single: any ExistentialAnyFixture.Marker\n" + ), + SpellingCase( + summary: "a composition writes one keyword", + bareSpelling: "var composition: ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker\n", + spellingWithKeyword: "var composition: any ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker\n" + ), + SpellingCase( + summary: "a class-bound composition", + bareSpelling: "var classBound: ExistentialAnyFixture.Marker & Swift.AnyObject\n", + spellingWithKeyword: "var classBound: any ExistentialAnyFixture.Marker & Swift.AnyObject\n" + ), + SpellingCase( + summary: "a superclass-bound composition", + bareSpelling: "var superclassBound: ExistentialAnyFixture.Base & ExistentialAnyFixture.Marker\n", + spellingWithKeyword: "var superclassBound: any ExistentialAnyFixture.Base & ExistentialAnyFixture.Marker\n" + ), + SpellingCase( + summary: "Any stays bare", + bareSpelling: "var anything: Any\n", + spellingWithKeyword: "var anything: Any\n" + ), + SpellingCase( + summary: "AnyObject stays bare", + bareSpelling: "var anyObject: Swift.AnyObject\n", + spellingWithKeyword: "var anyObject: Swift.AnyObject\n" + ), + SpellingCase( + summary: "a protocol with associated types", + bareSpelling: "var collection: Swift.Collection\n", + spellingWithKeyword: "var collection: any Swift.Collection\n" + ), + SpellingCase( + summary: "an optional existential is parenthesized", + bareSpelling: "var optional: ExistentialAnyFixture.Marker?\n", + spellingWithKeyword: "var optional: (any ExistentialAnyFixture.Marker)?\n" + ), + SpellingCase( + summary: "an optional composition", + bareSpelling: "var optionalComposition: (ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker)?\n", + spellingWithKeyword: "var optionalComposition: (any ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker)?\n" + ), + SpellingCase( + summary: "an optional error", + bareSpelling: "var optionalError: Swift.Error?\n", + spellingWithKeyword: "var optionalError: (any Swift.Error)?\n" + ), + SpellingCase( + summary: "an optional of Any stays unparenthesized", + bareSpelling: "var optionalAnything: Any?\n", + spellingWithKeyword: "var optionalAnything: Any?\n" + ), + SpellingCase( + summary: "an existential metatype", + bareSpelling: "var existentialMetatype: ExistentialAnyFixture.Marker.Type\n", + spellingWithKeyword: "var existentialMetatype: any ExistentialAnyFixture.Marker.Type\n" + ), + SpellingCase( + summary: "an existential metatype of a composition parenthesizes it", + bareSpelling: "var compositionMetatype: ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker.Type\n", + spellingWithKeyword: "var compositionMetatype: any (ExistentialAnyFixture.Marker & ExistentialAnyFixture.SecondMarker).Type\n" + ), + SpellingCase( + summary: "the existential metatype of Any gets the keyword", + bareSpelling: "var anythingMetatype: Any.Type\n", + spellingWithKeyword: "var anythingMetatype: any Any.Type\n" + ), + SpellingCase( + summary: "the existential metatype of AnyObject gets the keyword", + bareSpelling: "var anyObjectMetatype: Swift.AnyObject.Type\n", + spellingWithKeyword: "var anyObjectMetatype: any Swift.AnyObject.Type\n" + ), + SpellingCase( + summary: "an optional existential metatype is parenthesized", + bareSpelling: "var optionalExistentialMetatype: ExistentialAnyFixture.Marker.Type?\n", + spellingWithKeyword: "var optionalExistentialMetatype: (any ExistentialAnyFixture.Marker.Type)?\n" + ), + SpellingCase( + summary: "the metatype of an existential", + bareSpelling: "var protocolMetatype: ExistentialAnyFixture.Marker.Protocol\n", + spellingWithKeyword: "var protocolMetatype: (any ExistentialAnyFixture.Marker).Type\n" + ), + SpellingCase( + summary: "a constrained existential keeps its one keyword", + bareSpelling: "var constrained: any ExistentialAnyFixture.Boxed\n", + spellingWithKeyword: "var constrained: any ExistentialAnyFixture.Boxed\n" + ), + SpellingCase( + summary: "an optional constrained existential", + bareSpelling: "var optionalConstrained: (any ExistentialAnyFixture.Boxed)?\n", + spellingWithKeyword: "var optionalConstrained: (any ExistentialAnyFixture.Boxed)?\n" + ), + SpellingCase( + summary: "the existential metatype of a constrained existential writes one keyword", + bareSpelling: "var constrainedMetatype: any ExistentialAnyFixture.Boxed.Type\n", + spellingWithKeyword: "var constrainedMetatype: any ExistentialAnyFixture.Boxed.Type\n" + ), + SpellingCase( + summary: "an optional existential metatype of a constrained existential is parenthesized either way", + bareSpelling: "var optionalConstrainedMetatype: (any ExistentialAnyFixture.Boxed.Type)?\n", + spellingWithKeyword: "var optionalConstrainedMetatype: (any ExistentialAnyFixture.Boxed.Type)?\n" + ), + SpellingCase( + summary: "an array of existentials", + bareSpelling: "var existentialArray: [ExistentialAnyFixture.Marker]\n", + spellingWithKeyword: "var existentialArray: [any ExistentialAnyFixture.Marker]\n" + ), + SpellingCase( + summary: "a closure taking and returning existentials", + bareSpelling: "var existentialFunction: (_: ExistentialAnyFixture.Marker) -> ExistentialAnyFixture.SecondMarker\n", + spellingWithKeyword: "var existentialFunction: (_: any ExistentialAnyFixture.Marker) -> any ExistentialAnyFixture.SecondMarker\n" + ), + SpellingCase( + summary: "a parameter and a variadic parameter", + bareSpelling: "func accept(_: ExistentialAnyFixture.Marker, _: ExistentialAnyFixture.Marker...)\n", + spellingWithKeyword: "func accept(_: any ExistentialAnyFixture.Marker, _: any ExistentialAnyFixture.Marker...)\n" + ), + SpellingCase( + summary: "an inout parameter", + bareSpelling: "func acceptInout(_: inout ExistentialAnyFixture.Marker)\n", + spellingWithKeyword: "func acceptInout(_: inout any ExistentialAnyFixture.Marker)\n" + ), + SpellingCase( + summary: "a constrained existential parameter", + bareSpelling: "func acceptConstrained(_: any ExistentialAnyFixture.Boxed)\n", + spellingWithKeyword: "func acceptConstrained(_: any ExistentialAnyFixture.Boxed)\n" + ), + SpellingCase( + summary: "an existential argument of an opaque type's constraint", + bareSpelling: "func opaqueSequence() -> some Swift.Sequence\n", + spellingWithKeyword: "func opaqueSequence() -> some Swift.Sequence\n" + ), + ] + + @Test(arguments: spellingCases) + func interfaceSpellsExistentialsWithAny(_ spellingCase: SpellingCase) async throws { + let bareInterface = try await printedInterface(usesExistentialAny: false) + #expect(bareInterface.contains(spellingCase.bareSpelling), "\(bareInterface)") + let interface = try await printedInterface(usesExistentialAny: true) + #expect(interface.contains(spellingCase.spellingWithKeyword), "\(interface)") + } + + @Test func keywordIsOnByDefault() { + #expect(SwiftDeclarationPrintConfiguration().usesExistentialAny) + } + + /// The existential metatype of a constrained existential is a metadata + /// word plus one witness table, 16 bytes. The static layout engine used to + /// look for the constrained existential inside the field's extended + /// existential shape, so its metatype branch was never taken and the field + /// was laid out as a value container, 40 bytes; the field now reaches it + /// as an `existentialMetatype` like any other. + @Test func constrainedExistentialMetatypeIsLaidOutAsAMetatype() async throws { + let machOFile = try ExistentialAnyFixture.machOFile() + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.printTypeLayout = true + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: machOFile) + try await builder.prepare() + let interface = try await builder.printRoot().string + let lines = interface.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + let fieldIndex = try #require(lines.firstIndex { $0.hasPrefix("var constrainedMetatype: ") }, "\(interface)") + #expect(lines[fieldIndex - 1] == "// Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647)", "\(interface)") + } + + /// The keyword and module selectors are independent spellings: one name + /// takes both, and so does an opaque type's constraint, which the opaque + /// type provider spells. + @Test func keywordCombinesWithModuleSelectors() async throws { + let interface = try await printedInterface(usesExistentialAny: true, usesModuleSelectors: true) + #expect(interface.contains("var classBound: any ExistentialAnyFixture::Marker & Swift::AnyObject\n"), "\(interface)") + #expect(interface.contains("var protocolMetatype: (any ExistentialAnyFixture::Marker).Type\n"), "\(interface)") + #expect(interface.contains("func opaqueSequence() -> some Swift::Sequence\n"), "\(interface)") + } +} diff --git a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift index 1c09281b2..593983c40 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift @@ -1,12 +1,12 @@ import Foundation import Testing import MachOKit -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// End-to-end coverage for the `// not exported` annotation (evolution /// proposal 0008) on the `SymbolTestsCore` fixture — a library-evolution @@ -55,8 +55,8 @@ final class ExportStatusAnnotationTests: MachOFileTests, @unchecked Sendable { @Test func publicThunkExportedMemberIsNotAnnotated() async throws { let unsafeMachOFile = machOFile let implementationName = "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF" - #expect(SymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == true) let output = try await buildOutput(printExportStatus: true) #expect(try !isAnnotated("func mutateState()", in: output)) @@ -70,7 +70,7 @@ final class ExportStatusAnnotationTests: MachOFileTests, @unchecked Sendable { @Test func objcMemberIsExempt() async throws { let unsafeMachOFile = machOFile let implementationName = "_$s15SymbolTestsCore10AttributesO18ObjCAttributeClassC17objcDynamicMethodyyF" - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) let output = try await buildOutput(printExportStatus: true) #expect(try !isAnnotated("@objc func objcDynamicMethod()", in: output)) @@ -82,7 +82,7 @@ final class ExportStatusAnnotationTests: MachOFileTests, @unchecked Sendable { @Test func overrideMemberIsExempt() async throws { let unsafeMachOFile = machOFile let implementationName = "_$s15SymbolTestsCore7ClassesO25ExternalSwiftSubclassTestC14instanceMethodSSyF" - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) let output = try await buildOutput(printExportStatus: true) #expect(try !isAnnotated("override func instanceMethod() -> Swift.String", in: output)) diff --git a/Tests/SwiftInterfaceTests/ExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExportStatusTests.swift index 7ace68981..0234731f5 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusTests.swift @@ -2,11 +2,11 @@ import Foundation import Testing import MachOKit @_spi(Internals) @testable import Demangling -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// `TypeDefinition.exportStatus` / `ProtocolDefinition.exportStatus` — the /// export fact carried on the declaration model (evolution proposal @@ -42,19 +42,19 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { for typeDefinition in indexer.allTypeDefinitions.values { let descriptorOffset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset - let symbolsAtDescriptor = SymbolIndexStore.shared.symbols(for: descriptorOffset, in: unsafeMachOFile) + let symbolsAtDescriptor = SwiftSymbolIndexStore.shared.symbols(for: descriptorOffset, in: unsafeMachOFile) let descriptorSymbol = symbolsAtDescriptor?.first { $0.name.isSwiftSymbol && $0.name.hasSuffix("Mn") } // Every type of this fixture carries a symbol at its own // descriptor — the measured norm on shipped binaries too, which is // why the remangling leg practically never runs. let descriptorSymbolName = try #require(descriptorSymbol?.name, "\(typeDefinition.typeName.name) has no descriptor symbol") - let trieVerdict = SymbolIndexStore.shared.isExported(name: descriptorSymbolName, in: unsafeMachOFile) + let trieVerdict = SwiftSymbolIndexStore.shared.isExported(name: descriptorSymbolName, in: unsafeMachOFile) #expect(typeDefinition.exportStatus.isExported == trieVerdict, "\(typeDefinition.typeName.name)") switch typeDefinition.exportStatus { case .exported: exportedCount += 1 case .notExported: notExportedCount += 1 - case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable: + case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable, .declarationHasNoSymbol, .declarationIsCImported: Issue.record("\(typeDefinition.typeName.name) reached a no-verdict case on an image that has an export trie") } } @@ -72,16 +72,16 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { for protocolDefinition in indexer.allProtocolDefinitions.values { let descriptorOffset = protocolDefinition.protocolDescriptor.offset - let symbolsAtDescriptor = SymbolIndexStore.shared.symbols(for: descriptorOffset, in: unsafeMachOFile) + let symbolsAtDescriptor = SwiftSymbolIndexStore.shared.symbols(for: descriptorOffset, in: unsafeMachOFile) let descriptorSymbol = symbolsAtDescriptor?.first { $0.name.isSwiftSymbol && $0.name.hasSuffix("Mp") } let descriptorSymbolName = try #require(descriptorSymbol?.name, "\(protocolDefinition.protocolName.name) has no descriptor symbol") - let trieVerdict = SymbolIndexStore.shared.isExported(name: descriptorSymbolName, in: unsafeMachOFile) + let trieVerdict = SwiftSymbolIndexStore.shared.isExported(name: descriptorSymbolName, in: unsafeMachOFile) #expect(protocolDefinition.exportStatus.isExported == trieVerdict, "\(protocolDefinition.protocolName.name)") switch protocolDefinition.exportStatus { case .exported: exportedCount += 1 case .notExported: notExportedCount += 1 - case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable: + case .imageHasNoExportInformation, .descriptorSymbolNameUnresolvable, .declarationHasNoSymbol, .declarationIsCImported: Issue.record("\(protocolDefinition.protocolName.name) reached a no-verdict case on an image that has an export trie") } } @@ -101,7 +101,7 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { try #require( indexer.allTypeDefinitions.values.first { typeDefinition in let offset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset - return SymbolIndexStore.shared.symbols(for: offset, in: unsafeMachOFile)?.contains { $0.name == symbolName } == true + return SwiftSymbolIndexStore.shared.symbols(for: offset, in: unsafeMachOFile)?.contains { $0.name == symbolName } == true }, "expected a type definition whose descriptor carries \(symbolName)" ) @@ -118,7 +118,7 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { let privateProtocolDescriptorName = "_$s15SymbolTestsCore27PrivateDoppelgangerProtocol33_1282F137F8790A6AF4B7E2738A640142LLMp" let privateProtocol = try #require( indexer.allProtocolDefinitions.values.first { protocolDefinition in - SymbolIndexStore.shared.symbols(for: protocolDefinition.protocolDescriptor.offset, in: unsafeMachOFile)? + SwiftSymbolIndexStore.shared.symbols(for: protocolDefinition.protocolDescriptor.offset, in: unsafeMachOFile)? .contains { $0.name == privateProtocolDescriptorName } == true }, "expected a protocol definition whose descriptor carries \(privateProtocolDescriptorName)" @@ -126,6 +126,24 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { #expect(privateProtocol.exportStatus == .notExported) } + /// The fixture's one C-imported type, `CMTimeFlags`, carries a descriptor + /// the image emitted as its own copy — a private external, never in the + /// trie — so it reads as no verdict rather than as "not exported" + /// (evolution proposal `exported-only-marking-mode`). The verdict comes + /// from the descriptor's module, so it holds for any C type the indexer + /// shows. + @Test func cImportedTypeIsNotRuledOn() async throws { + let unsafeMachOFile = machOFile + let indexer = SwiftDeclarationIndexer(configuration: .init(showCImportedTypes: true), eventHandlers: [], in: machOFile) + try await indexer.prepare() + let cImportedType = try #require(indexer.allTypeDefinitions.values.first { typeDefinition in + let offset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset + return SwiftSymbolIndexStore.shared.symbols(for: offset, in: unsafeMachOFile)?.contains { $0.name == "_$sSo11CMTimeFlagsVMn" } == true + }) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$sSo11CMTimeFlagsVMn", in: unsafeMachOFile) == false) + #expect(cImportedType.exportStatus == .declarationIsCImported) + } + /// Why the descriptor-symbol leg is not optional: /// `Generics.GenericRequirementTest.RawRepresentableNestedStruct` is /// `public` and exported, but it is declared inside a CONSTRAINED @@ -140,7 +158,7 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { let nestedType = try #require( indexer.allTypeDefinitions.values.first { typeDefinition in let offset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset - return SymbolIndexStore.shared.symbols(for: offset, in: unsafeMachOFile)?.contains { $0.name == descriptorSymbolName } == true + return SwiftSymbolIndexStore.shared.symbols(for: offset, in: unsafeMachOFile)?.contains { $0.name == descriptorSymbolName } == true } ) @@ -153,11 +171,13 @@ final class ExportStatusTests: MachOFileTests, @unchecked Sendable { /// The projections, which every consumer rule is written against. @Suite struct ExportStatusProjectionTests { - @Test func isExportedProjectsBothNoVerdictCasesToNil() { + @Test func isExportedProjectsEveryNoVerdictCaseToNil() { #expect(ExportStatus.exported.isExported == true) #expect(ExportStatus.notExported.isExported == false) #expect(ExportStatus.imageHasNoExportInformation.isExported == nil) #expect(ExportStatus.descriptorSymbolNameUnresolvable.isExported == nil) + #expect(ExportStatus.declarationHasNoSymbol.isExported == nil) + #expect(ExportStatus.declarationIsCImported.isExported == nil) } /// The rule proposals 0008 / 0016 are built on: act only on a definitive @@ -167,5 +187,7 @@ struct ExportStatusProjectionTests { #expect(!ExportStatus.exported.isDefinitelyNotExported) #expect(!ExportStatus.imageHasNoExportInformation.isDefinitelyNotExported) #expect(!ExportStatus.descriptorSymbolNameUnresolvable.isDefinitelyNotExported) + #expect(!ExportStatus.declarationHasNoSymbol.isDefinitelyNotExported) + #expect(!ExportStatus.declarationIsCImported.isDefinitelyNotExported) } } diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift index 5ce9d3f82..0e89c38d4 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift @@ -1,12 +1,12 @@ import Foundation import Testing import MachOKit -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// End-to-end coverage for the exported-only filter (evolution proposal /// `exported-only-interface`) on the `SymbolTestsCore` fixture — a @@ -44,7 +44,7 @@ final class ExportedOnlyInterfaceTests: MachOFileTests, @unchecked Sendable { @Test func privateTypeIsDropped() async throws { let unsafeMachOFile = machOFile let descriptorName = "_$s15SymbolTestsCore19PrivateDoppelganger33_1282F137F8790A6AF4B7E2738A640142LLVMn" - #expect(SymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) let defaultOutput = try await buildOutput(exportedOnly: false) #expect(defaultOutput.contains("struct PrivateDoppelganger {")) @@ -61,7 +61,7 @@ final class ExportedOnlyInterfaceTests: MachOFileTests, @unchecked Sendable { @Test func privateProtocolAndItsDefaultImplementationsAreDropped() async throws { let unsafeMachOFile = machOFile let descriptorName = "_$s15SymbolTestsCore27PrivateDoppelgangerProtocol33_1282F137F8790A6AF4B7E2738A640142LLMp" - #expect(SymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) let defaultOutput = try await buildOutput(exportedOnly: false) #expect(defaultOutput.contains("protocol PrivateDoppelgangerProtocol {")) @@ -92,7 +92,7 @@ final class ExportedOnlyInterfaceTests: MachOFileTests, @unchecked Sendable { @Test func nestedPrivateTypeIsDroppedWhileParentStays() async throws { let unsafeMachOFile = machOFile let descriptorName = "_$s15SymbolTestsCore7StructsO19PrivateProtocolTest33_930E68B58AC9D850D1A6B7A3A1786E37LLOMn" - #expect(SymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == false) let defaultOutput = try await buildOutput(exportedOnly: false) #expect(defaultOutput.contains(" enum PrivateProtocolTest {")) @@ -115,7 +115,7 @@ final class ExportedOnlyInterfaceTests: MachOFileTests, @unchecked Sendable { @Test func publicTypeNestedInConstrainedExtensionIsKept() async throws { let unsafeMachOFile = machOFile let descriptorName = "_$s15SymbolTestsCore8GenericsO22GenericRequirementTestVAASYRzrlE28RawRepresentableNestedStructVMn" - #expect(SymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExported(name: descriptorName, in: unsafeMachOFile) == true) let filteredOutput = try await buildOutput(exportedOnly: true) #expect(filteredOutput.contains("struct RawRepresentableNestedStruct {")) @@ -154,10 +154,10 @@ final class ExportedOnlyInterfaceTests: MachOFileTests, @unchecked Sendable { /// `ExportStatusAnnotationTests`, so "kept" is the exemption's doing. @Test func thunkExportedObjCAndOverrideMembersAreKept() async throws { let unsafeMachOFile = machOFile - #expect(SymbolIndexStore.shared.isExported(name: "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF", in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF", in: unsafeMachOFile) == true) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore10AttributesO18ObjCAttributeClassC17objcDynamicMethodyyF", in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore7ClassesO25ExternalSwiftSubclassTestC14instanceMethodSSyF", in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF", in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF", in: unsafeMachOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore10AttributesO18ObjCAttributeClassC17objcDynamicMethodyyF", in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: "_$s15SymbolTestsCore7ClassesO25ExternalSwiftSubclassTestC14instanceMethodSSyF", in: unsafeMachOFile) == false) let filteredOutput = try await buildOutput(exportedOnly: true) #expect(filteredOutput.contains("func mutateState()")) diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift index b6c88930b..71beeff6f 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift @@ -2,168 +2,36 @@ import Foundation import Testing import MachOKit import Semantic -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @testable import MachOSwiftSection +import SwiftDeclaration +@_spi(Support) import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +import SwiftSectionTestingSupport /// The exported-only filter (evolution proposal -/// `exported-only-interface`) over `internal` declarations — the -/// shape `SymbolTestsCore` cannot pin, because that fixture is built with -/// `ENABLE_TESTABILITY` and exports its internals. This module is compiled -/// on the fly with `-enable-library-evolution` and WITHOUT `-enable-testing`, -/// so every `internal` declaration is a local symbol and the filter has a -/// definitive negative to act on for: a type, a nested type, a protocol and -/// its default implementation, a method, a stored property, a global, a -/// conformance to an internal protocol, and a constrained extension whose -/// members are all internal. +/// `exported-only-interface`) over `internal` declarations, on the +/// on-the-fly `ExportedOnlyFixture` module (see its documentation for the +/// shapes it carries and why `SymbolTestsCore` cannot pin them). @Suite(.serialized) struct ExportedOnlyLibraryEvolutionFixtureTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// The `Anchor` class is load-bearing fixture ballast: a struct-only - /// module compiles to a dylib with no `__DATA` segment, whose - /// chained-fixup pages MachOKit releases before 0.52.103 mis-walked (see - /// `DiffMemberIndentationTests`). `@inline(never)` keeps the internal - /// members' symbols from being folded away. - private static let fixtureSource = """ - public struct PublicShape { - public var title: String - var internalNote: String - public init(title: String, internalNote: String) { - self.title = title - self.internalNote = internalNote - } - public func publicMethod() {} - @inline(never) func internalMethod() {} - public struct PublicNested {} - struct InternalNested {} - } - struct InternalShape { - var value: Int - } - extension InternalShape { - @inline(never) func orphanMethod() {} - } - public protocol PublicContract { - func requirement() - } - protocol InternalContract { - func hidden() - } - extension InternalContract { - @inline(never) func hiddenDefault() {} - } - extension PublicShape: PublicContract { - public func requirement() {} - } - extension PublicShape: InternalContract { - @inline(never) func hidden() {} - } - public struct PublicBox { - public var element: Element - public init(element: Element) { self.element = element } - } - extension PublicBox where Element == Int { - @inline(never) func internalConstrainedMember() {} - } - extension PublicBox where Element == String { - public func publicConstrainedMember() {} - } - public struct PublicPair { - public var first: Element - public var second: Element - public init(first: Element, second: Element) { - self.first = first - self.second = second - } - } - extension PublicPair where Element == Int { - @inline(never) func internalOnlyConstrainedMember() {} - } - public enum PublicEnum { - case alpha - case beta - } - public class Anchor { - public func run() {} - } - public func publicGlobal() {} - @inline(never) func internalGlobal() {} - """ - - // `Swift.Error` spelled out: the `Semantic` import brings its own `Error` - // type into scope, which would otherwise win the lookup. - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ExportedOnlyFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("ExportedOnlyFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libExportedOnlyFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-enable-library-evolution", - "-module-name", "ExportedOnlyFixture", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - let diagnostics = String(decoding: diagnosticsData, as: UTF8.self) - throw FixtureCompilationError(diagnostics: diagnostics) - } - return libraryURL - } - }() - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "Exported-only fixture compilation failed:\n\(diagnostics)" } - } - - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - 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 func buildOutput(exportedOnly: Bool) async throws -> (output: String, machOFile: MachOFile) { - let machOFile = try loadFixtureMachOFile() + private func makePreparedBuilder(exportedOnly: Bool, showsCImportedTypes: Bool = false) async throws -> SwiftInterfaceBuilder { + let machOFile = try ExportedOnlyFixture.machOFile() var printConfiguration = SwiftDeclarationPrintConfiguration() printConfiguration.printExportedDeclarationsOnly = exportedOnly let builder = try SwiftInterfaceBuilder( - configuration: .init(printConfiguration: printConfiguration), + configuration: .init(indexConfiguration: .init(showCImportedTypes: showsCImportedTypes), printConfiguration: printConfiguration), eventHandlers: [], in: machOFile ) try await builder.prepare() - return (try await builder.printRoot().string, machOFile) + return builder + } + + private func buildOutput(exportedOnly: Bool, showsCImportedTypes: Bool = false) async throws -> (output: String, machOFile: MachOFile) { + let builder = try await makePreparedBuilder(exportedOnly: exportedOnly, showsCImportedTypes: showsCImportedTypes) + return (try await builder.printRoot().string, builder.machO) } /// The premise every assertion below rests on: without `-enable-testing` @@ -171,10 +39,10 @@ struct ExportedOnlyLibraryEvolutionFixtureTests { /// in the trie — the store must answer `false` / `true`, never `nil`. @Test func fixtureExportsExactlyItsPublicDescriptors() async throws { let (_, machOFile) = try await buildOutput(exportedOnly: false) - #expect(SymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture11PublicShapeVMn", in: machOFile) == true) - #expect(SymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture13InternalShapeVMn", in: machOFile) == false) - #expect(SymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture14PublicContractMp", in: machOFile) == true) - #expect(SymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture16InternalContractMp", in: machOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture11PublicShapeVMn", in: machOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture13InternalShapeVMn", in: machOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture14PublicContractMp", in: machOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s19ExportedOnlyFixture16InternalContractMp", in: machOFile) == false) } @Test func internalTypesAreDroppedAtEveryNestingLevel() async throws { @@ -259,6 +127,30 @@ struct ExportedOnlyLibraryEvolutionFixtureTests { #expect(filteredOutput.contains("case beta")) } + /// A C-imported type's descriptor is a copy each module using the type + /// emits for itself, under non-unique linkage, so no image exports it + /// and it says nothing about whether the type can be used from outside + /// (evolution proposal `exported-only-marking-mode`). Read as "not + /// exported", it put the type into the filter's scope once + /// `showCImportedTypes` indexed it, and the filter dropped the type along + /// with this image's public extension of it and its public conformance. + @Test func cImportedTypeIsNotRuledOnAndItsPublicExtensionsAreKept() async throws { + let builder = try await makePreparedBuilder(exportedOnly: true, showsCImportedTypes: true) + let cImportedTypeDefinition = try #require(builder.indexer.allTypeDefinitions.values.first { $0.typeName.name.hasSuffix("CGPoint") }) + #expect(!cImportedTypeDefinition.exportStatus.isDefinitelyNotExported) + #expect(cImportedTypeDefinition.exportStatus == .declarationIsCImported) + + let (defaultOutput, _) = try await buildOutput(exportedOnly: false, showsCImportedTypes: true) + #expect(defaultOutput.contains("struct CGPoint {")) + #expect(defaultOutput.contains("CGPoint: ExportedOnlyFixture.PublicContract {")) + #expect(defaultOutput.contains("func publicCImportedTypeMember()")) + + let filteredOutput = try await builder.printRoot().string + #expect(filteredOutput.contains("struct CGPoint {")) + #expect(filteredOutput.contains("CGPoint: ExportedOnlyFixture.PublicContract {")) + #expect(filteredOutput.contains("func publicCImportedTypeMember()")) + } + @Test func filteredOutputHasNoBlankLineArtifacts() async throws { let (filteredOutput, _) = try await buildOutput(exportedOnly: true) #expect(!filteredOutput.contains("\n\n\n")) diff --git a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift index 86030715e..be52598a4 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift @@ -6,8 +6,8 @@ import Testing import MachOKit @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Coverage for the extension-container unification (evolution proposal 0007): /// same-identity bucket merging, protocol attachment (a protocol's extension diff --git a/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift new file mode 100644 index 000000000..009cfaf01 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift @@ -0,0 +1,217 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) @testable import Demangling +@_spi(Internals) @testable import SwiftSymbols +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import SwiftInterface +@testable import SwiftSectionTestingSupport + +/// The export verdict of declarations in extensions of another module's +/// types, in images that keep no symbol at a non-exported descriptor +/// (evolution proposal `export-verdict-without-local-symbols`), on the +/// on-the-fly `ExtensionContextExportFixture` — see its documentation for +/// the declarations and the three variants. +/// +/// The bug this pins: AppKit in the macOS 27.2 dyld shared cache keeps no +/// local symbol but the `_symbolic` ones, so its non-exported types reached +/// the remangling leg, which refused every name with an extension context. +/// Every Swift type nested in an Objective-C class has one, so about 45 +/// AppKit types — 33 of them private — got no verdict, and RuntimeViewer +/// kept listing them after the user excluded what the image does not export. +@Suite(.serialized, ExclusiveImageAccess(ExtensionContextExportFixture.exclusiveAccessName)) +struct ExtensionContextExportStatusTests { + typealias Variant = ExtensionContextExportFixture.Variant + + /// The declarations the fixture keeps out of its export trie, and how + /// each one's name places it. + private static let declarationsInUnconstrainedExtensions = [ + "InternalNestedInExtension", + "PrivateNestedInExtension", + "NestedInPrivateType", + "InternalProtocolNestedInExtension", + "LocalTypeInExtension", + "InternalNestedInObjCClassExtension", + "PrivateNestedInObjCClassExtension", + ] + + private static let exportedDeclarations = [ + "PublicNestedInExtension", + "PublicNestedInObjCClassExtension", + "GenericBox", + "PublicNestedInConstrainedExtension", + ] + + private static func preparedIndexer(_ variant: Variant) async throws -> SwiftDeclarationIndexer { + let indexer = SwiftDeclarationIndexer( + configuration: .init(showCImportedTypes: false), + eventHandlers: [], + in: try ExtensionContextExportFixture.machOFile(variant) + ) + try await indexer.prepare() + return indexer + } + + /// Every type and protocol the fixture defines, by declared name. + private static func exportStatuses(in indexer: SwiftDeclarationIndexer) -> [String: ExportStatus] { + var statuses: [String: ExportStatus] = [:] + for typeDefinition in indexer.allTypeDefinitions.values { + statuses[typeDefinition.typeName.declaredNameForTesting] = typeDefinition.exportStatus + } + for protocolDefinition in indexer.allProtocolDefinitions.values { + statuses[protocolDefinition.protocolName.declaredNameForTesting] = protocolDefinition.exportStatus + } + return statuses + } + + /// How many unconstrained and constrained extension contexts a name runs + /// through. + private static func extensionContexts(of node: NodeReference) -> (unconstrained: Int, constrained: Int) { + var unconstrainedCount = 0 + var constrainedCount = 0 + for descendant in node.materialize() where descendant.kind == .extension { + if descendant.children.contains(where: { $0.kind == .dependentGenericSignature }) { + constrainedCount += 1 + } else { + unconstrainedCount += 1 + } + } + return (unconstrainedCount, constrainedCount) + } + + /// The premise: the unstripped variant carries a symbol at every + /// descriptor and rules by it, so it is the reference; the other two + /// carry none at a non-exported descriptor and must reach the later legs. + @Test(arguments: Variant.allCases) + func localDescriptorSymbolsAreWhereTheVariantSaysTheyAre(variant: Variant) async throws { + let indexer = try await Self.preparedIndexer(variant) + let machOFile = indexer.machO + for typeDefinition in indexer.allTypeDefinitions.values { + let name = typeDefinition.typeName.declaredNameForTesting + guard Self.declarationsInUnconstrainedExtensions.contains(name) else { continue } + let descriptorOffset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset + let descriptorSymbol = SwiftSymbolIndexStore.shared.symbols(for: descriptorOffset, in: machOFile)?.first { $0.name.isSwiftSymbol && $0.name.hasSuffix("Mn") } + #expect((descriptorSymbol != nil) == (variant == .unstripped), "\(name) in \(variant)") + } + #expect(SwiftSymbolIndexStore.shared.hasExportInformation(in: machOFile)) + } + + @Test(arguments: Variant.allCases) + func publicDeclarationsAreExported(variant: Variant) async throws { + let statuses = Self.exportStatuses(in: try await Self.preparedIndexer(variant)) + for name in Self.exportedDeclarations { + #expect(statuses[name] == .exported, "\(name) in \(variant)") + } + } + + /// The regression: without a symbol at the descriptor, an internal, + /// private or local declaration in an unconstrained extension used to + /// read `descriptorSymbolNameUnresolvable`. + @Test(arguments: Variant.allCases) + func declarationsInUnconstrainedExtensionsAreNotExported(variant: Variant) async throws { + let statuses = Self.exportStatuses(in: try await Self.preparedIndexer(variant)) + for name in Self.declarationsInUnconstrainedExtensions { + #expect(statuses[name] == .notExported, "\(name) in \(variant)") + } + } + + /// What makes it safe to remangle an unconstrained extension context: + /// where the compiler's own spelling sits at the descriptor, the + /// remangled name is exactly it, so an exported type reaching the + /// remangling leg would be found in the trie rather than dropped. + @Test func remanglingAnUnconstrainedExtensionContextSpellsTheCompilersName() async throws { + let indexer = try await Self.preparedIndexer(.unstripped) + let machOFile = indexer.machO + var comparedNames: [String] = [] + for typeDefinition in indexer.allTypeDefinitions.values { + let contexts = Self.extensionContexts(of: typeDefinition.typeName.node) + guard contexts.unconstrained > 0, contexts.constrained == 0 else { continue } + let descriptorOffset = typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.offset + let descriptorSymbolName = try #require( + SwiftSymbolIndexStore.shared.symbols(for: descriptorOffset, in: machOFile)?.first { $0.name.isSwiftSymbol && $0.name.hasSuffix("Mn") }?.name, + "\(typeDefinition.typeName.name) has no descriptor symbol" + ) + #expect(ExportStatus.descriptorSymbolName(for: typeDefinition.typeName.node, descriptorKind: .nominalTypeDescriptor) == descriptorSymbolName, "\(typeDefinition.typeName.name)") + comparedNames.append(typeDefinition.typeName.declaredNameForTesting) + } + for protocolDefinition in indexer.allProtocolDefinitions.values { + let contexts = Self.extensionContexts(of: protocolDefinition.protocolName.node) + guard contexts.unconstrained > 0, contexts.constrained == 0 else { continue } + let descriptorSymbolName = try #require( + SwiftSymbolIndexStore.shared.symbols(for: protocolDefinition.protocolDescriptor.offset, in: machOFile)?.first { $0.name.isSwiftSymbol && $0.name.hasSuffix("Mp") }?.name, + "\(protocolDefinition.protocolName.name) has no descriptor symbol" + ) + #expect(ExportStatus.descriptorSymbolName(for: protocolDefinition.protocolName.node, descriptorKind: .protocolDescriptor) == descriptorSymbolName, "\(protocolDefinition.protocolName.name)") + comparedNames.append(protocolDefinition.protocolName.declaredNameForTesting) + } + // Every shape the fixture declares in an unconstrained extension was compared. + #expect(Set(comparedNames).isSuperset(of: Self.declarationsInUnconstrainedExtensions + ["PublicNestedInExtension", "PublicNestedInObjCClassExtension"]), "\(comparedNames)") + } + + /// A constrained extension stays refused by the remangling leg, so an + /// internal type there keeps no verdict — but a private one is ruled on + /// by the third leg: by its name where the binary keeps its private + /// discriminator, by the anonymous context enclosing its descriptor where + /// it does not (the fully stripped variant names no anonymous context). + @Test(arguments: Variant.withoutLocalDescriptorSymbols) + func aConstrainedExtensionLeavesOnlyItsNonPrivateTypesUnjudged(variant: Variant) async throws { + let statuses = Self.exportStatuses(in: try await Self.preparedIndexer(variant)) + #expect(statuses["InternalNestedInConstrainedExtension"] == .descriptorSymbolNameUnresolvable) + #expect(statuses["PrivateNestedInConstrainedExtension"] == .notExported) + } + + /// The `@objc` protocols have no descriptor, so only the private one's + /// name rules, in every variant. + @Test(arguments: Variant.allCases) + func onlyThePrivateObjCProtocolIsRuledOn(variant: Variant) async throws { + let indexer = try await Self.preparedIndexer(variant) + var statuses: [String: ExportStatus] = [:] + for objcProtocolDefinition in indexer.objcProtocolDefinitions.values { + statuses[objcProtocolDefinition.protocolName.declaredNameForTesting] = objcProtocolDefinition.exportStatus + } + #expect(statuses["PrivateObjCProtocol"] == .notExported, "\(statuses)") + #expect(statuses["PublicObjCProtocol"] == .declarationHasNoSymbol, "\(statuses)") + } + + private static func interface(of variant: Variant, exportedOnly: Bool) async throws -> String { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.printExportedDeclarationsOnly = exportedOnly + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: try ExtensionContextExportFixture.machOFile(variant)) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// A category adopting only a private `@objc` protocol goes with the + /// protocol under the exported-only filter, as a conformance to a + /// non-exported Swift protocol does; one adopting a public protocol as + /// well stays whole. + @Test(arguments: Variant.allCases) + func exportedOnlyInterfaceDropsACategoryAdoptingOnlyAPrivateObjCProtocol(variant: Variant) async throws { + let unfiltered = try await Self.interface(of: variant, exportedOnly: false) + #expect(unfiltered.contains("extension __C.NSNumberFormatter:"), "\(unfiltered)") + #expect(unfiltered.contains("extension __C.NSByteCountFormatter:"), "\(unfiltered)") + + let filtered = try await Self.interface(of: variant, exportedOnly: true) + #expect(!filtered.contains("extension __C.NSNumberFormatter:"), "\(filtered)") + #expect(filtered.contains("extension __C.NSByteCountFormatter:"), "\(filtered)") + #expect(!filtered.contains("protocol PrivateObjCProtocol"), "\(filtered)") + #expect(filtered.contains("protocol PublicObjCProtocol"), "\(filtered)") + } + + /// End to end: the exported-only interface keeps the public types nested + /// in the extensions and drops every other one. + @Test(arguments: Variant.withoutLocalDescriptorSymbols) + func exportedOnlyInterfaceDropsTheNonExportedTypesInExtensions(variant: Variant) async throws { + let unfiltered = try await Self.interface(of: variant, exportedOnly: false) + let filtered = try await Self.interface(of: variant, exportedOnly: true) + for name in Self.declarationsInUnconstrainedExtensions where name != "LocalTypeInExtension" { + #expect(unfiltered.contains(name), "\(name) missing unfiltered in \(variant):\n\(unfiltered)") + #expect(!filtered.contains(name), "\(name) kept in \(variant):\n\(filtered)") + } + #expect(!filtered.contains("PrivateNestedInConstrainedExtension"), "\(filtered)") + for name in ["PublicNestedInExtension", "PublicNestedInObjCClassExtension", "PublicNestedInConstrainedExtension"] { + #expect(filtered.contains(name), "\(name) dropped in \(variant):\n\(filtered)") + } + } +} diff --git a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift index 995bfe3e1..a2b817fb7 100644 --- a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift +++ b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift @@ -6,8 +6,8 @@ import Testing import MachOKit @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Regression coverage for the identical-code-folding false positive in the /// `final` recovery (evolution proposal 0006), pinned against Xcode's real @@ -42,8 +42,10 @@ final class FinalKeywordICFRegressionTests: MachOFileTests, @unchecked Sendable // Positive control, straight from issue #106: the getter of // `SourceEditorDataSource.languageService` exports only a direct // symbol (no `Tq`, no thunk) — a genuine `final`, and its lazy - // storage's `Optional` must not leak into the printed type. - #expect(output.contains("final lazy var languageService: SourceEditor.SourceEditorLanguageService\n")) - #expect(!output.contains("languageService: SourceEditor.SourceEditorLanguageService?")) + // storage's `Optional` must not leak into the printed type. The + // property is an existential, spelled with `any` (evolution proposal + // `existential-any`). + #expect(output.contains("final lazy var languageService: any SourceEditor.SourceEditorLanguageService\n")) + #expect(!output.contains("languageService: (any SourceEditor.SourceEditorLanguageService)?")) } } diff --git a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift index 8018302a4..05b3888ee 100644 --- a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift @@ -6,8 +6,8 @@ import Testing import MachOKit @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// End-to-end coverage for the `final` keyword recovery and the lazy-var /// accessor-type correction (evolution proposal 0006), pinned against the diff --git a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift index f9ba16b19..1b51a2917 100644 --- a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift +++ b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface -import MachOTestingSupport +import SwiftSectionTestingSupport /// A generic parameter's printed name encodes its depth (`A1` is depth 1, /// index 0), and a depth counts only the contexts that declare parameters. diff --git a/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift new file mode 100644 index 000000000..89ba8ae51 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift @@ -0,0 +1,132 @@ +import Foundation +import Testing +import MachOKit +import SwiftDiffing +import SwiftInterface +@testable import SwiftSectionTestingSupport + +/// An evolution whose versions are groups of images (evolution proposal +/// `image-group-evolution`), over `ImageGroupFixture`: one module split from +/// 2.0 on into its own image and a core image, the way SwiftUI split into +/// SwiftUI and SwiftUICore. Compared one image per version, `Gauge` would +/// read as removed in 2.0; compared as a group it stays, and its move — and +/// `calibrated()`'s, a version later — is what the evolution records. +@Suite(.serialized, ExclusiveImageAccess(ImageGroupFixture.moduleName)) +struct ImageGroupEvolutionTests { + private static let moduleName = ImageGroupFixture.moduleName + private static let coreModuleName = ImageGroupFixture.coreModuleName + private static let gaugeName = "\(moduleName).Gauge" + private static let needleName = "\(coreModuleName).Needle" + + private func evolution() async throws -> ABIEvolution { + var imageGroups: [[ABIImageSnapshot]] = [] + for images in try ImageGroupFixture.imageGroups() { + var imageSnapshots: [ABIImageSnapshot] = [] + for image in images { + let builder = SwiftDiffableInterfaceBuilder(in: image.machOFile) + try await builder.prepare() + imageSnapshots.append(ABIImageSnapshot(imageName: image.name, snapshot: builder.snapshot())) + } + imageGroups.append(imageSnapshots) + } + return try ABIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: ImageGroupFixture.labels.map { ABIVersionDescriptor(label: $0) } + ) + } + + private func annotatedInterfaceLines() async throws -> [String] { + let imageGroups = try ImageGroupFixture.imageGroups().map { images in + images.map { SwiftEvolutionInterfaceImage(imageName: $0.name, machO: $0.machOFile) } + } + let builder = try AnySwiftEvolutionInterfaceBuilder(imageGroups: imageGroups, labels: ImageGroupFixture.labels) + try await builder.prepare() + return try await builder.printAnnotatedInterface().string.components(separatedBy: "\n") + } + + private func lineIndex(in lines: [String], where predicate: (String) -> Bool) throws -> Int { + let index = lines.firstIndex(where: predicate) + return try #require(index, "\(lines.joined(separator: "\n"))") + } + + // MARK: - The evolution + + @Test("a type moved into another image of the group stays present and records the move") + func movedTypeStaysPresent() async throws { + let result = try await evolution() + let gauge = try #require(result.types.first { $0.name == Self.gaugeName }) + #expect(gauge.presence == [true, true, true]) + #expect(gauge.events.isEmpty) + #expect(gauge.imageMoves == [ImageMove(versionIndex: 1, oldImageNames: [Self.moduleName], newImageNames: [Self.coreModuleName])]) + #expect(!result.hasBreakingChange) + } + + @Test("a member that stays behind when its type moves, and follows it a version later, moves once") + func memberLeftBehindMovesOnce() async throws { + let gauge = try #require(try await evolution().types.first { $0.name == Self.gaugeName }) + let calibrated = try #require(gauge.memberLineages.first { $0.latestSignature?.contains("calibrated()") == true }, "\(gauge.memberLineages)") + #expect(calibrated.events.isEmpty) + #expect(calibrated.imageMoves == [ImageMove(versionIndex: 2, oldImageNames: [Self.moduleName], newImageNames: [Self.coreModuleName])]) + // `reading()`, `value` and `init(value:)` moved with Gauge, `standard` + // never left the module's image: none has a story of its own. + #expect(gauge.memberLineages.count == 1, "\(gauge.memberLineages)") + } + + @Test("an extension one image declares on a type another image of the group defines reads as part of the type") + func extensionOfAGroupTypeFoldsIntoIt() async throws { + let result = try await evolution() + #expect(result.typeExtensions.isEmpty, "\(result.typeExtensions)") + let needle = try #require(result.types.first { $0.name == Self.needleName }) + #expect(needle.events == [LineageEvent(versionIndex: 1, status: .added)]) + } + + @Test("every version names its images") + func versionsNameTheirImages() async throws { + #expect(try await evolution().versions.map(\.imageNames) == [ + [Self.moduleName], + [Self.moduleName, Self.coreModuleName], + [Self.moduleName, Self.coreModuleName], + ]) + } + + // MARK: - The annotated interface + + @Test("the legend names each image with the versions holding it") + func legendNamesTheImageGroup() async throws { + let lines = try await annotatedInterfaceLines() + #expect(lines.contains("// Image group:")) + #expect(lines.contains("// [●●●] \(Self.moduleName)")) + #expect(lines.contains("// [○●●] \(Self.coreModuleName)")) + } + + @Test("the moved type keeps one body, its move annotated on the header") + func movedTypeKeepsOneBody() async throws { + let lines = try await annotatedInterfaceLines() + let headerIndex = try lineIndex(in: lines) { $0.contains("struct Gauge") && !$0.hasPrefix("extension") } + #expect(lines[headerIndex].contains("moved in 2.0: \(Self.moduleName) → \(Self.coreModuleName)"), "\(lines[headerIndex])") + #expect(!lines.contains { $0.hasPrefix("extension \(Self.gaugeName)") }, "\(lines.joined(separator: "\n"))") + } + + @Test("a member another image declares on the type renders in the type's body, its own move annotated") + func memberOfAnotherImageRendersInTheBody() async throws { + let lines = try await annotatedInterfaceLines() + let headerIndex = try lineIndex(in: lines) { $0.contains("struct Gauge") && !$0.hasPrefix("extension") } + let calibratedIndex = try lineIndex(in: lines) { $0.contains("func calibrated() -> Swift.Int") } + let closingIndex = try #require(lines[headerIndex...].firstIndex(of: "}")) + #expect(calibratedIndex > headerIndex && calibratedIndex < closingIndex) + #expect(lines[calibratedIndex].contains("// [●●●] moved in 3.0: \(Self.moduleName) → \(Self.coreModuleName)"), "\(lines[calibratedIndex])") + let standardIndex = try lineIndex(in: lines) { $0.contains("static var standard: \(Self.gaugeName)") } + #expect(standardIndex > headerIndex && standardIndex < closingIndex) + #expect(!lines[standardIndex].contains("// [")) + } + + @Test("a cross-module extension of a type the group defines renders in that type's body") + func crossModuleExtensionRendersInTheBody() async throws { + let lines = try await annotatedInterfaceLines() + let headerIndex = try lineIndex(in: lines) { $0.contains("struct Needle") && !$0.hasPrefix("extension") } + let sweepIndex = try lineIndex(in: lines) { $0.contains("func sweep() -> Swift.Int") } + let closingIndex = try #require(lines[headerIndex...].firstIndex(of: "}")) + #expect(sweepIndex > headerIndex && sweepIndex < closingIndex) + #expect(!lines.contains { $0.hasPrefix("extension \(Self.needleName)") }) + } +} diff --git a/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift new file mode 100644 index 000000000..c98dfa33b --- /dev/null +++ b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift @@ -0,0 +1,147 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import Demangling +import Semantic +import SwiftDeclarationRendering +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@testable import SwiftSectionTestingSupport + +/// The interface opens a property's accessor block with its SE-0400 `init` +/// (evolution proposal `init-accessor-recovery`): `@storageRestrictions(initializes: _x) init` +/// when the field it initializes is inferred, and the bare `init` under a +/// comment saying the binary does not record them otherwise. +@Suite(.serialized) +struct InitAccessorInterfaceTests { + private static let notRecordedComment = "// init accessor: the binary does not record which stored properties it initializes" + + private struct Indexed { + let machO: MachO + let indexer: SwiftDeclarationIndexer + + func printedType(_ typeName: String, _ configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> SemanticString { + var configuration = SwiftDeclarationPrintConfiguration() + configure(&configuration) + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machO) + printer.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + let definition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == typeName }, "no type named \(typeName)") + return try await printer.printTypeDefinition(definition) + } + } + + private func indexed(_ variant: InitAccessorFixture.Variant) async throws -> Indexed { + let machOFile = try await InitAccessorFixture.machOFile(variant) + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + return Indexed(machO: machOFile, indexer: indexer) + } + + /// `print`'s lines, each with its indentation trimmed. + private func lines(of print: String) -> [String] { + print.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + } + + /// The index of the line declaring `declaration` with an accessor block. + private func declarationIndex(of declaration: String, in lines: [String], sourceLocation: SourceLocation = #_sourceLocation) throws -> Int { + try #require(lines.firstIndex { $0.hasSuffix(declaration + " {") }, "no block declares \(declaration) in:\n\(lines.joined(separator: "\n"))", sourceLocation: sourceLocation) + } + + /// The lines inside the accessor block of `declaration`. + private func accessorBlock(of declaration: String, in print: String, sourceLocation: SourceLocation = #_sourceLocation) throws -> [String] { + let lines = lines(of: print) + let start = try declarationIndex(of: declaration, in: lines, sourceLocation: sourceLocation) + let end = try #require(lines[start...].firstIndex(of: "}"), "the block of \(declaration) does not close", sourceLocation: sourceLocation) + return Array(lines[(start + 1) ..< end]) + } + + // MARK: - Images that keep their init accessors + + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func anInferredFieldPrintsTheStorageRestrictions(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(variant) + let frozenBox = try await indexed.printedType("FrozenBox").string + #expect(try accessorBlock(of: "var value: A", in: frozenBox) == ["@storageRestrictions(initializes: _value) init", "get", "set"]) + let model = try await indexed.printedType("Model").string + #expect(try accessorBlock(of: "var name: Swift.String", in: model) == ["@storageRestrictions(initializes: _name) init", "get", "set"]) + // The field type is `weak Swift.AnyObject?`. + #expect(try accessorBlock(of: "var delegate: Swift.AnyObject?", in: model) == ["@storageRestrictions(initializes: _delegate) init", "get", "set"]) + // `accesses: b` is not recovered. + let mixed = try await indexed.printedType("Mixed").string + #expect(try accessorBlock(of: "var a: Swift.String", in: mixed) == ["@storageRestrictions(initializes: _a) init", "get", "set"]) + // The declaration prints from the getter, whose older mangling lacks + // `@Sendable`; the init accessor names the field's type. + let sendableUpgrade = try await indexed.printedType("SendableUpgrade").string + #expect(try accessorBlock(of: "var value: (_: Swift.Int) -> Swift.Int", in: sendableUpgrade) == ["@storageRestrictions(initializes: _value) init", "get", "set"]) + // The field is `() -> sending A`; the declaration's mangling, the init + // accessor's included, leaves `sending` out. + let sendingResult = try await indexed.printedType("SendingResult").string + #expect(try accessorBlock(of: "var make: () -> A", in: sendingResult) == ["@storageRestrictions(initializes: _make) init", "get", "set"]) + for print in [frozenBox, model, mixed, sendableUpgrade, sendingResult] { + #expect(!print.contains(Self.notRecordedComment), "\(print)") + } + } + + @Test(arguments: [InitAccessorFixture.Variant.debug, .release]) + func anUnnamedFieldPrintsTheBareInitUnderAComment(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(variant) + for (typeName, declaration) in [ + ("Angle", "var radians: Swift.Double"), + ("Titled", "var title: Swift.String"), + ("Pair", "var point: (x: Swift.Int, y: Swift.Int)"), + ("PersistedLookalike", "var name: Swift.String"), + ] { + let print = try await indexed.printedType(typeName).string + #expect(try accessorBlock(of: declaration, in: print) == ["init", "get", "set"], "\(typeName)") + let lines = lines(of: print) + let index = try declarationIndex(of: declaration, in: lines) + #expect(lines[index - 1] == Self.notRecordedComment, "\(typeName):\n\(print)") + } + } + + @Test func theInitAccessorsAddressIsOneOfThePropertys() async throws { + let print = try await indexed(.debug).printedType("Angle") { $0.printMemberAddress = true }.string + #expect(print.contains("// Address (init): 0x"), "\(print)") + } + + @Test func theCommentIsMarkedAsTheInitAccessorsComment() async throws { + let printed = try await indexed(.release).printedType("Angle") { $0.marksCommentStructure = true } + let separated = printed.frozen().separatingAnnotationRegions() + let utf8 = Array(separated.text.string.utf8) + let texts = separated.annotations.regions.filter { $0.kind == .initAccessorFields }.map { region in + let start = Int(region.utf8Offset) + return String(decoding: utf8[start ..< start + Int(region.utf8Length)], as: UTF8.self) + } + #expect(texts == [Self.notRecordedComment]) + } + + // MARK: - Stripped images + + /// An image keeps only the exported init accessor: every other property + /// prints the block it printed before. + @Test(arguments: [InitAccessorFixture.Variant.releaseDeadStripped, .releaseStripped]) + func aStrippedImagePrintsOnlyTheInitAccessorItKeeps(variant: InitAccessorFixture.Variant) async throws { + let indexed = try await indexed(variant) + let frozenBox = try await indexed.printedType("FrozenBox").string + #expect(try accessorBlock(of: "var value: A", in: frozenBox) == ["@storageRestrictions(initializes: _value) init", "get", "set"]) + let angle = try await indexed.printedType("Angle").string + #expect(try accessorBlock(of: "var radians: Swift.Double", in: angle) == ["get", "set"]) + #expect(!angle.contains(Self.notRecordedComment), "\(angle)") + } + + // MARK: - A stored property with an init accessor's symbol + + /// SwiftUICore's `_GeometryActionModifier.value`: the function under the + /// init accessor's name changes nothing in the stored property's print. + @Test(arguments: InitAccessorFixture.Variant.allCases) + func aStoredPropertyWithTheSymbolPrintsAsBefore(variant: InitAccessorFixture.Variant) async throws { + let print = try await indexed(variant).printedType("ShimmedBox").string + let lines = lines(of: print) + #expect(lines.contains { $0.hasSuffix("var value: Swift.Int") }, "\(print)") + #expect(!lines.contains { $0.hasSuffix("var value: Swift.Int {") }, "\(print)") + #expect(!lines.contains("init"), "\(print)") + #expect(!print.contains(Self.notRecordedComment), "\(print)") + } +} diff --git a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift index 975749a48..cc726eb2a 100644 --- a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift +++ b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift @@ -4,8 +4,8 @@ import MachOKit import Semantic @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Coverage for the interface header block (evolution proposal 0008): /// pure-value rendering (line composition, per-field omission, the diff --git a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift index e7d4eb33c..ff2b490b5 100644 --- a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift @@ -7,7 +7,8 @@ import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftPrinting @_spi(Support) import SwiftInterface -@testable import MachOTestingSupport +import Semantic +@testable import SwiftSectionTestingSupport /// Local types on the indexing and interface paths (evolution proposal /// `local-type-context-names`). Named after their method, two methods' @@ -35,6 +36,24 @@ struct LocalTypeInterfaceTests { return try await builder.printRoot().string } + /// The comment naming a local type's method, or saying that nothing + /// names it, is marked like every other comment (evolution proposal + /// `comment-structure`). + @Test(arguments: LocalTypeFixture.Variant.allCases) + func markingCommentStructureKeepsTheContract(variant: LocalTypeFixture.Variant) async throws { + func interface(marksCommentStructure: Bool) async throws -> FrozenSemanticString { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: try LocalTypeFixture.machOFile(variant)) + try await builder.prepare() + return try await builder.printRoot().frozen() + } + let marked = try await interface(marksCommentStructure: true) + let plain = try await interface(marksCommentStructure: false) + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") + } + /// The block whose header line STARTS with `prefix`, through its closing /// brace at the same indentation. private func block(startingWith prefix: String, in interface: String) -> String? { diff --git a/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift new file mode 100644 index 000000000..8b2c743f8 --- /dev/null +++ b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift @@ -0,0 +1,98 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftDeclarationRendering +import SwiftDiffing +import SwiftInterface +@_spi(Internals) import SwiftSymbols +@testable import SwiftSectionTestingSupport + +/// A member an image declares on a type another image defines, with no +/// extension context in its mangling (evolution proposal +/// `image-group-evolution`). SwiftUI declares such members on the types +/// SwiftUICore defines under `@_originallyDefinedIn(module: "SwiftUI", …)`: +/// `Text.accessibilityTextContentType(_:)` is +/// `$s7SwiftUI4TextV013accessibilityC11ContentType…`, the same shape as a +/// member declared in the type's own body. The index gathered non-extension +/// members only for the types the indexed image defines, so these belonged +/// to no definition: SwiftUI's dump, interface and ABI snapshot left them +/// out. They now read as members of an extension of their type, beside the +/// members of a cross-module extension, whose mangling names the extension. +@Suite(.serialized, ExclusiveImageAccess(ImageGroupFixture.moduleName)) +struct MembersOfAnotherImagesTypeTests { + /// `ImageGroupFixture` in 2.0, where `Gauge` lives in the core image and + /// the module's own image declares `calibrated()` and `standard` on it. + private func splitModuleImage() throws -> MachOFile { + try ImageGroupFixture.image(named: ImageGroupFixture.moduleName, atVersion: 1) + } + + private func interface(of machO: some MachOFieldLayoutRenderable) async throws -> String { + let builder = try SwiftInterfaceBuilder(configuration: SwiftInterfaceBuilderConfiguration(), eventHandlers: [], in: machO) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The block whose header line STARTS with `prefix`, through its closing + /// brace at the same indentation. + private func block(startingWith prefix: String, in interface: String) -> String? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[start...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[start...end].joined(separator: "\n") + } + + /// The premise: the image indexes `calibrated()` as a member of `Gauge` + /// declared outside any extension — the shape that had no definition to + /// land in. Without it, the tests below could pass on a compiler that + /// started naming the extension. + @Test func theMembersManglingNamesNoExtension() throws { + let machOFile = try splitModuleImage() + let gaugeName = "\(ImageGroupFixture.moduleName).Gauge" + let functionNames = SwiftSymbolIndexStore.shared.memberSymbols(of: .function(inExtension: false, isStatic: false), for: gaugeName, in: machOFile).map(\.name) + #expect(functionNames.contains { $0.contains("10calibrated") }, "\(functionNames)") + } + + @Test("a member declared on another image's type prints in an extension of that type") + func membersOfAnotherImagesTypePrintInAnExtension() async throws { + let interface = try await interface(of: try splitModuleImage()) + let gaugeExtension = try #require(block(startingWith: "extension \(ImageGroupFixture.moduleName).Gauge", in: interface), "\(interface)") + #expect(gaugeExtension.contains("func calibrated() -> Swift.Int"), "\(gaugeExtension)") + #expect(gaugeExtension.contains("static var standard: \(ImageGroupFixture.moduleName).Gauge"), "\(gaugeExtension)") + } + + @Test("a member of a cross-module extension keeps printing in its extension") + func crossModuleExtensionMembersKeepTheirExtension() async throws { + let interface = try await interface(of: try splitModuleImage()) + let needleExtension = try #require(block(startingWith: "extension \(ImageGroupFixture.coreModuleName).Needle", in: interface), "\(interface)") + #expect(needleExtension.contains("func sweep() -> Swift.Int"), "\(needleExtension)") + } + + /// The premise of the next test: the image carries members of a type + /// another module declares without declaring them itself — the + /// importer's `init?(rawValue:)` for a C enum, emitted into every image + /// that calls it, as the standard library's inlinable code is. + @Test func theImageCarriesAnotherModulesMembers() throws { + let allocatorNames = SwiftSymbolIndexStore.shared.memberSymbols(of: .allocator(inExtension: false), in: try splitModuleImage()).map(\.name) + #expect(allocatorNames.contains { $0.contains("NSComparisonResult") }, "\(allocatorNames)") + } + + @Test("another module's members the image only carries print nowhere") + func anotherModulesMembersStayOut() async throws { + let interface = try await interface(of: try splitModuleImage()) + #expect(!interface.contains("extension __C."), "\(interface)") + } + + @Test("the image's ABI snapshot carries the members declared on another image's type") + func snapshotCarriesMembersOfAnotherImagesType() async throws { + let builder = SwiftDiffableInterfaceBuilder(in: try splitModuleImage()) + try await builder.prepare() + let gaugeExtensionSignatures = builder.snapshot().typeExtensions + .filter { $0.name == "\(ImageGroupFixture.moduleName).Gauge" } + .flatMap(\.members) + .map(\.signature) + #expect(gaugeExtensionSignatures.contains { $0.contains("calibrated()") }, "\(gaugeExtensionSignatures)") + #expect(gaugeExtensionSignatures.contains { $0.contains("standard") }, "\(gaugeExtensionSignatures)") + } +} diff --git a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift index 2d51fe26f..f3e5dda28 100644 --- a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift @@ -3,7 +3,7 @@ import Testing import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// `SwiftDeclarationPrintConfiguration.usesModuleSelectors` qualifies the /// interface's names with SE-0491 module selectors, by the rules the Swift @@ -58,8 +58,8 @@ struct ModuleSelectorInterfaceTests { ), SpellingCase( summary: "AnyObject in a composition", - spellingWithoutSelectors: "var composition: ModuleSelectorFixture.Marker & Swift.AnyObject", - spellingWithSelectors: "var composition: ModuleSelectorFixture::Marker & Swift::AnyObject" + spellingWithoutSelectors: "var composition: any ModuleSelectorFixture.Marker & Swift.AnyObject", + spellingWithSelectors: "var composition: any ModuleSelectorFixture::Marker & Swift::AnyObject" ), SpellingCase( summary: "the header of an extension of another module's type", diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift index a0a643f5e..7b6e9c774 100644 --- a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -12,8 +12,8 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// With `SwiftDeclarationPrintConfiguration.marksNestedDefinitions`, every /// nested type and protocol taken out of its parent's print — @@ -33,6 +33,11 @@ import MachOFixtureSupport /// hard-coded level, a line its renderer does not indent — shows up here as a /// mismatch, or as a region whose indentation cannot be removed; a lost mark /// shows up as a parent with fewer regions than nested definitions. +/// +/// The one documented exception (evolution proposal +/// `exported-only-marking-mode`): marked, a definition the exported-only +/// filter keeps inside one it rules out is visible in its parent's print +/// only while the filter is off. Such a region is held to exactly that. @Suite(.serialized) final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { enum Variant: CaseIterable, Sendable, CustomStringConvertible { @@ -43,6 +48,10 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, /// proposal `private-declaration-source-files`), measured against a /// nested definition's parent whatever level it prints at. case privateDeclarationSourceFiles + /// Every comment marked with its kind and segments (evolution + /// proposal `comment-structure`): the marks of a nested definition's + /// comments must not depend on where it prints. + case everyOptionMarkingCommentStructure var description: String { switch self { @@ -50,6 +59,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, case .markedOptionalContent: "marked optional content" case .everyOptionWithTransformers: "every option with transformers" case .privateDeclarationSourceFiles: "private declaration source files" + case .everyOptionMarkingCommentStructure: "every option marking comment structure" } } @@ -77,6 +87,16 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, transformers.swiftTypeLayout.isEnabled = true transformers.swiftEnumLayout.isEnabled = true configuration.applyTransformers(transformers) + case .everyOptionMarkingCommentStructure: + configuration.printFieldOffset = true + configuration.printExpandedFieldOffsets = true + configuration.printMemberAddress = true + configuration.printVTableOffset = true + configuration.printPWTOffset = true + configuration.printTypeLayout = true + configuration.printEnumLayout = true + configuration.printExportStatus = true + configuration.marksCommentStructure = true } return configuration } @@ -130,13 +150,42 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, return "same text, span \(componentIndex) differs:\n taken out: \(takenOutComponent)\n own print: \(ownPrintComponent)" } + /// What the exception allows a region to differ by, and nothing more: + /// projected with the filter off it reads as the definition's own print + /// (all other options off, then all on), projected with the filter on it + /// is gone while the definition's own print is not. `nil` when it holds. + private static func exportFilterExceptionDifference(between takenOut: FrozenSemanticString, and ownPrint: FrozenSemanticString) -> String? { + let exportedOnlyOption = SwiftVisibilityOption.printExportedDeclarationsOnly.rawValue + let separatedTakenOut = takenOut.separatingVisibilityRegions() + let separatedOwnPrint = ownPrint.separatingVisibilityRegions() + let filterOffPredicates: [(String) -> Bool] = [{ _ in false }, { $0 != exportedOnlyOption }] + for isOptionEnabled in filterOffPredicates { + let projectedTakenOut = separatedTakenOut.regions.projection(of: separatedTakenOut.text, where: isOptionEnabled).text + let projectedOwnPrint = separatedOwnPrint.regions.projection(of: separatedOwnPrint.text, where: isOptionEnabled).text + if projectedTakenOut != projectedOwnPrint { + return "with the filter off, \(firstDifference(between: projectedTakenOut, and: projectedOwnPrint))" + } + } + let isOnlyTheFilterEnabled: (String) -> Bool = { $0 == exportedOnlyOption } + if !separatedTakenOut.regions.projection(of: separatedTakenOut.text, where: isOnlyTheFilterEnabled).text.string.isEmpty { + return "with the filter on, the region is still visible" + } + if separatedOwnPrint.regions.projection(of: separatedOwnPrint.text, where: isOnlyTheFilterEnabled).text.string.isEmpty { + return "with the filter on, the definition's own print is gone too: the filter rules it out" + } + return nil + } + /// Prints every parent with nested definitions, takes each region out, /// and describes the first few that differ from the definition's own - /// print. + /// print. A marked print installs the export filter scope, as a host + /// printing one declaration at a time does, and holds a region the + /// exported-only filter keeps inside a definition it rules out to the + /// documented exception instead. private static func mismatches( in machO: MachO, variant: Variant - ) async throws -> (checkedRegionCount: Int, mismatches: [String]) where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + ) async throws -> (checkedRegionCount: Int, exceptionRegionCount: Int, mismatches: [String]) where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { let indexer = SwiftDeclarationIndexer(in: machO) try await indexer.prepare() let printer = SwiftDeclarationPrinter(configuration: variant.configuration, in: machO) @@ -148,23 +197,44 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, index.recoverSourceFiles(ofEveryDeclarationIn: indexer) printer.setPrivateDeclarationSourceFileProvider(index) } + if variant == .markedOptionalContent { + printer.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + } + + func hasRuledOutAncestor(_ typeDefinition: TypeDefinition?) -> Bool { + var ancestor = typeDefinition + while let currentAncestor = ancestor { + if printer.isExcludedByExportFilter(currentAncestor) { return true } + ancestor = currentAncestor.parent + } + return false + } typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString // Every definition a region can name, by the identity the printer - // gives it. + // gives it, and whether the filter keeps it inside a type it rules + // out. var ownPrintingByIdentity: [String: Printing] = [:] + var isKeptInsideRuledOutTypeByIdentity: [String: Bool] = [:] + var isKeptByIdentity: [String: Bool] = [:] for typeDefinition in indexer.allTypeDefinitions.values { - ownPrintingByIdentity[try await mangleAsString(typeDefinition.typeName.node)] = { try await $0.printTypeDefinition(typeDefinition) } + let identity = try await mangleAsString(typeDefinition.typeName.node) + ownPrintingByIdentity[identity] = { try await $0.printTypeDefinition(typeDefinition) } + isKeptByIdentity[identity] = !printer.isExcludedByExportFilter(typeDefinition) + isKeptInsideRuledOutTypeByIdentity[identity] = !printer.isExcludedByExportFilter(typeDefinition) && hasRuledOutAncestor(typeDefinition.parent) } for protocolDefinition in indexer.allProtocolDefinitions.values { - ownPrintingByIdentity[try await mangleAsString(protocolDefinition.protocolName.node)] = { try await $0.printProtocolDefinition(protocolDefinition) } + let identity = try await mangleAsString(protocolDefinition.protocolName.node) + ownPrintingByIdentity[identity] = { try await $0.printProtocolDefinition(protocolDefinition) } + isKeptByIdentity[identity] = !printer.isExcludedByExportFilter(protocolDefinition) + isKeptInsideRuledOutTypeByIdentity[identity] = !printer.isExcludedByExportFilter(protocolDefinition) && hasRuledOutAncestor(protocolDefinition.parent) } - var parents: [(label: String, nestedDefinitionCount: Int, print: Printing)] = [] + var parents: [(label: String, nestedDefinitionCount: Int, isRuledOut: Bool, print: Printing)] = [] for (name, typeDefinition) in indexer.rootTypeDefinitions { let nestedDefinitionCount = nestedDefinitionCount(of: typeDefinition) guard nestedDefinitionCount > 0 else { continue } - parents.append(("type \(name.name)", nestedDefinitionCount, { try await $0.printTypeDefinition(typeDefinition) })) + parents.append(("type \(name.name)", nestedDefinitionCount, printer.isExcludedByExportFilter(typeDefinition), { try await $0.printTypeDefinition(typeDefinition) })) } let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] for extensionGroup in extensionGroups { @@ -172,12 +242,13 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, for extensionDefinition in extensionDefinitions { let nestedDefinitionCount = nestedDefinitionCount(of: extensionDefinition) guard nestedDefinitionCount > 0 else { continue } - parents.append(("extension \(name.name)", nestedDefinitionCount, { try await $0.printExtensionDefinition(extensionDefinition) })) + parents.append(("extension \(name.name)", nestedDefinitionCount, printer.isExcludedByExportFilter(extensionDefinition), { try await $0.printExtensionDefinition(extensionDefinition) })) } } } var checkedRegionCount = 0 + var exceptionRegionCount = 0 var mismatches: [String] = [] for parent in parents { let printed = try await parent.print(printer).frozen() @@ -198,17 +269,25 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, mismatches.append("\(label): the indentation could not be removed\n\(regionContent.string)") continue } - if takenOut != ownPrint { + let isKeptInsideRuledOutDefinition = isKeptInsideRuledOutTypeByIdentity[region.identity] == true || (parent.isRuledOut && isKeptByIdentity[region.identity] == true) + if variant.configuration.marksOptionalContent, isKeptInsideRuledOutDefinition { + exceptionRegionCount += 1 + if let difference = exportFilterExceptionDifference(between: takenOut, and: ownPrint) { + mismatches.append("\(label): \(difference)") + } + } else if takenOut != ownPrint { mismatches.append("\(label): \(firstDifference(between: takenOut, and: ownPrint))") } else if takenOut.separatingVisibilityRegions().regions != ownPrint.separatingVisibilityRegions().regions { mismatches.append("\(label): the visibility regions differ") } else if takenOut.separatingDefinitionRegions().definitions != ownPrint.separatingDefinitionRegions().definitions { mismatches.append("\(label): the nested definition regions differ") + } else if takenOut.separatingAnnotationRegions().annotations != ownPrint.separatingAnnotationRegions().annotations { + mismatches.append("\(label): the comment annotation regions differ") } } if mismatches.count >= 5 { break } } - return (checkedRegionCount, mismatches) + return (checkedRegionCount, exceptionRegionCount, mismatches) } @Test(arguments: Variant.allCases) @@ -225,6 +304,18 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") } + /// The exception on `ExportedOnlyFixture`, whose `UnexportedParent` the + /// link leaves unexported while its nested `ExportedNested` stays + /// exported — the shape of Foundation's + /// `LocalePreferences.ICUSymbolsAndStrings`, where RuntimeViewer met it. + /// Every other nested definition of the module keeps the contract. + @Test func exportedOnlyFixtureNestedDefinitionsTakeOutAsTheirOwnPrints() async throws { + let result = try await Self.mismatches(in: ExportedOnlyFixture.machOFile(), variant: .markedOptionalContent) + #expect(result.checkedRegionCount > 5) + #expect(result.exceptionRegionCount == 1) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + @Test func unmarkedPrintsAreUnchanged() async throws { let indexer = SwiftDeclarationIndexer(in: machOFile) try await indexer.prepare() diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index bccb48392..55290c789 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -5,8 +5,10 @@ import MachOFoundation import SwiftDeclaration import SwiftInterface import SwiftInspection -@_spi(Internals) import MachOSymbols -@testable import MachOTestingSupport +import SwiftObjCInterop +import Semantic +@_spi(Internals) import SwiftSymbols +@testable import SwiftSectionTestingSupport /// `@objc @implementation` recognition on the interface path (evolution /// proposal `objc-implementation-class-recognition`), over the on-the-fly @@ -16,12 +18,29 @@ import SwiftInspection @Suite(.serialized, ExclusiveImageAccess(ObjCImplementationFixture.moduleName)) struct ObjCImplementationClassRecognitionTests { private func interface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool = false) async throws -> String { + try await printInterface(of: variant, printFieldOffset: printFieldOffset, marksCommentStructure: false).string + } + + private func printInterface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool, marksCommentStructure: Bool) async throws -> SemanticString { let machOFile = try ObjCImplementationFixture.machOFile(variant) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.printFieldOffset = printFieldOffset + configuration.printConfiguration.marksCommentStructure = marksCommentStructure let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) try await builder.prepare() - return try await builder.printRoot().string + return try await builder.printRoot() + } + + /// The notes of a recognized `@objc @implementation` — inferred + /// evidence, an ivar's unrecoverable type — and its ivars' field offsets + /// are marked like every other comment (evolution proposal + /// `comment-structure`). + @Test(arguments: ObjCImplementationFixture.Variant.allCases) + func markingCommentStructureKeepsTheContract(variant: ObjCImplementationFixture.Variant) async throws { + let marked = try await printInterface(of: variant, printFieldOffset: true, marksCommentStructure: true).frozen() + let plain = try await printInterface(of: variant, printFieldOffset: true, marksCommentStructure: false).frozen() + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") } private func block(named header: String, in interface: String) -> String? { @@ -161,9 +180,10 @@ struct ObjCImplementationClassRecognitionTests { #expect(facts.properties.map(\.name).sorted() == ["count", "title"]) #expect(ObjCImplementationClasses.facts(forClassNamed: "ClangWidget", in: machOFile) == nil) - // Two `@implementation` bodies: `Widget` and the override-recovery - // fixture's `DerivedImplementationWidget`. - #expect(Set(ObjCImplementationClasses.all(in: machOFile).map(\.className)) == ["Widget", "DerivedImplementationWidget"]) + // Three `@implementation` bodies: `Widget`, the override-recovery + // fixture's `DerivedImplementationWidget` and the imported + // declarations' `ScenePresentationWidget`. + #expect(Set(ObjCImplementationClasses.all(in: machOFile).map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget"]) } /// An imported ObjC class has `PublicNonUnique` linkage, so any module @@ -174,7 +194,7 @@ struct ObjCImplementationClassRecognitionTests { /// `DateFormattingContext` (caught by the rendering A/B). @Test func aHiddenNonUniqueAccessorIsNotEvidence() throws { let machOFile = try ObjCImplementationFixture.machOFile(.full) - let symbolIndexStore = SymbolIndexStore.shared + let symbolIndexStore = SwiftSymbolIndexStore.shared // The premise: the fixture really does carry the clang class's accessor, // and it really is not exported. #expect(symbolIndexStore.containsSymbol(named: "_$sSo11ClangWidgetCMa", in: machOFile), "the fixture no longer emits the non-unique accessor the test is about") @@ -200,7 +220,7 @@ struct ObjCImplementationClassRecognitionTests { guard case .objcImplementationClassRecognized(let context) = event else { return nil } return context } - #expect(Set(recognized.map(\.className)) == ["Widget", "DerivedImplementationWidget"]) + #expect(Set(recognized.map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget"]) let widget = try #require(recognized.first { $0.className == "Widget" }) #expect(widget.isInferred == false) #expect(widget.instanceVariableCount == 5) diff --git a/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift new file mode 100644 index 000000000..031b78009 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift @@ -0,0 +1,277 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) import SwiftInterface +@_spi(Support) import SwiftPrinting +import SwiftDeclarationRendering +import SwiftObjCInterop +import Semantic +@testable import SwiftSectionTestingSupport + +/// The Objective-C declarations as Swift imports them (evolution proposal +/// `objc-imported-declarations`), over the shared `@objc @implementation` +/// fixture: a class declared and implemented in Objective-C, named by the +/// importer's rules; an `@objc @implementation` class whose members come from +/// its Swift implementation; a Swift class registered with the runtime; an +/// `@objc` protocol; and the separately shipped dylib's category on a class +/// of another image. +/// +/// The linker merges every category of a class the image defines into the +/// class's own lists, so the fixture itself lists no category: the members +/// of `@objc(Extras) @implementation extension Widget` and of the Swift +/// extensions with `@objc` members are the classes' methods. +@Suite(.serialized, ExclusiveImageAccess(ObjCImplementationFixture.moduleName)) +struct ObjCImportedDefinitionTests { + private func builder(of machOFile: MachOFile, printMemberAddress: Bool = false, marksCommentStructure: Bool = false) async throws -> SwiftInterfaceBuilder { + var configuration = SwiftInterfaceBuilderConfiguration( + indexConfiguration: .init(dependencySearchPaths: try ObjCImplementationFixture.dependencySearchPaths()) + ) + configuration.printConfiguration.printMemberAddress = printMemberAddress + configuration.printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) + try await builder.prepare() + return builder + } + + private func fixtureBuilder() async throws -> SwiftInterfaceBuilder { + try await builder(of: ObjCImplementationFixture.machOFile(.full)) + } + + @Test func aClassDeclaredInObjectiveCTakesTheImportersNames() async throws { + let builder = try await fixtureBuilder() + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "ClangWidget")) + #expect(!definition.isSwiftClass) + #expect(definition.swiftClassDefinition == nil) + // `extension ClangWidget { @objc public func swiftAdded() -> Int }`. + #expect(!definition.swiftExtensions.isEmpty) + + let printed = try await builder.printer.printObjCImportedClassDefinition(definition).string + #expect(printed.contains("class ClangWidget: __C.NSObject {"), "\(printed)") + #expect(printed.contains("Swift names follow the ClangImporter's rules"), "\(printed)") + // Unknown nullability is `!`; a `copy` `NSString` is a plain `String`. + #expect(printed.contains("var label: Swift.String!"), "\(printed)") + #expect(!printed.contains("@NSCopying"), "\(printed)") + #expect(printed.contains("var tally: Swift.Int"), "\(printed)") + #expect(printed.contains("func bump()"), "\(printed)") + #expect(printed.contains("class func pingCount() -> Swift.Int"), "\(printed)") + // The accessors are the properties, not methods of their own. + #expect(!printed.contains("func setLabel"), "\(printed)") + // The method the Swift extension adds, merged into the class's lists. + #expect(printed.contains("swiftAdded() -> Swift.Int"), "\(printed)") + } + + @Test func anImplementationClassTakesItsMembersFromSwift() async throws { + let builder = try await fixtureBuilder() + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "Widget")) + #expect(!definition.swiftExtensions.isEmpty) + + let printed = try await builder.printer.printObjCImportedClassDefinition(definition).string + #expect(printed.contains("class Widget: __C.NSObject {"), "\(printed)") + // The Swift members' own types: non-optional, which no method list + // records — the rules would print `String!`. + #expect(printed.contains("title: Swift.String"), "\(printed)") + #expect(!printed.contains("title: Swift.String!"), "\(printed)") + #expect(printed.contains("init(title: Swift.String)"), "\(printed)") + #expect(printed.contains("func refresh()"), "\(printed)") + // `@objc(Extras) @implementation extension Widget`, merged into the + // class's lists. + #expect(printed.contains("describe() -> Swift.String"), "\(printed)") + #expect(!printed.contains("describe() -> Swift.String!"), "\(printed)") + } + + /// An `@objc @implementation` class shaped like an OS framework's + /// (evolution proposal `swift-first-imported-declarations`): optimized + /// and stripped, so the thunks carry no symbol and call no Swift member, + /// and the joined tiers tie almost nothing. It prints as its Swift side: + /// the Swift members, the header's refined property as the Swift members + /// implementing and replacing it, and what the Swift side lacks from the + /// Objective-C side. + @Test func anOptimizedStrippedImplementationClassPrintsAsItsSwiftSide() async throws { + let builder = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped)) + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let printed = try await builder.printer.printObjCImportedClassDefinition(definition).string + #expect(printed.contains("class ScenePresentationWidget: __C.NSObject {"), "\(printed)") + // The Swift name the header's `NS_SWIFT_NAME` gives it, which the + // importer's rules miss — not `isHostingSceneLayer(_:)`. + #expect(printed.contains("func isHosting(sceneLayer: __C.FXSceneLayer) -> Swift.Bool"), "\(printed)") + #expect(!printed.contains("isHostingSceneLayer"), "\(printed)") + // `layerFilter`: the `__` member implementing it, and the Swift-only + // member the header leaves the plain name to. + #expect(printed.contains("var __layerFilter: __C.PresentationFilter"), "\(printed)") + #expect(printed.contains("var layerFilter: ObjCImplementationFixture.PresentationFilterValue"), "\(printed)") + #expect(!printed.contains("var layerFilter: __C.PresentationFilter!"), "\(printed)") + // `settings`: the Swift-only member, and the Objective-C property its + // implementation left no symbol of, under the name Swift gives it. + #expect(printed.contains("var settings: ObjCImplementationFixture.PresentationSettingsValue"), "\(printed)") + #expect(printed.contains("// NS_REFINED_FOR_SWIFT: var __settings: __C.PresentationSettings! { get set }\n"), "\(printed)") + #expect(!printed.contains("var settings: __C.PresentationSettings!"), "\(printed)") + // A stored property whose setter left no symbol is settable when + // Objective-C has a setter, and `weak` as Objective-C says. + #expect(printed.contains("weak var scene: __C.NSObject?"), "\(printed)") + // A stored property no symbol names: the Objective-C property + // synthesized on it, not a comment about its ivar. + #expect(printed.contains("var observers: Any"), "\(printed)") + #expect(!printed.contains("stored property observers"), "\(printed)") + } + + /// A property the header refines for Swift whose `__` declaration the + /// image keeps no symbol of is worded right above the Swift property that + /// took its plain name — before that property's own comments — not among + /// the Objective-C methods no Swift member answers to (evolution proposal + /// `swift-first-imported-declarations`). + @Test(arguments: [false, true]) + func aRefinedPropertysCommentSitsAboveTheSwiftPropertyTakingItsName(printMemberAddress: Bool) async throws { + let builder = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped), printMemberAddress: printMemberAddress) + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let printed = try await builder.printer.printObjCImportedClassDefinition(definition).string + let lines = printed.components(separatedBy: "\n") + let commentIndices = lines.indices.filter { lines[$0].contains("NS_REFINED_FOR_SWIFT") } + #expect(commentIndices.count == 1, "\(printed)") + let commentIndex = try #require(commentIndices.first, "\(printed)") + let comment = lines[commentIndex] + #expect(comment.trimmingCharacters(in: .whitespaces) == "// NS_REFINED_FOR_SWIFT: var __settings: __C.PresentationSettings! { get set }", "\(printed)") + // The Swift property's own rows follow: its address comments, when + // printed, then its declaration, all at the comment's indentation. + let isComment = { (line: String) in line.trimmingCharacters(in: .whitespaces).hasPrefix("//") } + let declarationIndex = try #require(lines[(commentIndex + 1)...].firstIndex { !isComment($0) }, "\(printed)") + let addressRows = lines[(commentIndex + 1) ..< declarationIndex] + #expect(lines[declarationIndex].contains("var settings: ObjCImplementationFixture.PresentationSettingsValue"), "\(printed)") + #expect(addressRows.allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("// Address") }, "\(printed)") + #expect(addressRows.isEmpty != printMemberAddress, "\(printed)") + let indentation = { (line: String) in line.prefix { $0 == " " }.count } + #expect((addressRows + [lines[declarationIndex]]).allSatisfy { indentation($0) == indentation(comment) }, "\(printed)") + // It was the only Objective-C member no Swift member answers to, so + // the group of those, and its note, are gone. + #expect(!printed.contains("no Swift member answers to"), "\(printed)") + } + + /// The declaration in that comment is marked by its parts — the + /// property's name and type — for a host to color as it colors a field + /// tree's rows; the punctuation inside the declaration plays no role, so + /// a host hiding separators keeps it (evolution proposal + /// `swift-first-imported-declarations`). + @Test func aRefinedPropertysCommentMarksTheDeclarationsNameAndType() async throws { + let marked = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped), marksCommentStructure: true) + let definition = try #require(marked.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let markedPrint = try await marked.printer.printObjCImportedClassDefinition(definition).frozen() + let separated = markedPrint.separatingAnnotationRegions() + let utf8 = Array(separated.text.string.utf8) + func text(utf8Offset: UInt32, utf8Length: UInt32) -> String { + String(decoding: utf8[Int(utf8Offset) ..< Int(utf8Offset) + Int(utf8Length)], as: UTF8.self) + } + let annotations = separated.annotations + let regionIndex = try #require(annotations.regions.indices.first { annotations.regions[$0].kind == .refinedForSwiftMember }, "\(separated.text.string)") + let region = annotations.regions[regionIndex] + #expect(text(utf8Offset: region.utf8Offset, utf8Length: region.utf8Length) == "// NS_REFINED_FOR_SWIFT: var __settings: __C.PresentationSettings! { get set }") + let segments = annotations.segments(inRegionAt: regionIndex).map { ($0.role.rawValue, text(utf8Offset: $0.utf8Offset, utf8Length: $0.utf8Length)) } + #expect(segments.map(\.0) == ["marker", "label", "separator", "name", "type"], "\(segments)") + #expect(segments.map(\.1) == ["// ", "NS_REFINED_FOR_SWIFT", ": ", "__settings", "__C.PresentationSettings!"], "\(segments)") + + let unmarked = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped)) + let unmarkedDefinition = try #require(unmarked.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let unmarkedPrint = try await unmarked.printer.printObjCImportedClassDefinition(unmarkedDefinition).frozen() + let violation = CommentStructureContract.violation(marked: markedPrint, unmarked: unmarkedPrint) + #expect(violation == nil, "\(violation ?? "")") + } + + /// What a host puts back on the header: the members it marks + /// `NS_REFINED_FOR_SWIFT`, keyed as API notes key them (evolution + /// proposal `swift-first-imported-declarations`). + @Test func theRefinedMembersOfAnImplementationClass() async throws { + let builder = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped)) + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let refinedMembers = try builder.printer.objcMembersRefinedForSwift(in: definition) + #expect(Set(refinedMembers) == [ + ObjCRefinedForSwiftMember(member: .property(name: "layerFilter", isClassProperty: false), evidence: .prefixedSwiftMember), + ObjCRefinedForSwiftMember(member: .property(name: "settings", isClassProperty: false), evidence: .nameTakenBySwiftDeclaration), + ]) + // A Swift extension of a class Objective-C implements refines nothing + // the fixture's header declares. + let clangWidget = try #require(builder.indexer.objcImportedClassDefinition(named: "ClangWidget")) + #expect(try builder.printer.objcMembersRefinedForSwift(in: clangWidget).isEmpty) + } + + /// The classes a host asks for refined members of: the ones the image's + /// Swift code extends, its `@objc @implementation` classes included — + /// not a Swift class's own extension, nor a class Swift only uses. + @Test func theClassesSwiftExtends() async throws { + let builder = try await fixtureBuilder() + let classNames = builder.indexer.objcClassRuntimeNamesExtendedInSwift + #expect(classNames.isSuperset(of: ["Widget", "DerivedImplementationWidget", "ClangWidget", "ScenePresentationWidget"]), "\(classNames)") + #expect(!classNames.contains("PresentationFilter"), "\(classNames)") + #expect(!classNames.contains { $0.contains("SwiftDerivedWidget") }, "\(classNames)") + } + + /// The Swift interface of the implementation itself: a stored property + /// whose setter left no symbol, of a settable `weak` Objective-C property + /// (evolution proposal `swift-first-imported-declarations`). It used to + /// print `let scene`. + @Test func aStoredPropertyIsAsSettableAndWeakAsItsObjectiveCProperty() async throws { + let builder = try await builder(of: ObjCImplementationFixture.machOFile(.optimizedStripped)) + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: "ScenePresentationWidget")) + let implementation = try #require(definition.swiftExtensions.first { $0.objcImplementation != nil }) + let printed = try await builder.printer.printExtensionDefinition(implementation).string + #expect(printed.contains("weak var scene: __C.NSObject?"), "\(printed)") + #expect(!printed.contains("let scene"), "\(printed)") + } + + @Test func aSwiftClassPrintsAsItself() async throws { + let builder = try await fixtureBuilder() + let runtimeName = try #require(builder.indexer.objcImportedClassRuntimeNames.first { $0.hasSuffix("SwiftDerivedWidget") }) + let definition = try #require(builder.indexer.objcImportedClassDefinition(named: runtimeName)) + #expect(definition.isSwiftClass) + #expect(definition.swiftClassDefinition != nil) + + let printed = try await builder.printer.printObjCImportedClassDefinition(definition).string + #expect(printed.contains("class SwiftDerivedWidget: __C.ClangWidget, ObjCImplementationFixture.WidgetObserving {"), "\(printed)") + #expect(printed.contains("@objc(pokeUsingForce:) func poke(force: Swift.Int)"), "\(printed)") + // An extension in the class's own module mangles its members as the + // class's, so `extension SwiftDerivedWidget { @objc public func + // fromExtension() }` is the class's member. + #expect(printed.contains("fromExtension()"), "\(printed)") + // Every Objective-C method is a member of the Swift class: no + // extension of the rest follows. + #expect(!printed.contains("no member of the Swift class answers to"), "\(printed)") + } + + /// `@objc public protocol WidgetObserving`, read from its record the way + /// the importer reads a header: its names are the importer's, whatever + /// the Swift source called them (`widgetWillPing()` was renamed + /// `@objc(widgetWillPingSoon)`). + @Test func aProtocolTakesTheImportersNames() async throws { + let builder = try await fixtureBuilder() + let definition = try #require(builder.indexer.objcImportedProtocolDefinition(named: "_TtP25ObjCImplementationFixture15WidgetObserving_")) + let printed = try await builder.printer.printObjCImportedProtocolDefinition(definition).string + #expect(printed.contains("protocol WidgetObserving"), "\(printed)") + #expect(printed.contains("func widgetDidPing(_: __C.ClangWidget!)"), "\(printed)") + #expect(printed.contains("optional func widgetWillPingSoon()"), "\(printed)") + } + + /// `@interface NSObject (SeparatelyShipped)`, implemented in the + /// separately shipped dylib: a category on a class of another image + /// stays a category. + @Test func aCategoryOnAClassOfAnotherImage() async throws { + let categoriesLibrary: MachOFile + switch try MachOKit.loadFromFile(url: ObjCImplementationFixture.categoriesLibraryURL()) { + case .machO(let machOFile): + categoriesLibrary = machOFile + case .fat(let fatFile): + categoriesLibrary = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + let builder = try await builder(of: categoriesLibrary) + #expect(builder.indexer.objcImportedCategoryUniqueNames == ["NSObject(SeparatelyShipped)"]) + let definition = try #require(builder.indexer.objcImportedCategoryDefinition(uniqueName: "NSObject(SeparatelyShipped)")) + #expect(definition.categoryName == "SeparatelyShipped") + #expect(definition.swiftExtensions.isEmpty) + + let printed = try await builder.printer.printObjCImportedCategoryDefinition(definition).string + #expect(printed.contains("extension __C.NSObject {"), "\(printed)") + #expect(printed.contains("The Objective-C category NSObject(SeparatelyShipped)."), "\(printed)") + // `noteValueForKeyPath:ofObject:` is `noteValue(forKeyPath:of:)` in + // the SDK: `Object` restates the type of an `id` argument. + #expect(printed.contains("func noteValue(forKeyPath: Any!, of: Any!)"), "\(printed)") + } +} diff --git a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift index d763aa684..9d743b289 100644 --- a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift @@ -10,8 +10,9 @@ import ObjCMetadataSource @_spi(Support) @testable import SwiftIndexing import SwiftInterface import SwiftInspection +import SwiftObjCInterop import SwiftThunkAnalysis -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The ObjC member recovery over the shared `@objc @implementation` fixture /// (evolution proposals `objc-ancestor-override-recovery` and @@ -643,6 +644,30 @@ struct ObjCMemberRecoveryTests { #expect(methodThunk == method) } + /// `NS_REFINED_FOR_SWIFT` puts `__` in front of a member's Swift name; + /// an `@objc @implementation` body implements it under that name + /// (evolution proposal `swift-first-imported-declarations`). The symbols + /// are SceneHosting's on macOS 27.2. + @Test func refinedForSwiftShapesAnswerTheUnprefixedSelector() throws { + let getter = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo19SHScenePresentationC12SceneHostingE13__layerFilterSo0a5LayerF0Cvg"))) + #expect(!getter.isConsistent(withSelector: "layerFilter", isClassMethod: false)) + let unprefixedGetter = try #require(getter.removingRefinedForSwiftPrefix) + #expect(unprefixedGetter.kind == .getter(propertyName: "layerFilter")) + #expect(unprefixedGetter.isConsistent(withSelector: "layerFilter", isClassMethod: false)) + + let setter = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo19SHScenePresentationC12SceneHostingE13__layerFilterSo0a5LayerF0Cvs"))) + #expect(try #require(setter.removingRefinedForSwiftPrefix).isConsistent(withSelector: "setLayerFilter:", isClassMethod: false)) + + let initializer = ObjCMemberShape(kind: .initializer(labels: ["__swiftScene", "registerPresenter"], arity: 2), isStatic: false, ownerQualifiedName: nil) + #expect(try #require(initializer.removingRefinedForSwiftPrefix).isConsistent(withSelector: "initWithSwiftScene:registerPresenter:", isClassMethod: false)) + + // A name without the prefix has no unprefixed shape, and the + // importer's plain spelling still matches it. + let hosting = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo19SHScenePresentationC12SceneHostingE02isD010sceneLayerSbSo07FBSceneG0C_tF"))) + #expect(hosting.removingRefinedForSwiftPrefix == nil) + #expect(hosting.isConsistent(withSelector: "isHostingSceneLayer:", isClassMethod: false)) + } + @Test func memberShapesFollowTheImporterSpelling() throws { let viewWillMove = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo17NSGlassEffectViewC6AppKitE12viewWillMove8toWindowySo8NSWindowCSg_tF"))) #expect(viewWillMove.kind == .method(baseName: "viewWillMove", labels: ["toWindow"], arity: 1)) diff --git a/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift new file mode 100644 index 000000000..a51020320 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift @@ -0,0 +1,400 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import Demangling +import Semantic +import SwiftDeclarationRendering +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@testable import SwiftSectionTestingSupport + +/// The interface folds what `@Observable` generated (evolution proposal +/// `observable-macro-folding`): by default a class the macro expanded reads +/// the way its source does, and `expandsMacros` prints the expansion as the +/// binary has it. `printMacroExpansion(of:attachedTo:level:)` prints the +/// expansion on its own, and `marksAttachedMacros` marks the attribute a host +/// anchors it to. +@Suite(.serialized) +struct ObservableMacroInterfaceTests { + private struct Indexed { + let machO: MachO + let indexer: SwiftDeclarationIndexer + + func typeDefinition(named typeName: String) throws -> TypeDefinition { + try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == typeName }, "no type named \(typeName)") + } + + func printer(_ configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) -> SwiftDeclarationPrinter { + var configuration = SwiftDeclarationPrintConfiguration() + configure(&configuration) + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machO) + printer.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + return printer + } + + func printedType(_ typeName: String, _ configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> String { + try await printer(configure).printTypeDefinition(typeDefinition(named: typeName)).string + } + } + + private func indexed(_ variant: ObservableMacroFixture.Variant) async throws -> Indexed { + let machOFile = try await ObservableMacroFixture.machOFile(variant) + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + return Indexed(machO: machOFile, indexer: indexer) + } + + /// The `count` lines above the line of `print` declaring `declaration`, + /// in order, with their indentation trimmed. + private func lines(above declaration: String, count: Int, in print: String, sourceLocation: SourceLocation = #_sourceLocation) throws -> [String] { + let printLines = print.split(separator: "\n", omittingEmptySubsequences: false) + let declarationIndex = try #require(printLines.firstIndex { $0.contains(declaration) }, "no line declares \(declaration) in:\n\(print)", sourceLocation: sourceLocation) + try #require(declarationIndex >= count, "fewer than \(count) lines above \(declaration) in:\n\(print)", sourceLocation: sourceLocation) + return printLines[(declarationIndex - count) ..< declarationIndex].map { $0.trimmingCharacters(in: .whitespaces) } + } + + /// The line of `print` declaring `declaration` — the first that contains + /// it — with its indentation trimmed. + private func line(declaring declaration: String, in print: String, sourceLocation: SourceLocation = #_sourceLocation) throws -> String { + let line = try #require(print.split(separator: "\n").first { $0.contains(declaration) }, "no line declares \(declaration) in:\n\(print)", sourceLocation: sourceLocation) + return line.trimmingCharacters(in: .whitespaces) + } + + // MARK: - The folded form + + /// Methods the source declares under the generated ones' names, in + /// shapes the macro does not generate — no parameters, another + /// parameter type — are the source's: the folded form prints them. + @Test(arguments: [ObservableMacroFixture.Variant.debug, .release]) + func methodsNamedLikeTheGeneratedOnesArePrinted(variant: ObservableMacroFixture.Variant) async throws { + let print = try await indexed(variant).printedType("HandwrittenNamesModel") + #expect(print.contains("func shouldNotifyObservers()"), "\(print)") + #expect(print.contains("func access(keyPath: Swift.String)"), "\(print)") + } + + @Test(arguments: [ObservableMacroFixture.Variant.debug, .release]) + func theFoldedFormReadsLikeTheSource(variant: ObservableMacroFixture.Variant) async throws { + let print = try await indexed(variant).printedType("FinalModel") + #expect(print.hasPrefix("@Observation.Observable\nclass FinalModel {"), "\(print)") + // Tracked properties, as stored `var`s under their own names. + for declaration in ["var name: Swift.String", "var count: Swift.Int", "var uninitialized: Swift.Double"] { + let declaringLine = try line(declaring: declaration, in: print) + #expect(!declaringLine.contains("@Observation"), "\(declaringLine)") + #expect(!declaringLine.contains("{"), "a tracked property prints as stored: \(declaringLine)") + } + // Stored `var`s the macro left alone say so, on a line of their own + // above the declaration; a `let` needs not. + for declaration in ["var ignored: Swift.Double", "var _cache: [Swift.Int]", "var lazyValue: Swift.Int"] { + #expect(!(try line(declaring: declaration, in: print)).contains("@"), "\(print)") + #expect(try lines(above: declaration, count: 1, in: print) == ["@Observation.ObservationIgnored"], "\(print)") + } + #expect(try line(declaring: "let constant: Swift.Int", in: print).hasPrefix("let ")) + // What the macro generated is left out. + for generated in ["_$observationRegistrar", "_name", "_count", "_uninitialized", "func access", "func withMutation", "shouldNotifyObservers"] { + #expect(!print.contains(generated), "\(generated) in:\n\(print)") + } + } + + @Test(arguments: [ObservableMacroFixture.Variant.debug, .release]) + func expandingMacrosPrintsTheExpansionWithoutTheAttribute(variant: ObservableMacroFixture.Variant) async throws { + let print = try await indexed(variant).printedType("FinalModel") { $0.expandsMacros = true } + #expect(!print.contains("@Observation"), "\(print)") + for generated in ["let _$observationRegistrar: Observation.ObservationRegistrar", "var _name: Swift.String", "var name: Swift.String {", "func access(keyPath:", "func withMutation(keyPath:"] { + #expect(print.contains(generated), "\(generated) not in:\n\(print)") + } + // The init accessor the macro writes, with the storage it + // initializes (evolution proposal `init-accessor-recovery`). + #expect(print.contains("@storageRestrictions(initializes: _name) init\n"), "\(print)") + } + + /// The folded form gives each attribute of an ignored wrapped property a + /// line of its own, at the declaration's indentation — whether the image + /// keeps the property's accessors or the declaration is synthesized from + /// its storage; the expanded form keeps the wrapper inline. + @Test(arguments: [ObservableMacroFixture.Variant.release, .releaseStripped]) + func aWrappedPropertyTheSourceIgnoredSaysSo(variant: ObservableMacroFixture.Variant) async throws { + let indexed = try await indexed(variant) + let folded = try await indexed.printedType("WrapperModel") + #expect(!(try line(declaring: "var clamped: Swift.Int", in: folded)).contains("@"), "\(folded)") + #expect(try lines(above: "var clamped: Swift.Int", count: 2, in: folded) == ["@Observation.ObservationIgnored", "@ObservableMacroFixture.Clamped"], "\(folded)") + let rawLines = folded.split(separator: "\n", omittingEmptySubsequences: false) + let declarationIndex = try #require(rawLines.firstIndex { $0.contains("var clamped: Swift.Int") }) + let indentations = rawLines[(declarationIndex - 2) ... declarationIndex].map { $0.prefix { $0 == " " }.count } + #expect(Set(indentations).count == 1, "\(folded)") + #expect(!(try line(declaring: "var tracked: Swift.Int", in: folded)).contains("@")) + let expanded = try await indexed.printedType("WrapperModel") { $0.expandsMacros = true } + #expect(try line(declaring: "var clamped: Swift.Int", in: expanded).hasPrefix("@ObservableMacroFixture.Clamped "), "\(expanded)") + } + + @Test func aStrippedClassSaysWhichPropertiesAreSynthesized() async throws { + let print = try await indexed(.releaseStripped).printedType("InternalModel") + #expect(print.hasPrefix("@Observation.Observable\nclass InternalModel {"), "\(print)") + let lines = print.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + for (storage, declaration) in [("_value", "var value: Swift.Int"), ("_optionalText", "var optionalText: Swift.String?"), ("_delegate", "weak var delegate: Swift.AnyObject?"), ("_underscored", "var underscored: Swift.Int")] { + let declarationIndex = try #require(lines.firstIndex { $0.hasSuffix(declaration) }, "\(declaration) not in:\n\(print)") + #expect(lines[declarationIndex - 1] == "// " + FieldRecordRendering.synthesizedTrackedPropertyComment(backingFieldName: storage)) + } + #expect(!print.contains("_$observationRegistrar")) + } + + @Test func moduleSelectorsReachTheAttributes() async throws { + let print = try await indexed(.release).printedType("FinalModel") { $0.usesModuleSelectors = true } + #expect(print.hasPrefix("@Observation::Observable\n"), "\(print)") + #expect(try lines(above: "var ignored: Swift::Double", count: 1, in: print) == ["@Observation::ObservationIgnored"], "\(print)") + } + + @Test func theExportedOnlyFilterRulesOnTheComputedProperty() async throws { + let print = try await indexed(.release).printedType("FinalModel") { $0.printExportedDeclarationsOnly = true } + // `name` is public: its computed property is exported. + #expect(print.contains("var name: Swift.String"), "\(print)") + // `count` is internal. + #expect(!print.contains("var count: Swift.Int"), "\(print)") + } + + /// A property of a function type with `sending` folds like any other. + /// Its accessor symbols leave `sending` out of the property's own type, + /// the storage's field record keeps it, and the folded declaration + /// prints the storage's type, `sending` included. + @Test func aPropertyOfAFunctionTypeWithSendingFolds() async throws { + let print = try await indexed(.release).printedType("SendingModel") + #expect(!print.contains("var _makeCoordinator") && !print.contains("var _takeCoordinator") && !print.contains("ObservationIgnored"), "\(print)") + #expect(try line(declaring: "var makeCoordinator: ", in: print).contains("sending ObservableMacroFixture.Coordinator"), "\(print)") + let takeCoordinator = try line(declaring: "var takeCoordinator: ", in: print) + #expect(takeCoordinator.contains("sending") && takeCoordinator.hasSuffix("ObservableMacroFixture.Coordinator) -> ()"), "\(print)") + } + + // MARK: - The whole interface + + @Test func theGeneratedConformanceIsPartOfTheExpansion() async throws { + let machOFile = try await ObservableMacroFixture.machOFile(.release) + func interface(expandsMacros: Bool) async throws -> String { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.expandsMacros = expandsMacros + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: machOFile) + try await builder.prepare() + return try await builder.printRoot().string + } + let folded = try await interface(expandsMacros: false) + #expect(!folded.contains("extension ObservableMacroFixture.FinalModel: Observation.Observable"), "\(folded)") + // A conformance written by hand is no macro's. + #expect(folded.contains("extension ObservableMacroFixture.ManualObservable: Observation.Observable {}"), "\(folded)") + let expanded = try await interface(expandsMacros: true) + #expect(expanded.contains("extension ObservableMacroFixture.FinalModel: Observation.Observable {}"), "\(expanded)") + #expect(expanded.contains("extension ObservableMacroFixture.ManualObservable: Observation.Observable {}"), "\(expanded)") + } + + // MARK: - The expansion on its own + + @Test func theExpansionPrintsAsOneBlock() async throws { + let indexed = try await indexed(.release) + let expansion = try await indexed.printer().printMacroExpansion(of: .observable, attachedTo: indexed.typeDefinition(named: "InternalModel")).string + #expect(!expansion.hasPrefix("\n") && !expansion.hasSuffix("\n"), "\(expansion)") + let lines = expansion.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + #expect(!lines.contains(""), "no blank line in:\n\(expansion)") + // The storage of the first tracked property opens it, at the members' + // indentation, as the expanded type body prints it. + let firstLine = try #require(lines.first) + #expect(firstLine.hasPrefix(" ") && firstLine.hasSuffix("var _value: Swift.Int"), "\(expansion)") + #expect(lines.last == "extension ObservableMacroFixture.InternalModel: Observation.Observable {}", "\(expansion)") + for declaration in ["let _$observationRegistrar: Observation.ObservationRegistrar", "var value: Swift.Int {", "func access(keyPath: Swift.KeyPath)", "func withMutation(keyPath:", "func shouldNotifyObservers("] { + #expect(expansion.contains(declaration), "\(declaration) not in:\n\(expansion)") + } + // A stored property the macro left alone is not part of it. + #expect(!expansion.contains("_underscored"), "\(expansion)") + #expect(!expansion.contains("@Observation"), "\(expansion)") + } + + @Test func theExpansionCarriesTheCommentsTheConfigurationAsksFor() async throws { + let indexed = try await indexed(.release) + let expansion = try await indexed.printer { $0.printMemberAddress = true }.printMacroExpansion(of: .observable, attachedTo: indexed.typeDefinition(named: "InternalModel")).string + #expect(expansion.contains("// Address (getter): 0x"), "\(expansion)") + } + + /// A tracked property whose accessors the image strips still has its + /// computed property in the block, the way the macro writes it, under a + /// note saying the declaration was recovered from the storage. + @Test func aStrippedPropertysComputedPropertyIsInTheBlockAllTheSame() async throws { + let indexed = try await indexed(.releaseStripped) + let expansion = try await indexed.printer().printMacroExpansion(of: .observable, attachedTo: indexed.typeDefinition(named: "InternalModel")).string + #expect(expansion.contains("var value: Swift.Int {\n @storageRestrictions(initializes: _value) init\n get\n set\n }"), "\(expansion)") + #expect(expansion.contains("synthesized from the storage `_value`"), "\(expansion)") + #expect(!expansion.contains("\n\n"), "\(expansion)") + } + + @Test func aTypeWithoutTheMacroHasNoExpansion() async throws { + let indexed = try await indexed(.release) + let expansion = try await indexed.printer().printMacroExpansion(of: .observable, attachedTo: indexed.typeDefinition(named: "ManualObservable")) + #expect(expansion.string.isEmpty) + } + + // MARK: - The expansion in parts + + /// `@Observable` writes an attribute on each tracked property, then the + /// members and the conformance; expanding that `@ObservationTracked` + /// gives the accessor block and the storage — the two levels Xcode + /// expands (evolution proposal `observable-nested-expansion`). + @Test func theExpansionPrintsInPartsPlacedLikeXcodes() async throws { + let indexed = try await indexed(.release) + let parts = try await indexed.printer().printMacroExpansionParts(of: .observable, attachedTo: indexed.typeDefinition(named: "InternalModel")) + #expect(parts.map(\.placement) == [ + .trackedPropertyAttribute(named: "value"), + .trackedPropertyAttribute(named: "optionalText"), + .trackedPropertyAttribute(named: "delegate"), + .members, + .conformance, + ]) + for part in parts + parts.flatMap(\.nestedExpansions).flatMap(\.parts) { + let content = part.content.string + #expect(!content.hasPrefix("\n") && !content.hasSuffix("\n") && !content.hasPrefix(" "), "\(part.placement): \(content)") + } + + let attribute = parts[0] + #expect(attribute.macro == .observable) + #expect(attribute.content.string == "@Observation.ObservationTracked") + #expect(attribute.nestedExpansions.count == 1) + let nestedExpansion = try #require(attribute.nestedExpansions.first) + #expect(nestedExpansion.macro == .observationTracked) + #expect(nestedExpansion.attributeUTF8Range == 0 ..< attribute.content.string.utf8.count) + #expect(nestedExpansion.parts.map(\.placement) == [.trackedProperty(named: "value")]) + // The computed property's accessor block, then its storage. + let value = try #require(nestedExpansion.parts.first) + #expect(value.macro == .observationTracked) + #expect(value.nestedExpansions.isEmpty) + #expect(value.content.string.hasPrefix("{\n") && value.content.string.contains("\n get\n set\n}\n"), "\(value.content.string)") + #expect(value.content.string.hasSuffix("var _value: Swift.Int"), "\(value.content.string)") + + let members = parts[3].content.string + for declaration in ["let _$observationRegistrar: Observation.ObservationRegistrar", "func access(keyPath:", "func withMutation(keyPath:", "func shouldNotifyObservers("] { + #expect(members.contains(declaration), "\(declaration) not in:\n\(members)") + } + // A tracked property's computed property is in its own piece. + #expect(!members.contains("var value"), "\(members)") + #expect(parts[3].nestedExpansions.isEmpty) + #expect(parts[4].content.string == "extension ObservableMacroFixture.InternalModel: Observation.Observable {}") + // Both levels are placed by the property's folded declaration. + #expect(attribute.anchorKind == .attachedMacroTrackedProperty(.observable, named: "value")) + #expect(value.anchorKind == .attachedMacroTrackedProperty(.observable, named: "value")) + #expect(parts[3].anchorKind == nil) + } + + /// The attribute prints through the type printer, so the configured + /// spelling reaches it as it reaches the folded attributes. + @Test func theAttributeFollowsTheConfiguredSpelling() async throws { + let indexed = try await indexed(.release) + let parts = try await indexed.printer { $0.usesModuleSelectors = true }.printMacroExpansionParts(of: .observable, attachedTo: indexed.typeDefinition(named: "InternalModel")) + let attribute = try #require(parts.first) + #expect(attribute.content.string == "@Observation::ObservationTracked") + #expect(attribute.nestedExpansions.first?.attributeUTF8Range == 0 ..< attribute.content.string.utf8.count) + } + + /// The accessor block `@Observable` writes for a tracked property stored + /// in `backingFieldName`, its init accessor included (evolution proposal + /// `init-accessor-recovery`). + private static func macroAccessorBlockLines(backingFieldName: String) -> [String] { + ["{", " @storageRestrictions(initializes: \(backingFieldName)) init", " get", " set", "}"] + } + + /// Every tracked property has its attribute piece, whose one nested + /// expansion opens with the accessor block the macro writes and ends + /// with the storage, whichever accessors the image keeps: all of them in + /// a debug or release build, none for a stripped internal class or a + /// dead-stripped final class's internal properties. + @Test(arguments: ObservableMacroFixture.Variant.allCases) + func everyTrackedPropertysAttributeExpandsToTheMacrosAccessorBlock(variant: ObservableMacroFixture.Variant) async throws { + let indexed = try await indexed(variant) + for typeName in ["FinalModel", "InternalModel"] { + let typeDefinition = try indexed.typeDefinition(named: typeName) + let parts = try await indexed.printer().printMacroExpansionParts(of: .observable, attachedTo: typeDefinition) + let attributeParts = parts.filter { part in + if case .trackedPropertyAttribute = part.placement { true } else { false } + } + // One piece a tracked property, as the recognition has them: in a + // stripped internal class, the misread `_underscored` among them. + let trackedProperties = try #require(typeDefinition.observableMacroExpansion).trackedProperties + #expect(attributeParts.map(\.placement) == trackedProperties.map { .trackedPropertyAttribute(named: $0.name) }, "\(typeName): \(parts.map(\.placement))") + for (attributePart, trackedProperty) in zip(attributeParts, trackedProperties) { + let nestedParts = attributePart.nestedExpansions.flatMap(\.parts) + #expect(nestedParts.map(\.placement) == [.trackedProperty(named: trackedProperty.name)], "\(typeName) \(attributePart.placement)") + let part = try #require(nestedParts.first) + let lines = part.content.string.components(separatedBy: "\n") + let expectedBlockLines = Self.macroAccessorBlockLines(backingFieldName: trackedProperty.backingFieldName) + #expect(Array(lines.prefix(expectedBlockLines.count)) == expectedBlockLines, "\(typeName) \(part.placement):\n\(part.content.string)") + #expect(lines.count > expectedBlockLines.count && lines.last?.contains("var _") == true, "\(typeName) \(part.placement):\n\(part.content.string)") + } + } + } + + @Test func aTypeWithoutTheMacroHasNoParts() async throws { + let indexed = try await indexed(.release) + #expect(try await indexed.printer().printMacroExpansionParts(of: .observable, attachedTo: indexed.typeDefinition(named: "ManualObservable")).isEmpty) + } + + /// Each tracked property's folded declaration is the anchor its piece + /// is placed below, told by kind. + @Test func eachTrackedPropertyIsAnchoredByItsName() async throws { + let indexed = try await indexed(.release) + let marked = try await indexed.printer { $0.marksAttachedMacros = true }.printTypeDefinition(indexed.typeDefinition(named: "FinalModel")).frozen() + let separated = marked.separatingAnnotationRegions() + let printedBytes = Array(separated.text.string.utf8) + for name in ["name", "count", "uninitialized"] { + let regions = separated.annotations.regions(ofKind: .attachedMacroTrackedProperty(.observable, named: name)) + #expect(regions.count == 1, "\(name)") + let region = try #require(regions.first) + let regionStart = Int(region.utf8Offset) + let regionText = String(decoding: printedBytes[regionStart ..< regionStart + Int(region.utf8Length)], as: UTF8.self) + #expect(regionText.contains("var \(name): ") && !regionText.contains("\n"), "\(regionText)") + } + // A stored property the macro left alone is no anchor. + #expect(separated.annotations.regions(ofKind: .attachedMacroTrackedProperty(.observable, named: "ignored")).isEmpty) + #expect(AnnotationRegion.Kind.attachedMacroTrackedProperty(.observable, named: "count").rawValue == "attachedMacro.Observation.Observable.trackedProperty.count") + } + + // MARK: - Anchoring the expansion + + @Test func theAttributeIsMarkedOnlyWhenAsked() async throws { + let indexed = try await indexed(.release) + let unmarked = try await indexed.printer().printTypeDefinition(indexed.typeDefinition(named: "FinalModel")).frozen() + let marked = try await indexed.printer { $0.marksAttachedMacros = true }.printTypeDefinition(indexed.typeDefinition(named: "FinalModel")).frozen() + let separated = marked.separatingAnnotationRegions() + #expect(separated.text == unmarked) + #expect(unmarked.separatingAnnotationRegions().annotations.isEmpty) + let regions = separated.annotations.regions(ofKind: .attachedMacro(.observable)) + #expect(regions.count == 1) + let region = try #require(regions.first) + let printedBytes = Array(separated.text.string.utf8) + let regionStart = Int(region.utf8Offset) + let regionEnd = regionStart + Int(region.utf8Length) + let attributeText = String(decoding: printedBytes[regionStart ..< regionEnd], as: UTF8.self) + #expect(attributeText == "@Observation.Observable") + #expect(AnnotationRegion.Kind.attachedMacro(.observable).rawValue == "attachedMacro.Observation.Observable") + } + + /// One print holds the attribute of a type and of the type nested in it; + /// the definition regions tell them apart, the innermost around an + /// attribute naming its type. + @Test func theNestedDefinitionRegionAroundAnAttributeNamesItsType() async throws { + let indexed = try await indexed(.release) + let container = try indexed.typeDefinition(named: "ContainerModel") + let nested = try indexed.typeDefinition(named: "NestedModel") + let marked = try await indexed.printer { + $0.marksAttachedMacros = true + $0.marksNestedDefinitions = true + }.printTypeDefinition(container).frozen() + let (afterAnnotations, annotations) = marked.separatingAnnotationRegions() + let (_, definitions) = afterAnnotations.separatingDefinitionRegions() + let attributeRegions = annotations.regions(ofKind: .attachedMacro(.observable)) + #expect(attributeRegions.count == 2) + + func enclosingIdentities(of attributeRegion: AnnotationRegionTable.Region) -> [String] { + definitions.regions.filter { definition in + definition.utf8Offset <= attributeRegion.utf8Offset + && attributeRegion.utf8Offset + attributeRegion.utf8Length <= definition.utf8Offset + definition.utf8Length + }.map { definition in definition.identity } + } + let nestedIdentity = try await mangleAsString(nested.typeName.node) + #expect(attributeRegions.map(enclosingIdentities) == [[], [nestedIdentity]]) + } +} diff --git a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift index 33d0b41df..06d14a140 100644 --- a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift @@ -1,7 +1,7 @@ import Foundation import Testing import MachOKit -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift new file mode 100644 index 000000000..17e1d6fd2 --- /dev/null +++ b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift @@ -0,0 +1,305 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftInterface + +/// The depth of an opaque result's parameters: the innermost depth of the +/// descriptor's own layout, counted over every context above it that adds +/// parameters, anonymous ones included. +/// +/// `swiftc -g -Onone` — every Xcode Debug build — adds +/// `-enable-anonymous-context-mangled-names`, and under it IRGen parents a +/// PROPERTY's opaque type descriptor on an anonymous context named after the +/// property (`OpaqueTypeDescriptorBuilder::getParent`). That context carries +/// the generic signature of the type or extension the property belongs to, +/// but its own parent is that type's parent — the module, for a top-level +/// type — so the type is nowhere on the descriptor's parent chain. +/// `SwiftInterfaceBuilderOpaqueTypeProvider` passed anonymous contexts over, +/// found no type or extension above, and put the opaque parameter of +/// `KeychainStorage.publisher` at depth 0 where the descriptor +/// constrains `τ_1_0`. A debug build trapped on the assertion guarding that +/// impossible depth — RuntimeViewer did, building its Find corpus over a test +/// bundle that links FoundationToolbox — and a release one printed a bare +/// `some`, or, for a `some Any` whose type has a constrained parameter, read +/// that parameter's constraint as the opaque one's: `some Storable`. +/// +/// A property in an extension is the harder half. An extension's parent is +/// the module too, so its property's context adds every parameter of the +/// extended type at once, `Outer`'s `A` and `Inner`'s `B` alike, and only the +/// extended type's descriptor tells the two depths apart. When another image +/// declares that type — `ProbeOpaqueDepthCore`'s `Nest.Inner` here — a file +/// reader has no descriptor to split with and leaves the result bare, while +/// an image loaded in the process finds the one that image exports. +/// +/// The provider also took a declaration to open a depth of its own whenever +/// its type carries a generic signature. A contextual `where` clause gives a +/// function one without a parameter, so in every build the opaque result of +/// `static func build() -> some Sequence where Value: Hashable` was +/// looked up one depth too deep and printed a bare `some` — SwiftUICore's +/// `KeyframesBuilder.buildBlock()` among them. +/// +/// Exit tests, because the defect traps. +@Suite(.serialized) +struct OpaqueParameterDepthTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Error, CustomStringConvertible { + let diagnostics: String + var description: String { "opaque-parameter depth fixture compilation failed:\n\(diagnostics)" } + } + + private struct UnexpectedInterface: Error, CustomStringConvertible { + let interface: String + var description: String { "the opaque results did not print their own constraints:\n\(interface)" } + } + + private static let moduleName = "ProbeOpaqueDebugDepth" + + private static let coreModuleName = "ProbeOpaqueDepthCore" + + /// A nested generic type for the fixture to extend from another module, + /// and the class every on-the-fly fixture carries as ballast: a + /// struct-only dylib has no `__DATA` segment, and MachOKit before 0.52.103 + /// mis-walked its chained-fixup pages. + private static let coreSource = """ + public final class CoreAnchor {} + + public struct Nest { + public struct Inner { + public init() {} + } + } + """ + + /// `Storage` has the shape of FoundationToolbox's `KeychainStorage`. + private static let source = """ + import Combine + import \(coreModuleName) + + public protocol Storable {} + + public final class Storage: @unchecked Sendable { + private let subject = PassthroughSubject() + public init() {} + public var publisher: some Publisher { subject } + // Constrains no opaque parameter, while the descriptor carries the + // requirement on `Value` at the coordinate a depth-0 reading looks at. + public var anything: some Any { 0 } + } + + public struct Outer { + public struct Inner { + public init() {} + // The context's parent is `Outer`: one depth short, not two. + public var values: some Sequence { [B]() } + } + } + + extension Outer.Inner where A: Hashable { + public var pairs: some Sequence { [B]() } + // A function's context sits in the extension in every build. + public func elements(_ element: Element) -> some Sequence { [element] } + } + + extension Outer.Inner { + public var outerValues: some Sequence { [A]() } + } + + public struct Builder { + // A generic signature of its own, and no parameter of its own. + public static func build() -> some Sequence where Value: Hashable { [Value]() } + } + + // The extended type's descriptor is in the other image. + extension Nest.Inner { + public var foreignValues: some Sequence { [B]() } + } + """ + + /// Each opaque result's line in the interface, its constraint spelled by + /// the parameter names its own depth gives it. `build`'s is matched from + /// its result on: what its header prints is not this suite's business. + private static let expectedInterfaceLines = [ + "final var publisher: some Combine.Publisher {", + "final var anything: some {", + "var values: some Swift.Sequence {", + "var pairs: some Swift.Sequence {", + "var outerValues: some Swift.Sequence {", + "func elements(_: A2) -> some Swift.Sequence", + "-> some Swift.Sequence where A: Swift.Hashable", + ] + + /// `foreignValues` read from the file: the core image's descriptor is out + /// of reach, so the depths cannot be told and the result stays bare. + private static let fileReaderExpectedInterfaceLine = "var foreignValues: some {" + + /// `foreignValues` read in-process: the loader finds the descriptor the + /// core image exports. + private static let inProcessReaderExpectedInterfaceLine = "var foreignValues: some Swift.Sequence {" + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("OpaqueParameterDepthFixture-\(UUID().uuidString)") + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let coreSourceURL = workingDirectory.appendingPathComponent("OpaqueParameterDepthCore.swift") + let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameterDepth.swift") + try coreSource.write(to: coreSourceURL, atomically: true, encoding: .utf8) + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try run(swiftcArguments: [ + "-swift-version", "5", "-Onone", "-emit-library", "-emit-module", "-module-name", coreModuleName, + "-target", "arm64-apple-macosx15.0", + "-Xlinker", "-install_name", "-Xlinker", "@rpath/lib\(coreModuleName).dylib", + coreSourceURL.path, "-o", workingDirectory.appendingPathComponent("lib\(coreModuleName).dylib").path, + ]) + try run(swiftcArguments: [ + // `-g -Onone` is what makes the driver pass + // `-enable-anonymous-context-mangled-names`. + "-swift-version", "5", "-g", "-Onone", "-emit-library", "-module-name", moduleName, + "-target", "arm64-apple-macosx15.0", + "-I", workingDirectory.path, "-L", workingDirectory.path, "-l\(coreModuleName)", + "-Xlinker", "-rpath", "-Xlinker", workingDirectory.path, + sourceURL.path, "-o", libraryURL.path, + ]) + return libraryURL + } + }() + + private static func run(swiftcArguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = ["swiftc"] + swiftcArguments + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + private static func machOFile() throws -> MachOFile { + let libraryURL = try fixtureCompilationResult.get() + switch try File.loadFromFile(url: libraryURL) { + case .machO(let file): + return file + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + } + + /// The fixture loaded into the process, read the way RuntimeViewer reads + /// an image. Only ever called in an exit test's child. + private static func loadedImage() throws -> MachOImage { + let libraryURL = try fixtureCompilationResult.get() + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + return try #require(MachOImage(name: libraryURL.deletingPathExtension().lastPathComponent), "the fixture dylib did not load in-process") + } + + /// The opaque type descriptor of the declaration whose mangled name + /// contains `fragment` — the identifier with its length, which no other + /// declaration of the fixture shares. + private static func opaqueTypeDescriptor(containing fragment: String, in machOFile: MachOFile) throws -> OpaqueTypeDescriptor { + let symbol = try #require( + machOFile.symbols.first { $0.nlist.flags?.stab == nil && $0.name.hasSuffix("QOMQ") && $0.name.contains(fragment) }, + "the fixture carries no opaque type descriptor for \(fragment)" + ) + return try OpaqueTypeDescriptor.resolve(at: symbol.offset, in: machOFile.context) + } + + /// The fixture's interface with the opaque type provider attached, as + /// `interface --parse-opaque-return-type` and RuntimeViewer print it; it + /// throws unless every opaque result prints its own constraint and none + /// prints one of its type's parameters. + static func printInterfaceNamingEachOpaqueConstraint(of machO: MachO, readerExpectedLine: String) async throws { + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machO) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + try await builder.prepare() + let interface = try await builder.printRoot().string + guard (expectedInterfaceLines + [readerExpectedLine]).allSatisfy(interface.contains), !interface.contains("some \(moduleName).Storable") else { + throw UnexpectedInterface(interface: interface) + } + } + + @Test("the fixture parents a property's opaque type on an anonymous context") + func fixtureHasTheDebugBuildShape() throws { + let machOFile = try Self.machOFile() + for fragment in ["9publisherQr", "6valuesQr", "5pairsQr", "11outerValuesQr"] { + let descriptor = try Self.opaqueTypeDescriptor(containing: fragment, in: machOFile) + let parent = try #require(try descriptor.parent(in: machOFile.context)?.resolved) + #expect(parent.isAnonymous, "\(fragment): the opaque type's parent is no longer the property's anonymous context; the fixture no longer has the shape this suite is about") + } + } + + @Test("an opaque type's depths count every context that adds parameters") + func opaqueTypeDepthsCountEveryContextAddingParameters() throws { + let machOFile = try Self.machOFile() + let expectedCountsByFragment: KeyValuePairs = [ + "9publisherQr": [1, 1], + "8anythingQr": [1, 1], + "6valuesQr": [1, 1, 1], + // The extended type's descriptor splits `A` and `B`. + "5pairsQr": [1, 1, 1], + "11outerValuesQr": [1, 1, 1], + "8elements": [1, 1, 1, 1], + "5buildQr": [1, 1], + // No descriptor to split them with: no answer rather than a guess. + "13foreignValuesQr": nil, + ] + for (fragment, expectedCounts) in expectedCountsByFragment { + let descriptor = try Self.opaqueTypeDescriptor(containing: fragment, in: machOFile) + let genericContext = try #require(try OpaqueType(descriptor: descriptor, in: machOFile.context).genericContext) + let depthLayout = GenericParameterDepthLayout.make(forOpaqueType: descriptor, genericContext: genericContext, in: machOFile.context) + #expect(depthLayout?.parameterCountsByDepth == expectedCounts, "\(fragment): \(String(describing: depthLayout?.parameterCountsByDepth))") + } + } + + @Test("opaque results name their own constraints, read from the file") + func opaqueResultsNameTheirConstraintsReadFromTheFile() async { + await #expect(processExitsWith: .success) { + do { + try await OpaqueParameterDepthTests.printInterfaceNamingEachOpaqueConstraint( + of: OpaqueParameterDepthTests.machOFile(), + readerExpectedLine: OpaqueParameterDepthTests.fileReaderExpectedInterfaceLine + ) + } catch { + // An error thrown out of an exit test ends the child on a + // trap too; exiting keeps a wrong interface apart from the + // provider's own trap. + exit(EXIT_FAILURE) + } + } + } + + @Test("opaque results name their own constraints, read in-process") + func opaqueResultsNameTheirConstraintsReadInProcess() async { + await #expect(processExitsWith: .success) { + do { + try await OpaqueParameterDepthTests.printInterfaceNamingEachOpaqueConstraint( + of: OpaqueParameterDepthTests.loadedImage(), + readerExpectedLine: OpaqueParameterDepthTests.inProcessReaderExpectedInterfaceLine + ) + } catch { + exit(EXIT_FAILURE) + } + } + } +} diff --git a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index 27d5152de..d8603bd60 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -7,8 +7,8 @@ import Testing import MachOKit import Dependencies @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A definition that cannot be printed must be **reported**, not printed away. /// @@ -261,7 +261,8 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { .deletingLastPathComponent() // Tests .deletingLastPathComponent() // package root .appendingPathComponent("Sources") - let hostModules: Set = ["swift-section", "MachOTestingSupport"] + // Hosts, not library: each owns its process's streams. + let hostModules: Set = ["swift-section", "reader-benchmark", "SwiftSectionTestingSupport"] let enumerator = try #require(FileManager.default.enumerator(at: sourcesDirectory, includingPropertiesForKeys: nil)) var files: [URL] = [] diff --git a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift index bb9b63489..938a37c4e 100644 --- a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift @@ -6,7 +6,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// How the interface prints a protocol's requirement signature (evolution /// proposal `protocol-requirement-placement`): every requirement in the @@ -50,7 +50,7 @@ struct ProtocolRequirementPlacementInterfaceTests { 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)") + requirements.append("\(requirement.descriptor.flags.kind.map { "\($0)" } ?? "unknown") \(requirementText)") } requirementSignatures[protocolModel.name] = requirements } diff --git a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift index d3cdcbd31..08a316304 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift @@ -4,6 +4,10 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +// Scoped: the module's `Error` component would shadow `Swift.Error` here. +import struct Semantic.SemanticString +import struct Semantic.FrozenSemanticString +import SwiftSectionTestingSupport /// `@_rawLayout` is an experimental feature any module can enable, not a /// standard-library privilege, and only its `like:` spelling leaves a field @@ -109,6 +113,10 @@ struct RawLayoutBuiltinDescriptorRenderingTests { """ private func renderInterface() async throws -> String { + try await printInterface(marksCommentStructure: false).string + } + + private func printInterface(marksCommentStructure: Bool) async throws -> SemanticString { let libraryURL = try Self.fixtureCompilationResult.get() let machOFile: MachOFile switch try File.loadFromFile(url: libraryURL) { @@ -117,9 +125,21 @@ struct RawLayoutBuiltinDescriptorRenderingTests { case .fat(let fatFile): machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) } - let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) try await builder.prepare() - return try await builder.printRoot().string + return try await builder.printRoot() + } + + /// The note beside `@_rawLayout(size:alignment:)` is marked like every + /// other comment (evolution proposal `comment-structure`). + @Test func markingCommentStructureKeepsTheContract() async throws { + let marked = try await printInterface(marksCommentStructure: true).frozen() + let plain = try await printInterface(marksCommentStructure: false).frozen() + #expect(plain.string.contains("size and alignment from the builtin type descriptor")) + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") } /// The line printed directly above `declaration`, or `nil` when the diff --git a/Tests/SwiftInterfaceTests/Snapshots/SymbolTestsCoreInterfaceSnapshotTests.swift b/Tests/SwiftInterfaceTests/Snapshots/SymbolTestsCoreInterfaceSnapshotTests.swift index 0708647d6..f6009a9d7 100644 --- a/Tests/SwiftInterfaceTests/Snapshots/SymbolTestsCoreInterfaceSnapshotTests.swift +++ b/Tests/SwiftInterfaceTests/Snapshots/SymbolTestsCoreInterfaceSnapshotTests.swift @@ -6,8 +6,8 @@ import Testing import SnapshotTesting import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import SwiftInterface @Suite(.serialized, .snapshots(record: .missing)) diff --git a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt index 78d069367..30b5ea8d0 100644 --- a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt +++ b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt @@ -319,7 +319,7 @@ enum Classes { class ExternalObjCSubclassTest: __C.NSObject { @objc override init() - @objc override func isKind(of: Swift.AnyObject.Type) -> Swift.Bool + @objc override func isKind(of: any Swift.AnyObject.Type) -> Swift.Bool deinit } @@ -995,7 +995,7 @@ enum ErrorTypes { // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) case withCode(Swift.Int) // Type Layout: (size: 32, stride: 32, alignment: 8, extraInhabitantCount: 2147483647) - case withContext(message: Swift.String, code: Swift.Int, underlying: Swift.Error?) + case withContext(message: Swift.String, code: Swift.Int, underlying: (any Swift.Error)?) } struct LocalizedErrorTest { // Field offset: 0x0 @@ -1042,34 +1042,34 @@ enum ExistentialAny { struct ExistentialFieldTest { // Field offset: 0x0 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483647) - var simpleExistential: SymbolTestsCore.Protocols.ProtocolTest + var simpleExistential: any SymbolTestsCore.Protocols.ProtocolTest // Field offset: 0x28 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483647) - var compositionExistential: SymbolTestsCore.Protocols.ProtocolTest + var compositionExistential: any SymbolTestsCore.Protocols.ProtocolTest // Field offset: 0x50 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483646) - var optionalExistential: SymbolTestsCore.Protocols.ProtocolTest? + var optionalExistential: (any SymbolTestsCore.Protocols.ProtocolTest)? // Field offset: 0x78 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var existentialArray: [SymbolTestsCore.Protocols.ProtocolTest] + var existentialArray: [any SymbolTestsCore.Protocols.ProtocolTest] // Field offset: 0x80 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var existentialDictionary: [Swift.String : SymbolTestsCore.Protocols.ProtocolTest] + var existentialDictionary: [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest] // Field offset: 0x88 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - var existentialFunction: (_: SymbolTestsCore.Protocols.ProtocolTest) -> () + var existentialFunction: (_: any SymbolTestsCore.Protocols.ProtocolTest) -> () - init(simpleExistential: SymbolTestsCore.Protocols.ProtocolTest, compositionExistential: Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest, optionalExistential: SymbolTestsCore.Protocols.ProtocolTest?, existentialArray: [SymbolTestsCore.Protocols.ProtocolTest], existentialDictionary: [Swift.String : SymbolTestsCore.Protocols.ProtocolTest], existentialFunction: @escaping (_: SymbolTestsCore.Protocols.ProtocolTest) -> ()) + init(simpleExistential: any SymbolTestsCore.Protocols.ProtocolTest, compositionExistential: any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest, optionalExistential: (any SymbolTestsCore.Protocols.ProtocolTest)?, existentialArray: [any SymbolTestsCore.Protocols.ProtocolTest], existentialDictionary: [Swift.String : any SymbolTestsCore.Protocols.ProtocolTest], existentialFunction: @escaping (_: any SymbolTestsCore.Protocols.ProtocolTest) -> ()) } struct ExistentialClassBoundTest { // Field offset: 0x0 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - var classBound: SymbolTestsCore.Protocols.ClassBoundProtocolTest + var classBound: any SymbolTestsCore.Protocols.ClassBoundProtocolTest // Field offset: 0x10 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) var anyObjectReference: Swift.AnyObject - init(classBound: SymbolTestsCore.Protocols.ClassBoundProtocolTest, anyObjectReference: Swift.AnyObject) + init(classBound: any SymbolTestsCore.Protocols.ClassBoundProtocolTest, anyObjectReference: Swift.AnyObject) } } enum Extensions { @@ -1217,7 +1217,7 @@ enum FunctionFeatures { static func staticConsume(_: consuming SymbolTestsCore.FunctionFeatures.OwnershipParameterTest.Box) } struct VariadicFunctionTest { - func format(_: Swift.String, _: Swift.CVarArg...) -> Swift.String + func format(_: Swift.String, _: any Swift.CVarArg...) -> Swift.String func sum(_: Swift.Int...) -> Swift.Int } struct ConventionFunctionTest { @@ -1225,12 +1225,12 @@ enum FunctionFeatures { func acceptBlockFunction(_: @convention(block) (_: Swift.Int32) -> Swift.Int32) -> Swift.Int32 } struct ExistentialAndMetatypeTest { - func returnExistential() -> Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest - func acceptMetatype(_: Any.Type) -> Swift.String - func acceptExistentialCollection(_: [SymbolTestsCore.Protocols.ProtocolTest]) -> Swift.Int - func acceptProtocolMetatype(_: SymbolTestsCore.Protocols.ProtocolTest.Protocol) -> Swift.Bool - func acceptExistential(_: SymbolTestsCore.Protocols.ProtocolTest) - func acceptComposition(_: Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest) + func returnExistential() -> any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest + func acceptMetatype(_: any Any.Type) -> Swift.String + func acceptExistentialCollection(_: [any SymbolTestsCore.Protocols.ProtocolTest]) -> Swift.Int + func acceptProtocolMetatype(_: (any SymbolTestsCore.Protocols.ProtocolTest).Type) -> Swift.Bool + func acceptExistential(_: any SymbolTestsCore.Protocols.ProtocolTest) + func acceptComposition(_: any Swift.Sendable & SymbolTestsCore.Protocols.ProtocolTest) } struct FailableInitTest { // Field offset: 0x0 @@ -1381,9 +1381,9 @@ enum GenericFieldLayout { // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) var field3: Swift.Int - @objc init(field1: Swift.Double, field2: A, field3: Swift.Int) + init(field1: Swift.Double, field2: A, field3: Swift.Int) - @objc init() + @objc override init() deinit } @@ -1398,9 +1398,9 @@ enum GenericFieldLayout { // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) var field3: Swift.Int - @objc init(field1: Swift.Double, field2: A, field3: Swift.Int) + init(field1: Swift.Double, field2: A, field3: Swift.Int) - @objc init() + @objc override init() deinit } @@ -1690,10 +1690,10 @@ enum GenericFieldLayout { var leading: Swift.Int // Field offset: 0x8 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483647) - var boxed: Swift.Int + var boxed: any SymbolTestsCore.GenericFieldLayout.Boxed // Field offset: 0x30 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483646) - var optionalBoxed: (Swift.String)? + var optionalBoxed: (any SymbolTestsCore.GenericFieldLayout.Boxed)? // Field offset: 0x58 // Type Layout: (size: 1, stride: 1, alignment: 1, extraInhabitantCount: 0) var trailing: Swift.Int8 @@ -1771,16 +1771,16 @@ enum GenericFieldLayout { var leading: Swift.Int // Field offset: 0x8 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var bareElement: SymbolTestsCore.ObjCOnlyElementProtocol + var bareElement: any SymbolTestsCore.ObjCOnlyElementProtocol // Field offset: 0x10 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var anchoredElement: __C.NSObject & SymbolTestsCore.ObjCOnlyElementProtocol + var anchoredElement: any __C.NSObject & SymbolTestsCore.ObjCOnlyElementProtocol // Field offset: 0x18 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483646) - var optionalElement: SymbolTestsCore.ObjCOnlyElementProtocol? + var optionalElement: (any SymbolTestsCore.ObjCOnlyElementProtocol)? // Field offset: 0x20 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - var composedElement: SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol + var composedElement: any SymbolTestsCore.DescriptorBackedSwiftProtocol & SymbolTestsCore.ObjCOnlyElementProtocol // Field offset: 0x30 // Type Layout: (size: 1, stride: 1, alignment: 1, extraInhabitantCount: 0) var trailing: Swift.Int8 @@ -1923,9 +1923,9 @@ enum GenericFieldLayout { // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) final var identifier: Swift.Int - @objc init(element: A, identifier: Swift.Int) + init(element: A, identifier: Swift.Int) - @objc init() + @objc override init() deinit } @@ -2245,18 +2245,18 @@ enum MetatypeUsage { var concreteMetatype: Swift.Int.Type // Field offset: 0x0 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var anyMetatype: Any.Type + var anyMetatype: any Any.Type // Field offset: 0x8 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - var protocolMetatype: SymbolTestsCore.Protocols.ProtocolTest.Type + var protocolMetatype: any SymbolTestsCore.Protocols.ProtocolTest.Type // Field offset: 0x18 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) - var anyObjectMetatype: Swift.AnyObject.Type + var anyObjectMetatype: any Swift.AnyObject.Type - init(concreteMetatype: Swift.Int.Type, anyMetatype: Any.Type, protocolMetatype: SymbolTestsCore.Protocols.ProtocolTest.Type, anyObjectMetatype: Swift.AnyObject.Type) + init(concreteMetatype: Swift.Int.Type, anyMetatype: any Any.Type, protocolMetatype: any SymbolTestsCore.Protocols.ProtocolTest.Type, anyObjectMetatype: any Swift.AnyObject.Type) } struct MetatypeFunctionTest { - func acceptProtocolMetatype(_: SymbolTestsCore.Protocols.ProtocolTest.Type) -> Swift.String + func acceptProtocolMetatype(_: any SymbolTestsCore.Protocols.ProtocolTest.Type) -> Swift.String func dynamicType(of: A) -> A.Type func acceptMetatype(_: A.Type) -> A.Type func returnMetatype() -> SymbolTestsCore.MetatypeUsage.MetatypeFunctionTest.Type @@ -2360,7 +2360,7 @@ enum ObjCClassWrapperFixtures { deinit } @objc(SymbolTestsCoreObjCBridgeWithProto) - class ObjCBridgeWithProto: __C.NSObject { + class ObjCBridgeWithProto: __C.NSObject, SymbolTestsCore.ObjCClassWrapperFixtures.ObjCProto { @objc func ping() @objc override init() @@ -2604,22 +2604,22 @@ enum ProtocolComposition { struct ProtocolCompositionFieldTest { // Field offset: 0x0 // Type Layout: (size: 48, stride: 48, alignment: 8, extraInhabitantCount: 2147483647) - var twoComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + var twoComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol // Field offset: 0x30 // Type Layout: (size: 56, stride: 56, alignment: 8, extraInhabitantCount: 2147483647) - var threeComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol + var threeComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol // Field offset: 0x68 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - var classBoundComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject + var classBoundComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject // Field offset: 0x78 // Type Layout: (size: 40, stride: 40, alignment: 8, extraInhabitantCount: 2147483647) - var sendableComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol + var sendableComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol - init(twoComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol, threeComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol, classBoundComposition: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject, sendableComposition: Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol) + init(twoComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol, threeComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol & SymbolTestsCore.ProtocolComposition.ComposeThirdProtocol, classBoundComposition: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & Swift.AnyObject, sendableComposition: any Swift.Sendable & SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol) } struct ProtocolCompositionFunctionTest { - func returnComposition() -> SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol - func acceptComposition(_: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol) + func returnComposition() -> any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol + func acceptComposition(_: any SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol & SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol) func genericCompositionParameter(_: A) where A: SymbolTestsCore.ProtocolComposition.ComposeFirstProtocol, A: SymbolTestsCore.ProtocolComposition.ComposeSecondProtocol } protocol ComposeFirstProtocol { @@ -3217,16 +3217,16 @@ enum WeakUnownedReferences { struct WeakExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - weak var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? - init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest?) + init(delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)?) } struct WeakCompositionExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 24, stride: 24, alignment: 8, extraInhabitantCount: 2147483647) - weak var delegate: (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)? - init(delegate: (SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)?) + init(delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest & SymbolTestsCore.WeakUnownedReferences.SecondaryDelegateTest)?) } struct WeakAnyObjectStructTest { // Field offset: 0x0 @@ -3238,35 +3238,35 @@ enum WeakUnownedReferences { struct WeakObjCExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) - weak var delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedObjCDelegateTest)? - init(delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest?) + init(delegate: (any SymbolTestsCore.WeakUnownedObjCDelegateTest)?) } struct UnownedObjCExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 1) - unowned var delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest + unowned var delegate: any SymbolTestsCore.WeakUnownedObjCDelegateTest - init(delegate: SymbolTestsCore.WeakUnownedObjCDelegateTest) + init(delegate: any SymbolTestsCore.WeakUnownedObjCDelegateTest) } struct UnownedExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - unowned var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + unowned var delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest - init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) + init(delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) } struct UnmanagedExistentialStructTest { // Field offset: 0x0 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - unowned(unsafe) var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest + unowned(unsafe) var delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest - init(delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) + init(delegate: any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest) } class WeakExistentialHolderTest { // Field offset: 0x10 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) - weak var delegate: SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest? + weak var delegate: (any SymbolTestsCore.WeakUnownedReferences.ReferenceDelegateTest)? // Field offset: 0x20 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) weak var parent: SymbolTestsCore.WeakUnownedReferences.ReferenceTargetTest? @@ -3323,6 +3323,21 @@ extension SymbolTestsCore.PrivateDoppelgangerProtocol { } +@objc protocol ObjCOnlyElementProtocol { + // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them. + @objc(identify) func identify() -> Swift.Int +} +extension SymbolTestsCore.ObjCClassWrapperFixtures { + @objc protocol ObjCProto { + // Taken from the conformer SymbolTestsCore.ObjCClassWrapperFixtures.ObjCBridgeWithProto. + @objc func ping() + } +} +@objc protocol WeakUnownedObjCDelegateTest { + // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them. + @objc(handle) func handle() +} + extension SymbolTestsCore.DefaultImplementationVariants.BasicDefaultProtocol { func withDefaultAndGeneric(_: A1) -> A1 func withDefault() -> Swift.String @@ -3495,7 +3510,7 @@ extension SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator: Sw typealias Failure = Swift.Never func next() async throws -> Self.Element? - func next(isolation: isolated Swift.Actor?) async throws(Self.Failure) -> Self.Element? + func next(isolation: isolated (any Swift.Actor)?) async throws(Self.Failure) -> Self.Element? } extension SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest: Swift.AsyncSequence { typealias AsyncIterator = SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest.AsyncIterator @@ -3506,15 +3521,15 @@ extension SymbolTestsCore.AsyncSequenceTests.AsyncSequenceTest: Swift.AsyncSeque } extension SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIterator: Swift.AsyncIteratorProtocol { typealias Element = Swift.String - typealias Failure = Swift.Error + typealias Failure = any Swift.Error func next() async throws -> Self.Element? - func next(isolation: isolated Swift.Actor?) async throws(Self.Failure) -> Self.Element? + func next(isolation: isolated (any Swift.Actor)?) async throws(Self.Failure) -> Self.Element? } extension SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest: Swift.AsyncSequence { typealias AsyncIterator = SymbolTestsCore.AsyncSequenceTests.ThrowingAsyncSequenceTest.AsyncIterator typealias Element = Swift.String - typealias Failure = Swift.Error + typealias Failure = any Swift.Error func makeAsyncIterator() -> Self.AsyncIterator } @@ -3523,7 +3538,7 @@ extension SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncItera typealias Failure = Swift.Never func next() async throws -> Self.Element? - func next(isolation: isolated Swift.Actor?) async throws(Self.Failure) -> Self.Element? + func next(isolation: isolated (any Swift.Actor)?) async throws(Self.Failure) -> Self.Element? } extension SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest: Swift.AsyncSequence { typealias AsyncIterator = SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest.AsyncIterator @@ -3533,34 +3548,34 @@ extension SymbolTestsCore.AsyncSequenceTests.GenericAsyncSequenceTest: Swift.Asy func makeAsyncIterator() -> Self.AsyncIterator } extension SymbolTestsCore.CodableTests.SynthesizedCodableTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.CodableTests.SynthesizedCodableTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.CodableTests.CustomCodableTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.CodableTests.CustomCodableTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.CodableTests.CodableClassTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.CodableTests.CodableClassTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.CodableTests.CodableEnumTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.CodableTests.CodableEnumTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.CodableTests.GenericCodableTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.CodableTests.GenericCodableTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.CodableTests.SynthesizedCodableTest.CodingKeys: Swift.CustomStringConvertible { var description: Swift.String { @@ -4117,7 +4132,7 @@ extension SymbolTestsCore.DiamondInheritance.DiamondImplementationTest: SymbolTe extension SymbolTestsCore.DiamondInheritance.DiamondImplementationTest: SymbolTestsCore.DiamondInheritance.DiamondBaseProtocol {} extension SymbolTestsCore.DistributedActors.DistributedActorTest: Distributed.DistributedActor { typealias ActorSystem = Distributed.LocalTestingDistributedActorSystem - typealias SerializationRequirement = Swift.Decodable & Swift.Encodable + typealias SerializationRequirement = any Swift.Decodable & Swift.Encodable var actorSystem: Self.ActorSystem { get @@ -4147,14 +4162,14 @@ extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Equatabl static func == (_: Self, _: Self) -> Swift.Bool } extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.DistributedActors.DistributedActorTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Distributed.DistributedActor { typealias ActorSystem = Distributed.LocalTestingDistributedActorSystem - typealias SerializationRequirement = Swift.Decodable & Swift.Encodable + typealias SerializationRequirement = any Swift.Decodable & Swift.Encodable var actorSystem: Self.ActorSystem { get @@ -4184,10 +4199,10 @@ extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.E static func == (_: Self, _: Self) -> Swift.Bool } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.Encodable { - func encode(to: Swift.Encoder) throws + func encode(to: any Swift.Encoder) throws } extension SymbolTestsCore.DistributedActors.GenericDistributedActorTest: Swift.Decodable { - init(from: Swift.Decoder) throws + init(from: any Swift.Decoder) throws } extension SymbolTestsCore.Enums.NoPayloadEnumTest: Swift.Equatable { static func == (_: Self, _: Self) -> Swift.Bool diff --git a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift index 8af50bab0..258e70fcb 100644 --- a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift @@ -4,6 +4,11 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +import SwiftPrinting +// Scoped: the module's `Error` component would shadow `Swift.Error` here. +import struct Semantic.SemanticString +import struct Semantic.FrozenSemanticString +import SwiftSectionTestingSupport /// The interface side of wrapped-property recovery for the two cases the /// same-image suite (`PropertyWrapperSynthesizedMemberTests`) cannot show: @@ -113,6 +118,10 @@ struct StrippedWrappedPropertyRenderingTests { } private func renderOfflineInterface() async throws -> String { + try await printOfflineInterface(marksCommentStructure: false).string + } + + private func printOfflineInterface(marksCommentStructure: Bool) async throws -> SemanticString { let products = try Self.compilationResult.get() let machOFile: MachOFile switch try File.loadFromFile(url: products.clientURL) { @@ -121,13 +130,25 @@ struct StrippedWrappedPropertyRenderingTests { case .fat(let fatFile): machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) } + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.marksCommentStructure = marksCommentStructure let configuration = SwiftInterfaceBuilderConfiguration( indexConfiguration: .init(showCImportedTypes: false, dependencySearchPaths: [.machOFile(path: products.kitURL.path), .systemDyldSharedCache]), - printConfiguration: .init() + printConfiguration: printConfiguration ) let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) try await builder.prepare() - return try await builder.printRoot().string + return try await builder.printRoot() + } + + /// The note on a property recovered from its backing storage is marked + /// like every other comment (evolution proposal `comment-structure`). + @Test func markingCommentStructureKeepsTheContract() async throws { + let marked = try await printOfflineInterface(marksCommentStructure: true).frozen() + let plain = try await printOfflineInterface(marksCommentStructure: false).frozen() + #expect(plain.string.contains("synthesized from the backing storage")) + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") } private func renderInProcessInterface() async throws -> String { diff --git a/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift b/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift index 9d8d5e583..075cf6141 100644 --- a/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/Swift64DeclarationShapeInterfaceTests.swift @@ -5,7 +5,8 @@ import MachOFoundation import MachOSwiftSection import SwiftPrinting import SwiftInterface -@testable import MachOTestingSupport +import Semantic +@testable import SwiftSectionTestingSupport /// The interface of the declaration shapes Swift 6.4 introduced (evolution /// proposal `borrow-accessors-and-suppressed-associated-types`). The expected @@ -15,9 +16,25 @@ import SwiftInterface struct Swift64DeclarationShapeInterfaceTests { /// The fixture is a handful of declarations, so each test builds its own. private func printedInterface(printConfiguration: SwiftDeclarationPrintConfiguration = .init()) async throws -> String { + try await semanticInterface(printConfiguration: printConfiguration).string + } + + private func semanticInterface(printConfiguration: SwiftDeclarationPrintConfiguration) async throws -> SemanticString { let builder = try SwiftInterfaceBuilder(configuration: SwiftInterfaceBuilderConfiguration(printConfiguration: printConfiguration), eventHandlers: [], in: try Swift64DeclarationShapesFixture.machOFile()) try await builder.prepare() - return try await builder.printRoot().string + return try await builder.printRoot() + } + + /// The note in place of an element the records keep no name for is + /// marked like every other comment (evolution proposal + /// `comment-structure`). + @Test func markingCommentStructureKeepsTheContract() async throws { + var markedConfiguration = SwiftDeclarationPrintConfiguration() + markedConfiguration.marksCommentStructure = true + let marked = try await semanticInterface(printConfiguration: markedConfiguration).frozen() + let plain = try await semanticInterface(printConfiguration: .init()).frozen() + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") } /// The lines of the block whose header line, trimmed, starts with diff --git a/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift new file mode 100644 index 000000000..b9b5423bb --- /dev/null +++ b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift @@ -0,0 +1,199 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDeclaration +import SwiftDeclarationRendering +import SwiftInterface +import Semantic +@testable import SwiftSectionTestingSupport + +/// The `@objc` protocols a Swift module declares, on the interface path +/// (evolution proposal `swift-declared-objc-protocols`): they have no +/// protocol descriptor, and used to be missing from the interface — only +/// their protocol extensions printed, as extensions of nothing declared. +/// +/// Holds `ExclusiveImageAccess` because the indexer registers an ancestor +/// resolver per image for the file leg. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct SwiftDeclaredObjCProtocolInterfaceTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private func interface(of machO: some MachOFieldLayoutRenderable) async throws -> String { + try await printInterface(of: machO, marksCommentStructure: false).string + } + + private func printInterface(of machO: some MachOFieldLayoutRenderable, marksCommentStructure: Bool) async throws -> SemanticString { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.indexConfiguration.dependencySearchPaths = try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths() + configuration.printConfiguration.marksCommentStructure = marksCommentStructure + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machO) + try await builder.prepare() + return try await builder.printRoot() + } + + /// The notes of an `@objc` protocol — its requirements' Swift names, a + /// requirement taken from a conformer — are marked like every other + /// comment (evolution proposal `comment-structure`). + @Test(arguments: SwiftDeclaredObjCProtocolsFixture.Variant.allCases) + func markingCommentStructureKeepsTheContract(variant: SwiftDeclaredObjCProtocolsFixture.Variant) async throws { + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(variant) + let marked = try await printInterface(of: machOFile, marksCommentStructure: true).frozen() + let plain = try await printInterface(of: machOFile, marksCommentStructure: false).frozen() + let violation = CommentStructureContract.violation(marked: marked, unmarked: plain) + #expect(violation == nil, "\(violation ?? "")") + } + + /// The block whose header line STARTS with `prefix`, through its closing + /// brace at the same indentation. + private func block(startingWith prefix: String, in interface: String) -> String? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[start...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[start...end].joined(separator: "\n") + } + + /// No class adopts it: every requirement is named from its selector by + /// the importer's rules, and pinned to it. + @Test func requirementsNamedFromSelectors() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let declaration = try #require(block(startingWith: "@objc protocol DerivedSelectors:", in: interface), "\(interface)") + for expectedLine in [ + "@objc protocol DerivedSelectors: __C.NSObject {", + " // Swift names follow the ClangImporter's rules for these selectors; the binary records no Swift names for them.", + " @objc(initWithIdentifier:) init!(identifier: Swift.String!)", + " @objc(nameFor:) func name(for: Any!) -> Swift.String!", + " @objc(teamNameFor:error:) func teamName(for: Swift.String!) throws -> Swift.String", + " @objc(hangPointsWithInput:error:) func hangPoints(input: __C.NSObject!) throws -> [Any]", + " @objc(perform:with:) func perform(_: Swift.String!, with: Any!)", + " @objc(tokenAndReturnError:) func token() throws -> Swift.String", + " @objc(isEnabled) var isEnabled: Swift.Bool {", + " @objc(objectAtIndexedSubscript:) subscript(_: Swift.Int) -> Any! {", + " @objc(makeDefault) static func makeDefault() -> __C.NSObject!", + " @objc(shared) static var shared: __C.NSObject! {", + " @objc(scrollTo:animated:) optional func scroll(to: Swift.Int, animated: Swift.Bool)", + " @objc(optionalCount) optional var optionalCount: Swift.Int {", + ] { + #expect(declaration.contains(expectedLine), "\(expectedLine)\n---\n\(declaration)") + } + } + + /// The protocol extension trails its protocol, as a Swift protocol's + /// does, instead of standing alone among the extensions. + @Test func protocolExtensionTrailsTheProtocol() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let declaration = try #require(block(startingWith: "@objc protocol DerivedSelectors:", in: interface), "\(interface)") + let trailingExtension = "\(declaration)\nextension \(Self.moduleName).DerivedSelectors {\n func describe() -> Swift.String\n}" + #expect(interface.contains(trailingExtension), "\(interface)") + #expect(interface.components(separatedBy: "extension \(Self.moduleName).DerivedSelectors {").count == 2, "\(interface)") + } + + /// Implemented by a class of the image: the member's own signature, + /// with the class it was taken from. + @Test func requirementsTakenFromConformers() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let sameNameRenamed = try #require(block(startingWith: "@objc(SameNameRenamed) protocol SameNameRenamed {", in: interface), "\(interface)") + #expect(sameNameRenamed.contains(" @objc func ping()"), "\(sameNameRenamed)") + #expect(sameNameRenamed.contains(" // Taken from the conformer \(Self.moduleName)."), "\(sameNameRenamed)") + #expect(!sameNameRenamed.contains("ClangImporter"), "\(sameNameRenamed)") + + let refined = try #require(block(startingWith: "@objc protocol RefinedProtocol: \(Self.moduleName).SameNameRenamed {", in: interface), "\(interface)") + #expect(refined.contains(" // Taken from the conformer \(Self.moduleName).ExtensionConformer.\n @objc func refine()"), "\(refined)") + + let internalProtocol = try #require(block(startingWith: "@objc protocol InternalProtocol {", in: interface), "\(interface)") + #expect(internalProtocol.contains(" // Taken from the conformer \(Self.moduleName).InternalConformer.\n @objc func internalRequirement()"), "\(internalProtocol)") + } + + /// Renamed to a name other than its Swift name: nothing pairs the + /// record with it, and the declaration says so. + @Test func unpairedRenamedProtocol() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let declaration = try #require(block(startingWith: "@objc protocol DifferentlyNamed {", in: interface), "\(interface)") + #expect(declaration.contains("No Objective-C protocol record pairs with this declaration"), "\(declaration)") + } + + /// File-private: its Swift name carries a private discriminator, which + /// the header leaves out, as a Swift protocol's does. + @Test func privateProtocolHeaderPrintsTheBareName() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + #expect(block(startingWith: "@objc protocol PrivateProtocol {", in: interface) != nil, "\(interface)") + #expect(!interface.contains("PrivateProtocol in _"), "\(interface)") + } + + /// A private protocol is ruled not exported by its name alone (evolution + /// proposal `export-verdict-without-local-symbols`): the exported-only + /// filter drops it, while the internal one, which nothing rules on, stays. + @Test(arguments: SwiftDeclaredObjCProtocolsFixture.Variant.allCases) + func exportedOnlyDropsThePrivateProtocol(variant: SwiftDeclaredObjCProtocolsFixture.Variant) async throws { + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(variant) + let unfiltered = try await interface(of: machOFile) + #expect(unfiltered.contains("@objc protocol PrivateProtocol {"), "\(unfiltered)") + + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.indexConfiguration.dependencySearchPaths = try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths() + configuration.printConfiguration.printExportedDeclarationsOnly = true + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) + try await builder.prepare() + let filtered = try await builder.printRoot().string + #expect(!filtered.contains("PrivateProtocol"), "\(filtered)") + #expect(!filtered.contains("privateRequirement"), "\(filtered)") + #expect(filtered.contains("@objc protocol InternalProtocol {"), "\(filtered)") + } + + /// Declared in a type: printed in an extension of the type. + @Test func nestedProtocolPrintsInAnExtensionOfItsParent() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let parentExtension = try #require(block(startingWith: "extension \(Self.moduleName).Outer {", in: interface), "\(interface)") + #expect(parentExtension.contains(" @objc protocol NestedProtocol {"), "\(parentExtension)") + #expect(parentExtension.contains(" @objc func nestedRequirement()"), "\(parentExtension)") + } + + /// The protocols another module declares — the kit's, whose records the + /// client holds copies of — are not declared here. + @Test func adoptedProtocolsOfAnotherModuleAreNotDeclared() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + #expect(!interface.contains("protocol KitObserver"), "\(interface)") + #expect(!interface.contains("protocol RenamedKitObserver"), "\(interface)") + } + + /// A class's header lists the Objective-C protocols its own data lists — + /// an extension of its own module's included — named in Swift: another + /// module's protocol renamed to its own name found through the + /// dependency closure, one renamed to another name left as it is, and + /// one a Swift conformance implies left out. + @Test func classHeadersListAdoptedObjCProtocols() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let kitModuleName = SwiftDeclaredObjCProtocolsFixture.kitModuleName + for expectedHeader in [ + "class Conformer: __C.NSObject, \(Self.moduleName).SameNameRenamed, __C.NSCopying {", + "class ExtensionConformer: __C.NSObject, \(Self.moduleName).RefinedProtocol {", + "class KitObserverConformer: __C.NSObject, \(kitModuleName).KitObserver, __C.KITRenamedObserver, \(kitModuleName).KitSameName {", + "class ImpliedConformer: __C.NSObject {", + ] { + #expect(interface.contains("\n\(expectedHeader)"), "\(expectedHeader)\n---\n\(interface)") + } + // The implied protocol's Swift conformance prints as before. + #expect(interface.contains("extension \(Self.moduleName).ImpliedConformer: \(Self.moduleName).CopyingRefinement {}"), "\(interface)") + } + + /// An extension of another module's class adopting one: its category's + /// protocol list, as an extension of its own. + @Test func categoryConformancePrintsAsAnExtension() async throws { + let interface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + #expect(interface.contains("\nextension __C.NSDateFormatter: \(Self.moduleName).SameNameRenamed {}"), "\(interface)") + } + + /// The in-process image prints the same declarations. + @Test func loadedImageMatchesTheFile() async throws { + let fileInterface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let imageInterface = try await interface(of: SwiftDeclaredObjCProtocolsFixture.loadedImage()) + for prefix in ["@objc protocol DerivedSelectors:", "@objc(SameNameRenamed) protocol SameNameRenamed {", "@objc protocol RefinedProtocol:", "@objc protocol InternalProtocol {", "extension \(Self.moduleName).Outer {", "class Conformer:", "class KitObserverConformer:"] { + let fileBlock = block(startingWith: prefix, in: fileInterface) + #expect(fileBlock != nil, "\(prefix)") + #expect(fileBlock == block(startingWith: prefix, in: imageInterface), "\(prefix)") + } + #expect(imageInterface.contains("\nextension __C.NSDateFormatter: \(Self.moduleName).SameNameRenamed {}"), "\(imageInterface)") + } +} diff --git a/Tests/SwiftInterfaceTests/SwiftInterfaceBuilderDependenciesTests.swift b/Tests/SwiftInterfaceTests/SwiftInterfaceBuilderDependenciesTests.swift index 31db42d7f..4b2841367 100644 --- a/Tests/SwiftInterfaceTests/SwiftInterfaceBuilderDependenciesTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftInterfaceBuilderDependenciesTests.swift @@ -1,10 +1,10 @@ import Foundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport import MachOKit import MachOKitExtensions import MachODependencies import Testing -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @testable import SwiftInterface /// Pins what `SwiftInterfaceBuilderDependencies` promises now that it is a diff --git a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift index edd0f1877..cdc194bc9 100644 --- a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift @@ -1,19 +1,20 @@ +@_spi(Internals) import MachOSymbols @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing import Foundation import Testing import MachOKit -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A `DemangledSymbol` stored in the declaration model must not keep the /// shared per-image symbol table alive. /// -/// `SymbolIndexStore` vends values that share one `[Symbol]` buffer, which +/// `SwiftSymbolIndexStore` vends values that share one `[Symbol]` buffer, which /// keeps each of the hundreds of thousands it produces at 32 bytes. Those /// values are meant to be dropped when the query result is; a few thousand of /// them are instead stored in the model (accessors, functions, deallocators) @@ -39,7 +40,7 @@ final class SymbolTableRetentionTests: MachOFileTests, @unchecked Sendable { try await builder.prepare() _ = try await builder.printRoot() - let storage = try #require(SymbolIndexStore.shared.storage(in: machOFile)) + let storage = try #require(SwiftSymbolIndexStore.shared.storage(in: machOFile)) let sharedTableRowCount = storage.symbolTable.rowCount // Otherwise the assertion below cannot distinguish a detached value // from a shared one. diff --git a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift index c193da626..beb9314b1 100644 --- a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift @@ -5,12 +5,12 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import SwiftDump @Suite(.serialized) diff --git a/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift new file mode 100644 index 000000000..e247f83c2 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift @@ -0,0 +1,210 @@ +import Foundation +import Testing +import MachOKit +import MachOKitExtensions +import MachOFoundation +import MachOSwiftSection +import SwiftDeclarationRendering +import SwiftInterface +@_spi(Internals) import SwiftSymbols +@testable import SwiftSectionTestingSupport + +/// Members whose implementation symbol the optimizer deleted while another of +/// their entry points survived (evolution proposal `thunk-only-objc-members`): +/// an `@objc` member whose body was inlined into its Objective-C thunk, and a +/// class initializer whose allocating entry point was inlined into its +/// callers. The interface built every member from its implementation symbol +/// and printed none of these; Xcode 27.2's `Xcode Service` lost 22 `@objc` +/// members and 9 initializers that way (issues #137 and #138). Each is now +/// built from the entry point the image kept. +/// +/// The unoptimized build of the same source is the independent truth: it +/// keeps every entry point, so whatever the optimized build prints must be +/// what the unoptimized one prints. +@Suite(.serialized, ExclusiveImageAccess(ThunkOnlyMemberFixture.moduleName)) +struct ThunkOnlyObjCMemberTests { + private static let typeQualifiedNamePrefix = ThunkOnlyMemberFixture.moduleName + "." + + /// The header lines of the blocks the fixture declares, each the start of + /// a line in the interface. + private static let blockHeaders = [ + "class ThunkOnlyWidget: ", + "class GenericThunkOnlyWidget<", + "class InitializingEntryOnlyHolder", + "extension __C.NSObject", + ] + + private func interface(of machO: some MachOFieldLayoutRenderable, printsMemberAddresses: Bool = false) async throws -> String { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.printMemberAddress = printsMemberAddresses + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machO) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The block whose header line STARTS with `prefix`, through its closing + /// brace at the same indentation. + private func block(startingWith prefix: String, in interface: String) -> String? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[start...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[start...end].joined(separator: "\n") + } + + /// The declaration lines of a block: every line after the header that is + /// not a comment, an accessor keyword, a closing brace or blank. + private func declarations(in block: String) -> [String] { + block.split(separator: "\n").dropFirst().compactMap { line in + let trimmedLine = line.trimmingCharacters(in: .whitespaces) + guard !trimmedLine.isEmpty, !trimmedLine.hasPrefix("//"), trimmedLine != "}", trimmedLine != "get", trimmedLine != "set" else { return nil } + return trimmedLine + } + } + + // MARK: - The premise + + /// What the optimized build lost: `isEqual(_:)` has no Swift entry point + /// beside its thunk, `init(values:)` no allocating entry point beside its + /// initializing one — and from Swift 6.4 no initializing entry point + /// either, only that entry point's function signature specialization. + /// Without this, the tests below could pass on a compiler that stopped + /// deleting the entry points. + @Test func optimizedBuildKeepsOnlyTheThunkOrTheInitializingEntryPoint() throws { + let machOFile = try ThunkOnlyMemberFixture.machOFile(.wholeModuleOptimized) + let symbolIndexStore = SwiftSymbolIndexStore.shared + let widgetName = Self.typeQualifiedNamePrefix + "ThunkOnlyWidget" + let functionNames = symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: false), for: widgetName, in: machOFile).map(\.name) + #expect(!functionNames.contains { $0.contains("7isEqual") }, "\(functionNames)") + let thunkNames = symbolIndexStore.objcThunkMemberSymbols(of: .function(inExtension: false, isStatic: false), for: widgetName, in: machOFile).map(\.name) + #expect(thunkNames.contains { $0.hasSuffix("7isEqualySbypSgFTo") }, "\(thunkNames)") + + let holderName = Self.typeQualifiedNamePrefix + "InitializingEntryOnlyHolder" + #expect(symbolIndexStore.memberSymbols(of: .allocator(inExtension: false), for: holderName, in: machOFile).isEmpty) + let initializingEntryPoints = symbolIndexStore.memberSymbols(of: .constructor(inExtension: false), for: holderName, in: machOFile) + let specializedInitializingEntryPoints = symbolIndexStore.specializedInitializerSymbols(of: .constructor(inExtension: false), for: holderName, in: machOFile) + #expect( + initializingEntryPoints.count == 1 || (initializingEntryPoints.isEmpty && !specializedInitializingEntryPoints.isEmpty), + "\(initializingEntryPoints.map(\.name)) \(specializedInitializingEntryPoints.map(\.name))" + ) + } + + /// The thunk index holds the thunk's own symbol, and nothing it holds is + /// a member symbol of its own: the unoptimized build files `isEqual(_:)` + /// in the member index (its Swift entry point) and in the thunk index + /// (its thunk), each under its own name. + @Test func thunkIndexHoldsTheThunksOwnSymbol() throws { + let machOFile = try ThunkOnlyMemberFixture.machOFile(.unoptimized) + let symbolIndexStore = SwiftSymbolIndexStore.shared + let widgetName = Self.typeQualifiedNamePrefix + "ThunkOnlyWidget" + let implementationNames = symbolIndexStore.memberSymbols(of: .function(inExtension: false, isStatic: false), for: widgetName, in: machOFile).map(\.name) + let thunkNames = symbolIndexStore.objcThunkMemberSymbols(of: .function(inExtension: false, isStatic: false), for: widgetName, in: machOFile).map(\.name) + let implementationName = try #require(implementationNames.first { $0.hasSuffix("7isEqualySbypSgF") }, "\(implementationNames)") + #expect(thunkNames.contains(implementationName + "To"), "\(thunkNames)") + #expect(!implementationNames.contains { $0.hasSuffix("To") }, "\(implementationNames)") + #expect(thunkNames.allSatisfy { $0.hasSuffix("To") }, "\(thunkNames)") + } + + // MARK: - The interface + + /// Every block the fixture declares prints the same declarations from + /// both builds. The order may differ — an unoptimized class gives its + /// ObjC overrides vtable slots, which print first — so the declarations + /// compare as sets. + @Test(arguments: blockHeaders) + func optimizedBuildDeclaresWhatTheUnoptimizedBuildDeclares(blockHeader: String) async throws { + let unoptimizedInterface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(.unoptimized)) + let optimizedInterface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(.wholeModuleOptimized)) + let unoptimizedBlock = try #require(block(startingWith: blockHeader, in: unoptimizedInterface), "\(unoptimizedInterface)") + let optimizedBlock = try #require(block(startingWith: blockHeader, in: optimizedInterface), "\(optimizedInterface)") + #expect(Set(declarations(in: optimizedBlock)) == Set(declarations(in: unoptimizedBlock)), "unoptimized:\n\(unoptimizedBlock)\n\noptimized:\n\(optimizedBlock)") + } + + /// The members as issue #137 expects them: `@objc`, and `override` where + /// the ObjC method table ties the thunk to an ancestor's selector. + @Test func thunkOnlyMembersPrintWithTheirObjCFacts() async throws { + let optimizedInterface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(.wholeModuleOptimized)) + let widgetBlock = try #require(block(startingWith: "class ThunkOnlyWidget: ", in: optimizedInterface), "\(optimizedInterface)") + let widgetDeclarations = declarations(in: widgetBlock) + #expect(widgetDeclarations.contains("@objc override init()"), "\(widgetBlock)") + #expect(widgetDeclarations.contains("@objc override func isEqual(_: Any?) -> Swift.Bool"), "\(widgetBlock)") + #expect(widgetDeclarations.contains("@objc override var description: Swift.String {"), "\(widgetBlock)") + #expect(widgetDeclarations.contains("@objc func handleTick(_: Any?)"), "\(widgetBlock)") + #expect(widgetDeclarations.contains("@objc func handleExtensionTick(_: Any?)"), "\(widgetBlock)") + + // No static class object: the ObjC method table is the template in the + // generic metadata pattern (evolution proposal + // `objc-classes-without-class-objects`), which ties the thunks to + // NSObject's selectors as for the class above. + let genericBlock = try #require(block(startingWith: "class GenericThunkOnlyWidget<", in: optimizedInterface), "\(optimizedInterface)") + let genericDeclarations = declarations(in: genericBlock) + #expect(genericDeclarations.contains("@objc override var description: Swift.String {"), "\(genericBlock)") + #expect(genericDeclarations.contains("@objc override init()"), "\(genericBlock)") + #expect(genericDeclarations.contains("@objc func handleTick(_: Any?)"), "\(genericBlock)") + + let holderBlock = try #require(block(startingWith: "class InitializingEntryOnlyHolder", in: optimizedInterface), "\(optimizedInterface)") + #expect(declarations(in: holderBlock).contains("init(values: [Swift.String])"), "\(holderBlock)") + + let extensionBlock = try #require(block(startingWith: "extension __C.NSObject", in: optimizedInterface), "\(optimizedInterface)") + #expect(declarations(in: extensionBlock).contains("@objc func thunkOnlyFixtureHook()"), "\(extensionBlock)") + } + + /// Only an initializer that has an `@objc` thunk of its own is `@objc`. + /// An initializer's thunk names no member to match by, and every + /// initializer of the class used to get the attribute as soon as one had a + /// thunk: `init(tags:)` printed `@objc` beside `@objc override init()`, as + /// `MenuBarLabelHostingView.init(rootView:)` did in Xcode Service. + @Test(arguments: ThunkOnlyMemberFixture.Variant.allCases) + func onlyAnInitializerWithAnObjCThunkIsObjC(variant: ThunkOnlyMemberFixture.Variant) async throws { + let interface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(variant)) + let widgetBlock = try #require(block(startingWith: "class ThunkOnlyWidget: ", in: interface), "\(interface)") + let widgetDeclarations = declarations(in: widgetBlock) + #expect(widgetDeclarations.contains("init(tags: [Swift.String])"), "\(widgetBlock)") + #expect(widgetDeclarations.contains("@objc override init()"), "\(widgetBlock)") + } + + /// Only the overload that has an `@objc` thunk of its own is `@objc`: + /// overloads share a member name, and the name alone gave the attribute + /// to `handleTick(count:)` beside `@objc func handleTick(_:)`. + @Test(arguments: ThunkOnlyMemberFixture.Variant.allCases) + func onlyAnOverloadWithAnObjCThunkIsObjC(variant: ThunkOnlyMemberFixture.Variant) async throws { + let interface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(variant)) + let widgetBlock = try #require(block(startingWith: "class ThunkOnlyWidget: ", in: interface), "\(interface)") + let widgetDeclarations = declarations(in: widgetBlock) + #expect(widgetDeclarations.contains("@objc func handleTick(_: Any?)"), "\(widgetBlock)") + #expect(widgetDeclarations.contains { $0.hasPrefix("func handleTick(count: Swift.Int) -> Swift.Int") || $0.hasPrefix("final func handleTick(count: Swift.Int) -> Swift.Int") }, "\(widgetBlock)") + } + + /// A member built from its thunk is located at the thunk, the only code it + /// has; an initializer built from its initializing entry point, there, or + /// at that entry point's specialization when only the specialization is + /// left. + @Test func standInMembersPrintTheAddressOfTheEntryPointTheImageKept() async throws { + let machOFile = try ThunkOnlyMemberFixture.machOFile(.wholeModuleOptimized) + let symbolIndexStore = SwiftSymbolIndexStore.shared + let widgetName = Self.typeQualifiedNamePrefix + "ThunkOnlyWidget" + let thunkSymbol = try #require(symbolIndexStore.objcThunkMemberSymbols(of: .function(inExtension: false, isStatic: false), for: widgetName, in: machOFile).first { $0.name.hasSuffix("7isEqualySbypSgFTo") }) + let holderName = Self.typeQualifiedNamePrefix + "InitializingEntryOnlyHolder" + let initializerSymbol = try #require( + symbolIndexStore.memberSymbols(of: .constructor(inExtension: false), for: holderName, in: machOFile).first + ?? symbolIndexStore.specializedInitializerSymbols(of: .constructor(inExtension: false), for: holderName, in: machOFile).first + ) + + let optimizedInterface = try await interface(of: machOFile, printsMemberAddresses: true) + let widgetBlock = try #require(block(startingWith: "class ThunkOnlyWidget: ", in: optimizedInterface), "\(optimizedInterface)") + #expect(widgetBlock.contains("// Address: 0x\(machOFile.addressString(forOffset: thunkSymbol.offset))\n @objc override func isEqual("), "\(widgetBlock)") + let holderBlock = try #require(block(startingWith: "class InitializingEntryOnlyHolder", in: optimizedInterface), "\(optimizedInterface)") + #expect(holderBlock.contains("// Address: 0x\(machOFile.addressString(forOffset: initializerSymbol.offset))\n init(values: [Swift.String])"), "\(holderBlock)") + } + + /// RuntimeViewer's path: the optimized image loaded into the process and + /// read through `MachOImage` prints what the file prints. + @Test(arguments: blockHeaders) + func optimizedImageInProcessDeclaresWhatTheFileDeclares(blockHeader: String) async throws { + let fileInterface = try await interface(of: try ThunkOnlyMemberFixture.machOFile(.wholeModuleOptimized)) + let imageInterface = try await interface(of: try ThunkOnlyMemberFixture.loadedOptimizedImage()) + let fileBlock = try #require(block(startingWith: blockHeader, in: fileInterface), "\(fileInterface)") + let imageBlock = try #require(block(startingWith: blockHeader, in: imageInterface), "\(imageInterface)") + #expect(Set(declarations(in: imageBlock)) == Set(declarations(in: fileBlock)), "file:\n\(fileBlock)\n\nimage:\n\(imageBlock)") + } +} diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift new file mode 100644 index 000000000..30c7a4e3f --- /dev/null +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -0,0 +1,112 @@ +import Foundation +import Testing +import MachOKit +import SwiftDiffing +import SwiftInterface +@testable import SwiftSectionTestingSupport + +/// Telling a declaration a version cannot show from one that is gone +/// (evolution proposal `evolution-unobservable-presence`), over +/// `UnobservablePresenceFixture`'s three compiled versions, the middle one +/// stripped of its local symbols. +@Suite(.serialized) +struct UnobservablePresenceTests { + private static let panelName = "\(UnobservablePresenceFixture.moduleName).Panel" + + private func snapshots() async throws -> [ABISnapshot] { + var snapshots: [ABISnapshot] = [] + for machOFile in try UnobservablePresenceFixture.machOFiles() { + let builder = SwiftDiffableInterfaceBuilder(in: machOFile) + try await builder.prepare() + snapshots.append(builder.snapshot()) + } + return snapshots + } + + private func panelMembers(in snapshot: ABISnapshot) throws -> [MemberRecord] { + try #require(snapshot.types.first { $0.name == Self.panelName }).members + } + + // MARK: - Snapshot facts + + @Test("a snapshot records whether its image keeps local Swift symbols") + func snapshotsRecordLocalSwiftSymbols() async throws { + let hasLocalSwiftSymbols = try await snapshots().map(\.hasLocalSwiftSymbols) + #expect(hasLocalSwiftSymbols == [true, false, true]) + } + + @Test("a snapshot records each symbol-backed member's export verdict") + func snapshotsRecordExportVerdicts() async throws { + let members = try panelMembers(in: try await snapshots()[0]) + let layout = try #require(members.first { $0.kind == .function && $0.signature.contains(".layout()") }) + let render = try #require(members.first { $0.kind == .function && $0.signature.contains(".render()") }) + let title = try #require(members.first { $0.kind == .field }) + #expect(layout.isExported == false) + #expect(render.isExported == true) + // A stored field is read from the field descriptor, not a symbol. + #expect(title.isExported == nil) + } + + @Test("the stripped version shows the public members and none of the internal ones") + func strippedVersionHidesInternalMembers() async throws { + let signatures = try panelMembers(in: try await snapshots()[UnobservablePresenceFixture.strippedVersionIndex]).map(\.signature) + #expect(signatures.contains { $0.contains(".render()") }) + #expect(!signatures.contains { $0.contains(".layout()") }) + } + + // MARK: - Annotated evolution interface + + private func interfaceLines() async throws -> [String] { + let builder = try AnySwiftEvolutionInterfaceBuilder( + versions: try UnobservablePresenceFixture.machOFiles(), + labels: UnobservablePresenceFixture.labels, + availabilityAnnotationPlatform: "macOS" + ) + try await builder.prepare() + return try await builder.printAnnotatedInterface().string.components(separatedBy: "\n") + } + + private func lineIndex(containing fragment: String, in lines: [String]) throws -> Int { + try #require(lines.firstIndex { $0.contains(fragment) }, "no line contains \(fragment)") + } + + @Test("the legend names the version without local Swift symbols") + func legendNamesTheStrippedVersion() async throws { + let lines = try await interfaceLines() + #expect(lines.contains { $0.hasPrefix("// 2.0 carries no local Swift symbols") }) + } + + @Test("an internal member present on both sides of the stripped version is inferred present there") + func internalMemberIsInferredPresent() async throws { + let lines = try await interfaceLines() + #expect(lines[try lineIndex(containing: "func layout()", in: lines)].contains("// [●◍●] inferred present in 2.0")) + } + + @Test("an internal member's removal and addition are placed between the versions that saw them, without @available") + func internalChangesArePlacedBetweenObservations() async throws { + let lines = try await interfaceLines() + let removedIndex = try lineIndex(containing: "func legacyLayout()", in: lines) + let addedIndex = try lineIndex(containing: "func freshLayout()", in: lines) + #expect(lines[removedIndex].contains("// [●◌○] removed between 1.0 and 3.0")) + #expect(lines[addedIndex].contains("// [○◌●] added between 1.0 and 3.0")) + #expect(!lines[removedIndex - 1].contains("@available")) + #expect(!lines[addedIndex - 1].contains("@available")) + } + + @Test("a public member's removal stays exact in the stripped version") + func publicRemovalStaysExact() async throws { + let lines = try await interfaceLines() + let retiredIndex = try lineIndex(containing: "func retiredRender()", in: lines) + #expect(lines[retiredIndex].contains("// [●○○] removed in 2.0")) + #expect(lines[retiredIndex - 1].contains("@available(macOS, obsoleted: 2.0)")) + } + + @Test("an extension of internal members alone is inferred present, its members with it") + func internalExtensionIsInferredPresent() async throws { + let lines = try await interfaceLines() + #expect(lines[try lineIndex(containing: "extension Swift.Int", in: lines)].contains("// [●◍●] inferred present in 2.0")) + // The container's annotation tells the member's story, as it does for + // the members of an added or removed container. + #expect(!lines[try lineIndex(containing: "func panelScale()", in: lines)].contains("// [")) + } +} diff --git a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift index 647b8042a..6436c5301 100644 --- a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift +++ b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift @@ -8,8 +8,8 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A marked print (`SwiftDeclarationPrintConfiguration.marksOptionalContent`), /// projected to a configuration, reads byte for byte as printing with that @@ -52,6 +52,8 @@ final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unc configuration.printTypeLayout = options.contains(.printTypeLayout) configuration.printEnumLayout = options.contains(.printEnumLayout) configuration.infersObjCOverridesFromSelectorNames = options.contains(.infersObjCOverridesFromSelectorNames) + configuration.printExportedDeclarationsOnly = options.contains(.printExportedDeclarationsOnly) + configuration.expandsMacros = options.contains(.expandsMacros) return configuration } @@ -68,7 +70,9 @@ final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unc } /// Prints every declaration marked and plainly under every combination, - /// and describes the first few whose projection differs. + /// and describes the first few whose projection differs. Every printer + /// carries the same export filter scope, as a host printing one + /// declaration at a time installs it. private static func mismatches( in machO: MachO, optionCombinations: [Set] @@ -82,6 +86,9 @@ final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unc let plainPrinters = optionCombinations.map { options in (options, configuration(enabling: options), makePrinter(configuration(enabling: options), resolvesOpaqueTypes: options.contains(.opaqueTypeResolution), in: machO)) } + for printer in [markedPrinter] + plainPrinters.map(\.2) { + printer.installExportFilterScope(types: indexer.allTypeDefinitions.values, protocols: indexer.allProtocolDefinitions.values) + } typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString var printings: [(label: String, print: Printing)] = [] @@ -130,4 +137,77 @@ final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unc #expect(result.checkedDeclarationCount > 100) #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") } + + // MARK: - Attached macros + + /// The `@Observable` folding (evolution proposal + /// `observable-macro-folding`): marked, a class the macro expanded prints + /// both forms — the attribute and the declared properties visible only + /// while `expandsMacros` is off, the registrar, the storage, the computed + /// properties, the generated methods and conformance only while it is on + /// — and projects to either print, the exported-only filter and the + /// comments the members carry included. + @Test(arguments: ObservableMacroFixture.Variant.allCases) + func observableMacroFixturePrintsProjectToEveryConfiguration(variant: ObservableMacroFixture.Variant) async throws { + let result = try await Self.mismatches( + in: try await ObservableMacroFixture.machOFile(variant), + optionCombinations: Self.optionCombinations(varying: [.expandsMacros, .printExportedDeclarationsOnly, .printMemberAddress, .printVTableOffset, .printFieldOffset]) + ) + #expect(result.checkedDeclarationCount > 10) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + @Test func observableMacroFixtureInProcessPrintsProjectToEveryConfiguration() async throws { + let result = try await Self.mismatches( + in: try await ObservableMacroFixture.loadedImage(), + optionCombinations: Self.optionCombinations(varying: [.expandsMacros, .printExportedDeclarationsOnly, .printMemberAddress, .printVTableOffset, .printFieldOffset]) + ) + #expect(result.checkedDeclarationCount > 10) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + // MARK: - The exported-only filter + + /// The exported-only filter over `internal` declarations, which + /// `SymbolTestsCore` exports (evolution proposal + /// `exported-only-marking-mode`): a definition, member, stored property + /// or extension the filter leaves out is marked instead, and the + /// separators and line breaks around it go with it. `ExportedOnlyFixture` + /// carries the bodies whose last line break only the filter decides — + /// nested types kept, everything after them left out. + @Test func exportedOnlyFixturePrintsProjectToTheFilterBothWays() async throws { + let result = try await Self.mismatches(in: ExportedOnlyFixture.machOFile(), optionCombinations: Self.optionCombinations(varying: [.printExportedDeclarationsOnly])) + #expect(result.checkedDeclarationCount > 20) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + /// The whole interface, `printRoot()`, which also leaves out globals and + /// installs the export filter scope by itself. + @Test func exportedOnlyFixtureRootPrintProjectsToTheFilterBothWays() async throws { + let machOFile = try ExportedOnlyFixture.machOFile() + var markedConfiguration = SwiftDeclarationPrintConfiguration() + markedConfiguration.marksOptionalContent = true + let separated = try await Self.rootPrint(of: machOFile, configuration: markedConfiguration).frozen().separatingVisibilityRegions() + + var plainPrints: [FrozenSemanticString] = [] + for printsExportedDeclarationsOnly in [false, true] { + var plainConfiguration = SwiftDeclarationPrintConfiguration() + plainConfiguration.printExportedDeclarationsOnly = printsExportedDeclarationsOnly + let expected = try await Self.rootPrint(of: machOFile, configuration: plainConfiguration).frozen() + let projected = separated.regions.projection(of: separated.text) { + plainConfiguration.isVisibilityOptionEnabled($0, resolvesOpaqueTypes: false) + }.text + #expect(projected == expected, "printExportedDeclarationsOnly \(printsExportedDeclarationsOnly):\n\(projected.string)\n--- expected ---\n\(expected.string)") + plainPrints.append(expected) + } + // Not vacuous: the filter leaves something out at the top level. + #expect(plainPrints[0].string.contains("func internalGlobal()")) + #expect(!plainPrints[1].string.contains("func internalGlobal()")) + } + + private static func rootPrint(of machOFile: MachOFile, configuration: SwiftDeclarationPrintConfiguration) async throws -> SemanticString { + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: configuration), eventHandlers: [], in: machOFile) + try await builder.prepare() + return try await builder.printRoot() + } } diff --git a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift index 458da3667..06ad5da95 100644 --- a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift @@ -6,7 +6,7 @@ import MachOSwiftSection import SwiftPrinting import SwiftInterface import SwiftDeclarationRendering -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// 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 diff --git a/Tests/SwiftLayoutTests/AssociatedTypeAndConstrainedExistentialLayoutTests.swift b/Tests/SwiftLayoutTests/AssociatedTypeAndConstrainedExistentialLayoutTests.swift index 5e1af8c42..22cd9c75f 100644 --- a/Tests/SwiftLayoutTests/AssociatedTypeAndConstrainedExistentialLayoutTests.swift +++ b/Tests/SwiftLayoutTests/AssociatedTypeAndConstrainedExistentialLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates the three resolution paths added on top of the generic-instantiation diff --git a/Tests/SwiftLayoutTests/BorrowLayoutTests.swift b/Tests/SwiftLayoutTests/BorrowLayoutTests.swift index 3983deb31..e91b2b8e2 100644 --- a/Tests/SwiftLayoutTests/BorrowLayoutTests.swift +++ b/Tests/SwiftLayoutTests/BorrowLayoutTests.swift @@ -4,8 +4,8 @@ import MachOKit import Demangling @testable import MachOSwiftSection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// `Builtin.Borrow` (Swift 6.4, the storage behind `Swift.Ref`) is /// laid out inline like its referent unless the referent is larger than four diff --git a/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift index 279663866..f9f836e36 100644 --- a/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift +++ b/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift @@ -5,7 +5,7 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -import MachOTestingSupport +import SwiftSectionTestingSupport import Demangling /// Layouts of instantiations a `GenericArgumentBinding` describes — an diff --git a/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift b/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift index 48f82f1c8..e486c6641 100644 --- a/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift +++ b/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Validates that `__swift5_builtin` `BuiltinTypeDescriptor` records back the /// layouts of types the structural engine cannot derive — multi-payload enums diff --git a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift index 573abd833..e9a0ccf37 100644 --- a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift +++ b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift @@ -5,7 +5,7 @@ import MachOFoundation import Demangling @testable import MachOSwiftSection @testable import SwiftLayout -import MachOFixtureSupport +import SwiftSectionFixtureSupport /// Where the archived-cache-gated suite below finds its cache. A separate /// type on purpose: a `@Suite(.enabled(if:))` condition that reads a static diff --git a/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift b/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift index e2cea3526..411d3ae95 100644 --- a/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates the class-bound generic parameter path: a parameter constrained diff --git a/Tests/SwiftLayoutTests/DependencyClosureLayoutTests.swift b/Tests/SwiftLayoutTests/DependencyClosureLayoutTests.swift index 3c60b5474..dc9f0fde3 100644 --- a/Tests/SwiftLayoutTests/DependencyClosureLayoutTests.swift +++ b/Tests/SwiftLayoutTests/DependencyClosureLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Validates the dependency-closure phase: field types, superclasses and /// protocols that live in *other* images now resolve, closing the cross-module diff --git a/Tests/MachODependenciesTests/DependencyClosureTests.swift b/Tests/SwiftLayoutTests/DependencyClosureTests.swift similarity index 99% rename from Tests/MachODependenciesTests/DependencyClosureTests.swift rename to Tests/SwiftLayoutTests/DependencyClosureTests.swift index 36e561a40..56fd12202 100644 --- a/Tests/MachODependenciesTests/DependencyClosureTests.swift +++ b/Tests/SwiftLayoutTests/DependencyClosureTests.swift @@ -1,10 +1,10 @@ import Foundation -import MachOFixtureSupport +import SwiftSectionFixtureSupport import MachOKit import MachOKitExtensions import Testing -@testable import MachODependencies -@testable import MachOTestingSupport +import MachODependencies +@testable import SwiftSectionTestingSupport /// Covers the traversal contract of `DependencyClosure` on the /// `SymbolTestsCore` fixture, whose load commands mix every shape the diff --git a/Tests/SwiftLayoutTests/EdgeTypeKindLayoutTests.swift b/Tests/SwiftLayoutTests/EdgeTypeKindLayoutTests.swift index 87119f71a..b3753f94c 100644 --- a/Tests/SwiftLayoutTests/EdgeTypeKindLayoutTests.swift +++ b/Tests/SwiftLayoutTests/EdgeTypeKindLayoutTests.swift @@ -4,8 +4,8 @@ import MachOKit import Demangling @testable import MachOSwiftSection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Covers the edge function-reference type kinds the resolver now models as a /// single pointer: C function pointers (`@convention(c)`/`@convention(thin)`) diff --git a/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift b/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift index d459b505d..971efa29c 100644 --- a/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Pins the exact field-offset vectors the existential and default-actor layout /// support must produce, with literal expected values, so a regression in the diff --git a/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift index 9fb196420..aa0b3f5c7 100644 --- a/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift @@ -5,7 +5,7 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -import MachOTestingSupport +import SwiftSectionTestingSupport /// An instantiation of a type declared in a constrained extension names its /// context as an extension: `DepthOuter.ConstrainedInner` diff --git a/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift b/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift index 684a14b1d..5949a6991 100644 --- a/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A C-imported (foreign) struct's Swift field records do not describe its /// real C layout — bitfields and padding are invisible to reflection — so the diff --git a/Tests/SwiftLayoutTests/GenericInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/GenericInstantiationLayoutTests.swift index 924510c0a..0df20063a 100644 --- a/Tests/SwiftLayoutTests/GenericInstantiationLayoutTests.swift +++ b/Tests/SwiftLayoutTests/GenericInstantiationLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates concrete bound-generic field substitution: a non-generic holder diff --git a/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift b/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift index ae5e420c9..437044af0 100644 --- a/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift +++ b/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A generic multi-payload enum whose layout is argument-independent is laid /// out **statically with the spare-bits strategy** — the compiler bakes the diff --git a/Tests/SwiftLayoutTests/ImageUniverseLazyFoldingTests.swift b/Tests/SwiftLayoutTests/ImageUniverseLazyFoldingTests.swift new file mode 100644 index 000000000..f6cf97299 --- /dev/null +++ b/Tests/SwiftLayoutTests/ImageUniverseLazyFoldingTests.swift @@ -0,0 +1,85 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import Demangling +@testable import SwiftLayout +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// Pins what a layout lookup builds (evolution proposal +/// `machofile-performance`): a lookup folds images into the indexes of its +/// own kind only, an image builds an index the first time it is read, and +/// every universe that folds an image in shares one reference to it. +/// +/// Before, folding a dependency built all seven of its indexes, so the type +/// lookups that resolve field types also read every passed dependency's +/// Objective-C protocol list — 2.4 of the 12 seconds the dependency indexes +/// of SwiftUI cost — and each universe built its own copy of an image's +/// indexes. +@Suite +final class ImageUniverseLazyFoldingTests: MachOFileTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + /// A type defined nowhere folds every image into the type index and + /// nothing into the others. + @Test func typeLookupsFoldOnlyTheTypeIndexes() throws { + let universe = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache]) + try #require(universe.dependencyImageCount > 0, "the closure must collect dependency images") + + #expect(universe.resolveType(byQualifiedTypeName: "NoSuchModule.NoSuchType") == nil) + + #expect(universe.foldedImageCount(for: .types) == universe.dependencyImageCount + 1) + #expect(universe.foldedImageCount(for: .protocols) == 0) + #expect(universe.foldedImageCount(for: .objCClasses) == 0) + #expect(universe.foldedImageCount(for: .associatedTypeWitnesses) == 0) + } + + /// A member of the stand-in for an unbound class-bound parameter is + /// answered without folding anything: no image records a conformance of + /// `Swift.AnyObject`. Asked like any other conforming type, the one such + /// member SwiftUI's layouts meet folded all 552 images of its closure + /// into the witness index, to answer `nil` all the same. + @Test func aWitnessOfTheClassBoundPlaceholderFoldsNothing() throws { + let universe = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache]) + try #require(universe.dependencyImageCount > 0, "the closure must collect dependency images") + + let placeholderName = try #require(NodeTypeNaming.nominalQualifiedName(of: GenericArgumentEnvironment.classBoundParameterPlaceholderNode())) + #expect(placeholderName == GenericArgumentEnvironment.classBoundParameterPlaceholderQualifiedName) + + #expect(universe.resolveAssociatedTypeWitness(conformingName: placeholderName, protocolName: "Swift.IteratorProtocol", associatedTypeName: "Element") == nil) + #expect(universe.foldedImageCount(for: .associatedTypeWitnesses) == 0) + + // Every other conforming type folds images in until it resolves. + #expect(universe.resolveAssociatedTypeWitness(conformingName: "Swift.IndexingIterator", protocolName: "Swift.IteratorProtocol", associatedTypeName: "Element") != nil) + #expect(universe.foldedImageCount(for: .associatedTypeWitnesses) > 1) + } + + /// Reading one index builds that index alone. Asked of a reference of + /// its own, so no other test's lookups can have built anything on it. + @Test func readingAnIndexBuildsOnlyThatIndex() throws { + let reference = ImageReference(indexingLazily: machOFile) + #expect(reference.builtIndexNamesForTesting.isEmpty) + + #expect(!reference.typeDescriptorsByQualifiedName.isEmpty) + #expect(reference.builtIndexNamesForTesting == ["typeDescriptors"]) + + _ = reference.protocolClassConstraintsByQualifiedName + #expect(reference.builtIndexNamesForTesting == ["typeDescriptors", "protocolClassConstraints"]) + } + + /// Two universes over one root share the root's reference and the + /// reference of every dependency both fold in. + @Test func universesShareEachImagesReference() throws { + let firstUniverse = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache]) + let secondUniverse = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache]) + #expect(firstUniverse.rootImage === secondUniverse.rootImage) + + let firstResolution = try #require(firstUniverse.resolveType(byQualifiedTypeName: "Swift.Int")) + let secondResolution = try #require(secondUniverse.resolveType(byQualifiedTypeName: "Swift.Int")) + #expect(firstResolution.image === secondResolution.image) + #expect(firstResolution.image !== firstUniverse.rootImage) + } +} diff --git a/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift b/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift index ce9a90280..164f0de6c 100644 --- a/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift +++ b/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates two extensions made after the class-bound-parameter phase: diff --git a/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift b/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift index 85dd63a35..f3922fe78 100644 --- a/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift +++ b/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Validates the structural multi-payload enum path (the fallback reached when no /// `__swift5_builtin` whole-type descriptor exists). The resolver prefers the diff --git a/Tests/SwiftLayoutTests/NestedParentArgumentAndObjCProtocolLayoutTests.swift b/Tests/SwiftLayoutTests/NestedParentArgumentAndObjCProtocolLayoutTests.swift index 988da0370..34e535edd 100644 --- a/Tests/SwiftLayoutTests/NestedParentArgumentAndObjCProtocolLayoutTests.swift +++ b/Tests/SwiftLayoutTests/NestedParentArgumentAndObjCProtocolLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates the two resolution paths added on top of phase 7: nested types diff --git a/Tests/SwiftLayoutTests/ObjCAncestorLayoutTests.swift b/Tests/SwiftLayoutTests/ObjCAncestorLayoutTests.swift index 0e3936765..fc9aae8de 100644 --- a/Tests/SwiftLayoutTests/ObjCAncestorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ObjCAncestorLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Validates phase 4: a Swift class whose ancestor is an Objective-C class /// (`NSObject`) has no Swift superclass descriptor, so its first stored property diff --git a/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift b/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift index 1f141ee07..d0feba5c9 100644 --- a/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A statically-emitted Swift subclass of an ObjC class does **not** start its /// fields at the ancestor's raw instance size: the compiler lays the ivars diff --git a/Tests/SwiftLayoutTests/ObjCProtocolExistentialTests.swift b/Tests/SwiftLayoutTests/ObjCProtocolExistentialTests.swift index fd568cbf7..773889728 100644 --- a/Tests/SwiftLayoutTests/ObjCProtocolExistentialTests.swift +++ b/Tests/SwiftLayoutTests/ObjCProtocolExistentialTests.swift @@ -5,8 +5,8 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftLayout @testable import SwiftInspection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Covers existentials over imported Objective-C protocols (`any NSCopying`), /// which have no Swift protocol descriptor. An ObjC protocol is always diff --git a/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift b/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift index 23bda9c40..890440d12 100644 --- a/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift +++ b/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// The static (offline) counterpart of diff --git a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift index baa1956de..d8620d74d 100644 --- a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift +++ b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift @@ -5,7 +5,7 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport import Demangling /// Validates concrete same-type pinning: a generic parameter pinned to a diff --git a/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift b/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift index 3b5cfd7fd..07725dc09 100644 --- a/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift +++ b/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The core correctness suite: for every non-generic struct/class defined in /// the fixture module, materialize the runtime field-offset vector via the diff --git a/Tests/SwiftLayoutTests/SwiftDeclaredObjCProtocolExistentialLayoutTests.swift b/Tests/SwiftLayoutTests/SwiftDeclaredObjCProtocolExistentialLayoutTests.swift new file mode 100644 index 000000000..c48978834 --- /dev/null +++ b/Tests/SwiftLayoutTests/SwiftDeclaredObjCProtocolExistentialLayoutTests.swift @@ -0,0 +1,64 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +@testable import SwiftSectionTestingSupport + +/// Existentials of `@objc` protocols declared in Swift that only their field +/// descriptors name (evolution proposal `swift-declared-objc-protocols`): +/// one the source renamed with `@objc(Name)` has a record under that name, +/// and one declared in a type a `_TtPC…` name — neither of which the legacy +/// `_TtP_` reading recognizes, so the existential's layout went +/// unresolved. The runtime field-offset vector of the non-generic holder is +/// the ground truth, on the in-process reader and the file reader alike. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct SwiftDeclaredObjCProtocolExistentialLayoutTests { + private static let qualifiedTypeName = "\(SwiftDeclaredObjCProtocolsFixture.moduleName).RenamedProtocolExistentialHolder" + + @Test func renamedAndNestedProtocolExistentialsResolve() throws { + let machOImage = try SwiftDeclaredObjCProtocolsFixture.loadedImage() + let runtimeOffsets = try #require(try runtimeFieldOffsets(ofQualifiedTypeName: Self.qualifiedTypeName, in: machOImage), "no runtime field-offset vector") + + let imageAggregate = try fieldLayout(ofQualifiedTypeName: Self.qualifiedTypeName, with: StaticLayoutCalculator(machO: machOImage), in: machOImage) + assertFullyComputed(imageAggregate, equals: runtimeOffsets, typeName: Self.qualifiedTypeName) + + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let fileAggregate = try fieldLayout(ofQualifiedTypeName: Self.qualifiedTypeName, with: StaticLayoutCalculator(machO: machOFile), in: machOFile) + assertFullyComputed(fileAggregate, equals: runtimeOffsets, typeName: "\(Self.qualifiedTypeName) (MachOFile)") + } + + /// Over a whole dependency closure, a protocol the root's own Objective-C + /// protocol records name resolves in the root. Asked of the Swift + /// protocol descriptors first, every such protocol — which has none — + /// indexed the root's entire closure before its record was looked at: + /// hundreds of images of the system's dyld cache for each image a host + /// read, which is how RuntimeViewer's offline service, laying out a + /// field of a Swift-declared `@objc` protocol in DockHelper, mapped the + /// cache files over two thousand times. + @Test func objCProtocolExistentialsResolveWithoutIndexingDependencies() throws { + let machOImage = try SwiftDeclaredObjCProtocolsFixture.loadedImage() + let runtimeOffsets = try #require(try runtimeFieldOffsets(ofQualifiedTypeName: Self.qualifiedTypeName, in: machOImage), "no runtime field-offset vector") + + let machOFile = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let universe = try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths()) + try #require(universe.dependencyImageCount > 0, "the closure must collect dependency images") + let fileAggregate = try fieldLayout(ofQualifiedTypeName: Self.qualifiedTypeName, with: StaticLayoutCalculator(imageUniverse: universe), in: machOFile) + + assertFullyComputed(fileAggregate, equals: runtimeOffsets, typeName: "\(Self.qualifiedTypeName) (MachOFile, dependency closure)") + #expect(universe.indexedDependencyImageCount == 0, "indexed \(universe.indexedDependencyImageCount) of \(universe.dependencyImageCount) dependency images") + } + + /// The protocols the image declares, as the layout engine keys them. + @Test func imageIndexNamesRenamedAndNestedProtocols() throws { + let qualifiedNames = ObjCProtocolIndex.qualifiedNames(in: try SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + #expect(qualifiedNames.contains("\(moduleName).SameNameRenamed")) + #expect(qualifiedNames.contains("\(moduleName).Outer.NestedProtocol")) + // The legacy reading still covers the kit's records the client + // holds copies of. + #expect(qualifiedNames.contains("\(SwiftDeclaredObjCProtocolsFixture.kitModuleName).KitObserver")) + } +} diff --git a/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift index a0f528e75..39554ac86 100644 --- a/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift +++ b/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates the *top-level* concrete generic instantiation entry points diff --git a/Tests/SwiftLayoutTests/ValueGenericAndPackLayoutTests.swift b/Tests/SwiftLayoutTests/ValueGenericAndPackLayoutTests.swift index d414496d3..d12473e18 100644 --- a/Tests/SwiftLayoutTests/ValueGenericAndPackLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ValueGenericAndPackLayoutTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport import Demangling /// Validates value-generic (SE-0452) and parameter-pack (SE-0393) layout diff --git a/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift b/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift index 9fb3d8abc..b75d2331d 100644 --- a/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift +++ b/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift @@ -5,8 +5,8 @@ import MachOFoundation @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection @testable import SwiftLayout -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The whole-type companion to `StaticLayoutVsRuntimeTests`: for every /// non-generic **struct/enum** defined in the fixture module, materialize the diff --git a/Tests/SwiftObjCInteropTests/ObjCImportedMemberBuilderTests.swift b/Tests/SwiftObjCInteropTests/ObjCImportedMemberBuilderTests.swift new file mode 100644 index 000000000..669d61d94 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCImportedMemberBuilderTests.swift @@ -0,0 +1,174 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftSectionFixtureSupport +@_spi(Internals) import Demangling +@testable import MachOSwiftSection +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `ObjCImportedContainerIndex` and `ObjCImportedMemberBuilder` (evolution +/// proposal `objc-imported-declarations`): an Objective-C class of AppKit, +/// loaded into the test process, read from its method and property lists and +/// built into the members Swift imports. +@Suite +struct ObjCImportedMemberBuilderTests { + private static func appKit() throws -> MachOImage { + _ = dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", RTLD_NOW) + return try #require(MachOImage(named: .AppKit)) + } + + private static func members(ofClassNamed className: String, in machO: MachOImage) throws -> [ObjCImportedMember] { + let record = try #require(ObjCImportedContainerIndex.shared.classRecord(named: className, in: machO)) + let classNode = ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO) + return ObjCImportedMemberBuilder.members(of: record, contextNode: classNode, contextTypeName: className, in: machO) + } + + private static func printed(_ member: ObjCImportedMember) -> String { + member.node.print(using: .interface) + } + + @Test func readsAClassFromItsLists() throws { + let appKit = try Self.appKit() + let record = try #require(ObjCImportedContainerIndex.shared.classRecord(named: "NSColor", in: appKit)) + #expect(record.kind == .class) + #expect(record.uniqueName == "NSColor") + #expect(record.superclassRuntimeName == "NSObject") + #expect(!record.isSwiftClass) + #expect(record.protocolRuntimeNames.contains("NSCopying")) + #expect(record.classMethods.contains { $0.selector == "colorWithRed:green:blue:alpha:" }) + #expect(record.classProperties.contains { $0.name == "blackColor" }) + #expect(record.instanceProperties.contains { $0.name == "CGColor" }) + #expect(ObjCImportedContainerIndex.shared.classRuntimeNames(in: appKit).contains("NSColor")) + } + + @Test func readsTheImageCategories() throws { + let appKit = try Self.appKit() + let uniqueNames = ObjCImportedContainerIndex.shared.categoryUniqueNames(in: appKit) + #expect(!uniqueNames.isEmpty) + for uniqueName in uniqueNames { + let record = try #require(ObjCImportedContainerIndex.shared.categoryRecord(uniqueName: uniqueName, in: appKit)) + guard case .category(let name) = record.kind else { + Issue.record("\(uniqueName) reads as a class") + continue + } + #expect(uniqueName == "\(record.classRuntimeName)(\(name))") + #expect(!record.isSwiftClass) + } + } + + @Test func buildsTheMembersSwiftImports() throws { + let appKit = try Self.appKit() + let members = try Self.members(ofClassNamed: "NSColor", in: appKit) + + // A factory method restating the class name is an initializer. + let factory = try #require(members.first { $0.selector == "colorWithRed:green:blue:alpha:" }) + #expect(factory.kind == .factoryInitializer) + #expect(!factory.isClassMember) + #expect(Self.printed(factory).contains("init(red: Swift.Double, green: Swift.Double, blue: Swift.Double, alpha: Swift.Double)"), "\(Self.printed(factory))") + + // A class property of the class's own type drops the type's name. + let black = try #require(members.first { $0.selector == "blackColor" && $0.isClassMember }) + #expect(black.kind == .property) + #expect(!black.isSettable) + #expect(Self.printed(black).contains("black"), "\(Self.printed(black))") + #expect(!Self.printed(black).contains("blackColor"), "\(Self.printed(black))") + + // A property is listed once, where its getter is, never as methods. + let cgColor = members.filter { $0.selector == "CGColor" } + #expect(cgColor.map(\.kind) == [.property]) + #expect(cgColor.first.map(Self.printed)?.contains("cgColor") == true) + + // What Swift never sees is left out. + #expect(!members.contains { $0.selector == ".cxx_destruct" || $0.selector == "dealloc" }) + + // The selector is pinned only where the compiler would derive + // another one from the printed name. + #expect(factory.hasExplicitSelector) + #expect(black.hasExplicitSelector) + #expect(members.first { $0.selector == "initWithCoder:" }?.hasExplicitSelector == false) + } + + /// An encoding whose arguments do not pair with the selector's colons — + /// a record could carry one — never pairs names with the wrong types: the + /// method is left out instead of trapping on a missing argument. An + /// initializer with no argument whose first piece goes on past `init` + /// takes the `()` parameter the importer gives it. + @Test func encodingsThatDoNotPairWithTheSelector() throws { + let appKit = try Self.appKit() + let record = ObjCImportedContainerRecord( + kind: .class, + classRuntimeName: "Probe", + superclassRuntimeName: "NSObject", + protocolRuntimeNames: [], + isSwiftClass: false, + instanceMethods: [ + .init(selector: "takeOne:andAnother:", typeEncoding: "v24@0:8@16", implementationOffset: nil), + .init(selector: "initForIncrementalLoad", typeEncoding: "@16@0:8", implementationOffset: nil), + ], + classMethods: [], + instanceProperties: [], + classProperties: [] + ) + let classNode = ObjCRuntimeNames.classNode(forRuntimeName: "Probe", in: appKit) + let members = ObjCImportedMemberBuilder.members(of: record, contextNode: classNode, contextTypeName: "Probe", in: appKit) + #expect(members.map(\.selector) == ["initForIncrementalLoad"]) + let initializer = try #require(members.first) + #expect(initializer.kind == .initializer) + #expect(Self.printed(initializer).contains("init(forIncrementalLoad: ())"), "\(Self.printed(initializer))") + } + + @Test func objectPropertiesCarryTheirOwnership() throws { + let appKit = try Self.appKit() + let members = try Self.members(ofClassNamed: "NSWindow", in: appKit) + func property(_ getterSelector: String) throws -> ObjCImportedMember { + try #require(members.first { $0.selector == getterSelector && !$0.isClassMember && $0.kind == .property }, "\(getterSelector)") + } + // `copy` of a class type is `@NSCopying`. + #expect(try property("backgroundColor").ownership == .copy) + // `copy` of a class Swift imports as a value type is nothing more. + let title = try property("title") + #expect(title.ownership == nil) + #expect(title.setterSelector == "setTitle:") + #expect(try property("delegate").ownership == .weak) + // A read-only property records no ownership it was not given. + #expect(try property("screen").ownership == nil) + // A non-object property has none. + #expect(try property("level").ownership == nil) + } + + /// `const char *` — `r*` in an encoding — imports as `UnsafePointer`, as + /// the importer has it: `NSString.utf8String`, whose getter's encoding is + /// `r*16@0:8`. + @Test func aConstantCStringImportsAsAnImmutablePointer() throws { + _ = dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_NOW) + let foundation = try #require(MachOImage(named: .Foundation)) + let members = try Self.members(ofClassNamed: "NSString", in: foundation) + let utf8String = try #require(members.first { $0.selector == "UTF8String" }, "NSString has no UTF8String") + #expect(utf8String.typeEncoding.contains("r*"), "\(utf8String.typeEncoding)") + let printed = Self.printed(utf8String) + #expect(printed.contains("UnsafePointer"), "\(printed)") + #expect(!printed.contains("UnsafeMutablePointer"), "\(printed)") + } + + /// C arrays import the way ClangImporter imports them + /// (`VisitConstantArrayType`): a tuple of their elements, a single + /// element as the element itself, and nothing past 4,096 elements — a + /// pointer to such an array is an `OpaquePointer`. Nested arrays stop at + /// 65,536 elements in all, so no encoding makes the importer build or + /// print a tuple without end. + @Test(arguments: [ + ("^[4c]", "Swift.UnsafeMutablePointer<(Swift.Int8, Swift.Int8, Swift.Int8, Swift.Int8)>"), + ("^[1c]", "Swift.UnsafeMutablePointer"), + ("^[5000c]", "Swift.OpaquePointer"), + ("^[300[300c]]", "Swift.OpaquePointer"), + ]) + func aCArrayImportsAsClangImporterImportsIt(encoding: String, expectedType: String) throws { + _ = dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_NOW) + let foundation = try #require(MachOImage(named: .Foundation)) + let type = try #require(ObjCTypeEncodingParser.type(from: encoding), "\(encoding)") + let printed = ObjCImportedTypes(machO: foundation).typeNode(type, position: .nonOptional).print(using: .interface) + #expect(printed == expectedType) + } +} diff --git a/Tests/SwiftObjCInteropTests/ObjCImporterNamingClassMemberTests.swift b/Tests/SwiftObjCInteropTests/ObjCImporterNamingClassMemberTests.swift new file mode 100644 index 000000000..3ab293afa --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCImporterNamingClassMemberTests.swift @@ -0,0 +1,111 @@ +import Foundation +import Testing +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `ObjCImporterNaming` for the members of an Objective-C class (evolution +/// proposal `objc-imported-declarations`): factory methods imported as +/// initializers, the error convention told apart from other `^@` parameters, +/// and property names. +/// +/// The selectors and encodings are AppKit's, as macOS 27.2's method and +/// property lists record them; the expected names are the macOS 27.2 SDK's +/// (its symbol graph), which the proposal's measurement compared against. +/// Where a method list's encoding loses the class name the SDK's naming +/// depends on, the extended encoding a protocol would carry is used instead, +/// so each case tests the rule and not the missing information. +@Suite +struct ObjCImporterNamingClassMemberTests { + private static func spelling(of name: ObjCImporterNaming.ImportedName) -> String { + let labels = name.argumentLabels.map { ($0.isEmpty ? "_" : $0) + ":" }.joined() + return "\(name.baseName)(\(labels))" + } + + private static func importedName(_ selector: String, _ encoding: String, in className: String, isClassMethod: Bool = false) throws -> ObjCImporterNaming.ImportedName { + let methodType = try #require(ObjCTypeEncodingParser.methodType(from: encoding), "\(encoding)") + return ObjCImporterNaming.importedName( + selector: selector, + isClassMethod: isClassMethod, + methodType: methodType, + contextTypeName: className, + undoesSwiftInsertedWith: false, + factoryInitializerClassName: className + ) + } + + // MARK: - Factory methods + + @Test func aClassMethodRestatingItsClassNameIsAnInitializer() throws { + let color = try Self.importedName("colorWithRed:green:blue:alpha:", "@48@0:8d16d24d32d40", in: "NSColor", isClassMethod: true) + #expect(color.kind == .factoryInitializer) + #expect(Self.spelling(of: color) == "init(red:green:blue:alpha:)") + + let image = try Self.importedName("imageNamed:", "@24@0:8@16", in: "NSImage", isClassMethod: true) + #expect(image.kind == .factoryInitializer) + #expect(Self.spelling(of: image) == "init(named:)") + + let font = try Self.importedName("fontWithName:size:", "@32@0:8@16d24", in: "NSFont", isClassMethod: true) + #expect(Self.spelling(of: font) == "init(name:size:)") + + // With no argument, the first piece has to restate the name whole. + let date = try Self.importedName("date", "@16@0:8", in: "NSDate", isClassMethod: true) + #expect(date.kind == .factoryInitializer) + #expect(Self.spelling(of: date) == "init()") + } + + @Test func aClassMethodThatIsNoFactoryStaysAMethod() throws { + // The first piece does not restate the class name. + let event = try Self.importedName("mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", "@92@0:8Q16{CGPoint=dd}24Q40d48q56@64q72q80f88", in: "NSEvent", isClassMethod: true) + #expect(event.kind == .method) + // It does, but leaves words behind with no argument to label. + #expect(try Self.importedName("colorSpaceName", "@16@0:8", in: "NSColor", isClassMethod: true).kind == .method) + // It returns another class. + #expect(try Self.importedName("colorWithName:", #"@"NSString"24@0:8@16"#, in: "NSColor", isClassMethod: true).kind == .method) + // It returns no object. + #expect(try Self.importedName("colorCount", "q16@0:8", in: "NSColor", isClassMethod: true).kind == .method) + // An instance method never is one. + #expect(try Self.importedName("colorWithAlphaComponent:", "@24@0:8d16", in: "NSColor").kind == .method) + // Nor is a class method the caller asked about for no class. + let methodType = try #require(ObjCTypeEncodingParser.methodType(from: "@48@0:8d16d24d32d40")) + let withoutClass = ObjCImporterNaming.importedName(selector: "colorWithRed:green:blue:alpha:", isClassMethod: true, methodType: methodType, contextTypeName: "NSColor", undoesSwiftInsertedWith: false) + #expect(withoutClass.kind == .method) + } + + // MARK: - The error convention + + @Test func onlyAParameterNamedForTheErrorFollowsTheErrorConvention() throws { + // `NSDictionary **` encodes as `^@` like `NSError **` does. + let rtf = try Self.importedName("initWithRTF:documentAttributes:", "@32@0:8@16^@24", in: "NSAttributedString") + #expect(rtf.errorConvention == nil) + #expect(Self.spelling(of: rtf) == "init(rtf:documentAttributes:)") + + let write = try Self.importedName("writeToURL:options:error:", #"B40@0:8@"NSURL"16Q24^@32"#, in: "NSData") + #expect(write.errorConvention == .booleanResult) + #expect(Self.spelling(of: write) == "write(to:options:)") + + let read = try Self.importedName("checkResourceIsReachableAndReturnError:", "B24@0:8^@16", in: "NSURL") + #expect(read.errorConvention == .booleanResult) + #expect(Self.spelling(of: read) == "checkResourceIsReachable()") + } + + // MARK: - Property names + + @Test(arguments: [ + // A `BOOL` goes by its getter. + ("NSView", "hidden", "TB,N,GisHidden", "isHidden"), + ("NSView", "flipped", "TB,R,N,GisFlipped", "isFlipped"), + ("NSView", "wantsLayer", "TB,N", "wantsLayer"), + // A leading initialism is lowercased. + ("NSBezierPath", "CGPath", "T^{CGPath=},N", "cgPath"), + ("NSBitmapImageRep", "TIFFRepresentation", #"T@"NSData",R,C"#, "tiffRepresentation"), + ("NSCursor", "IBeamCursorForVerticalLayout", #"T@"NSCursor",R"#, "iBeamCursorForVerticalLayout"), + // A result of the context's own type drops its name. + ("NSColor", "blackColor", #"T@"NSColor",R"#, "black"), + ("NSAppearance", "currentAppearance", #"T@"NSAppearance",&,N"#, "current"), + // A result of another type keeps it. + ("NSWindow", "backgroundColor", #"T@"NSColor",C,N"#, "backgroundColor"), + ]) + func propertyNamesMatchTheSDK(className: String, propertyName: String, attributes: String, swiftName: String) { + #expect(ObjCImporterNaming.importedPropertyName(propertyName, attributes: attributes, contextTypeName: className) == swiftName) + } +} diff --git a/Tests/SwiftObjCInteropTests/ObjCImporterNamingTests.swift b/Tests/SwiftObjCInteropTests/ObjCImporterNamingTests.swift new file mode 100644 index 000000000..018e5d150 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCImporterNamingTests.swift @@ -0,0 +1,208 @@ +import Foundation +import Testing +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `ObjCImporterNaming` (evolution proposal `swift-declared-objc-protocols`): +/// the importer's names for the methods of an `@objc` protocol, from the +/// selector and extended type encoding alone. +/// +/// The expected names are the real ClangImporter's. They were taken by +/// writing each protocol's binary facts — selectors, extended encodings, the +/// property list, no nullability, no parameter names, Swift classes and +/// protocols under the Swift names a generated header gives them — into an +/// Objective-C header and printing its import with `swift-synthesize-interface` +/// (Swift 6.4.2). Two sources: a probe module with one protocol whose +/// selectors the compiler derived and one written Apple's way, with explicit +/// selectors; and the 11 protocols of Xcode's DVTFoundation. +@Suite +struct ObjCImporterNamingTests { + private struct Case: CustomTestStringConvertible, Sendable { + let contextTypeName: String + let selector: String + let isClassMethod: Bool + let encoding: String + /// The importer's name, `teamName(for:)`. + let importerName: String + let throwsError: Bool + + init(_ contextTypeName: String, _ selector: String, isClassMethod: Bool = false, _ encoding: String, _ importerName: String, throwsError: Bool = false) { + self.contextTypeName = contextTypeName + self.selector = selector + self.isClassMethod = isClassMethod + self.encoding = encoding + self.importerName = importerName + self.throwsError = throwsError + } + + var testDescription: String { "\(contextTypeName) \(selector)" } + } + + private static let probeDerived = "PublicDerivedSelectors" + private static let probeExplicit = "PRBExplicitSelectors" + + private static let cases: [Case] = [ + // The probe's selectors the compiler derived from Swift names. + Case(probeDerived, "nameFor:", #"@"NSString"24@0:8@16"#, "name(for:)"), + Case(probeDerived, "teamNameFor:error:", #"@"NSString"32@0:8@"NSString"16^@24"#, "teamName(for:)", throwsError: true), + Case(probeDerived, "hangPointsWithInput:error:", #"@"NSArray"32@0:8@"NSObject"16^@24"#, "hangPoints(withInput:)", throwsError: true), + Case(probeDerived, "userVisibleRolesForDeveloperTeamId:", #"@"NSArray"24@0:8@"NSString"16"#, "userVisibleRoles(forDeveloperTeamId:)"), + Case(probeDerived, "perform:with:", #"v32@0:8@"NSString"16@24"#, "perform(_:with:)"), + Case(probeDerived, "downloadWithIdentifier:completion:", #"v32@0:8@"NSString"16@?24"#, "download(withIdentifier:completion:)"), + Case(probeDerived, "refreshWithCompletionHandler:", #"v24@0:8@?16"#, "refresh(completionHandler:)"), + Case(probeDerived, "tokenAndReturnError:", #"@"NSString"24@0:8^@16"#, "token()", throwsError: true), + Case(probeDerived, "isEntitlementGrantedWithProfile:entitlement:", #"B32@0:8@"NSObject"16@"NSString"24"#, "isEntitlementGranted(withProfile:entitlement:)"), + Case(probeDerived, "reload", "v16@0:8", "reload()"), + Case(probeDerived, "insert:at:", #"v32@0:8@"NSString"16q24"#, "insert(_:at:)"), + Case(probeDerived, "makeDefault", isClassMethod: true, #"@"NSObject"16@0:8"#, "makeDefault()"), + Case(probeDerived, "scrollTo:animated:", "v28@0:8q16B24", "scroll(to:animated:)"), + // The probe's explicit selectors. + Case(probeExplicit, "nameForObject:", #"@"NSString"24@0:8@16"#, "name(for:)"), + Case(probeExplicit, "tableView:numberOfRowsInSection:", #"q32@0:8@"NSObject"16q24"#, "tableView(_:numberOfRowsInSection:)"), + Case(probeExplicit, "indexOfObject:", "q24@0:8@16", "index(of:)"), + Case(probeExplicit, "removeObjectAtIndex:", "v24@0:8q16", "removeObject(at:)"), + Case(probeExplicit, "stringByAppendingString:", #"@"NSString"24@0:8@"NSString"16"#, "string(byAppending:)"), + Case(probeExplicit, "fetchItemsWithIdentifier:completionHandler:", #"v32@0:8@"NSString"16@?24"#, "fetchItems(withIdentifier:completionHandler:)"), + Case(probeExplicit, "objectForKey:", #"@24@0:8@"NSString"16"#, "object(forKey:)"), + Case(probeExplicit, "setValue:forKey:", #"v32@0:8@16@"NSString"24"#, "setValue(_:forKey:)"), + Case(probeExplicit, "addObserver:forKeyPath:", #"v32@0:8@"NSObject"16@"NSString"24"#, "addObserver(_:forKeyPath:)"), + // DVTFoundation's protocols. + Case("DVTTeamCredential", "tokenAndReturnError:", #"@"NSString"24@0:8^@16"#, "token()", throwsError: true), + Case("DVTFieldReportDirectSourceProtocol", "hangPointsWithInput:error:", #"@"NSArray"32@0:8@"_TtC13DVTFoundation31DVTFieldReportDirectSourceInput"16^@24"#, "hangPoints(with:)", throwsError: true), + Case("DVTAppStoreConnectExtensionProtocol", "init", "@16@0:8", "init()"), + Case("DVTAppStoreConnectExtensionProtocol", "actorForCredentialsProvider:", #"@24@0:8@"<_TtP13DVTFoundation26BackendCredentialsProvider_>"16"#, "actor(for:)"), + Case("DVTProvisioningProfileEntitlementMatchingProvider", "isEntitlementGrantedWithProfile:entitlement:value:logAspect:", #"B48@0:8@"DVTProvisioningProfile"16@"NSString"24@32@"DVTLogAspect"40"#, "isEntitlementGranted(with:entitlement:value:logAspect:)"), + Case("DVTRuntimeEnvironmentVariable", "variableFromExistingWithVariable:macros:", #"@"<_TtP13DVTFoundation29DVTRuntimeEnvironmentVariable_>"32@0:8@"<_TtP13DVTFoundation29DVTRuntimeEnvironmentVariable_>"16@"NSDictionary"24"#, "fromExisting(with:macros:)"), + Case("DVTDownloadableUtilitiesProvider_ObjC", "downloadSimulatorRuntimeCryptexWithAbsoluteAssetID:patchableFrom:progressUpdateBlock:completionHandler:", #"v48@0:8@"MAAbsoluteAssetId"16@"NSArray"24@?32@?40"#, "downloadSimulatorRuntimeCryptex(with:patchableFrom:progressUpdate:completionHandler:)"), + Case("DVTDownloadableUtilitiesProvider_ObjC", "cancelDownloadSimulatorRuntimeCryptexWithAbsoluteAssetID:completionHandler:", #"v32@0:8@"MAAbsoluteAssetId"16@?24"#, "cancelDownloadSimulatorRuntimeCryptex(with:completionHandler:)"), + Case("DVTDownloadableUtilitiesProvider_ObjC", "mobileAssetAbsoluteIDWithDownloadable:installedOnly:completionHandler:", #"v36@0:8@"_TtC13DVTFoundation15DVTDownloadable"16B24@?28"#, "mobileAssetAbsoluteID(with:installedOnly:completionHandler:)"), + Case("DVTDownloadableUtilitiesProvider_ObjC", "updateDefaultSDKMobileAssetCatalogCatalogStatusWithCompletion:", "v24@0:8@?16", "updateDefaultSDKMobileAssetCatalogCatalogStatus(completion:)"), + Case("BackendCredentialsProvider", "sessionProviderCredentialAndReturnError:", #"@"_TtC13DVTFoundation36DVTServicesSessionProviderCredential"24@0:8^@16"#, "sessionProviderCredential()", throwsError: true), + Case("DVTActorProtocol", "userVisibleRolesForDeveloperTeamId:", #"@"NSArray"24@0:8@"NSString"16"#, "userVisibleRoles(forDeveloperTeamId:)"), + Case("DVTActorProtocol", "teamNameFor:error:", #"@"NSString"32@0:8@"NSString"16^@24"#, "teamName(for:)", throwsError: true), + ] + + private static func spelling(of name: ObjCImporterNaming.ImportedName) -> String { + "\(name.baseName)(\(name.argumentLabels.map { ($0.isEmpty ? "_" : $0) + ":" }.joined()))" + } + + private static func importedName(_ testCase: Case, undoesSwiftInsertedWith: Bool) throws -> ObjCImporterNaming.ImportedName { + let methodType = try #require(ObjCTypeEncodingParser.methodType(from: testCase.encoding), "\(testCase.encoding)") + return ObjCImporterNaming.importedName( + selector: testCase.selector, + isClassMethod: testCase.isClassMethod, + methodType: methodType, + contextTypeName: testCase.contextTypeName, + undoesSwiftInsertedWith: undoesSwiftInsertedWith + ) + } + + @Test(arguments: cases) + private func matchesTheImporter(_ testCase: Case) throws { + let name = try Self.importedName(testCase, undoesSwiftInsertedWith: false) + #expect(Self.spelling(of: name) == testCase.importerName) + #expect((name.errorConvention != nil) == testCase.throwsError) + } + + /// The library's own step, after the importer's: a first label starting + /// with `with` and going on loses it — the `With` Swift inserts before a + /// first label that starts with no preposition. A label that is `with` + /// alone, or an initializer's, stays. + @Test func undoesTheWithSwiftInserts() throws { + let expectations: [(selector: String, encoding: String, name: String)] = [ + ("hangPointsWithInput:error:", #"@"NSArray"32@0:8@"NSObject"16^@24"#, "hangPoints(input:)"), + ("downloadWithIdentifier:completion:", #"v32@0:8@"NSString"16@?24"#, "download(identifier:completion:)"), + ("isEntitlementGrantedWithProfile:entitlement:", #"B32@0:8@"NSObject"16@"NSString"24"#, "isEntitlementGranted(profile:entitlement:)"), + ("fetchItemsWithIdentifier:completionHandler:", #"v32@0:8@"NSString"16@?24"#, "fetchItems(identifier:completionHandler:)"), + ("loadWithURL:", #"v24@0:8@"NSString"16"#, "load(url:)"), + ("perform:with:", #"v32@0:8@"NSString"16@24"#, "perform(_:with:)"), + ("initWithIdentifier:", #"@24@0:8@"NSString"16"#, "init(identifier:)"), + ] + for expectation in expectations { + let methodType = try #require(ObjCTypeEncodingParser.methodType(from: expectation.encoding)) + let name = ObjCImporterNaming.importedName(selector: expectation.selector, isClassMethod: false, methodType: methodType, contextTypeName: "Probe") + #expect(Self.spelling(of: name) == expectation.name, "\(expectation.selector)") + } + // A label left as `with` alone after the type name went stays. + let directSource = try Self.importedName(Self.cases.first { $0.importerName == "hangPoints(with:)" }!, undoesSwiftInsertedWith: true) + #expect(Self.spelling(of: directSource) == "hangPoints(with:)") + } + + @Test func classifiesInitializersSubscriptsAndTheErrorConvention() throws { + func name(_ selector: String, _ encoding: String, isClassMethod: Bool = false) throws -> ObjCImporterNaming.ImportedName { + ObjCImporterNaming.importedName(selector: selector, isClassMethod: isClassMethod, methodType: try #require(ObjCTypeEncodingParser.methodType(from: encoding)), contextTypeName: "DerivedSelectors") + } + let initializer = try name("initWithIdentifier:", #"@24@0:8@"NSString"16"#) + #expect(initializer.kind == .initializer) + #expect(Self.spelling(of: initializer) == "init(identifier:)") + // `initialize` is not of the `init` family. + #expect(try name("initialize", "v16@0:8").kind == .method) + // A class method returning an object is no initializer either. + #expect(try name("initWithIdentifier:", #"@24@0:8@"NSString"16"#, isClassMethod: true).kind == .method) + + #expect(try name("objectAtIndexedSubscript:", "@24@0:8q16").kind == .subscriptGetter) + #expect(try name("setObject:atIndexedSubscript:", "v32@0:8@16q24").kind == .subscriptSetter) + #expect(try name("objectForKeyedSubscript:", "@24@0:8@16").kind == .subscriptGetter) + + let booleanThrowing = try name("saveAndReturnError:", "B24@0:8^@16") + #expect(booleanThrowing.errorConvention == .booleanResult) + #expect(Self.spelling(of: booleanThrowing) == "save()") + #expect(booleanThrowing.parameterIndices.isEmpty) + + let objectThrowing = try name("teamNameFor:error:", #"@"NSString"32@0:8@"NSString"16^@24"#) + #expect(objectThrowing.errorConvention == .nonNilResult) + #expect(objectThrowing.parameterIndices == [0]) + + // `void` results never follow the error convention. + let voidResult = try name("validate:error:", "v32@0:8@16^@24") + #expect(voidResult.errorConvention == nil) + #expect(voidResult.argumentLabels.count == 2) + } + + @Test func wordsSplitLikeTheImporter() { + func words(_ string: String) -> [String] { + let words = ObjCImporterNaming.Words(string) + return (0 ..< words.count).map(words.word) + } + #expect(words("userVisibleRolesForDeveloperTeamId") == ["user", "Visible", "Roles", "For", "Developer", "Team", "Id"]) + #expect(words("URLForResource") == ["URL", "For", "Resource"]) + #expect(words("URLs") == ["URLs"]) + #expect(words("UTF8String") == ["UTF", "8", "String"]) + #expect(words("NSURL") == ["NSURL"]) + #expect(words("updateDefaultSDKMobileAsset") == ["update", "Default", "SDK", "Mobile", "Asset"]) + #expect(words("snake_case") == ["snake", "_", "case"]) + #expect(ObjCImporterNaming.toLowercaseInitialisms("URLForResource") == "urlForResource") + #expect(ObjCImporterNaming.toLowercaseInitialisms("UTF8String") == "utf8String") + #expect(ObjCImporterNaming.toLowercaseWord("URL") == "URL") + #expect(ObjCImporterNaming.toLowercaseWord("Identifier") == "identifier") + } + + @Test func partsOfSpeech() { + #expect(ObjCImporterNaming.partOfSpeech("For") == .preposition) + #expect(ObjCImporterNaming.partOfSpeech("remove") == .verb) + #expect(ObjCImporterNaming.partOfSpeech("Appending") == .gerund) + #expect(ObjCImporterNaming.partOfSpeech("running") == .gerund) + #expect(ObjCImporterNaming.partOfSpeech("reload") == .verb) + #expect(ObjCImporterNaming.partOfSpeech("Roles") == .unknown) + } + + @Test func typeEncodings() throws { + let method = try #require(ObjCTypeEncodingParser.methodType(from: #"v48@0:8@"MAAbsoluteAssetId"16@"NSArray"24@?32@?40"#)) + #expect(method.returnType == .void) + #expect(method.parameterTypes == [ + .object(className: "MAAbsoluteAssetId", protocolNames: []), + .object(className: "NSArray", protocolNames: []), + .block(ObjCBlockSignature(returnType: .void, parameterTypes: [.object(className: "_TtC13DVTFoundation29DVTDownloadableProgressUpdate", protocolNames: [])])), + .block(ObjCBlockSignature(returnType: .void, parameterTypes: [.object(className: "NSURL", protocolNames: []), .object(className: "NSError", protocolNames: [])])), + ]) + #expect(ObjCTypeEncodingParser.type(from: #"@"NSObject""#) == .object(className: "NSObject", protocolNames: ["NSCopying", "NSCoding"])) + #expect(ObjCTypeEncodingParser.type(from: #"@"""#) == .object(className: nil, protocolNames: ["NSCopying"])) + #expect(ObjCTypeEncodingParser.type(from: #"{CGRect="origin"{CGPoint="x"d"y"d}"size"{CGSize="width"d"height"d}}"#) == .structure(name: "CGRect")) + #expect(ObjCTypeEncodingParser.type(from: "r^v") == .pointer(.void, isConst: true)) + #expect(ObjCTypeEncodingParser.type(from: "^?") == .pointer(.unknown, isConst: false)) + #expect(ObjCTypeEncodingParser.propertyType(fromAttributes: #"T@"NSString",N,R"#) == .object(className: "NSString", protocolNames: [])) + #expect(ObjCTypeEncodingParser.propertyType(fromAttributes: "T{_NSRange=QQ},N") == .structure(name: "_NSRange")) + // `self` and `_cmd` are required. + #expect(ObjCTypeEncodingParser.methodType(from: "v16") == nil) + } +} diff --git a/Tests/SwiftObjCInteropTests/ObjCProtocolRequirementBuilderTests.swift b/Tests/SwiftObjCInteropTests/ObjCProtocolRequirementBuilderTests.swift new file mode 100644 index 000000000..a367184cc --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCProtocolRequirementBuilderTests.swift @@ -0,0 +1,176 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Core) import MachOObjCSection +@_spi(Internals) import Demangling +@testable import MachOSwiftSection +@testable import SwiftSectionTestingSupport +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `ObjCProtocolRequirementBuilder` (evolution proposal +/// `swift-declared-objc-protocols`): the requirements of an `@objc` protocol +/// declared in Swift, built from its Objective-C record as Swift declarations +/// — every list, in record order, a property and a subscript where their +/// getters are — through both readers. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct ObjCProtocolRequirementBuilderTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private static func requirements(of name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [ObjCProtocolRequirement] { + let declared = try #require(SwiftDeclaredObjCProtocolIndex.shared.protocols(in: machO).first { $0.qualifiedName == "\(moduleName).\(name)" }) + let record = try #require(declared.record) + let protocolNode = try #require(try demangleAsNodeTransient(declared.mangledName).first(of: .protocol)) + return ObjCProtocolRequirementBuilder.requirements(of: record, protocolNode: protocolNode, in: machO) + } + + private static func printed(_ requirement: ObjCProtocolRequirement) -> String { + requirement.node.print(using: .interface) + } + + private static func expectDerivedSelectors(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + let requirements = try requirements(of: "DerivedSelectors", in: machO) + #expect(requirements.map(\.selector) == [ + "initWithIdentifier:", "nameFor:", "teamNameFor:error:", "hangPointsWithInput:error:", "perform:with:", + "downloadWithIdentifier:completion:", "tokenAndReturnError:", "reload", "title", "isEnabled", + "objectAtIndexedSubscript:", "makeDefault", "shared", "scrollTo:animated:", "optionalCount", + ]) + #expect(requirements.map(\.kind) == [ + .initializer, .method, .method, .method, .method, .method, .method, .method, .property, .property, + .subscript, .method, .property, .method, .property, + ]) + + let bySelector = Dictionary(requirements.map { ($0.selector, $0) }, uniquingKeysWith: { first, _ in first }) + // Accessors: a read-only property, a settable one, a settable subscript. + #expect(bySelector["title"]?.isSettable == false) + #expect(bySelector["isEnabled"]?.setterSelector == "setIsEnabled:") + #expect(bySelector["objectAtIndexedSubscript:"]?.setterSelector == "setObject:atIndexedSubscript:") + // Class members and optional requirements. + #expect(bySelector["makeDefault"]?.isClassMember == true) + #expect(bySelector["shared"]?.isClassMember == true) + #expect(bySelector["initWithIdentifier:"]?.isClassMember == false) + #expect(requirements.filter(\.isOptional).map(\.selector) == ["scrollTo:animated:", "optionalCount"]) + + // The declarations: the importer's names with the `With` Swift + // inserted undone, bridged types, `!` where nullability is unknown, + // `?` inside a closure, `throws` from the error convention. + let expectedFragments: [String: String] = [ + "nameFor:": "name(for: Any!) -> Swift.String!", + "teamNameFor:error:": "teamName(for: Swift.String!) throws -> Swift.String", + "hangPointsWithInput:error:": "hangPoints(input: NSObject!) throws -> [Any]", + "perform:with:": "perform(_: Swift.String!, with: Any!)", + "downloadWithIdentifier:completion:": "download(identifier: Swift.String!, completion: ((Foundation.URL?, Swift.Error?) -> ())!)", + "tokenAndReturnError:": "token() throws -> Swift.String", + "scrollTo:animated:": "scroll(to: Swift.Int, animated: Swift.Bool)", + "makeDefault": "makeDefault() -> NSObject!", + "initWithIdentifier:": "init(identifier: Swift.String!)", + "title": "title", + ] + for (selector, fragment) in expectedFragments { + let requirement = try #require(bySelector[selector], "\(selector)") + #expect(printed(requirement).contains(fragment), "\(selector): \(printed(requirement))") + } + #expect(printed(try #require(bySelector["title"])).contains("Swift.String!")) + #expect(printed(try #require(bySelector["shared"])).hasPrefix("static ")) + } + + @Test func derivedSelectorsFromTheFile() throws { + try Self.expectDerivedSelectors(in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + } + + @Test func derivedSelectorsFromTheLoadedImage() throws { + try Self.expectDerivedSelectors(in: SwiftDeclaredObjCProtocolsFixture.loadedImage()) + } + + /// A requirement typed with another of the image's protocols, renamed to + /// its own name, and an explicit selector Apple's way. + @Test func protocolTypesAndExplicitSelectors() throws { + let machO = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let refined = try Self.requirements(of: "RefinedProtocol", in: machO) + #expect(refined.map(\.selector) == ["refine"]) + #expect(Self.printed(refined[0]).contains("refine()")) + + let sameNameRenamed = try Self.requirements(of: "SameNameRenamed", in: machO) + #expect(sameNameRenamed.map(\.selector) == ["ping"]) + } + + /// An encoding with fewer parameters than the selector has colons — what + /// a record whose extended types are misaligned hands over — imports + /// nothing: the extended encoding gives way to the method list's when + /// only that one fits, and a requirement neither fits is left out. Built + /// in a child process: the importer indexed past the encoding's + /// parameters and trapped. + @Test func anEncodingThatDoesNotFitTheSelectorIsNotImported() async { + await #expect(processExitsWith: .success) { + do { + let machO = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let record = ObjCProtocolRecord( + offset: 0, + runtimeName: "MismatchedEncodings", + flags: 1, + inheritedProtocolRuntimeNames: [], + requiredInstanceMethods: [ + // Neither encoding fits. + ObjCProtocolRecord.Method(selector: "takeOne:andAnother:", typeEncoding: "v24@0:8@16", extendedTypeEncoding: nil), + // The extended encoding is another method's; the + // method list's fits. + ObjCProtocolRecord.Method(selector: "pair:with:", typeEncoding: "v32@0:8@16@24", extendedTypeEncoding: #"v24@0:8@"NSString"16"#), + ObjCProtocolRecord.Method(selector: "reload", typeEncoding: "v16@0:8", extendedTypeEncoding: nil), + ], + requiredClassMethods: [], + optionalInstanceMethods: [], + optionalClassMethods: [], + instanceProperties: [], + classProperties: [] + ) + let protocolNode = Node.createTransient(kind: .protocol, children: [ + Node.createTransient(kind: .module, text: SwiftDeclaredObjCProtocolsFixture.moduleName), + Node.createTransient(kind: .identifier, text: "MismatchedEncodings"), + ]) + let requirements = ObjCProtocolRequirementBuilder.requirements(of: record, protocolNode: protocolNode, in: machO) + guard requirements.map(\.selector) == ["pair:with:", "reload"], + requirements.first?.typeEncoding == "v32@0:8@16@24" + else { exit(EXIT_FAILURE) } + } catch { + exit(EXIT_FAILURE) + } + } + } + + /// The extended method types follow every method of the four lists in + /// order, so a list the reader cannot read shifts every later method's + /// slot onto another method's encoding. A shifted encoding describes + /// another method, and is paired with none. + @Test func extendedTypesThatDoNotFitTheirMethodsAreNotPaired() throws { + let machO = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let declared = try #require(SwiftDeclaredObjCProtocolIndex.shared.protocols(in: machO).first { $0.qualifiedName == "\(Self.moduleName).DerivedSelectors" }) + let record = try #require(declared.record) + let objcProtocol = try #require(machO.objc.protocols64?.first { $0.offset == record.offset }) + func rawMethods(_ methods: [ObjCProtocolRecord.Method]) -> [(selector: String, typeEncoding: String)] { + methods.map { (selector: $0.selector, typeEncoding: $0.typeEncoding) } + } + // What the reader hands over when it cannot read the required + // instance methods. + let shifted = ObjCProtocolRecord.make( + offset: record.offset, + runtimeName: record.runtimeName, + flags: record.flags, + recordSize: objcProtocol.size, + inheritedProtocolRuntimeNames: record.inheritedProtocolRuntimeNames, + methodLists: [[], rawMethods(record.requiredClassMethods), rawMethods(record.optionalInstanceMethods), rawMethods(record.optionalClassMethods)], + instanceProperties: record.instanceProperties, + classProperties: record.classProperties, + in: machO + ) + #expect(!shifted.allMethods.isEmpty) + for method in shifted.allMethods { + guard let extendedTypeEncoding = method.extendedTypeEncoding else { continue } + let extendedParameterCount = try #require(ObjCTypeEncodingParser.methodType(from: extendedTypeEncoding)).parameterTypes.count + let parameterCount = try #require(ObjCTypeEncodingParser.methodType(from: method.typeEncoding)).parameterTypes.count + #expect(extendedParameterCount == parameterCount, "\(method.selector) paired with \(extendedTypeEncoding)") + } + // Read whole, every method keeps its own. + #expect(record.allMethods.allSatisfy { $0.extendedTypeEncoding != nil }) + } +} diff --git a/Tests/SwiftObjCInteropTests/ObjCSwiftTypeCompatibilityTests.swift b/Tests/SwiftObjCInteropTests/ObjCSwiftTypeCompatibilityTests.swift new file mode 100644 index 000000000..186c76b18 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCSwiftTypeCompatibilityTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +@_spi(Internals) import Demangling +@_spi(Internals) @testable import SwiftObjCInterop + +/// Whether a Swift member's type can be its Objective-C member's (evolution +/// proposal `swift-first-imported-declarations`), over SceneHosting's symbols +/// on macOS 27.2: only a clear mismatch counts. +@Suite +struct ObjCSwiftTypeCompatibilityTests { + private static let implementingModuleName = "SceneHosting" + + private func propertyType(_ symbolName: String) throws -> Node { + try #require(ObjCSwiftTypeCompatibility.propertyType(ofDemangledMember: try demangleAsNode(symbolName))) + } + + private let object = ObjCEncodedType.object(className: "SHScenePresentationSettings", protocolNames: []) + + @Test func anObjectIsNotAStructOfTheImplementingModule() throws { + // `settings: SceneHosting.ScenePresentationSettings`, the Swift-only + // refinement of the Objective-C `settings`. + let settings = try propertyType("$sSo19SHScenePresentationC12SceneHostingE8settingsAC0cB8SettingsVvg") + #expect(ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: object, swiftType: settings, implementingModuleName: Self.implementingModuleName)) + // A value type of another module may bridge, and an unknown module + // judges nothing. + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: object, swiftType: settings, implementingModuleName: "OtherModule")) + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: object, swiftType: settings, implementingModuleName: nil)) + } + + @Test func anObjectIsAClassOrABridgedValue() throws { + // `__layerFilter: __C.SHSceneLayerFilter`. + let layerFilter = try propertyType("$sSo19SHScenePresentationC12SceneHostingE13__layerFilterSo0a5LayerF0Cvg") + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: object, swiftType: layerFilter, implementingModuleName: Self.implementingModuleName)) + // `isActive: Swift.Bool`, a struct of the standard library. + let isActive = try propertyType("$sSo19SHScenePresentationC12SceneHostingE8isActiveSbvg") + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: object, swiftType: isActive, implementingModuleName: Self.implementingModuleName)) + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: .bool, swiftType: isActive, implementingModuleName: Self.implementingModuleName)) + } + + @Test func aScalarIsNotAReference() throws { + // `scene: __C.FBScene?`: the optional is looked through. + let scene = try propertyType("$sSo19SHScenePresentationC12SceneHostingE5sceneSo7FBSceneCSgvg") + #expect(ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: .longLong, swiftType: scene, implementingModuleName: Self.implementingModuleName)) + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcType: .object(className: "FBScene", protocolNames: []), swiftType: scene, implementingModuleName: Self.implementingModuleName)) + } + + @Test func aMethodComparesItsParametersAndResult() throws { + // `isHosting(sceneLayer: __C.FBSceneLayer) -> Swift.Bool` against + // `- (BOOL)isHostingSceneLayer:(id)`. + let root = try demangleAsNode("$sSo19SHScenePresentationC12SceneHostingE02isD010sceneLayerSbSo07FBSceneG0C_tF") + let functionType = try #require(ObjCSwiftTypeCompatibility.functionType(ofDemangledMember: root)) + let methodType = try #require(ObjCTypeEncodingParser.methodType(from: "B24@0:8@16", matchingArgumentsOf: "isHostingSceneLayer:")) + #expect(!ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcMethodType: methodType, swiftFunctionType: functionType, comparesResult: true, implementingModuleName: Self.implementingModuleName)) + // A scalar parameter where Swift takes a class. + let scalarParameter = try #require(ObjCTypeEncodingParser.methodType(from: "B24@0:8q16", matchingArgumentsOf: "isHostingSceneLayer:")) + #expect(ObjCSwiftTypeCompatibility.isClearlyIncompatible(objcMethodType: scalarParameter, swiftFunctionType: functionType, comparesResult: true, implementingModuleName: Self.implementingModuleName)) + } +} diff --git a/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift b/Tests/SwiftObjCInteropTests/SwiftClassObjectIndexTests.swift similarity index 98% rename from Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift rename to Tests/SwiftObjCInteropTests/SwiftClassObjectIndexTests.swift index 34f7f59ba..2ea1e136a 100644 --- a/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift +++ b/Tests/SwiftObjCInteropTests/SwiftClassObjectIndexTests.swift @@ -4,9 +4,10 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection import MachOObjCSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop /// `SwiftClassObjectIndex` (evolution proposal `objc-custom-class-name`): /// the runtime name a source gave a Swift class, read off the class metadata diff --git a/Tests/SwiftObjCInteropTests/SwiftClassWithoutClassObjectIndexTests.swift b/Tests/SwiftObjCInteropTests/SwiftClassWithoutClassObjectIndexTests.swift new file mode 100644 index 000000000..de18a3cb7 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/SwiftClassWithoutClassObjectIndexTests.swift @@ -0,0 +1,190 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftSymbols +@testable import MachOSwiftSection +import MachOObjCSection +@testable import SwiftSectionTestingSupport +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `SwiftClassWithoutClassObjectIndex` (evolution proposal +/// `objc-classes-without-class-objects`): the Swift classes +/// `__objc_classlist` does not list — generic ones, one with a resilient +/// superclass, ones with generic ancestry — their `class_ro_t` read from +/// Swift metadata through both readers, and the ObjC method table built +/// from it. +@Suite(.serialized, ExclusiveImageAccess(ClassesWithoutClassObjectsFixture.moduleName)) +struct SwiftClassWithoutClassObjectIndexTests { + private static let moduleName = ClassesWithoutClassObjectsFixture.moduleName + + private static let kitModuleName = ClassesWithoutClassObjectsFixture.kitModuleName + + private static let resilientChildRuntimeName = "_TtC\(moduleName.count)\(moduleName)14ResilientChild" + + private static let concreteSubclassRuntimeName = "_TtC\(moduleName.count)\(moduleName)16ConcreteSubclass" + + private static func classesByQualifiedName(in machO: some MachORepresentableWithCache) -> [String: SwiftClassWithoutClassObject] { + Dictionary(SwiftClassWithoutClassObjectIndex.shared.classes(in: machO).map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first }) + } + + /// The offset of the one Swift symbol whose name ends in `suffix`. + private static func offset(ofSymbolEndingIn suffix: String, in machO: some MachORepresentable) -> Int? { + let offsets = machO.swiftSymbols.filter { $0.name.hasSuffix(suffix) }.map(\.offset) + return offsets.count == 1 ? offsets[0] : nil + } + + private static func expectSelectors(of swiftClass: SwiftClassWithoutClassObject, in machO: some ObjCImplementationClassReading, instance instanceSelectors: Set, class classSelectors: Set = []) throws { + let readOnlyData = try #require(swiftClass.readOnlyData(in: machO), "\(swiftClass.name)") + #expect(!readOnlyData.isMetaClass, "\(swiftClass.name)") + #expect(Set(machO.methods(of: readOnlyData).map(\.selector)).isSuperset(of: instanceSelectors), "\(swiftClass.name)") + let metaclassReadOnlyData = try #require(swiftClass.metaclassReadOnlyData(in: machO), "\(swiftClass.name)") + #expect(metaclassReadOnlyData.isMetaClass, "\(swiftClass.name)") + #expect(Set(machO.methods(of: metaclassReadOnlyData).map(\.selector)).isSuperset(of: classSelectors), "\(swiftClass.name)") + } + + private static func expectClasses(in machO: some ObjCImplementationClassReading, keepsLocalSymbols: Bool) throws { + let classes = classesByQualifiedName(in: machO) + + // The negative control has a class object in the class list. + #expect(classes["\(moduleName).PlainWidget"] == nil) + + let genericWidget = try #require(classes["\(moduleName).GenericWidget"]) + #expect(genericWidget.kind == .generic) + #expect(genericWidget.name == "\(moduleName).GenericWidget") + #expect(genericWidget.superclass == .objectiveC(runtimeName: "NSObject")) + #expect(genericWidget.hasObjectiveCAncestry) + #expect(genericWidget.classStubOffset == nil) + try expectSelectors(of: genericWidget, in: machO, instance: ["description", "poke"], class: ["classPoke"]) + + let nestedGenericWidget = try #require(classes["\(moduleName).Namespace.NestedGenericWidget"]) + #expect(nestedGenericWidget.name == "\(moduleName).Namespace.NestedGenericWidget") + try expectSelectors(of: nestedGenericWidget, in: machO, instance: ["nestedPoke"]) + + // The native object model: `SwiftObject` stands in for a superclass. + let genericNativeRoot = try #require(classes["\(moduleName).GenericNativeRoot"]) + #expect(genericNativeRoot.kind == .generic) + #expect(genericNativeRoot.superclass == .objectiveC(runtimeName: "_TtCs12_SwiftObject")) + #expect(!genericNativeRoot.hasObjectiveCAncestry) + + // A resilient superclass: the descriptor records the stub, stripped + // or not; the superclass is a Swift class of another image. + let resilientChild = try #require(classes["\(moduleName).ResilientChild"]) + #expect(resilientChild.kind == .resilientAncestry) + #expect(resilientChild.name == resilientChildRuntimeName) + #expect(resilientChild.superclass == .swiftClass(displayName: "\(kitModuleName).ResilientBase")) + #expect(resilientChild.hasObjectiveCAncestry) + let resilientChildStubOffset = try #require(resilientChild.classStubOffset) + if keepsLocalSymbols { + // A public stub: `…CMs` names its isa word. + #expect(resilientChildStubOffset == offset(ofSymbolEndingIn: "14ResilientChildCMs", in: machO)) + } + try expectSelectors(of: resilientChild, in: machO, instance: ["description", "resilientPoke"]) + + // A generic superclass of another image keeps its arguments. + let resilientGenericChild = try #require(classes["\(moduleName).ResilientGenericChild"]) + #expect(resilientGenericChild.kind == .resilientAncestry) + #expect(resilientGenericChild.superclass == .swiftClass(displayName: "\(kitModuleName).ResilientGenericBase")) + try expectSelectors(of: resilientGenericChild, in: machO, instance: ["resilientGenericPoke"]) + + // Generic ancestry: the stub only its symbol names, and the + // superclass another class without a class object. + let concreteSubclass = try #require(classes["\(moduleName).ConcreteSubclass"]) + #expect(concreteSubclass.kind == .genericAncestry) + #expect(concreteSubclass.name == concreteSubclassRuntimeName) + #expect(concreteSubclass.superclass == .withoutClassObject(name: "\(moduleName).GenericWidget")) + #expect(concreteSubclass.hasObjectiveCAncestry) + if keepsLocalSymbols { + // A non-public stub has no `…CMs` alias: the isa word is one + // reserved word into the full stub `…CMt`. + let concreteSubclassStubOffset = try #require(concreteSubclass.classStubOffset) + let fullStubOffset = try #require(offset(ofSymbolEndingIn: "16ConcreteSubclassCMt", in: machO)) + #expect(concreteSubclassStubOffset == fullStubOffset + 8) + #expect(offset(ofSymbolEndingIn: "16ConcreteSubclassCMs", in: machO) == nil) + } else { + #expect(concreteSubclass.classStubOffset == nil) + } + try expectSelectors(of: concreteSubclass, in: machO, instance: ["description", "concretePoke"]) + + // Generic ancestry on the native object model: no stub at all. + let nativeConcreteSubclass = try #require(classes["\(moduleName).NativeConcreteSubclass"]) + #expect(nativeConcreteSubclass.kind == .genericAncestry) + #expect(nativeConcreteSubclass.superclass == .withoutClassObject(name: "\(moduleName).GenericNativeRoot")) + #expect(!nativeConcreteSubclass.hasObjectiveCAncestry) + #expect(nativeConcreteSubclass.classStubOffset == nil) + } + + @Test func classesWithoutClassObjectsAreReadFromTheFile() throws { + try Self.expectClasses(in: try ClassesWithoutClassObjectsFixture.machOFile(.full), keepsLocalSymbols: true) + } + + @Test func classesWithoutClassObjectsAreReadFromAStrippedFile() throws { + try Self.expectClasses(in: try ClassesWithoutClassObjectsFixture.machOFile(.strippedLocals), keepsLocalSymbols: false) + } + + @Test func classesWithoutClassObjectsAreReadInProcess() throws { + try Self.expectClasses(in: try ClassesWithoutClassObjectsFixture.loadedImage(), keepsLocalSymbols: true) + } + + /// The method index answers for these classes under the names this index + /// gives them, and walks their chains: through another class without a + /// class object, and on to `NSObject` in the system's dyld shared cache. + @Test func hierarchiesWalkThroughClassesWithoutClassObjects() throws { + let machOFile = try ClassesWithoutClassObjectsFixture.machOFile(.full) + let methodIndex = ObjCClassMethodIndex.shared + #expect(methodIndex.runtimeNames(forSwiftClassQualifiedName: "\(Self.moduleName).GenericWidget", in: machOFile) == ["\(Self.moduleName).GenericWidget"]) + #expect(methodIndex.runtimeNames(forSwiftClassQualifiedName: "\(Self.moduleName).ConcreteSubclass", in: machOFile) == [Self.concreteSubclassRuntimeName]) + + let genericWidget = try #require(methodIndex.hierarchy(forRuntimeName: "\(Self.moduleName).GenericWidget", in: machOFile)) + #expect(genericWidget.isAncestorChainComplete) + #expect(genericWidget.ancestors.first?.className == "NSObject") + #expect(genericWidget.ancestorDeclaring(selector: "description", isClassMethod: false)?.className == "NSObject") + #expect(genericWidget.ancestorDeclaring(selector: "poke", isClassMethod: false) == nil) + + let concreteSubclass = try #require(methodIndex.hierarchy(forRuntimeName: Self.concreteSubclassRuntimeName, in: machOFile)) + #expect(concreteSubclass.isAncestorChainComplete) + #expect(concreteSubclass.ancestors.map(\.className).prefix(2) == ["\(Self.moduleName).GenericWidget", "NSObject"]) + #expect(concreteSubclass.ancestorDeclaring(selector: "poke", isClassMethod: false)?.className == "\(Self.moduleName).GenericWidget") + #expect(concreteSubclass.ancestorDeclaring(selector: "concretePoke", isClassMethod: false) == nil) + + // A Swift superclass another image defines: the chain stops at once, + // unnamed — no lookup could answer for its Swift spelling. + let resilientChild = try #require(methodIndex.hierarchy(forRuntimeName: Self.resilientChildRuntimeName, in: machOFile)) + #expect(!resilientChild.isAncestorChainComplete) + #expect(resilientChild.unresolvedAncestorName == nil) + #expect(resilientChild.ancestors.isEmpty) + } + + /// In-process every class object's superclass is a pointer, but a class + /// without a class object only has its superclass's name: the resolver + /// looks it up in the loaded images, and the chain reaches `NSObject` + /// as it does from the file. + @Test func hierarchiesWalkThroughClassesWithoutClassObjectsInProcess() throws { + let machOImage = try ClassesWithoutClassObjectsFixture.loadedImage() + let methodIndex = ObjCClassMethodIndex.shared + let genericWidget = try #require(methodIndex.hierarchy(forRuntimeName: "\(Self.moduleName).GenericWidget", in: machOImage)) + #expect(genericWidget.isAncestorChainComplete) + #expect(genericWidget.ancestorDeclaring(selector: "description", isClassMethod: false)?.className == "NSObject") + + let concreteSubclass = try #require(methodIndex.hierarchy(forRuntimeName: Self.concreteSubclassRuntimeName, in: machOImage)) + #expect(concreteSubclass.isAncestorChainComplete) + #expect(concreteSubclass.ancestors.map(\.className).prefix(2) == ["\(Self.moduleName).GenericWidget", "NSObject"]) + } + + /// One private generic class of each source file under one name: the + /// index names both `SameNamedPrivateGeneric`, so the name tells + /// neither apart. Both are listed under their qualified name — which + /// `ObjCMembers` takes as ambiguous and attributes no member through — + /// and a lookup by the shared name answers neither. + @Test(arguments: ClassesWithoutClassObjectsFixture.Variant.allCases) + func sameNamedPrivateGenericClassesAreBothListed(variant: ClassesWithoutClassObjectsFixture.Variant) throws { + let machO = try ClassesWithoutClassObjectsFixture.machOFile(variant) + let qualifiedName = "\(Self.moduleName).SameNamedPrivateGeneric" + let classes = SwiftClassWithoutClassObjectIndex.shared.classes(in: machO).filter { $0.qualifiedName == qualifiedName } + try #require(classes.count == 2, "\(SwiftClassWithoutClassObjectIndex.shared.classes(in: machO).map(\.qualifiedName))") + #expect(Set(classes.map(\.name)) == ["\(qualifiedName)"]) + #expect(SwiftClassWithoutClassObjectIndex.shared.names(forSwiftClassQualifiedName: qualifiedName, in: machO).count == 2) + #expect(SwiftClassWithoutClassObjectIndex.shared.swiftClass(named: "\(qualifiedName)", in: machO) == nil) + } +} diff --git a/Tests/SwiftObjCInteropTests/SwiftDeclaredObjCProtocolIndexTests.swift b/Tests/SwiftObjCInteropTests/SwiftDeclaredObjCProtocolIndexTests.swift new file mode 100644 index 000000000..51437d0b4 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/SwiftDeclaredObjCProtocolIndexTests.swift @@ -0,0 +1,148 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@_spi(Internals) import Demangling +@testable import MachOSwiftSection +@testable import SwiftSectionTestingSupport +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// `SwiftDeclaredObjCProtocolIndex` (evolution proposal +/// `swift-declared-objc-protocols`): which `@objc` protocols declared in +/// Swift an image defines — from `__swift5_fieldmd`, never from the records' +/// `IsSwift` bit, which the kit's protocols carry in the client too — each +/// paired with its Objective-C record, read in full through every reader. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct SwiftDeclaredObjCProtocolIndexTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private static let kitModuleName = SwiftDeclaredObjCProtocolsFixture.kitModuleName + + private static func defaultRuntimeName(of name: String, module: String = moduleName) -> String { + "_TtP\(module.count)\(module)\(name.count)\(name)_" + } + + private static func qualifiedName(_ name: String) -> String { + "\(moduleName).\(name)" + } + + private static func protocolsByQualifiedName(in machO: some MachORepresentableWithCache) -> [String: SwiftDeclaredObjCProtocol] { + Dictionary(SwiftDeclaredObjCProtocolIndex.shared.protocols(in: machO).map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first }) + } + + /// The client's protocols and nothing else — not the kit's, whose + /// Swift-emitted copies the client holds — paired by default runtime name + /// or, renamed to its own name, by name; renamed to another, unpaired. + private static func expectDeclaredProtocols(in machO: some MachORepresentableWithCache) throws { + let protocols = protocolsByQualifiedName(in: machO) + #expect(Set(protocols.keys) == Set(["DerivedSelectors", "SameNameRenamed", "DifferentlyNamed", "RefinedProtocol", "InternalProtocol", "PrivateProtocol", "Outer.NestedProtocol", "KitWidgetAdopted"].map(qualifiedName))) + for declaredProtocol in protocols.values { + guard case .fieldDescriptor = declaredProtocol.evidence else { + Issue.record("\(declaredProtocol.qualifiedName) was not found through its field descriptor") + continue + } + #expect(declaredProtocol.mangledName.hasPrefix("$s"), "\(declaredProtocol.qualifiedName)") + } + + let derivedSelectors = try #require(protocols[qualifiedName("DerivedSelectors")]) + #expect(derivedSelectors.record?.runtimeName == defaultRuntimeName(of: "DerivedSelectors")) + #expect(!derivedSelectors.hasExplicitObjCName) + + let refinedProtocol = try #require(protocols[qualifiedName("RefinedProtocol")]) + #expect(refinedProtocol.record?.runtimeName == defaultRuntimeName(of: "RefinedProtocol")) + #expect(refinedProtocol.record?.inheritedProtocolRuntimeNames == ["SameNameRenamed"]) + + let internalProtocol = try #require(protocols[qualifiedName("InternalProtocol")]) + #expect(internalProtocol.record?.runtimeName == defaultRuntimeName(of: "InternalProtocol")) + + let sameNameRenamed = try #require(protocols[qualifiedName("SameNameRenamed")]) + #expect(sameNameRenamed.record?.runtimeName == "SameNameRenamed") + #expect(sameNameRenamed.hasExplicitObjCName) + + let differentlyNamed = try #require(protocols[qualifiedName("DifferentlyNamed")]) + #expect(differentlyNamed.record == nil) + #expect(differentlyNamed.hasExplicitObjCName) + + // The renamed records nothing claims: the client's own one renamed to + // another name, and the kit's renamed ones it references. + let unclaimedNames = SwiftDeclaredObjCProtocolIndex.shared.unclaimedSwiftEmittedRecords(in: machO).map(\.runtimeName) + #expect(Set(unclaimedNames) == ["PRBDifferentlyNamed", "KITRenamedObserver", "KitSameName"]) + + #expect(SwiftDeclaredObjCProtocolIndex.shared.qualifiedName(forRuntimeName: defaultRuntimeName(of: "DerivedSelectors"), in: machO) == qualifiedName("DerivedSelectors")) + #expect(SwiftDeclaredObjCProtocolIndex.shared.qualifiedName(forRuntimeName: "SameNameRenamed", in: machO) == qualifiedName("SameNameRenamed")) + #expect(SwiftDeclaredObjCProtocolIndex.shared.qualifiedName(forRuntimeName: defaultRuntimeName(of: "KitObserver", module: kitModuleName), in: machO) == nil) + + try expectDerivedSelectorsRecord(try #require(derivedSelectors.record)) + } + + /// Every list of the record, and one extended encoding per method in + /// list order: the array MachOObjCSection reads only the first entry of. + private static func expectDerivedSelectorsRecord(_ record: ObjCProtocolRecord) throws { + #expect(record.isEmittedBySwift) + #expect(record.inheritedProtocolRuntimeNames == ["NSObject"]) + #expect(Set(record.requiredInstanceMethods.map(\.selector)) == [ + "initWithIdentifier:", "nameFor:", "teamNameFor:error:", "hangPointsWithInput:error:", "perform:with:", + "downloadWithIdentifier:completion:", "tokenAndReturnError:", "reload", "title", "isEnabled", "setIsEnabled:", + "objectAtIndexedSubscript:", "setObject:atIndexedSubscript:", + ]) + #expect(Set(record.requiredClassMethods.map(\.selector)) == ["makeDefault", "shared"]) + #expect(Set(record.optionalInstanceMethods.map(\.selector)) == ["scrollTo:animated:", "optionalCount"]) + #expect(record.optionalClassMethods.isEmpty) + #expect(record.instanceProperties.map(\.name) == ["title", "isEnabled", "optionalCount"]) + #expect(record.instanceProperties.first?.attributes == #"T@"NSString",N,R"#) + #expect(record.classProperties.map(\.name) == ["shared"]) + + let extendedEncodingsBySelector = Dictionary(record.allMethods.map { ($0.selector, $0.extendedTypeEncoding) }, uniquingKeysWith: { first, _ in first }) + #expect(record.allMethods.allSatisfy { $0.extendedTypeEncoding != nil }) + #expect(extendedEncodingsBySelector["teamNameFor:error:"] == #"@"NSString"32@0:8@"NSString"16^@24"#) + #expect(extendedEncodingsBySelector["downloadWithIdentifier:completion:"] == #"v32@0:8@"NSString"16@?24"#) + #expect(extendedEncodingsBySelector["scrollTo:animated:"] == "v28@0:8q16B24") + #expect(extendedEncodingsBySelector["shared"] == #"@"NSObject"16@0:8"#) + // The plain encoding stays the method list's own. + #expect(record.requiredInstanceMethods.first { $0.selector == "teamNameFor:error:" }?.typeEncoding == "@32@0:8@16^@24") + } + + @Test func fileDefinesItsOwnProtocolsOnly() throws { + try Self.expectDeclaredProtocols(in: SwiftDeclaredObjCProtocolsFixture.machOFile(.full)) + } + + /// Nothing the index reads is a local symbol. + @Test func strippedFileDefinesTheSameProtocols() throws { + try Self.expectDeclaredProtocols(in: SwiftDeclaredObjCProtocolsFixture.machOFile(.strippedLocals)) + } + + @Test func loadedImageDefinesTheSameProtocols() throws { + try Self.expectDeclaredProtocols(in: SwiftDeclaredObjCProtocolsFixture.loadedImage()) + } + + /// No `__swift5_fieldmd`: a `_TtP` record spelling the image's own module + /// is the image's; the renamed ones go unseen, and the kit's copies stay + /// out. + @Test func withoutReflectionMetadataTheRuntimeNamesDecide() throws { + let machO = try SwiftDeclaredObjCProtocolsFixture.machOFile(.withoutReflectionMetadata) + #expect(throws: (any Error).self) { try machO.swift.fieldDescriptors } + + let protocols = Self.protocolsByQualifiedName(in: machO) + #expect(Set(protocols.keys) == Set(["DerivedSelectors", "RefinedProtocol", "InternalProtocol", "PrivateProtocol", "Outer.NestedProtocol", "KitWidgetAdopted"].map(Self.qualifiedName))) + for declaredProtocol in protocols.values { + #expect(declaredProtocol.evidence == .runtimeName, "\(declaredProtocol.qualifiedName)") + #expect(!declaredProtocol.hasExplicitObjCName, "\(declaredProtocol.qualifiedName)") + // The modern spelling of the name, as a field descriptor gives it. + let node = try demangleAsNodeTransient(declaredProtocol.mangledName) + #expect(NodeTypeNaming.protocolQualifiedName(of: try #require(node.first(of: .protocol))) == declaredProtocol.qualifiedName) + } + try Self.expectDerivedSelectorsRecord(try #require(protocols[Self.qualifiedName("DerivedSelectors")]?.record)) + } + + /// The field descriptors the index reads are the section walk's: one of + /// kind `ObjCProtocol` per protocol the client declares. + @Test func fieldDescriptorWalkFindsTheProtocolRecords() throws { + let machO = try SwiftDeclaredObjCProtocolsFixture.machOFile(.full) + let descriptors = try machO.swift.fieldDescriptors + for (earlier, later) in zip(descriptors, descriptors.dropFirst()) { + #expect(later.offset - earlier.offset == earlier.actualSize) + } + #expect(descriptors.filter { $0.kind == .objCProtocol }.count == 8) + } +} diff --git a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift index 18a65574e..2e4a8b299 100644 --- a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift +++ b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift @@ -7,8 +7,8 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Printing the SymbolTestsCore fixture's definitions from several tasks at /// once reads byte for byte as printing them one after another (evolution diff --git a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift index c4e956e27..731524a94 100644 --- a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift +++ b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift @@ -6,7 +6,7 @@ import Testing import MachOKit import Demangling @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport import SwiftDump // MARK: - In-process fixture diff --git a/Tests/SwiftPrintingTests/NodePrinterTests.swift b/Tests/SwiftPrintingTests/NodePrinterTests.swift index f4737653a..246c98329 100644 --- a/Tests/SwiftPrintingTests/NodePrinterTests.swift +++ b/Tests/SwiftPrintingTests/NodePrinterTests.swift @@ -6,9 +6,9 @@ import Demangling import Testing import Dependencies @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport -@_spi(Internals) import MachOSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +@_spi(Internals) import SwiftSymbols @testable import SwiftDump @testable import SwiftInterface @testable @_spi(Internals) import SwiftInspection @@ -254,7 +254,7 @@ struct NodePrinterUnitTests { @Suite final class NodePrinterIntegrationTests: DyldCacheTests, @unchecked Sendable { - @Dependency(\.symbolIndexStore) + @Dependency(\.swiftSymbolIndexStore) private var symbolIndexStore override class var cacheImageName: MachOImageName { .SwiftUICore } diff --git a/Tests/SwiftPrintingTests/StaticFieldLayoutProviderReuseTests.swift b/Tests/SwiftPrintingTests/StaticFieldLayoutProviderReuseTests.swift new file mode 100644 index 000000000..d5be0a6a0 --- /dev/null +++ b/Tests/SwiftPrintingTests/StaticFieldLayoutProviderReuseTests.swift @@ -0,0 +1,106 @@ +import Foundation +import Testing +import MachOKit +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftPrinting +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// `updateConfiguration(_:)` keeps the memoized static field-layout provider +/// while the provider's inputs stay the same, and rebuilds it when they +/// change. +/// +/// RuntimeViewer hands the printer its configuration before every interface +/// print, usually unchanged. Each call used to discard the provider, so an +/// offline (`MachOFile`) print with a layout comment on rebuilt the static +/// layout calculator — over the default resolution a new dependency closure, +/// a new walk over every image of the dyld caches searched, and a dependency +/// type index started from scratch — for every interface it printed. +/// +/// The provider depends on two things only: whether any configuration flag +/// asks for one, and `staticLayoutDependencyResolution`. A change to either +/// still rebuilds it, which is what the reset was added for. +@Suite +final class StaticFieldLayoutProviderReuseTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + /// A configuration asking for field offsets, laid out over the fixture + /// alone so that building a provider stays cheap. + private static func fieldOffsetConfiguration() -> SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.printFieldOffset = true + configuration.staticLayoutDependencyResolution = .singleImage + return configuration + } + + @Test func anEqualConfigurationKeepsTheProvider() throws { + let configuration = Self.fieldOffsetConfiguration() + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + let provider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + + printer.updateConfiguration(configuration) + + let providerAfterUpdate = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + #expect(providerAfterUpdate === provider) + } + + /// Any layout flag needs the same provider: turning a second one on, or + /// changing a flag the provider does not read, keeps it. + @Test func aChangeThatStillNeedsAProviderKeepsIt() throws { + var configuration = Self.fieldOffsetConfiguration() + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + let provider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + + configuration.printTypeLayout = true + configuration.printEnumLayout = true + configuration.printMemberAddress = true + printer.updateConfiguration(configuration) + let providerAfterMoreFlags = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + #expect(providerAfterMoreFlags === provider) + + configuration.printFieldOffset = false + printer.updateConfiguration(configuration) + let providerAfterDroppingTheFirstFlag = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + #expect(providerAfterDroppingTheFirstFlag === provider) + } + + /// The guarantee the reset was added for: a change that turns the need + /// off, turns it back on, or changes the resolution reaches the provider. + @Test func aChangeOfTheProvidersInputsRebuildsIt() throws { + var configuration = Self.fieldOffsetConfiguration() + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + let firstProvider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + + configuration.printFieldOffset = false + printer.updateConfiguration(configuration) + #expect(printer.staticFieldLayoutProvider() == nil, "no flag needs a provider") + + configuration.printFieldOffset = true + printer.updateConfiguration(configuration) + let secondProvider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + #expect(secondProvider !== firstProvider) + + configuration.staticLayoutDependencyResolution = .dependencyClosure(searchPaths: []) + printer.updateConfiguration(configuration) + let thirdProvider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + #expect(thirdProvider !== secondProvider, "a new resolution builds a new provider") + + printer.updateConfiguration(configuration) + #expect(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider === thirdProvider) + } + + /// A marked print needs every layout comment's content, so it needs a + /// provider with every layout flag off. + @Test func markingOptionalContentNeedsAProvider() throws { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.staticLayoutDependencyResolution = .singleImage + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + #expect(printer.staticFieldLayoutProvider() == nil) + + configuration.marksOptionalContent = true + printer.updateConfiguration(configuration) + let provider = try #require(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider) + + configuration.printFieldOffset = true + printer.updateConfiguration(configuration) + #expect(printer.staticFieldLayoutProvider() as? MachOFileStaticFieldLayoutProvider === provider) + } +} diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift index e94117d28..f6c827974 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift @@ -1,8 +1,8 @@ import Foundation import Testing import MachOKit -import MachOFixtureSupport -@testable import MachOTestingSupport +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport @_spi(Support) import SwiftIndexing import SwiftInspection import SwiftDeclarationRendering diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift index a7fefa5bd..706959d3f 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing import MachOKit -import MachOFixtureSupport +import SwiftSectionFixtureSupport @_spi(Support) import SwiftIndexing import SwiftInspection @_spi(Support) import SwiftPrivateDiscriminators diff --git a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift index 782cbdb45..437d22f83 100644 --- a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift @@ -52,6 +52,20 @@ struct CommandLineErrorTranslationTests { #expect((CommandLineErrorTranslation.translated(error) as? ValidationError)?.message == expectedMessage) } + @Test("A platform objc evolution --emit-available cannot infer is a usage error that points at --platform", arguments: [ + ( + ObjCAvailabilityPlatformInferenceError.noPlatform(path: "bridge.dylib"), + "--emit-available could not infer an availability-macro platform from bridge.dylib (no LC_BUILD_VERSION, or a platform the availability macros have no name for); pass --platform explicitly." + ), + ( + .conflictingPlatforms(["ios", "macos"]), + "--emit-available found conflicting platforms across the inputs (ios, macos); pass --platform explicitly." + ), + ]) + func objcAvailabilityPlatformInference(error: ObjCAvailabilityPlatformInferenceError, expectedMessage: String) { + #expect((CommandLineErrorTranslation.translated(error) as? ValidationError)?.message == expectedMessage) + } + @Test("Errors the command line never reworded pass through unchanged") func unrelatedErrorsPassThrough() { let translated = CommandLineErrorTranslation.translated(ObjCDeclarationLookupError.declarationNotFound("NSString")) diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index 7c1cc64a0..6e16f97a8 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -96,6 +96,22 @@ struct CommandRequestMappingTests { #expect(request.demangleOptions == expectedOptions) } + @Test("the dump spells existentials with any under every preset unless --disable-existential-any") + func dumpExistentialAny() throws { + let defaultRequest = try DumpCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.demangleOptions.contains(.useExistentialAny)) + // The library's own default is what the CLI prints by default. + #expect(DumpRequest(source: defaultRequest.source).demangleOptions == defaultRequest.demangleOptions) + for preset in ["default", "simplified", "interface"] { + let presetRequest = try DumpCommand.parse(["/tmp/Sample", "--demangle-options", preset]).makeRequest() + #expect(presetRequest.demangleOptions.contains(.useExistentialAny), "\(preset)") + } + var expectedOptions = defaultRequest.demangleOptions + expectedOptions.remove(.useExistentialAny) + let request = try DumpCommand.parse(["/tmp/Sample", "--disable-existential-any"]).makeRequest() + #expect(request.demangleOptions == expectedOptions) + } + @Test("--emit-field-offsets alone is the flat form") func dumpFlatFieldOffsets() throws { #expect(try DumpCommand.parse(["/tmp/Sample", "--emit-field-offsets"]).makeRequest().fieldOffsetComments == .flat) @@ -118,7 +134,7 @@ struct CommandRequestMappingTests { "--resolve-c-module-names", "--supplementary-apinotes", "/tmp/Extra.apinotes", "--emit-offset-comments", "--sort-members-by-offset", "--exported-only", "--infer-objc-overrides", "--module-selectors", "--requirements-on-associated-types", "--emit-header", - "--emit-private-source-files", + "--emit-private-source-files", "--expand-macros", ]).makeRequest() #expect(request.showsCImportedTypes) #expect(request.parsesOpaqueReturnTypes) @@ -131,6 +147,7 @@ struct CommandRequestMappingTests { #expect(request.protocolRequirementPlacement == .associatedTypes) #expect(request.emitsHeader) #expect(request.emitsPrivateDeclarationSourceFiles) + #expect(request.expandsMacros) } @Test("interface prints without module selectors unless asked") @@ -138,6 +155,22 @@ struct CommandRequestMappingTests { #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().usesModuleSelectors == false) } + @Test("interface spells existentials with any unless --no-existential-any") + func interfaceExistentialAny() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.usesExistentialAny) + #expect(InterfaceRequest(source: defaultRequest.source).usesExistentialAny) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--no-existential-any"]).makeRequest().usesExistentialAny == false) + } + + @Test("interface folds what an attached macro generated unless --expand-macros") + func interfaceExpandMacros() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.expandsMacros == false) + #expect(InterfaceRequest(source: defaultRequest.source).expandsMacros == false) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--expand-macros"]).makeRequest().expandsMacros) + } + @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) @@ -237,4 +270,16 @@ struct CommandRequestMappingTests { #expect(request.labels == ["a", "b"]) #expect(request.report == .json) } + + @Test("objc evolution's output flags become one report", arguments: [ + ([String](), ObjCAPIEvolutionRequest.Report.lineage), + (["--summary-only"], .summary), + (["--json"], .json), + (["--interface"], .annotatedInterface(availabilityAttributes: .none)), + (["--interface", "--emit-available"], .annotatedInterface(availabilityAttributes: .inferredPlatform)), + (["--interface", "--emit-available", "--platform", "ios"], .annotatedInterface(availabilityAttributes: .platform("ios"))), + ]) + func objcEvolutionReport(flags: [String], expectedReport: ObjCAPIEvolutionRequest.Report) throws { + #expect(try ObjCEvolutionCommand.parse(flags + ["old.dylib", "new.dylib"]).makeRequest().report == expectedReport) + } } diff --git a/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift new file mode 100644 index 000000000..026f3a325 --- /dev/null +++ b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift @@ -0,0 +1,107 @@ +import Foundation +import Testing +import ArgumentParser +import SwiftSectionKit +@testable import swift_section + +/// `refs` and `symbolicate`: the flags each reaches in the request, and the +/// combinations the command line refuses. +@Suite +struct CrossReferenceCommandTests { + @Test func refsRequiresExactlyOneQuery() { + #expect(throws: (any Error).self) { try ReferencesCommand.parse(["--uses-system-dyld-shared-cache"]) } + #expect(throws: (any Error).self) { try ReferencesCommand.parse(["--uses-system-dyld-shared-cache", "--selector", "init", "--string", "init"]) } + } + + @Test("refs needs exactly one input", arguments: [ + ["--selector", "init"], + ["/tmp/Sample", "--uses-system-dyld-shared-cache", "--selector", "init"], + ["--dyld-shared-cache", "/tmp/cache", "--uses-system-dyld-shared-cache", "--selector", "init"], + ]) + func refsRequiresExactlyOneInput(arguments: [String]) { + #expect(throws: (any Error).self) { try ReferencesCommand.parse(arguments) } + } + + @Test func refsMapsItsFlagsOntoTheRequest() throws { + let request = try ReferencesCommand.parse([ + "--selector", "makeKeyAndOrderFront:", "--dyld-shared-cache", "/tmp/cache", + "--in-image", "AppKit", "--in-image", "Foundation", "--limit", "5", "--json", + ]).makeRequest() + #expect(request == ReferencesRequest( + input: .dyldSharedCache(path: "/tmp/cache"), + subject: .selector("makeKeyAndOrderFront:"), + imageNames: ["AppKit", "Foundation"], + limit: 5, + format: .json + )) + } + + @Test func refsReadsFilesWithAnArchitecture() throws { + let request = try ReferencesCommand.parse(["/tmp/Foo", "/tmp/Bar.dylib", "-a", "arm64e", "--string", "Hello"]).makeRequest() + #expect(request.input == .files(paths: ["/tmp/Foo", "/tmp/Bar.dylib"], architecture: .arm64e)) + #expect(request.subject == .string("Hello")) + #expect(request.format == .text) + } + + @Test("Each query flag reaches its subject", arguments: [ + (["--symbol", "_objc_msgSend"], CrossReferenceSubject.symbol("_objc_msgSend")), + (["--class", "NSWindow"], .objectiveCClass("NSWindow")), + (["--function", "0x1880a1000"], .function(address: 0x1_880A_1000, imageName: nil)), + (["--function", "4096", "--function-image", "Foo"], .function(address: 4096, imageName: "Foo")), + (["--ivar", "NSWindow._frame"], .instanceVariable(className: "NSWindow", name: "_frame")), + (["--string", "NSWindowDidBecomeKeyNotification"], .string("NSWindowDidBecomeKeyNotification")), + ]) + func refsMapsEachQuery(arguments: [String], subject: CrossReferenceSubject) throws { + let request = try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]).makeRequest() + #expect(request.subject == subject) + #expect(request.input == .systemDyldSharedCache) + #expect(request.direction == .callers) + } + + @Test func refsCalleesFollowAFunction() throws { + let request = try ReferencesCommand.parse(["--function", "0x10", "--callees", "--uses-system-dyld-shared-cache"]).makeRequest() + #expect(request.direction == .callees) + } + + @Test("refs refuses flags that need another one", arguments: [ + ["--selector", "init", "--callees"], + ["--selector", "init", "--function-image", "Foo"], + ["--ivar", "NoDot"], + ["--ivar", "Trailing."], + ["--function", "nowhere"], + ["--selector", "init", "--limit", "0"], + ]) + func refsRefusesIncompleteFlags(arguments: [String]) { + #expect(throws: (any Error).self) { try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]) } + } + + @Test func symbolicateMapsItsFlagsOntoTheRequest() throws { + let request = try SymbolicateCommand.parse(["0x10", "42", "--file", "/tmp/Foo", "--file", "/tmp/Bar.dylib", "--in-image", "Bar.dylib", "--json"]).makeRequest() + #expect(request == SymbolicateRequest( + input: .files(paths: ["/tmp/Foo", "/tmp/Bar.dylib"], architecture: nil), + addresses: [0x10, 42], + imageName: "Bar.dylib", + format: .json + )) + } + + @Test("symbolicate refuses what it cannot read", arguments: [ + ["--uses-system-dyld-shared-cache"], + ["zz", "--uses-system-dyld-shared-cache"], + ["0x10"], + ["0x10", "--uses-system-dyld-shared-cache", "--in-image", "A", "--in-image", "B"], + ]) + func symbolicateRefusesBadInput(arguments: [String]) { + #expect(throws: (any Error).self) { try SymbolicateCommand.parse(arguments) } + } + + /// Naming a missing image is a usage mistake: exit code 64, the flags + /// named. + @Test func crossReferenceUsageErrorsBecomeValidationErrors() { + let missingImage = CommandLineErrorTranslation.translated(CrossReferenceRequestError.imageNotFound(name: "Nowhere")) + #expect((missingImage as? ValidationError)?.message.contains("--in-image") == true) + let ambiguous = CommandLineErrorTranslation.translated(CrossReferenceRequestError.ambiguousFunction(address: 0x10, imagePaths: ["/tmp/A", "/tmp/B"])) + #expect((ambiguous as? ValidationError)?.message.contains("--function-image") == true) + #expect(CommandLineErrorTranslation.translated(CrossReferenceRequestError.noFunction(address: 0x10)) is CrossReferenceRequestError) + } +} diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift index e3f2a07aa..bbdb2d2e1 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift @@ -102,4 +102,25 @@ struct ObjCAPICommandParsingTests { try ObjCEvolutionCommand.parse(["/tmp/v1", "/tmp/v2", "--json", "--summary-only"]) } } + + @Test("evolution parses the annotated-header flags") + func evolutionParsesInterfaceFlags() throws { + let command = try ObjCEvolutionCommand.parse(["/tmp/v1", "/tmp/v2", "--interface", "--emit-available", "--platform", "ios"]) + #expect(command.interface) + #expect(command.emitAvailable) + #expect(command.platform == "ios") + } + + @Test("evolution rejects the annotated-header flags it cannot honor", arguments: [ + (["--interface", "--json"], "--json and --interface are mutually exclusive"), + (["--interface", "--summary-only"], "--interface and --summary-only are mutually exclusive"), + (["--emit-available"], "--emit-available requires --interface"), + (["--interface", "--platform", "ios"], "--platform requires --emit-available"), + ]) + func evolutionRejectsInterfaceFlagMisuse(flags: [String], messagePart: String) { + let error = #expect(throws: (any Error).self) { + try ObjCEvolutionCommand.parse(flags + ["/tmp/v1", "/tmp/v2"]) + } + #expect(error.map { ObjCEvolutionCommand.message(for: $0) }?.contains(messagePart) == true) + } } diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift index 9bdc35af1..4044e1343 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift @@ -246,6 +246,17 @@ struct ObjCSectionCommandTests { #expect(command.kind == .categories) } + @Test("The interface subcommand prints the Swift view only with --swift, and the request knows") + func parsesSwiftView() throws { + let header = try ObjCInterfaceCommand.parse(["NSColor", "/tmp/Sample"]) + #expect(!header.printsSwiftImport) + #expect(try !header.makeRequest().printsSwiftImport) + + let swiftView = try ObjCInterfaceCommand.parse(["NSColor", "/tmp/Sample", "--swift"]) + #expect(swiftView.printsSwiftImport) + #expect(try swiftView.makeRequest().printsSwiftImport) + } + // MARK: - Command Tree @Test("dump is the default objc subcommand") diff --git a/Tests/SwiftSectionKitTests/ClassesWithoutClassObjectsRequestTests.swift b/Tests/SwiftSectionKitTests/ClassesWithoutClassObjectsRequestTests.swift new file mode 100644 index 000000000..faf60e335 --- /dev/null +++ b/Tests/SwiftSectionKitTests/ClassesWithoutClassObjectsRequestTests.swift @@ -0,0 +1,42 @@ +import Foundation +import Testing +import SwiftSectionKit +@testable import SwiftSectionTestingSupport + +/// The `objc` requests list the Swift classes an image keeps no class object +/// for (evolution proposal `objc-classes-without-class-objects`), their +/// `class_ro_t` read from Swift metadata and handed to the ObjC indexer: +/// generic classes, and the classes `__objc_stublist` registers. +@Suite(.serialized, ExclusiveImageAccess(ClassesWithoutClassObjectsFixture.moduleName)) +struct ClassesWithoutClassObjectsRequestTests { + private static let moduleName = ClassesWithoutClassObjectsFixture.moduleName + + private static let kitModuleName = ClassesWithoutClassObjectsFixture.kitModuleName + + private static func source() throws -> MachOSource { + .file(path: try ClassesWithoutClassObjectsFixture.libraryURL(.full).path, architecture: nil) + } + + @Test("An ObjC dump lists the classes without a class object, under the comment naming why") + func dumpListsClassesWithoutClassObjects() async throws { + let output = RecordingOutput() + try await ObjCDumpRequest(source: try Self.source(), kinds: [.classes]).run(output: output) + let product = output.printedProduct + + #expect(product.contains("// Generic Swift class, instantiated at runtime\n@interface \(Self.moduleName).GenericWidget : NSObject"), "\(product)") + #expect(product.contains("// Generic Swift class, instantiated at runtime\n@interface \(Self.moduleName).Namespace.NestedGenericWidget : NSObject"), "\(product)") + #expect(product.contains("// Generic Swift class, instantiated at runtime\n@interface \(Self.moduleName).GenericNativeRoot : _TtCs12_SwiftObject"), "\(product)") + #expect(product.contains("// Swift class with resilient ancestry, registered through __objc_stublist\n@interface _TtC\(Self.moduleName.count)\(Self.moduleName)14ResilientChild : \(Self.kitModuleName).ResilientBase"), "\(product)") + #expect(product.contains("// Swift class with resilient ancestry, registered through __objc_stublist\n@interface _TtC\(Self.moduleName.count)\(Self.moduleName)21ResilientGenericChild : \(Self.kitModuleName).ResilientGenericBase"), "\(product)") + #expect(product.contains("// Swift class with generic ancestry, registered through __objc_stublist\n@interface _TtC\(Self.moduleName.count)\(Self.moduleName)16ConcreteSubclass : \(Self.moduleName).GenericWidget"), "\(product)") + // Generic ancestry on the native object model: nothing registers it. + #expect(!product.contains("NativeConcreteSubclass"), "\(product)") + // The methods come from the templates. + #expect(product.contains("- (void)poke;"), "\(product)") + #expect(product.contains("+ (void)classPoke;"), "\(product)") + #expect(product.contains("- (void)resilientPoke;"), "\(product)") + #expect(product.contains("- (void)concretePoke;"), "\(product)") + // The negative control is listed as before. + #expect(product.contains("@interface _TtC\(Self.moduleName.count)\(Self.moduleName)11PlainWidget : NSObject"), "\(product)") + } +} diff --git a/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift new file mode 100644 index 000000000..f650cff4e --- /dev/null +++ b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift @@ -0,0 +1,193 @@ +import Foundation +import Testing +import MachOKit +import MachOKitExtensions +import CrossReferenceAnalysis +import SwiftSectionKit + +/// `refs` and `symbolicate` as a host runs them: over the running system's +/// dyld shared cache read from its files, an archived cache, and a +/// standalone app executable. +@Suite(.enabled(if: FullDyldCache.cachedHost != nil, "needs the running system's dyld shared cache")) +struct CrossReferenceRequestTests { + static let archivedCachePath = "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e" + static let selector = "makeKeyAndOrderFront:" + + private static func isSend(_ target: CodeReferenceTarget, of selector: String) -> Bool { + switch target { + case .messageSend(selector, _), .superMessageSend(selector, _): true + default: false + } + } + + @Test(.enabled(if: FileManager.default.fileExists(atPath: archivedCachePath), "needs the archived macOS 27.2 cache")) + func refsListsCallerRowsForASelectorInAnArchivedCache() async throws { + let output = RecordingOutput() + let result = try await ReferencesRequest(input: .dyldSharedCache(path: Self.archivedCachePath), subject: .selector(Self.selector)).run(output: output) + #expect(result.rows.count > 100) + #expect(!result.isTruncated) + #expect(result.rows.allSatisfy { Self.isSend($0.reference.target, of: Self.selector) }) + #expect(result.rows.contains { $0.imagePath.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) + let lines = output.printedProduct.split(separator: "\n") + #expect(lines.count == result.rows.count) + #expect(lines.allSatisfy { $0.hasPrefix("0x") && $0.contains(" \(Self.selector)") }) + #expect(output.messages(of: .note).count == 1) + } + + @Test func refsJSONUsesHexadecimalStringAddresses() async throws { + let output = RecordingOutput() + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), imageNames: ["AppKit"], limit: 5, format: .json).run(output: output) + guard case .data(let data)? = output.products.first, output.products.count == 1 else { + Issue.record("expected one JSON document, got \(output.products.count) pieces") + return + } + let document = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect((document["query"] as? [String: Any])?["selector"] as? String == Self.selector) + #expect(document["isTruncated"] as? Bool == true) + #expect((document["scannedImageCount"] as? Int).map { $0 >= 1 } == true) + #expect(((document["input"] as? [String: Any])?["imageCount"] as? Int).map { $0 > 1000 } == true) + let references = try #require(document["references"] as? [[String: Any]]) + #expect(references.count == 5) + for reference in references { + let site = try #require(reference["site"] as? String) + #expect(site.hasPrefix("0x")) + let function = try #require(reference["function"] as? [String: Any]) + #expect((function["address"] as? String)?.hasPrefix("0x") == true) + #expect((reference["image"] as? String)?.hasSuffix("/AppKit") == true) + #expect(["call", "tailCall"].contains(reference["kind"] as? String)) + let target = try #require(reference["target"] as? [String: Any]) + let send = (target["messageSend"] ?? target["superMessageSend"]) as? [String: Any] + #expect(send?["selector"] as? String == Self.selector) + } + } + + @Test func refsMarksTruncatedResultsWhenLimited() async throws { + let request = ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), imageNames: ["AppKit"]) + let whole = try await request.run(output: RecordingOutput()) + #expect(whole.rows.count > 1) + #expect(!whole.isTruncated) + + var limited = request + limited.limit = 1 + let output = RecordingOutput() + let truncated = try await limited.run(output: output) + #expect(truncated.isTruncated) + #expect(truncated.rows == Array(whole.rows.prefix(1))) + #expect(output.printedProduct.split(separator: "\n").count == 1) + #expect(output.messages(of: .note).first?.contains("the first 1 of \(whole.rows.count)") == true) + + limited.limit = whole.rows.count + #expect(try await !limited.run(output: RecordingOutput()).isTruncated) + } + + @Test func refsListsTheCalleesOfAFunction() async throws { + let callers = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), imageNames: ["AppKit"], limit: 1).run(output: RecordingOutput()) + let caller = try #require(callers.rows.first) + let callees = try await ReferencesRequest( + input: .systemDyldSharedCache, + subject: .function(address: caller.reference.function.address, imageName: nil), + direction: .callees + ).run(output: RecordingOutput()) + #expect(callees.scannedImageCount == 1) + #expect(callees.rows.contains { $0.reference == caller.reference }) + #expect(callees.rows.allSatisfy { $0.reference.function == caller.reference.function }) + } + + /// The callers of `objc_autoreleasePoolPush` AppKit holds: it calls the + /// function libobjc defines. + @Test func refsListsTheCallersOfASymbol() async throws { + let result = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .symbol("_objc_autoreleasePoolPush"), imageNames: ["AppKit"]).run(output: RecordingOutput()) + #expect(!result.rows.isEmpty) + #expect(result.rows.allSatisfy { $0.imagePath.hasSuffix("/AppKit") && $0.reference.kind != .reference }) + let callee = try #require(result.rows.first.flatMap { row -> CodeLocation? in + if case .function(let location) = row.reference.target { location } else { nil } + }) + let symbolications = try await SymbolicateRequest(input: .systemDyldSharedCache, addresses: [callee.address]).run(output: RecordingOutput()) + guard case .function(_, let name, 0)? = symbolications.first?.meaning else { + Issue.record("\(String(describing: symbolications.first))") + return + } + #expect(name == "_objc_autoreleasePoolPush") + } + + @Test func refsListsTheReferencesToAClass() async throws { + let result = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .objectiveCClass("NSWindow"), imageNames: ["AppKit"]).run(output: RecordingOutput()) + #expect(!result.rows.isEmpty) + #expect(result.rows.allSatisfy { row in + if case .objectiveCClass("NSWindow", _) = row.reference.target { true } else { false } + }) + // The class symbol is the same subject. + let bySymbol = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .symbol("_OBJC_CLASS_$_NSWindow"), imageNames: ["AppKit"]).run(output: RecordingOutput()) + #expect(bySymbol.rows == result.rows) + } + + @Test func refsRejectsAnImageNoAnalyzedImageHas() async throws { + await #expect(throws: CrossReferenceRequestError.imageNotFound(name: "NoSuchImage")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), imageNames: ["NoSuchImage"]).run(output: RecordingOutput()) + } + await #expect(throws: CrossReferenceRequestError.symbolNotFound(name: "_NoSuchSymbolAnywhere")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .symbol("_NoSuchSymbolAnywhere"), imageNames: ["AppKit"]).run(output: RecordingOutput()) + } + await #expect(throws: CrossReferenceRequestError.calleesRequireFunction) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), direction: .callees).run(output: RecordingOutput()) + } + } + + /// A standalone, fat app executable: the slice named is read, its sends + /// are found in it alone — and without a slice named, none is picked. + @Test(.enabled(if: FileManager.default.fileExists(atPath: "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit"), "needs TextEdit")) + func refsReadsAStandaloneFatExecutable() async throws { + let path = "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit" + let result = try await ReferencesRequest(input: .files(paths: [path], architecture: .arm64e), subject: .selector("init")).run(output: RecordingOutput()) + #expect(!result.rows.isEmpty) + #expect(result.scannedImageCount == 1) + #expect(result.rows.allSatisfy { $0.imagePath == path && Self.isSend($0.reference.target, of: "init") }) + await #expect(performing: { + try await ReferencesRequest(input: .files(paths: [path], architecture: nil), subject: .selector("init")).run(output: RecordingOutput()) + }, throws: { error in + if case MachOSourceError.fatBinaryRequiresArchitecture = error { true } else { false } + }) + } + + @Test func symbolicateAcceptsSeveralAddresses() async throws { + let callers = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .selector(Self.selector), imageNames: ["AppKit"], limit: 1).run(output: RecordingOutput()) + let reference = try #require(callers.rows.first?.reference) + let addresses = [reference.instructionAddress, reference.function.address, 0x10] + let output = RecordingOutput() + let symbolications = try await SymbolicateRequest(input: .systemDyldSharedCache, addresses: addresses).run(output: output) + #expect(symbolications.map(\.address) == addresses) + #expect(symbolications[0].meaning.functionStart == reference.function.address) + #expect(symbolications[0].meaning.functionOffset == reference.instructionAddress - reference.function.address) + #expect(symbolications[1].meaning.functionOffset == 0) + #expect(symbolications[2].meaning == .unmapped) + #expect(symbolications[0].imagePath?.hasSuffix("/AppKit") == true) + let lines = output.printedProduct.split(separator: "\n").map(String.init) + #expect(lines.count == 3) + #expect(lines[2] == "0x10 - - unmapped") + #expect(lines[0].hasPrefix(String(format: "0x%llx AppKit __TEXT,__text ", reference.instructionAddress))) + } + + @Test func symbolicateJSONUsesHexadecimalStringAddresses() async throws { + let output = RecordingOutput() + try await SymbolicateRequest(input: .systemDyldSharedCache, addresses: [0x10], format: .json).run(output: output) + guard case .data(let data)? = output.products.first else { + Issue.record("expected a JSON document") + return + } + let document = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + let symbolications = try #require(document["symbolications"] as? [[String: Any]]) + #expect(symbolications.count == 1) + #expect(symbolications.first?["address"] as? String == "0x10") + #expect((symbolications.first?["meaning"] as? [String: Any])?["unmapped"] != nil) + } +} + +extension AddressSymbolication.Meaning { + fileprivate var functionStart: UInt64? { + if case .function(let start, _, _) = self { start.address } else { nil } + } + + fileprivate var functionOffset: UInt64? { + if case .function(_, _, let offset) = self { offset } else { nil } + } +} diff --git a/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift index 09212831e..bd57667f6 100644 --- a/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift +++ b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift @@ -63,6 +63,22 @@ struct InterfaceAnnotationStyleTests { #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.header, .plain, .added, .plain, .removed]) } + /// Evolution proposal `evolution-unobservable-presence`: a change across + /// versions that could not show the declaration is placed `between` two + /// versions; an annotation that only marks such versions records no + /// change. + @Test("A change placed between two versions reads by its phrase; marking unobservable versions alone stays plain") + func evolutionUnobservableAnnotations() { + let text = """ + func retired() // [●◌○] removed between 1.0 and 3.0 + func fresh() // [○◌●] added between 1.0 and 3.0 + var value: Int // [●◍●] modified between 1.0 and 3.0: var value: Int → let value: Int + func kept() // [●◍●] inferred present in 2.0 + func trailing() // [●◌] not observable in 2.0 + """ + #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.removed, .added, .modified, .plain, .plain]) + } + @Test("A declaration whose name mentions a lifecycle word stays plain") func evolutionClassifiesByAnnotationOnly() { #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: "public func removedInLegacyMode()") == [.plain]) diff --git a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift index a1a7c1852..374943975 100644 --- a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift +++ b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import MachO import ObjCDiffing import ObjCOutputTransformer import OutputTransformer @@ -74,6 +75,19 @@ struct ObjCRequestTests { } } + /// The bridge class is a Swift class renamed for Objective-C + /// (`@objc(SymbolTestsCoreObjCBridgeClass)`), so its Swift view is the + /// Swift class itself rather than names the importer's rules derive. + @Test("The Swift view prints a Swift class as the Swift class") + func swiftViewOfASwiftClass() async throws { + let output = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture, printsSwiftImport: true).run(output: output) + + #expect(output.printedProduct.contains("class ObjCBridge"), "\(output.printedProduct)") + #expect(output.printedProduct.contains("var label: Swift.String"), "\(output.printedProduct)") + #expect(!output.printedProduct.contains("@interface"), "\(output.printedProduct)") + } + @Test("A binary diffed against its own snapshot breaks no API") func diffAgainstOwnSnapshot() async throws { let directoryURL = try FixtureFiles.makeTemporaryDirectory() @@ -99,4 +113,128 @@ struct ObjCRequestTests { .run(output: RecordingOutput(), environment: .testing) } } + + /// One binary given twice changes nothing: the header carries the legend + /// and the declarations `objc dump` renders, and no lifecycle annotation. + @Test("An annotated ObjC evolution of one binary against itself annotates nothing") + func annotatedEvolutionOfOneBinaryAnnotatesNothing() async throws { + let output = RecordingOutput() + let outcome = try await ObjCAPIEvolutionRequest( + inputs: [.path(FixtureFiles.symbolTestsCore), .path(FixtureFiles.symbolTestsCore)], + labels: ["1.0", "2.0"], + report: .annotatedInterface(availabilityAttributes: .none) + ).run(output: output, environment: .testing) + + guard case .annotatedInterface(let text, let style)? = output.products.first, output.products.count == 1 else { + Issue.record("expected one annotated header, got \(output.products)") + return + } + #expect(style == .evolution) + let lines = text.split(separator: "\n", omittingEmptySubsequences: false) + #expect(lines.prefix(2) == ["// ObjC API evolution across 2 versions: 1.0 → 2.0", "// Bitmap positions: [1] 1.0 [2] 2.0"]) + #expect(lines.contains { $0.hasPrefix("@interface \(Self.bridgeClassName)") }) + #expect(!lines.contains { $0.contains(" added in ") || $0.contains(" removed in ") || $0.contains(" modified in ") }) + #expect(!outcome.hasBreakingChange) + } + + @Test("An annotated ObjC evolution explains its availability macros exactly when they are on", arguments: [ + (ObjCAPIEvolutionRequest.AvailabilityAttributes.none, false), + (.inferredPlatform, true), + (.platform("visionos"), true), + ]) + func annotatedEvolutionAvailabilityLegend(availabilityAttributes: ObjCAPIEvolutionRequest.AvailabilityAttributes, expectsLegend: Bool) async throws { + let output = RecordingOutput() + _ = try await ObjCAPIEvolutionRequest( + inputs: [.path(FixtureFiles.symbolTestsCore), .path(FixtureFiles.symbolTestsCore)], + labels: ["1.0", "2.0"], + report: .annotatedInterface(availabilityAttributes: availabilityAttributes) + ).run(output: output, environment: .testing) + + guard case .annotatedInterface(let text, _)? = output.products.first else { + Issue.record("expected an annotated header, got \(output.products)") + return + } + let legendLines = text.split(separator: "\n").filter { $0.hasPrefix("// API_AVAILABLE and API_OBSOLETED versions are axis points") } + #expect(legendLines.count == (expectsLegend ? 1 : 0)) + } + + @Test("An annotated ObjC evolution written to a file holds the bytes printing shows") + func annotatedEvolutionToFile() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let headerPath = directoryURL.appendingPathComponent("evolution.h").path + let inputs: [SnapshotSource] = [.path(FixtureFiles.symbolTestsCore), .path(FixtureFiles.symbolTestsCore)] + + let printed = RecordingOutput() + _ = try await ObjCAPIEvolutionRequest(inputs: inputs, labels: ["1.0", "2.0"], report: .annotatedInterface(availabilityAttributes: .none)) + .run(output: printed, environment: .testing) + let written = RecordingOutput() + _ = try await ObjCAPIEvolutionRequest(inputs: inputs, labels: ["1.0", "2.0"], report: .annotatedInterface(availabilityAttributes: .none), destination: .file(path: headerPath)) + .run(output: written, environment: .testing) + + #expect(try String(contentsOfFile: headerPath, encoding: .utf8) == printed.printedProduct) + #expect(written.products.isEmpty) + #expect(written.messages(of: .progress).last == "Annotated header written to \(headerPath)") + } + + @Test("An annotated ObjC evolution refuses a snapshot document before loading anything") + func annotatedEvolutionRejectsADocument() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = directoryURL.appendingPathComponent("baseline.json").path + _ = try await ObjCAPISnapshotRequest(source: .path(FixtureFiles.symbolTestsCore), destination: .file(path: documentPath)) + .run(output: RecordingOutput(), environment: .testing) + + let output = RecordingOutput() + await #expect(throws: SnapshotSourceError.binaryRequired(path: documentPath)) { + _ = try await ObjCAPIEvolutionRequest( + inputs: [.path(FixtureFiles.symbolTestsCore), .path(documentPath)], + report: .annotatedInterface(availabilityAttributes: .none) + ).run(output: output, environment: .testing) + } + #expect(output.events.isEmpty) + } + + /// The copy names another platform than the fixture's macOS; a simulator + /// counts as its device, and the names are the availability macros' own + /// (`API_AVAILABLE(macCatalyst(…))`). Thrown after loading and before any + /// indexing. + @Test("Inputs naming different platforms leave no availability platform to infer", arguments: [ + (PLATFORM_IOSSIMULATOR, ["ios", "macos"]), + (PLATFORM_TVOS, ["macos", "tvos"]), + (PLATFORM_WATCHOSSIMULATOR, ["macos", "watchos"]), + (PLATFORM_VISIONOSSIMULATOR, ["macos", "visionos"]), + (PLATFORM_MACCATALYST, ["macCatalyst", "macos"]), + (PLATFORM_DRIVERKIT, ["driverkit", "macos"]), + ]) + func annotatedEvolutionRefusesConflictingPlatforms(buildPlatform: Int32, expectedPlatforms: [String]) async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let copyPath = try FixtureFiles.makeCopy(of: FixtureFiles.symbolTestsCore, buildPlatform: buildPlatform, in: directoryURL) + + let output = RecordingOutput() + await #expect(throws: ObjCAvailabilityPlatformInferenceError.conflictingPlatforms(expectedPlatforms)) { + _ = try await ObjCAPIEvolutionRequest( + inputs: [.path(FixtureFiles.symbolTestsCore), .path(copyPath)], + report: .annotatedInterface(availabilityAttributes: .inferredPlatform) + ).run(output: output, environment: .testing) + } + #expect(!output.messages(of: .progress).contains { $0.hasPrefix("Indexing") }) + } + + @Test("An input naming a platform the availability macros cannot spell leaves nothing to infer") + func annotatedEvolutionRefusesAnUnspellablePlatform() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let copyPath = try FixtureFiles.makeCopy(of: FixtureFiles.symbolTestsCore, buildPlatform: PLATFORM_BRIDGEOS, in: directoryURL) + + let output = RecordingOutput() + await #expect(throws: ObjCAvailabilityPlatformInferenceError.noPlatform(path: copyPath)) { + _ = try await ObjCAPIEvolutionRequest( + inputs: [.path(FixtureFiles.symbolTestsCore), .path(copyPath)], + report: .annotatedInterface(availabilityAttributes: .inferredPlatform) + ).run(output: output, environment: .testing) + } + #expect(!output.messages(of: .progress).contains { $0.hasPrefix("Indexing") }) + } } diff --git a/Tests/SwiftSectionKitTests/ObservableMacroRequestTests.swift b/Tests/SwiftSectionKitTests/ObservableMacroRequestTests.swift new file mode 100644 index 000000000..2ee6b0ee9 --- /dev/null +++ b/Tests/SwiftSectionKitTests/ObservableMacroRequestTests.swift @@ -0,0 +1,41 @@ +import Foundation +import Testing +import SwiftSectionKit +@testable import SwiftSectionTestingSupport + +/// `interface` folds what `@Observable` generated unless the request expands +/// macros, and `dump` names the macro on the class's header line (evolution +/// proposal `observable-macro-folding`). +@Suite(.serialized) +struct ObservableMacroRequestTests { + private static func source() async throws -> MachOSource { + .file(path: try await ObservableMacroFixture.libraryURL(.release).path, architecture: nil) + } + + @Test("The interface folds the expansion unless the request expands macros") + func interfaceFoldsTheExpansion() async throws { + let folded = RecordingOutput() + try await InterfaceRequest(source: try await Self.source()).run(output: folded, environment: .testing) + #expect(folded.printedProduct.contains("@Observation.Observable\nclass FinalModel {"), "\(folded.printedProduct)") + // The look-alikes declare a registrar of their own; the class the + // macro expanded prints none. + let finalModelStart = try #require(folded.printedProduct.range(of: "class FinalModel {"), "\(folded.printedProduct)") + let finalModelEnd = try #require(folded.printedProduct.range(of: "\n}", range: finalModelStart.upperBound ..< folded.printedProduct.endIndex)) + let finalModel = folded.printedProduct[finalModelStart.lowerBound ..< finalModelEnd.upperBound] + #expect(!finalModel.contains("_$observationRegistrar"), "\(finalModel)") + + let expanded = RecordingOutput() + try await InterfaceRequest(source: try await Self.source(), expandsMacros: true).run(output: expanded, environment: .testing) + #expect(!expanded.printedProduct.contains("@Observation."), "\(expanded.printedProduct)") + #expect(expanded.printedProduct.contains("_$observationRegistrar"), "\(expanded.printedProduct)") + #expect(expanded.printedProduct.contains("extension ObservableMacroFixture.FinalModel: Observation.Observable {}"), "\(expanded.printedProduct)") + } + + @Test("The dump names the macro on the class's header line") + func dumpNamesTheMacro() async throws { + let output = RecordingOutput() + try await DumpRequest(source: try await Self.source()).run(output: output, environment: .testing) + #expect(output.printedProduct.contains("@Observation.Observable class ObservableMacroFixture.FinalModel"), "\(output.printedProduct)") + #expect(output.printedProduct.contains("_$observationRegistrar"), "\(output.printedProduct)") + } +} diff --git a/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift b/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift index b349e2202..df4613b4d 100644 --- a/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift +++ b/Tests/SwiftSectionKitTests/PrivateDeclarationSourceFileRequestTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -import MachOTestingSupport +import SwiftSectionTestingSupport import SwiftSectionKit /// `dump` and `interface` naming the source file of each private declaration diff --git a/Tests/SwiftSectionKitTests/SwiftDeclaredObjCProtocolRequestTests.swift b/Tests/SwiftSectionKitTests/SwiftDeclaredObjCProtocolRequestTests.swift new file mode 100644 index 000000000..97057bdaf --- /dev/null +++ b/Tests/SwiftSectionKitTests/SwiftDeclaredObjCProtocolRequestTests.swift @@ -0,0 +1,63 @@ +import Foundation +import Testing +import SwiftSectionKit +@testable import SwiftSectionTestingSupport + +/// `dump`'s `protocols` section and `interface` carry the `@objc` protocols +/// a Swift module declares (evolution proposal +/// `swift-declared-objc-protocols`), which have no protocol descriptor. +@Suite(.serialized, ExclusiveImageAccess(SwiftDeclaredObjCProtocolsFixture.moduleName)) +struct SwiftDeclaredObjCProtocolRequestTests { + private static let moduleName = SwiftDeclaredObjCProtocolsFixture.moduleName + + private static func source() throws -> MachOSource { + .file(path: try SwiftDeclaredObjCProtocolsFixture.libraryURL(.full).path, architecture: nil) + } + + @Test("Both dump orderings list the protocols, then the records no protocol claims", arguments: [DumpRequest.Ordering.bySection, .binaryOrder]) + func dumpListsTheProtocols(ordering: DumpRequest.Ordering) async throws { + let output = RecordingOutput() + try await DumpRequest( + source: try Self.source(), + dependencySearchPaths: try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths(), + ordering: ordering + ).run(output: output, environment: .testing) + let product = output.printedProduct + + for name in ["DerivedSelectors", "SameNameRenamed", "DifferentlyNamed", "RefinedProtocol", "InternalProtocol", "Outer.NestedProtocol"] { + #expect(product.contains(" protocol \(Self.moduleName).\(name)"), "\(name)\n---\n\(product)") + } + let unclaimedRecords = try #require(product.range(of: "// ObjC protocol records emitted by Swift that no protocol of this image claims"), "\(product)") + let lastProtocol = try #require(product.range(of: " protocol \(Self.moduleName).", options: .backwards), "\(product)") + #expect(lastProtocol.upperBound < unclaimedRecords.lowerBound, "\(product)") + } + + @Test("The dump names the ObjC protocols a class adopts, and a category's as a conformance") + func dumpListsAdoptedObjCProtocols() async throws { + let output = RecordingOutput() + try await DumpRequest( + source: try Self.source(), + dependencySearchPaths: try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths() + ).run(output: output, environment: .testing) + let product = output.printedProduct + + #expect(product.contains("// ObjC protocols: \(Self.moduleName).SameNameRenamed, __C.NSCopying\n"), "\(product)") + #expect(product.contains("// ObjC protocols: __C.NSCopying (implied by a Swift conformance)\n"), "\(product)") + #expect(product.contains("// ObjC protocols: \(SwiftDeclaredObjCProtocolsFixture.kitModuleName).KitObserver, __C.KITRenamedObserver, \(SwiftDeclaredObjCProtocolsFixture.kitModuleName).KitSameName\n"), "\(product)") + #expect(product.contains("extension __C.NSDateFormatter: \(Self.moduleName).SameNameRenamed {} // ObjC category at 0x"), "\(product)") + } + + @Test("The interface declares the protocols") + func interfaceDeclaresTheProtocols() async throws { + let output = RecordingOutput() + try await InterfaceRequest( + source: try Self.source(), + dependencySearchPaths: try SwiftDeclaredObjCProtocolsFixture.dependencySearchPaths() + ).run(output: output, environment: .testing) + let product = output.printedProduct + + #expect(product.contains("@objc protocol DerivedSelectors: __C.NSObject {"), "\(product)") + #expect(product.contains("@objc(SameNameRenamed) protocol SameNameRenamed {"), "\(product)") + #expect(product.contains("extension \(Self.moduleName).Outer {\n @objc protocol NestedProtocol {"), "\(product)") + } +} diff --git a/Tests/MachOTestingSupportTests/Baseline/BaselineEmitterTests.swift b/Tests/SwiftSectionTestingSupportTests/Baseline/BaselineEmitterTests.swift similarity index 91% rename from Tests/MachOTestingSupportTests/Baseline/BaselineEmitterTests.swift rename to Tests/SwiftSectionTestingSupportTests/Baseline/BaselineEmitterTests.swift index 8da97755a..0e28f53df 100644 --- a/Tests/MachOTestingSupportTests/Baseline/BaselineEmitterTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/Baseline/BaselineEmitterTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite struct BaselineEmitterTests { diff --git a/Tests/MachOTestingSupportTests/ContinuousIntegrationTestFilterTests.swift b/Tests/SwiftSectionTestingSupportTests/ContinuousIntegrationTestFilterTests.swift similarity index 97% rename from Tests/MachOTestingSupportTests/ContinuousIntegrationTestFilterTests.swift rename to Tests/SwiftSectionTestingSupportTests/ContinuousIntegrationTestFilterTests.swift index b0d4303bb..baff71c86 100644 --- a/Tests/MachOTestingSupportTests/ContinuousIntegrationTestFilterTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/ContinuousIntegrationTestFilterTests.swift @@ -13,7 +13,7 @@ import Testing @Suite struct ContinuousIntegrationTestFilterTests { private static let packageRoot = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent() // MachOTestingSupportTests + .deletingLastPathComponent() // SwiftSectionTestingSupportTests .deletingLastPathComponent() // Tests .deletingLastPathComponent() // package root diff --git a/Tests/MachOTestingSupportTests/Coverage/Fixtures/SampleSource.swift.txt b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SampleSource.swift.txt similarity index 100% rename from Tests/MachOTestingSupportTests/Coverage/Fixtures/SampleSource.swift.txt rename to Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SampleSource.swift.txt diff --git a/Tests/MachOTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt similarity index 100% rename from Tests/MachOTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt rename to Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt diff --git a/Tests/MachOTestingSupportTests/Coverage/PublicMemberScannerTests.swift b/Tests/SwiftSectionTestingSupportTests/Coverage/PublicMemberScannerTests.swift similarity index 98% rename from Tests/MachOTestingSupportTests/Coverage/PublicMemberScannerTests.swift rename to Tests/SwiftSectionTestingSupportTests/Coverage/PublicMemberScannerTests.swift index 299aae10d..af5779cb7 100644 --- a/Tests/MachOTestingSupportTests/Coverage/PublicMemberScannerTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/PublicMemberScannerTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite struct PublicMemberScannerTests { diff --git a/Tests/MachOTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift similarity index 97% rename from Tests/MachOTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift rename to Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift index 801f4f172..5921c6415 100644 --- a/Tests/MachOTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @Suite struct SuiteBehaviorScannerTests { diff --git a/Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift b/Tests/SwiftSectionTestingSupportTests/DeclaredNameForTestingTests.swift similarity index 97% rename from Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift rename to Tests/SwiftSectionTestingSupportTests/DeclaredNameForTestingTests.swift index d3b6805e6..6f7cd6c08 100644 --- a/Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/DeclaredNameForTestingTests.swift @@ -1,7 +1,7 @@ import Testing import Demangling import SwiftDeclaration -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// `declaredNameForTesting` is what tests look definitions up by. It exists /// because `currentName` misnames a function-local type — the case this suite diff --git a/Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift similarity index 98% rename from Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift rename to Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift index 96f943961..14d022941 100644 --- a/Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift @@ -1,5 +1,5 @@ import Testing -import MachOFixtureSupport +import SwiftSectionFixtureSupport /// `DyldSharedCachePath` builds an archived cache's path and label from its /// version. The named macOS caches are built that way too, and only the diff --git a/Tests/MachOTestingSupportTests/ExclusiveImageAccessTests.swift b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift similarity index 98% rename from Tests/MachOTestingSupportTests/ExclusiveImageAccessTests.swift rename to Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift index 1cc6356b0..60caffd2a 100644 --- a/Tests/MachOTestingSupportTests/ExclusiveImageAccessTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// The exclusion must be demonstrated, not asserted in prose — a promise in a /// doc comment is exactly what failed here the first time. diff --git a/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift b/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift index c1c1be81b..3b6638940 100644 --- a/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift +++ b/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift @@ -6,7 +6,7 @@ import Testing import MachOKit import Demangling @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport /// `GenericSpecializer` names each parameter by its `(depth, index)` — `A`, /// `B`, `A1`, … — and collects the parameter's requirements by matching that diff --git a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift index b40395baa..13b9f7036 100644 --- a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift +++ b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift @@ -5,10 +5,10 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// `IndexerConformanceProvider` builds its class hierarchy on a large stack. /// diff --git a/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift b/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift index 1a464cac6..f9329ab77 100644 --- a/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift @@ -6,7 +6,7 @@ import Testing import MachOKit import Demangling @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport /// `specialize(...)` appends the new definition to the generic definition's /// `specializedChildren`: an associated object, retained non-atomically, read, diff --git a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift index 69699067a..e6a70a43a 100644 --- a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift @@ -6,12 +6,12 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport @testable import SwiftDump @testable @_spi(Internals) import SwiftInspection @testable import Demangling diff --git a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift index 9faab1405..798d86cce 100644 --- a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift +++ b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift @@ -6,10 +6,10 @@ import Foundation import Testing import MachOKit import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport @_spi(Internals) import SwiftInspection // MARK: - Pure helper unit tests (no fixture) diff --git a/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift b/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift index 1028a5e25..5dc9a2dd6 100644 --- a/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift +++ b/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift @@ -8,7 +8,7 @@ import Demangling @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering -import MachOTestingSupport +import SwiftSectionTestingSupport /// A specialization's name hangs each argument on the level that declares /// its parameter — `Outer.Inner`, the shape the diff --git a/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift b/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift index 8831bae91..e4958caa2 100644 --- a/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift @@ -5,7 +5,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport /// A conformance the indexed images record under a generic type's unbound /// name may hold only under conditions — `Array: Hashable where Element: diff --git a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift index b26bdce21..e9304ca56 100644 --- a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift @@ -5,7 +5,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport /// A base-class requirement on an Objective-C class, checked offline /// (evolution proposal `offline-generic-specialization`). diff --git a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift index d59e3ea3c..afab5025d 100644 --- a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift @@ -6,7 +6,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport import SwiftDeclarationRendering /// An archived iOS simulator cache: the dependency closure an iOS simulator diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift index 09a9abb6b..e02f204a2 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift @@ -7,7 +7,7 @@ import Testing import MachOKit import Demangling @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport import SwiftDeclarationRendering /// One instantiation, specialized and printed both ways, must read the same diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift index 05d991b03..814b6430c 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift @@ -7,7 +7,7 @@ import MachOKit import Demangling @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection -import MachOTestingSupport +import SwiftSectionTestingSupport /// A host type with no conformance any indexed image records. private struct HostUnmarked { diff --git a/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift b/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift index 955f4a964..15d2d14a6 100644 --- a/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift +++ b/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift @@ -5,9 +5,9 @@ import Foundation import Testing import MachOKit import Demangling -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable import MachOSwiftSection -import MachOTestingSupport +import SwiftSectionTestingSupport /// The async `TypeDefinition.specialize` overloads are library entry points, /// so their bodies run on the large-stack task executor like every other diff --git a/Tests/SwiftSpecializationTests/SpecializedExportStatusTests.swift b/Tests/SwiftSpecializationTests/SpecializedExportStatusTests.swift index cb2f73564..1764564b8 100644 --- a/Tests/SwiftSpecializationTests/SpecializedExportStatusTests.swift +++ b/Tests/SwiftSpecializationTests/SpecializedExportStatusTests.swift @@ -5,7 +5,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// A specialized definition shares its generic definition's descriptor, so it /// must carry the same `exportStatus` (evolution proposal diff --git a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift index 3e7f53b30..a4ba5bfef 100644 --- a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift +++ b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift @@ -6,7 +6,7 @@ import Foundation import Testing import MachOKit @testable import MachOSwiftSection -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport // MARK: - Fixtures // diff --git a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift index 651a9128b..69d707347 100644 --- a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift +++ b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift @@ -5,10 +5,10 @@ import Foundation import Testing import MachOKit import Dependencies -@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftSymbols @testable import MachOSwiftSection -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// `IndexerConformanceProvider`'s subclass map must not lose a class silently. /// diff --git a/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift b/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift index 47578d39d..84d80d311 100644 --- a/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift +++ b/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift @@ -8,7 +8,7 @@ import Demangling @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering -import MachOTestingSupport +import SwiftSectionTestingSupport /// A same-type requirement between two parameters — `TiedParameterPair where First == Second` — leaves the second without a key argument: diff --git a/Tests/MachOSymbolsTests/ExportedSymbolFactsTests.swift b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift similarity index 76% rename from Tests/MachOSymbolsTests/ExportedSymbolFactsTests.swift rename to Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift index d500f7b88..a6fe31aae 100644 --- a/Tests/MachOSymbolsTests/ExportedSymbolFactsTests.swift +++ b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift @@ -1,10 +1,11 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing @_spi(Internals) import Demangling -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Fixture-based coverage for the export facts (evolution proposal 0008): /// `isExported(name:in:)` answering the export-trie membership FACT, and @@ -22,9 +23,9 @@ import MachOFixtureSupport final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } - private var storage: SymbolIndexStore.Storage { + private var storage: SwiftSymbolIndexStore.Storage { get throws { - try #require(SymbolIndexStore.shared.storage(in: machOFile)) + try #require(SwiftSymbolIndexStore.shared.storage(in: machOFile)) } } @@ -35,7 +36,7 @@ final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { let unsafeMachOFile = machOFile var checkedCount = 0 for exportedSymbol in unsafeMachOFile.exportedSymbols where exportedSymbol.name.isSwiftSymbol { - if SymbolIndexStore.shared.isExported(name: exportedSymbol.name, in: unsafeMachOFile) != true { + if SwiftSymbolIndexStore.shared.isExported(name: exportedSymbol.name, in: unsafeMachOFile) != true { Issue.record("exported trie name answered not-exported: \(exportedSymbol.name)") } checkedCount += 1 @@ -53,7 +54,7 @@ final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { $0.name.isSwiftSymbol && !$0.nlist.isExternal && !exportedNames.contains($0.name) }?.name ) - #expect(SymbolIndexStore.shared.isExported(name: localSwiftName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: localSwiftName, in: unsafeMachOFile) == false) } /// The motivating case for the derived-form query: `ActorTest.mutateState` @@ -64,9 +65,9 @@ final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { @Test func derivedFormQueryRecognizesThunkOnlyExportedMember() throws { let unsafeMachOFile = machOFile let implementationName = "_$s15SymbolTestsCore6ActorsO9ActorTestC11mutateStateyyF" - #expect(SymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.isExported(name: implementationName + "Tj", in: unsafeMachOFile) == true) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: implementationName + "Tj", in: unsafeMachOFile) == true) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == true) } /// `GenericAsyncSequenceTest.AsyncIterator` declares no initializer, so @@ -80,8 +81,8 @@ final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { @Test func internalSynthesizedInitStaysNotExportedUnderDerivedFormQuery() throws { let unsafeMachOFile = machOFile let implementationName = "_$s15SymbolTestsCore013AsyncSequenceB0O07GenericdE4TestV0D8IteratorVAGy_x_GycfC" - #expect(SymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) - #expect(SymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExported(name: implementationName, in: unsafeMachOFile) == false) + #expect(SwiftSymbolIndexStore.shared.isExportedIncludingDerivedSymbols(name: implementationName, in: unsafeMachOFile) == false) } /// The fixture carries export information, so the verdict is never `nil` @@ -89,6 +90,6 @@ final class ExportedSymbolFactsTests: MachOFileTests, @unchecked Sendable { /// an input with no export trie, which no current fixture provides). @Test func imageWithExportTrieNeverAnswersNil() throws { let unsafeMachOFile = machOFile - #expect(SymbolIndexStore.shared.isExported(name: "_$s_definitely_not_a_symbol", in: unsafeMachOFile) != nil) + #expect(SwiftSymbolIndexStore.shared.isExported(name: "_$s_definitely_not_a_symbol", in: unsafeMachOFile) != nil) } } diff --git a/Tests/MachOSymbolsTests/InternedNodeReferenceCacheTests.swift b/Tests/SwiftSymbolsTests/InternedNodeReferenceCacheTests.swift similarity index 97% rename from Tests/MachOSymbolsTests/InternedNodeReferenceCacheTests.swift rename to Tests/SwiftSymbolsTests/InternedNodeReferenceCacheTests.swift index 2e183f298..cfbd6a3c2 100644 --- a/Tests/MachOSymbolsTests/InternedNodeReferenceCacheTests.swift +++ b/Tests/SwiftSymbolsTests/InternedNodeReferenceCacheTests.swift @@ -1,10 +1,10 @@ import Foundation import Testing @_spi(Internals) import Demangling -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Unit coverage for `InternedNodeReferenceCache` — the structural /// deduplication layer over `NodeReference(interning:)`. The batching claim diff --git a/Tests/MachOSymbolsTests/LargeStackTaskExecutionTests.swift b/Tests/SwiftSymbolsTests/LargeStackTaskExecutionTests.swift similarity index 99% rename from Tests/MachOSymbolsTests/LargeStackTaskExecutionTests.swift rename to Tests/SwiftSymbolsTests/LargeStackTaskExecutionTests.swift index 0bfc5cd9d..a18f71301 100644 --- a/Tests/MachOSymbolsTests/LargeStackTaskExecutionTests.swift +++ b/Tests/SwiftSymbolsTests/LargeStackTaskExecutionTests.swift @@ -1,7 +1,7 @@ import Foundation import Testing @_spi(Internals) import Demangling -@testable import MachOSymbols +@testable import SwiftSymbols /// Pins `LargeStackTaskExecution.run` (evolution proposal /// `large-stack-executor-and-cross-version-parallelism`): on a runtime with diff --git a/Tests/MachOSymbolsTests/NodeStoreMigrationInvariantTests.swift b/Tests/SwiftSymbolsTests/NodeStoreMigrationInvariantTests.swift similarity index 98% rename from Tests/MachOSymbolsTests/NodeStoreMigrationInvariantTests.swift rename to Tests/SwiftSymbolsTests/NodeStoreMigrationInvariantTests.swift index 2de7a130c..ce0468d08 100644 --- a/Tests/MachOSymbolsTests/NodeStoreMigrationInvariantTests.swift +++ b/Tests/SwiftSymbolsTests/NodeStoreMigrationInvariantTests.swift @@ -5,7 +5,7 @@ import Testing /// states in prose: **"Sources now carries zero cached `demangleAsNode(` call /// sites."** /// -/// A behavioral test cannot enforce this. `SymbolIndexStore.Storage` holds +/// A behavioral test cannot enforce this. `SwiftSymbolIndexStore.Storage` holds /// `NodeReference`s into a frozen arena, so materializing one twice yields two /// distinct trees no matter which demangle entry point the build sweep used — /// instance identity carries no signal about the sweep. Process-global diff --git a/Tests/SwiftSymbolsTests/PackedNameReferenceBudgetTests.swift b/Tests/SwiftSymbolsTests/PackedNameReferenceBudgetTests.swift new file mode 100644 index 000000000..aab179ac8 --- /dev/null +++ b/Tests/SwiftSymbolsTests/PackedNameReferenceBudgetTests.swift @@ -0,0 +1,38 @@ +import Foundation +import MachOResolving +import Testing +import Demangling +@_spi(Internals) @testable import SwiftSymbols +@_spi(Internals) import MachOSymbols + +/// The packed name-reference budgets (22-bit byte length / 40-bit byte +/// offset) are enforced against binary-supplied values: a name that cannot +/// pack must degrade — the build sweep skips its row, the standalone public +/// initializer clamps — never trap. `precondition` here is fatal in release +/// builds, so a malformed or hostile binary's symbol-table geometry would +/// decide whether the host process lives (PR #103 review, finding M3). +@Suite +struct PackedNameReferenceBudgetTests { + private static let oversizedName = "$s" + String(repeating: "A", count: PackedNameReference.maximumByteLength + 64) + + private static func makeNodeReference() -> NodeReference { + var nodeStoreBuilder = NodeStoreBuilder() + let nodeIndex = nodeStoreBuilder.intern(Node.create(kind: .identifier, text: "PackedNameReferenceBudgetTests")) + return nodeStoreBuilder.freeze().reference(at: nodeIndex) + } + + /// The public `DemangledSymbol(symbol:demangledNode:)` initializer packs + /// the caller's name into a one-row table; a name beyond the budget + /// clamps to the representable prefix instead of trapping (a legitimate + /// mangled name never approaches the 4 MB budget, so the clamp is + /// unreachable for honest input). + @Test func standalonePublicInitializerClampsInsteadOfTrapping() { + let demangledSymbol = DemangledSymbol( + symbol: Symbol(offset: 0, name: Self.oversizedName), + demangledNode: Self.makeNodeReference() + ) + #expect(demangledSymbol.name.utf8.count == PackedNameReference.maximumByteLength) + #expect(Self.oversizedName.hasPrefix(demangledSymbol.name)) + #expect(demangledSymbol.retainedSymbolTableRowCount == 1) + } +} diff --git a/Tests/MachOSymbolsTests/StructuralNodeReferenceKeyTests.swift b/Tests/SwiftSymbolsTests/StructuralNodeReferenceKeyTests.swift similarity index 94% rename from Tests/MachOSymbolsTests/StructuralNodeReferenceKeyTests.swift rename to Tests/SwiftSymbolsTests/StructuralNodeReferenceKeyTests.swift index d7cb7806b..c70201264 100644 --- a/Tests/MachOSymbolsTests/StructuralNodeReferenceKeyTests.swift +++ b/Tests/SwiftSymbolsTests/StructuralNodeReferenceKeyTests.swift @@ -1,4 +1,4 @@ -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols import Demangling import Testing @@ -6,13 +6,13 @@ import Testing /// /// `TypeDefinition.index` keys `methodDescriptorLookup` / `vtableOffsetLookup` /// from override descriptors' implementation symbols, which -/// `SymbolIndexStore.demangledNodeReference(for:)` can hand back from a +/// `SwiftSymbolIndexStore.demangledNodeReference(for:)` can hand back from a /// mini store, while the member side looks them up with references from the /// shared image store. `NodeReference`'s intrinsic `Hashable` is store-identity /// based, so a bare-`NodeReference` key silently dropped the `override` keyword /// and the vtable-offset comment for those symbols. /// `StructuralNodeReferenceKey` restores structural matching; the same wrapper -/// now also keys `DefinitionBuilder`'s accessor / merged-thunk dedup and every +/// now also keys `MemberDefinitionBuilder`'s accessor / merged-thunk dedup and every /// `visitedNodes` set in the declaration and dump layers. /// /// `NodeReference(interning:)` mints a fresh private store per call, so diff --git a/Tests/SwiftSymbolsTests/SwiftSymbolTableRoutingTests.swift b/Tests/SwiftSymbolsTests/SwiftSymbolTableRoutingTests.swift new file mode 100644 index 000000000..f8b903d57 --- /dev/null +++ b/Tests/SwiftSymbolsTests/SwiftSymbolTableRoutingTests.swift @@ -0,0 +1,36 @@ +import Foundation +import Testing +@_spi(Internals) import MachOSymbols +@testable import SwiftSymbols + +/// What the Swift store hands MachOKitExtensions' symbol sweep: Swift-mangled +/// names into the demangled, offset-indexed table, the linker de-duplication +/// names into their own name-only table, and nothing else. +@Suite +struct SwiftSymbolTableRoutingTests { + private let routing = SwiftSymbolTableRouting() + + private func table(forSymbolNamed name: String) -> SwiftSymbolTableRouting.Table? { + name.withCString { routing.table(forSymbolNamed: $0, language: SymbolLanguage(ofSymbolNameBytes: $0)) } + } + + @Test func swiftRoutingFilesSymbolicManglingNamesIntoTheirOwnTable() { + #expect(table(forSymbolNamed: "$s7SwiftUI4TextVMn") == .swift) + #expect(table(forSymbolNamed: "_$s7SwiftUI4TextVMn") == .swift) + #expect(table(forSymbolNamed: "_symbolic _____ 7SwiftUI4TextV") == .symbolicMangling) + #expect(table(forSymbolNamed: "_default assoc type _____y_____") == .symbolicMangling) + } + + @Test func swiftRoutingLeavesOtherLanguagesOut() { + #expect(table(forSymbolNamed: "_malloc") == nil) + #expect(table(forSymbolNamed: "__ZN4llvm5Value4dumpEv") == nil) + #expect(table(forSymbolNamed: "-[NSView setNeedsDisplay:]") == nil) + #expect(table(forSymbolNamed: "_OBJC_CLASS_$__TtC7SwiftUI14NSHostingView") == nil) + } + + @Test func onlyTheSwiftTableIsIndexedByOffset() { + #expect(routing.offsetIndexing(in: .swift) == .byOffset) + #expect(routing.offsetIndexing(in: .symbolicMangling) == .nameOnly) + #expect(routing.mayReferenceStringTablesOfLoadedImages) + } +} diff --git a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift new file mode 100644 index 000000000..75056daea --- /dev/null +++ b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift @@ -0,0 +1,179 @@ +@_spi(Internals) import MachOSymbols +import Foundation +import Testing +import MachOKit +import MachOResolving +@_spi(Internals) import Demangling +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// Pins when a symbol index demangles its names (evolution proposal +/// `machofile-performance`): the storage's first stage — the symbol table, +/// the offset index, the symbolic-mangling table and the export facts — +/// demangles nothing, and the demangled index is built on the first query +/// that needs a tree, once, however many threads ask at the same time. +/// +/// The layout engine names a dependency image's private types through the +/// symbol on each anonymous context descriptor. When looking that symbol up +/// demangled the whole image, laying out SwiftUI spent 7.7 of its 27.8 +/// seconds demangling every name of every dependency it named a type in. +/// +/// Each test builds a storage of its own outside the cache, so no other +/// suite's queries can have built its demangled index already. +@Suite +final class SymbolIndexDemangledIndexTests: MachOFileTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + @Test func offsetLookupsLeaveTheNamesUndemangled() throws { + let storage = try #require(SwiftSymbolIndexStore.shared.buildStorageWithoutDemangledIndexForTesting(for: machOFile)) + let (offset, rows) = try #require(storage.symbolRowsByOffset.first) + #expect(!rows.isEmpty) + #expect(storage.symbolTable.rowCount > 0) + #expect(storage.isExported(name: storage.symbolTable.materializedName(atRow: 0)) != nil) + _ = storage.symbolicManglingSymbolTable.rowCount + _ = storage.hasLocalSwiftSymbols + _ = offset + #expect(!storage.hasBuiltDemangledIndex) + + // The first query that needs a tree builds the index. + _ = storage.demangledSymbols(atRows: rows) + #expect(storage.hasBuiltDemangledIndex) + } + + /// The index built on demand holds what a full build holds: the same + /// rows demangle to the same trees. + @Test func theIndexBuiltOnDemandMatchesAFullBuild() throws { + let onDemandStorage = try #require(SwiftSymbolIndexStore.shared.buildStorageWithoutDemangledIndexForTesting(for: machOFile)) + let fullStorage = try #require(SwiftSymbolIndexStore.shared.buildStorage(for: machOFile)) + #expect(fullStorage.hasBuiltDemangledIndex) + #expect(onDemandStorage.symbolTable.rowCount == fullStorage.symbolTable.rowCount) + + let onDemandIndex = onDemandStorage.demangledIndex + let fullIndex = fullStorage.demangledIndex + #expect(onDemandIndex.rootNodeIndexByTableRow.count == fullIndex.rootNodeIndexByTableRow.count) + var comparedTreeCount = 0 + for row in 0 ..< onDemandIndex.rootNodeIndexByTableRow.count { + switch (onDemandIndex.rootNodeIndexByTableRow[row], fullIndex.rootNodeIndexByTableRow[row]) { + case (nil, nil): + continue + case (let onDemandRootNodeIndex?, let fullRootNodeIndex?): + let onDemandTree = onDemandIndex.nodeStore.reference(at: onDemandRootNodeIndex) + let fullTree = fullIndex.nodeStore.reference(at: fullRootNodeIndex) + #expect(onDemandTree.structurallyEquals(fullTree)) + comparedTreeCount += 1 + default: + Issue.record("row \(row) demangled in one build and not in the other") + } + } + #expect(comparedTreeCount > 0) + #expect(Array(onDemandIndex.symbolRowsByKind.keys) == Array(fullIndex.symbolRowsByKind.keys)) + #expect(Array(onDemandIndex.memberSymbolRowsByKind.keys) == Array(fullIndex.memberSymbolRowsByKind.keys)) + } + + /// The sweep demangles a wave of rows ahead on several threads at once + /// and interns each wave in row order (`DemanglingWave`). Every row must + /// still hold the tree its own name demangles to, and a name the + /// demangler rejects none — across a wave boundary, and through the + /// last, partial wave. + @Test func everyRowHoldsTheTreeOfItsOwnName() throws { + let storage = try #require(SwiftSymbolIndexStore.shared.buildStorageWithoutDemangledIndexForTesting(for: machOFile)) + let symbolTable = storage.symbolTable + #expect(symbolTable.rowCount > DemanglingWave.size) + #expect(symbolTable.rowCount % DemanglingWave.size != 0) + + let index = storage.demangledIndex + #expect(index.rootNodeIndexByTableRow.count == symbolTable.rowCount) + var comparedTreeCount = 0 + var mismatchedRows: [Int] = [] + for row in 0 ..< symbolTable.rowCount { + let expectedTree = try? demangleAsNodeTransient(symbolTable.materializedName(atRow: UInt32(row))) + switch (index.rootNodeIndexByTableRow[row], expectedTree) { + case (nil, nil): + continue + case (let rootNodeIndex?, let expectedTree?): + if index.nodeStore.reference(at: rootNodeIndex).structurallyEquals(expectedTree) { + comparedTreeCount += 1 + } else { + mismatchedRows.append(row) + } + default: + mismatchedRows.append(row) + } + } + #expect(comparedTreeCount > DemanglingWave.size) + #expect(mismatchedRows.isEmpty, "rows whose tree is not their own name's: \(mismatchedRows.prefix(20))") + } + + /// Threads asking for the index at once wait for one build and all get + /// it. Each asks from a thread of its own, so a blocked asker never holds + /// a cooperative pool thread the build might need. + @Test func concurrentFirstReadersShareOneBuild() async throws { + let storage = try #require(SwiftSymbolIndexStore.shared.buildStorageWithoutDemangledIndexForTesting(for: machOFile)) + let askerCount = 8 + let indexes = await withCheckedContinuation { (continuation: CheckedContinuation<[ObjectIdentifier], Never>) in + let collected = Collected() + for _ in 0 ..< askerCount { + Thread { + let identifier = ObjectIdentifier(storage.demangledIndex) + if let all = collected.append(identifier, expecting: askerCount) { + continuation.resume(returning: all) + } + }.start() + } + } + #expect(indexes.count == askerCount) + #expect(Set(indexes).count == 1) + } + + /// Twice as many first readers as the cooperative pool has threads, each + /// of a storage of its own, all asking from the pool at once: every pool + /// thread blocks on its large-stack hop while the builders wait for the + /// names they handed out to be demangled. Run in a child process with a + /// watchdog, so a hang fails the test instead of stopping the run. + @Test func firstReadersOnEveryCooperativeThreadAllFinish() async { + await #expect(processExitsWith: .success) { + Thread { + Thread.sleep(forTimeInterval: 300) + exit(EXIT_FAILURE) + }.start() + let machOFile: MachOFile + do { + switch try loadFromFile(named: .SymbolTestsCore) { + case .machO(let machO): + machOFile = machO + case .fat(let fatFile): + guard let machO = try fatFile.machOFiles().first(where: { $0.header.cpuType == .arm64 }) else { exit(EXIT_FAILURE) } + machOFile = machO + } + } catch { + exit(EXIT_FAILURE) + } + let readerCount = ProcessInfo.processInfo.activeProcessorCount * 2 + var storages: [SwiftSymbolIndexStore.Storage] = [] + for _ in 0 ..< readerCount { + guard let storage = SwiftSymbolIndexStore.shared.buildStorageWithoutDemangledIndexForTesting(for: machOFile) else { exit(EXIT_FAILURE) } + storages.append(storage) + } + await withTaskGroup(of: Void.self) { group in + for storage in storages { + group.addTask { _ = storage.demangledIndex } + } + } + } + } + + private final class Collected: @unchecked Sendable { + private let lock = NSLock() + private var identifiers: [ObjectIdentifier] = [] + + /// Appends `identifier`; returns every identifier once the expected + /// number has arrived, `nil` before that. + func append(_ identifier: ObjectIdentifier, expecting expectedCount: Int) -> [ObjectIdentifier]? { + lock.lock() + defer { lock.unlock() } + identifiers.append(identifier) + return identifiers.count == expectedCount ? identifiers : nil + } + } +} diff --git a/Tests/SwiftSymbolsTests/SymbolIndexModuleNameTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexModuleNameTests.swift new file mode 100644 index 000000000..c4eea4f46 --- /dev/null +++ b/Tests/SwiftSymbolsTests/SymbolIndexModuleNameTests.swift @@ -0,0 +1,35 @@ +import Testing +@_spi(Internals) import Demangling +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// Pins `SwiftSymbolIndexStore.moduleNamesInAllSymbols(in:)`, which the interface +/// builder reads the modules it imports from (evolution proposal +/// `machofile-performance`). It walks the node store once and enters each +/// shared subtree once; what it returns must be what walking every symbol's +/// whole tree returns — the same names, met first in the same order, and the +/// same number of symbols. +@Suite +final class SymbolIndexModuleNameTests: MachOFileTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + @Test func moduleNamesMatchAWalkOfEveryTree() throws { + let (symbolCount, moduleNames) = SwiftSymbolIndexStore.shared.moduleNamesInAllSymbols(in: machOFile) + + let allSymbols = SwiftSymbolIndexStore.shared.allSymbols(in: machOFile) + var expectedModuleNames: [String] = [] + var seenModuleNames: Set = [] + for symbol in allSymbols { + for moduleNode in symbol.demangledNode.all(of: .module) { + if let moduleName = moduleNode.text, seenModuleNames.insert(moduleName).inserted { + expectedModuleNames.append(moduleName) + } + } + } + + #expect(symbolCount == allSymbols.count) + #expect(Array(moduleNames) == expectedModuleNames) + #expect(expectedModuleNames.count > 2) + } +} diff --git a/Tests/MachOSymbolsTests/SymbolIndexStoreFixtureTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift similarity index 83% rename from Tests/MachOSymbolsTests/SymbolIndexStoreFixtureTests.swift rename to Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift index f92ce5231..530995e8c 100644 --- a/Tests/MachOSymbolsTests/SymbolIndexStoreFixtureTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift @@ -2,12 +2,13 @@ import Foundation import MachOResolving import Testing @_spi(Internals) import Demangling -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) import MachOSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport -/// Fixture-based unit coverage for `SymbolIndexStore` against the +/// Fixture-based unit coverage for `SwiftSymbolIndexStore` against the /// `SymbolTestsCore` framework (self-built fixture, no external Xcode /// dependency). Complements the heavyweight integration/baseline tests: /// these assert the NodeStore-backed pipeline's invariants — cache-free @@ -20,9 +21,9 @@ import MachOFixtureSupport final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } - private var storage: SymbolIndexStore.Storage { + private var storage: SwiftSymbolIndexStore.Storage { get throws { - try #require(SymbolIndexStore.shared.storage(in: machOFile)) + try #require(SwiftSymbolIndexStore.shared.storage(in: machOFile)) } } @@ -44,7 +45,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { /// when it is broken. (The process-global zero-growth measurement lives in /// the manually run `SymbolIndexStoreBaselineTests`.) @Test func buildPipelineStaysOffGlobalNodeCache() throws { - let builtStorage = try #require(SymbolIndexStore.shared.buildStorage(for: machOFile)) + let builtStorage = try #require(SwiftSymbolIndexStore.shared.buildStorage(for: machOFile)) #expect(builtStorage.symbolTable.rowCount > 0) let sampleRow = try #require(builtStorage.rootNodeIndexByTableRow.firstIndex(where: { $0 != nil })) @@ -97,33 +98,6 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { // MARK: - Row buckets (proposal 0003) - /// The bucket's whole contract: first append stays inline, the second - /// spills to an array, iteration preserves insertion order (the - /// byte-identical-output guarantee), and `contains` answers both forms. - @Test func symbolRowBucketAppendMigrationAndIterationOrder() { - var bucket = SymbolRowBucket.empty - #expect(bucket.isEmpty) - #expect(bucket.count == 0) - #expect(!bucket.contains(7)) - - bucket.append(7) - #expect(bucket == .single(7)) - #expect(bucket.count == 1) - #expect(Array(bucket) == [7]) - #expect(bucket.contains(7)) - #expect(!bucket.contains(9)) - - bucket.append(9) - #expect(bucket == .multiple([7, 9])) - - bucket.append(5) - #expect(bucket == .multiple([7, 9, 5])) - #expect(Array(bucket) == [7, 9, 5]) - #expect(bucket.count == 3) - #expect(bucket.contains(5)) - #expect(!bucket.contains(6)) - } - /// Single-row dominance is what proposal 0003's memory estimate rests /// on; assert the direction on the fixture and surface the exact ratio /// as acceptance evidence (the framework-scale ratio is re-measured by @@ -186,7 +160,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { // regression on cache-adjusted keys reproducible. var checkedOffsetCount = 0 for (offset, rows) in storage.symbolRowsByOffset.sorted(by: { $0.key < $1.key }) { - let queried = try #require(SymbolIndexStore.shared.symbols(for: offset, in: machOFile)) + let queried = try #require(SwiftSymbolIndexStore.shared.symbols(for: offset, in: machOFile)) #expect(queried.count == rows.count) #expect(queried.allSatisfy { $0.offset == offset }) for (queriedSymbol, row) in zip(queried, rows) { @@ -209,7 +183,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { for (typeName, rowsByTypeNodeIndex) in memberRows { for (typeNodeIndex, expectedRows) in rowsByTypeNodeIndex { let externalNode = storage.nodeStore.reference(at: typeNodeIndex).materialize() - let queried = SymbolIndexStore.shared.memberSymbols(of: memberKind, for: typeName, node: externalNode, in: machOFile) + let queried = SwiftSymbolIndexStore.shared.memberSymbols(of: memberKind, for: typeName, node: externalNode, in: machOFile) #expect(queried.count == expectedRows.count, "bucket \(memberKind) / \(typeName)") checkedBucketCount += 1 } @@ -222,7 +196,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { let storage = try storage #expect(!storage.symbolRowsByKind.isEmpty) for (kind, expectedRows) in storage.symbolRowsByKind { - let queried = SymbolIndexStore.shared.symbols(of: kind, in: machOFile) + let queried = SwiftSymbolIndexStore.shared.symbols(of: kind, in: machOFile) #expect(queried.count == expectedRows.count) #expect(queried.allSatisfy { $0.demangledNode.children.first?.kind == kind }) } @@ -234,13 +208,13 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { for (typeName, typeInfoByTypeNodeIndex) in storage.typeInfoByName { // Name-only lookup answers first-wins across the (rare) // same-named private types sharing the stripped name bucket. - let queriedByNameOnly = try #require(SymbolIndexStore.shared.typeInfo(for: typeName, in: machOFile)) + let queriedByNameOnly = try #require(SwiftSymbolIndexStore.shared.typeInfo(for: typeName, in: machOFile)) #expect(queriedByNameOnly.name == typeInfoByTypeNodeIndex.values.first?.name) // The node-matched overload resolves each context node's own // entry (issue #115's family). for (typeNodeIndex, expectedTypeInfo) in typeInfoByTypeNodeIndex { let keyReference = storage.nodeStore.reference(at: typeNodeIndex) - let queried = try #require(SymbolIndexStore.shared.typeInfo(for: typeName, node: keyReference, in: machOFile)) + let queried = try #require(SwiftSymbolIndexStore.shared.typeInfo(for: typeName, node: keyReference, in: machOFile)) #expect(queried.name == expectedTypeInfo.name) #expect(queried.kind == expectedTypeInfo.kind) } @@ -251,7 +225,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { let storage = try storage for (nodeIndex, expectedRow) in storage.opaqueTypeDescriptorSymbolRowByNodeIndex { let keyReference = storage.nodeStore.reference(at: nodeIndex) - let queried = try #require(SymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: keyReference.materialize(), in: machOFile)) + let queried = try #require(SwiftSymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: keyReference.materialize(), in: machOFile)) #expect(queried.symbol == storage.symbolTable.symbol(atRow: expectedRow)) } } @@ -269,7 +243,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { /// to express a lookup by a caller-side tree.) @Test func bulkOpaqueQueryIsProbableWithACallerDemangledTree() throws { let storage = try storage - let bulkSymbols = try #require(SymbolIndexStore.shared.allOpaqueTypeDescriptorSymbols(in: machOFile)) + let bulkSymbols = try #require(SwiftSymbolIndexStore.shared.allOpaqueTypeDescriptorSymbols(in: machOFile)) try #require(!bulkSymbols.isEmpty, "fixture must carry opaque type descriptors for this test to be meaningful") for (nodeIndex, expectedRow) in storage.opaqueTypeDescriptorSymbolRowByNodeIndex { @@ -294,9 +268,9 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { guard let rootNodeIndex = storage.rootNodeIndexByTableRow[row] else { continue } let symbol = storage.symbolTable.symbol(atRow: UInt32(row)) let reference = storage.nodeStore.reference(at: rootNodeIndex) - let materialized = try #require(SymbolIndexStore.shared.demangledNode(for: symbol, in: machOFile)) + let materialized = try #require(SwiftSymbolIndexStore.shared.demangledNode(for: symbol, in: machOFile)) #expect(reference.structurallyEquals(materialized)) - let referenceAgain = try #require(SymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machOFile)) + let referenceAgain = try #require(SwiftSymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machOFile)) #expect(referenceAgain == reference) checkedCount += 1 } @@ -310,14 +284,14 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { _ = try storage let lateSymbol = Symbol(offset: -1, name: "$s7SwiftUI4ViewP") - let reference = try #require(SymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile)) + let reference = try #require(SwiftSymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile)) let expected = try demangleAsNode(lateSymbol.name, internsSubtrees: false).print(using: .default) #expect(reference.print(using: .default) == expected) - let referenceAgain = try #require(SymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile)) + let referenceAgain = try #require(SwiftSymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile)) #expect(referenceAgain == reference) - let materialized = try #require(SymbolIndexStore.shared.demangledNode(for: lateSymbol, in: machOFile)) + let materialized = try #require(SwiftSymbolIndexStore.shared.demangledNode(for: lateSymbol, in: machOFile)) #expect(reference.structurallyEquals(materialized)) } @@ -330,11 +304,11 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { let bogusSymbol = Symbol(offset: -1, name: "$s999999999999") #expect(storage.symbolTable.row(forName: bogusSymbol.name) == nil) - #expect(SymbolIndexStore.shared.demangledNodeReference(for: bogusSymbol, in: machOFile) == nil) + #expect(SwiftSymbolIndexStore.shared.demangledNodeReference(for: bogusSymbol, in: machOFile) == nil) let verdict = try #require(storage.lateDemangleVerdictForTesting(forName: bogusSymbol.name)) #expect(verdict == nil) - #expect(SymbolIndexStore.shared.demangledNodeReference(for: bogusSymbol, in: machOFile) == nil) + #expect(SwiftSymbolIndexStore.shared.demangledNodeReference(for: bogusSymbol, in: machOFile) == nil) } /// A name the build sweep covered answers from the table verdict — hit @@ -347,12 +321,12 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { let demangledRow = try #require(storage.rootNodeIndexByTableRow.firstIndex(where: { $0 != nil })) let demangledSymbol = storage.symbolTable.symbol(atRow: UInt32(demangledRow)) - _ = try #require(SymbolIndexStore.shared.demangledNodeReference(for: demangledSymbol, in: machOFile)) + _ = try #require(SwiftSymbolIndexStore.shared.demangledNodeReference(for: demangledSymbol, in: machOFile)) #expect(storage.lateDemangleVerdictForTesting(forName: demangledSymbol.name) == nil) if let rejectedRow = storage.rootNodeIndexByTableRow.firstIndex(where: { $0 == nil }) { let rejectedSymbol = storage.symbolTable.symbol(atRow: UInt32(rejectedRow)) - #expect(SymbolIndexStore.shared.demangledNodeReference(for: rejectedSymbol, in: machOFile) == nil) + #expect(SwiftSymbolIndexStore.shared.demangledNodeReference(for: rejectedSymbol, in: machOFile) == nil) #expect(storage.lateDemangleVerdictForTesting(forName: rejectedSymbol.name) == nil) } } @@ -370,7 +344,7 @@ final class SymbolIndexStoreFixtureTests: MachOFileTests, @unchecked Sendable { let references = await withTaskGroup(of: NodeReference?.self) { group in for _ in 0 ..< 16 { group.addTask { [machOFile] in - SymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile) + SwiftSymbolIndexStore.shared.demangledNodeReference(for: lateSymbol, in: machOFile) } } var collected: [NodeReference?] = [] diff --git a/Tests/SwiftSymbolsTests/SymbolIndexStoreNamingScanTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexStoreNamingScanTests.swift new file mode 100644 index 000000000..070ea846f --- /dev/null +++ b/Tests/SwiftSymbolsTests/SymbolIndexStoreNamingScanTests.swift @@ -0,0 +1,43 @@ +import Foundation +import Testing + +/// `SymbolIndexStore` is MachOKitExtensions' C, C++ and Objective-C symbol +/// index; this package's Swift one is `SwiftSymbolIndexStore`. The two share +/// their query names (`symbols(for:in:)`, `isExported(name:in:)`, +/// `containsSymbol(named:in:)`, `offset(ofSymbolNamed:in:)`), so code that +/// still spells the old name compiles against the wrong store and quietly +/// answers with no Swift name at all. Nothing in this package means the C +/// store, so the bare name may not appear in code. +@Suite +struct SymbolIndexStoreNamingScanTests { + private static let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + + // Spelled in two pieces so that this file does not match itself. + private static let bareNamePattern = try! NSRegularExpression(pattern: "(? 500) + #expect(offendingLines.isEmpty, "\(offendingLines.prefix(10))") + } +} diff --git a/Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift b/Tests/SwiftSymbolsTests/SymbolOwnerGroupingTests.swift similarity index 77% rename from Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift rename to Tests/SwiftSymbolsTests/SymbolOwnerGroupingTests.swift index a82adee24..adce214f1 100644 --- a/Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolOwnerGroupingTests.swift @@ -1,13 +1,14 @@ +@_spi(Internals) import MachOSymbols import Foundation import Testing import MachOKit import MachOResolving @_spi(Internals) import Demangling -@_spi(Internals) @testable import MachOSymbols -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) @testable import SwiftSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport -/// Pins `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` — +/// Pins `SwiftSymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` — /// the per-address grouping that tells which of the names identical code /// folding put on one address belongs to a given conformance or protocol /// (evolution proposal `faster-lazy-definition-indexing`) — to the @@ -25,13 +26,13 @@ final class SymbolOwnerGroupingSwiftUITests: MachOImageTests, @unchecked Sendabl override class var imageName: MachOImageName { .SwiftUI } @Test(arguments: [ - (SymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceTypeBuilderOnly), - (SymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceType), - (SymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceTypeBuilderOnly), - (SymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceType), + (SwiftSymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceTypeBuilderOnly), + (SwiftSymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceType), + (SwiftSymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceTypeBuilderOnly), + (SwiftSymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceType), ]) - func groupingAnswersLikeTheOneByOneRule(ownerKind: SymbolIndexStore.SymbolOwnerKind, options: DemangleOptions) throws { - let storage = try #require(SymbolIndexStore.shared.storage(in: machOImage)) + func groupingAnswersLikeTheOneByOneRule(ownerKind: SwiftSymbolIndexStore.SymbolOwnerKind, options: DemangleOptions) throws { + let storage = try #require(SwiftSymbolIndexStore.shared.storage(in: machOImage)) let sharedOffsets = storage.symbolRowsByOffset.filter { $0.value.count > 1 }.keys.sorted() // Not vacuous: the image really folds, at the scale that made the // one-by-one rule quadratic. @@ -43,7 +44,7 @@ final class SymbolOwnerGroupingSwiftUITests: MachOImageTests, @unchecked Sendabl for offset in sharedOffsets { let expectedMatchesByOwnerName = OneByOneOwnerRule.matchesByOwnerName(at: offset, ownerKind: ownerKind, options: options, in: machOImage) for (ownerName, expectedMatches) in expectedMatchesByOwnerName { - let answer = SymbolIndexStore.shared.symbols(for: offset, ownedBy: ownerName, ownerKind: ownerKind, printedWith: options, in: machOImage).map(OneByOneOwnerRule.Match.init) + let answer = SwiftSymbolIndexStore.shared.symbols(for: offset, ownedBy: ownerName, ownerKind: ownerKind, printedWith: options, in: machOImage).map(OneByOneOwnerRule.Match.init) comparedOwnerCount += 1 if answer != expectedMatches { mismatchCount += 1 @@ -53,7 +54,7 @@ final class SymbolOwnerGroupingSwiftUITests: MachOImageTests, @unchecked Sendabl } } // A name no symbol there is owned by gets nothing. - if !SymbolIndexStore.shared.symbols(for: offset, ownedBy: "No.Such.Owner", ownerKind: ownerKind, printedWith: options, in: machOImage).isEmpty { + if !SwiftSymbolIndexStore.shared.symbols(for: offset, ownedBy: "No.Such.Owner", ownerKind: ownerKind, printedWith: options, in: machOImage).isEmpty { mismatchCount += 1 Issue.record("offset \(offset) answered symbols for an owner none of them has") } @@ -68,7 +69,7 @@ final class SymbolOwnerGroupingSwiftUITests: MachOImageTests, @unchecked Sendabl /// built for this test alone, so no other test has grouped the address /// yet. @Test func concurrentFirstQuestionsAgree() async throws { - let storage = try #require(SymbolIndexStore.shared.buildStorage(for: machOImage)) + let storage = try #require(SwiftSymbolIndexStore.shared.buildStorage(for: machOImage)) let (offset, rows) = try #require(storage.symbolRowsByOffset.max { $0.value.count < $1.value.count }) let expectedMatchesByOwnerName = OneByOneOwnerRule.matchesByOwnerName(at: offset, ownerKind: .conformingType, options: .interfaceTypeBuilderOnly, in: machOImage) let ownerName = try #require(expectedMatchesByOwnerName.max { $0.value.count < $1.value.count }?.key) @@ -116,11 +117,11 @@ enum OneByOneOwnerRule { } } - static func matchesByOwnerName(at offset: Int, ownerKind: SymbolIndexStore.SymbolOwnerKind, options: DemangleOptions, in machO: MachOImage) -> [String: [Match]] { - guard let symbols = SymbolIndexStore.shared.symbols(for: offset, in: machO) else { return [:] } + static func matchesByOwnerName(at offset: Int, ownerKind: SwiftSymbolIndexStore.SymbolOwnerKind, options: DemangleOptions, in machO: MachOImage) -> [String: [Match]] { + guard let symbols = SwiftSymbolIndexStore.shared.symbols(for: offset, in: machO) else { return [:] } var matchesByOwnerName: [String: [Match]] = [:] for symbol in symbols { - guard let node = SymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO) else { continue } + guard let node = SwiftSymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO) else { continue } let ownerNode: NodeReference? = switch ownerKind { case .conformingType: node.first(of: .protocolConformance)?.children.first diff --git a/Tests/MachOSymbolsTests/SymbolTableEquivalenceTests.swift b/Tests/SwiftSymbolsTests/SymbolTableEquivalenceTests.swift similarity index 75% rename from Tests/MachOSymbolsTests/SymbolTableEquivalenceTests.swift rename to Tests/SwiftSymbolsTests/SymbolTableEquivalenceTests.swift index 32f5e40c8..9dfcfee80 100644 --- a/Tests/MachOSymbolsTests/SymbolTableEquivalenceTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolTableEquivalenceTests.swift @@ -2,20 +2,22 @@ import Foundation import Testing import MachOKit @_spi(Internals) import Demangling -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) import MachOSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// Equivalence pins for the offset-ized symbol table (evolution proposal /// 0001), run against a real in-process image so the mapped-string-table /// leg — the one the fixture-file suite cannot exercise — is covered end /// to end: /// -/// 1. the byte-level Swift-symbol test agrees with `String.isSwiftSymbol` -/// on every entry of a real symbol table (the byte version re-states the -/// demangler's prefix list and would silently diverge if that list ever -/// grew); +/// 1. MachOKitExtensions' `SymbolLanguage`, which tells Swift names from the +/// others byte by byte, agrees with `String.isSwiftSymbol` on every entry +/// of a real symbol table once the symbolic-mangling names (Swift too, +/// but no mangling) are set apart (it re-states the demangler's prefix +/// list and would silently diverge if that list ever grew); /// 2. the collection sweep retains exactly the rows the former /// `String`-keyed collection pass retained, with the same last-wins /// canonical offsets; @@ -23,11 +25,15 @@ import MachOFixtureSupport /// materialized name with that row (the dictionary it replaced was /// keyed on those exact strings). final class SymbolTableImageEquivalenceTests: MachOImageTests, @unchecked Sendable { - @Test func byteLevelSwiftSymbolCheckMatchesStringCheck() throws { + @Test func symbolLanguageSwiftMatchesDemanglingIsSwiftSymbol() throws { var checkedCount = 0 var mismatchCount = 0 func check(nameC: UnsafePointer, name: String) { - if nameBytesHaveSwiftManglingPrefix(nameC) != name.isSwiftSymbol { + // Evaluated before the `&&`: its right side is an autoclosure, and capturing + // the non-Sendable pointer there is a region-isolation error in release builds. + let hasSymbolicManglingPrefix = nameBytesHaveSymbolicManglingSymbolPrefix(nameC) + let isSwiftMangling = SymbolLanguage(ofSymbolNameBytes: nameC) == .swift && !hasSymbolicManglingPrefix + if isSwiftMangling != name.isSwiftSymbol { mismatchCount += 1 if mismatchCount <= 3 { Issue.record("byte-level Swift-symbol check mismatch for \(name)") @@ -49,7 +55,7 @@ final class SymbolTableImageEquivalenceTests: MachOImageTests, @unchecked Sendab } @Test func mappedCollectionMatchesStringBasedCollection() throws { - let storage = try #require(SymbolIndexStore.shared.storage(in: machOImage)) + let storage = try #require(SwiftSymbolIndexStore.shared.storage(in: machOImage)) let symbolTable = storage.symbolTable // The pre-0001 collection pass, re-run through the reader-generic @@ -80,7 +86,7 @@ final class SymbolTableImageEquivalenceTests: MachOImageTests, @unchecked Sendab } @Test func binarySearchAnswersEveryRowByItsOwnName() throws { - let storage = try #require(SymbolIndexStore.shared.storage(in: machOImage)) + let storage = try #require(SwiftSymbolIndexStore.shared.storage(in: machOImage)) let symbolTable = storage.symbolTable try #require(symbolTable.rowCount > 0) diff --git a/Tests/MachOSymbolsTests/SymbolicManglingSymbolCollectionTests.swift b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift similarity index 90% rename from Tests/MachOSymbolsTests/SymbolicManglingSymbolCollectionTests.swift rename to Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift index 9e3b8594d..48a94f195 100644 --- a/Tests/MachOSymbolsTests/SymbolicManglingSymbolCollectionTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift @@ -1,10 +1,11 @@ import Foundation import Testing import MachOKit -@_spi(Internals) @testable import MachOSymbols +@_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches -@testable import MachOTestingSupport -import MachOFixtureSupport +@_spi(Internals) import MachOSymbols +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// The collection layer of evolution proposal `symbolic-mangling-symbol-index`: /// the build sweep gathers every `_symbolic ` / `_default assoc type ` symbol @@ -56,7 +57,7 @@ struct SymbolicManglingSymbolCollectionTests { for symbol in machOImage.symbols where SymbolicManglingSymbolName.hasPrefix(symbol.name) && !symbol.nlist.isExternal { expectedOffsetByName[symbol.name] = symbol.offset } - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOImage)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOImage)) try Self.expectCollection(collectedSymbols, equals: expectedOffsetByName) } @@ -72,7 +73,7 @@ struct SymbolicManglingSymbolCollectionTests { for symbol in machOFile.symbols where SymbolicManglingSymbolName.hasPrefix(symbol.name) && !symbol.nlist.isExternal { expectedOffsetByName[symbol.name] = symbol.offset - sharedRegionStart } - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) try Self.expectCollection(collectedSymbols, equals: expectedOffsetByName) } @@ -82,12 +83,12 @@ struct SymbolicManglingSymbolCollectionTests { @Test(.enabled(if: runsOnMacOS26OrLater, "AppKit's symbolic-mangling symbols are pinned on macOS 26")) func symbolicManglingSymbolsStayOutOfTheMainTable() throws { let machOFile = try Self.appKitFileInSystemCache() - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) try #require(!collectedSymbols.isEmpty) var leakedCount = 0 for symbol in collectedSymbols { - let symbolsAtOffset = SymbolIndexStore.shared.symbols(for: symbol.offset, in: machOFile).map { Array($0) } ?? [] - if symbolsAtOffset.contains(where: { SymbolicManglingSymbolName.hasPrefix($0.name) }) || SymbolIndexStore.shared.containsSymbol(named: symbol.name, in: machOFile) { + let symbolsAtOffset = SwiftSymbolIndexStore.shared.symbols(for: symbol.offset, in: machOFile).map { Array($0) } ?? [] + if symbolsAtOffset.contains(where: { SymbolicManglingSymbolName.hasPrefix($0.name) }) || SwiftSymbolIndexStore.shared.containsSymbol(named: symbol.name, in: machOFile) { leakedCount += 1 if leakedCount <= 3 { Issue.record("\(symbol.name) is visible through the main table") @@ -129,7 +130,7 @@ struct SymbolicManglingSymbolCollectionTests { var censusLines: [String] = [] for imageName in [MachOImageName.AppKit, .SwiftUICore] { let machOFile = try #require(cache.machOFile(named: imageName), "the running system's cache has no \(imageName)") - let collectedSymbols = try #require(SymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) + let collectedSymbols = try #require(SwiftSymbolIndexStore.shared.symbolicManglingSymbols(in: machOFile)) var symbolCount = 0 var withReferentsCount = 0 var referentCount = 0 @@ -146,8 +147,8 @@ struct SymbolicManglingSymbolCollectionTests { } } let symbolTable = collectedSymbols.symbolTable - let tableByteCount = symbolTable.rows.count * MemoryLayout.stride + symbolTable.rowsSortedByName.count * MemoryLayout.stride + symbolTable.privateNameBuffer.count - censusLines.append("\(imageName): \(symbolCount) symbols, \(withReferentsCount) with referents, \(referentCount) referents, \(defaultAssociatedTypeWitnessCount) default assoc type, table \(tableByteCount) bytes (names \(symbolTable.privateNameBuffer.count))") + let tableByteCount = symbolTable.retainedByteCount + censusLines.append("\(imageName): \(symbolCount) symbols, \(withReferentsCount) with referents, \(referentCount) referents, \(defaultAssociatedTypeWitnessCount) default assoc type, table \(tableByteCount) bytes (names \(symbolTable.privateNameByteCount))") #expect(withReferentsCount > 0, "\(imageName) carries no symbolic-mangling symbol with referents") if imageName == .SwiftUICore { #expect(defaultAssociatedTypeWitnessCount > 0, "SwiftUICore's default associated type witnesses were not collected") diff --git a/Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift similarity index 96% rename from Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift rename to Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift index 7626f15b0..1d7c1a18e 100644 --- a/Tests/MachOSymbolsTests/WrappedReaderSymbolTests.swift +++ b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift @@ -2,9 +2,9 @@ import Foundation import Testing import MachOKit import MachOFoundation -import MachOSymbols -import MachOTestingSupport -import MachOFixtureSupport +import SwiftSymbols +import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport /// A host's wrapper — MachOKitUI's `MachOFileSource` / `MachOImageSource` — /// around a reader of the system dyld shared cache. diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift index ee4bca8f9..da3aef0c3 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift @@ -4,7 +4,7 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftThunkAnalysis -import MachOTestingSupport +import SwiftSectionTestingSupport /// An accessor thunk reads its owner's generic arguments out of one buffer, /// and `AccessorThunkOwnerLayout` names the k-th word as the parameter it diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift index be10f1883..fd39b67ca 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift @@ -3,7 +3,7 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering diff --git a/Tests/SwiftThunkAnalysisTests/CapstoneThunkDecoderTests.swift b/Tests/SwiftThunkAnalysisTests/CapstoneThunkDecoderTests.swift index 1c9417868..030c2a464 100644 --- a/Tests/SwiftThunkAnalysisTests/CapstoneThunkDecoderTests.swift +++ b/Tests/SwiftThunkAnalysisTests/CapstoneThunkDecoderTests.swift @@ -73,6 +73,18 @@ struct CapstoneThunkDecoderTests { #expect(operations == Array(repeating: .signOrAuthenticatePointer(register: ThunkRegister(number: 16)), count: 4)) } + /// ld64 rewrites an `adrp` / `ldr` pair whose slot lies within a megabyte + /// into `nop` / `ldr x8, ` (`LinkerOptimizationHintTests` in + /// `CrossReferenceAnalysisTests`); the load still says which slot it + /// read, as the pair did. + @Test func aLiteralLoadNamesItsSlot() throws { + let operations = try decoded([0x5800_0048]) // ldr x8, #8 + #expect(operations != [.unmodelled(writtenRegisters: [ThunkRegister(number: 8)])]) + #expect(operations == [.loadFromSlot(destination: ThunkRegister(number: 8), slotAddress: 0x1008)]) + // A 32-bit literal load is no pointer; it only forgets its register. + #expect(try decoded([0x1800_0048]) == [.unmodelled(writtenRegisters: [ThunkRegister(number: 8)])]) // ldr w8, #8 + } + @Test func aTrapIsATrap() throws { #expect(try decoded([0xD43E_8E20]) == [.trap]) // brk #0xf471 } diff --git a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift index b52c73e66..d266536d7 100644 --- a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering diff --git a/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift index 7c8398498..7addef3ad 100644 --- a/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift @@ -3,12 +3,12 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering import SwiftThunkAnalysis -@testable import MachOTestingSupport +@testable import SwiftSectionTestingSupport /// Kind-9 *field records* resolved offline through the same reader, pinned /// on the fixture — a standalone dylib, so no shared-cache stub and no OS diff --git a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift index 3739ab4e4..91c9c1abe 100644 --- a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift +++ b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering diff --git a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift index 16c6c3771..5397d86b9 100644 --- a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift @@ -3,7 +3,7 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Demangling @_spi(Internals) import SwiftInspection @testable import SwiftThunkAnalysis diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index 83d504ee4..ac4f0b19f 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -3,8 +3,8 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport -import MachOTestingSupport +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering diff --git a/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift b/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift new file mode 100644 index 000000000..757f5edf6 --- /dev/null +++ b/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift @@ -0,0 +1,88 @@ +import Foundation +import Testing +import MachOKit +@_spi(Internals) import MachOAddressResolution +import MachOFoundation +import MachOSwiftSection +import SwiftSectionFixtureSupport +import SwiftThunkAnalysis + +/// `AccessorThunkReader.read` makes a new thunk environment for every thunk, +/// so what an environment reads from the image or its dyld cache to name a +/// call target has to be read once per image, not once per environment. +/// +/// Two tables were rebuilt per environment, so per thunk: the image's own +/// runtime symbols, picked out of the whole symbol table — about a sixth of +/// reading SwiftUI's interface offline — and the address table of every image +/// in the cache, with the image opened for each target found there. +/// +/// After one environment has named a target, a fresh environment must name +/// it with lookups, not by reading the table again. Reading the table is +/// timed directly as the yardstick, so the comparison holds on a busy machine +/// as well as an idle one. +@Suite("Thunk environment image tables") +struct ThunkEnvironmentImageTablesTests { + @Test("A fresh environment does not walk the symbol table again") + func freshEnvironmentReusesTheImagesRuntimeSymbols() throws { + let cache = try DyldCache(path: .current) + let machOFile = try #require(cache.machOFile(named: .SwiftUI)) + // A type descriptor: inside the image and not a metadata accessor, + // so a lookup gets as far as the image's own runtime symbols. + let descriptor = try #require(try machOFile.swift.typeContextDescriptors.first) + let address = try #require(ImageAddressSpace(of: machOFile).address(forOffset: descriptor.typeContextDescriptor.offset)) + + // Builds everything the environment shares per image — the accessor + // index, the symbol index — and pages the symbol table in. + _ = MachOThunkEnvironment(machO: machOFile).callee(at: address) + + let symbolTableWalkNanoseconds = Self.nanoseconds { + var nameByteCount = 0 + for symbol in machOFile.symbols { + nameByteCount &+= symbol.name.utf8.count + } + #expect(nameByteCount > 0) + } + let freshEnvironmentLookupNanoseconds = Self.nanoseconds { + _ = MachOThunkEnvironment(machO: machOFile).callee(at: address) + } + + #expect(freshEnvironmentLookupNanoseconds * 5 < symbolTableWalkNanoseconds) + } + + @Test("A fresh environment does not read the cache's image list again") + func freshEnvironmentReusesTheCachesImageTable() throws { + let cache = try DyldCache(path: .current) + let machOFile = try #require(cache.machOFile(named: .SwiftUI)) + let swiftCore = try #require(cache.machOFile(by: .path("/usr/lib/swift/libswiftCore.dylib"))) + // A runtime entry point another image of the cache exports: naming it + // goes through the table of the cache's images. + let exportedSymbol = try #require(swiftCore.exportTrie?.search(by: "_swift_getWitnessTable")) + let exportedSymbolOffset = try #require(exportedSymbol.offset) + let address = try #require(ImageAddressSpace(of: swiftCore).address(forExportedSymbolOffset: exportedSymbolOffset)) + + #expect(MachOThunkEnvironment(machO: machOFile).callee(at: address) == .witnessTableLookup) + + let mainCache = cache.mainCache ?? cache + let imageInfos = try #require(mainCache.imageInfos) + let imageListReadNanoseconds = Self.nanoseconds { + var pathByteCount = 0 + for imageInfo in imageInfos { + pathByteCount &+= imageInfo.path(in: mainCache)?.utf8.count ?? 0 + } + #expect(pathByteCount > 0) + } + var freshEnvironmentCallee: ThunkCallee? + let freshEnvironmentLookupNanoseconds = Self.nanoseconds { + freshEnvironmentCallee = MachOThunkEnvironment(machO: machOFile).callee(at: address) + } + + #expect(freshEnvironmentCallee == .witnessTableLookup) + #expect(freshEnvironmentLookupNanoseconds * 5 < imageListReadNanoseconds) + } + + private static func nanoseconds(of body: () -> Void) -> UInt64 { + let start = DispatchTime.now().uptimeNanoseconds + body() + return DispatchTime.now().uptimeNanoseconds - start + } +} diff --git a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift index 586a24087..248d1b9c8 100644 --- a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift @@ -3,7 +3,7 @@ import Testing import MachOKit import MachOFoundation import MachOSwiftSection -import MachOFixtureSupport +import SwiftSectionFixtureSupport import Demangling @_spi(Internals) import SwiftInspection @testable import SwiftThunkAnalysis